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
1100
<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): :param tornado.concurrent.Future future: future for new conn result """ # Create a new PostgreSQL connection kwargs = utils.uri_to_kwargs(self._uri) 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 try: # Add the connection to the pool self._pool_manager.add(self.pid, connection) except Exception as error: LOGGER.exception('Failed to add %r to the pool', self.pid) future.set_exception(error) return # 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()], self._exec_cleanup(cursor, conn.fileno()) future.set_exception(error) else: results = Results(cursor, self._exec_cleanup, conn.fileno()) future.set_result(results) # Setup a callback to wait on the query result self._futures[conn.fileno()] = concurrent.TracebackFuture() # 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> Be more explicit in exception catching - Instead of catchig a bare exception, catch the two known exception types that could be thrown when adding a connection to a pool. - Increase logging usefulness - Don't resue the results variable that is used as an import for queries.results <DFF> @@ -291,6 +291,8 @@ class TornadoSession(session.Session): :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) @@ -314,8 +316,9 @@ class TornadoSession(session.Session): try: # Add the connection to the pool + LOGGER.debug('Connection established for %s', self.pid) self._pool_manager.add(self.pid, connection) - except Exception as error: + except (ValueError, pool.PoolException) as error: LOGGER.exception('Failed to add %r to the pool', self.pid) future.set_exception(error) return @@ -387,10 +390,8 @@ class TornadoSession(session.Session): self._exec_cleanup(cursor, conn.fileno()) future.set_exception(error) else: - results = Results(cursor, - self._exec_cleanup, - conn.fileno()) - future.set_result(results) + 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.TracebackFuture()
6
Be more explicit in exception catching
5
.py
py
bsd-3-clause
gmr/queries
1101
<NME> tornado_session_tests.py <BEF> """ Tests for functionality in the tornado_session module """ import unittest import mock # Out of order import to ensure psycopg2cffi is registered from queries import pool, tornado_session from psycopg2 import extras from tornado import concurrent, gen, ioloop, testing class ResultsTests(unittest.TestCase): def setUp(self): self.cursor = mock.Mock() self.fd = 10 self.cleanup = mock.Mock() self.obj = tornado_session.Results(self.cursor, self.cleanup, self.fd) def test_cursor_is_assigned(self): self.assertEqual(self.obj.cursor, self.cursor) def test_fd_is_assigned(self): self.assertEqual(self.obj._fd, self.fd) def test_cleanup_is_assigned(self): self.assertEqual(self.obj._cleanup, self.cleanup) @gen.coroutine def test_free_invokes_cleanup(self): yield self.obj.free() self.cleanup.assert_called_once_with(self.cursor, self.fd) class SessionInitTests(unittest.TestCase): def setUp(self): self.obj = tornado_session.TornadoSession() def test_creates_empty_callback_dict(self): self.assertDictEqual(self.obj._futures, {}) def test_creates_empty_connections_dict(self): self.assertDictEqual(self.obj._connections, {}) def test_sets_default_cursor_factory(self): self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor) def test_sets_tornado_ioloop_instance(self): self.assertEqual(self.obj._ioloop, ioloop.IOLoop.instance()) def test_sets_poolmananger_instance(self): self.assertEqual(self.obj._pool_manager, pool.PoolManager.instance()) def test_sets_uri(self): self.assertEqual(self.obj._uri, tornado_session.session.DEFAULT_URI) def test_creates_pool_in_manager(self): self.assertIn(self.obj.pid, self.obj._pool_manager._pools) def test_connection_is_none(self): self.assertIsNone(self.obj.connection) def test_cursor_is_none(self): self.assertIsNone(self.obj.cursor) class SessionConnectTests(testing.AsyncTestCase): def setUp(self): super(SessionConnectTests, self).setUp() self.conn = mock.Mock() self.conn.fileno = mock.Mock(return_value=10) self.obj = tornado_session.TornadoSession(io_loop=self.io_loop) def create_connection(future): future.set_result(self.conn) self.obj._create_connection = create_connection @testing.gen_test def test_connect_returns_new_connection(self): conn = yield self.obj._connect() self.assertEqual(conn, self.conn) @testing.gen_test def test_connect_returns_pooled_connection(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) second_result = yield self.obj._connect() self.assertEqual(second_result, conn) @testing.gen_test def test_connect_gets_pooled_connection(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) with mock.patch.object(self.obj._pool_manager, 'get') as get: with mock.patch.object(self.io_loop, 'add_handler'): yield self.obj._connect() get.assert_called_once_with(self.obj.pid, self.obj) @testing.gen_test def test_connect_pooled_connection_invokes_add_handler(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) with mock.patch.object(self.obj._pool_manager, 'get') as get: get.return_value = self.conn with mock.patch.object(self.io_loop, 'add_handler') as add_handler: yield self.obj._connect() add_handler.assert_called_once_with(self.conn.fileno(), self.obj._on_io_events, ioloop.IOLoop.WRITE) def test_psycopg2_connect_invokes_psycopg2_connect(self): with mock.patch('psycopg2.connect') as connect: self.obj._psycopg2_connect({}) connect.assert_called_once_with(**{'async': True}) def test_on_io_events_returns_if_fd_not_present(self): with mock.patch.object(self.obj, '_poll_connection') as poll: self.obj._on_io_events(1337, ioloop.IOLoop.WRITE) poll.assert_not_called() def test_on_io_events_calls_poll_connection(self): with mock.patch.object(self.obj, '_poll_connection') as poll: self.obj._connections[1337] = True self.obj._on_io_events(1337, ioloop.IOLoop.WRITE) poll.assert_called_once_with(1337) def test_exec_cleanup_closes_cursor(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() cursor = mock.Mock() cursor.close = mock.Mock() self.obj._exec_cleanup(cursor, 14) cursor.close.assert_called_once_with() def test_exec_cleanup_frees_connection(self): with mock.patch.object(self.obj._pool_manager, 'free') as pm_free: with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = conn = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) pm_free.assert_called_once_with(self.obj.pid, conn) def test_exec_cleanup_remove_handler_invoked(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler') as rh: self.obj._connections[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) rh.assert_called_once_with(14) def test_exec_removes_connection(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) self.assertNotIn(14, self.obj._connections) def test_exec_removes_future(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() self.obj._futures[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) self.assertNotIn(14, self.obj._futures) def test_pool_manager_add_failures_are_propagated(self): futures = [] def add_future(future, callback): futures.append((future, callback)) obj = tornado_session.TornadoSession() obj._ioloop = mock.Mock() obj._ioloop.add_future = add_future future = concurrent.Future() with mock.patch.object(obj._pool_manager, 'add') as add_method: add_method.side_effect = pool.PoolFullError(mock.Mock()) obj._create_connection(future) self.assertEqual(len(futures), 1) connected_future, callback = futures.pop() connected_future.set_result(True) callback(connected_future) self.assertIs(future.exception(), add_method.side_effect) class SessionPublicMethodTests(testing.AsyncTestCase): @testing.gen_test def test_callproc_invokes_execute(self): with mock.patch('queries.tornado_session.TornadoSession._execute') as \ _execute: future = concurrent.Future() future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) yield obj.callproc('foo', ['bar']) _execute.assert_called_once_with('callproc', 'foo', ['bar']) future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) result = yield obj.callproc('foo', ['bar']) _execute.assert_called_once_with('callproc', 'foo', ['bar']) @testing.gen_test obj = tornado_session.TornadoSession(io_loop=self.io_loop) yield obj.query('SELECT 1') _execute.assert_called_once_with('execute', 'SELECT 1', None) future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) result = yield obj.query('SELECT 1') _execute.assert_called_once_with('execute', 'SELECT 1', None) <MSG> Add a bare exception around invoking psycopg2 methods <DFF> @@ -207,7 +207,7 @@ class SessionPublicMethodTests(testing.AsyncTestCase): future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) - result = yield obj.callproc('foo', ['bar']) + yield obj.callproc('foo', ['bar']) _execute.assert_called_once_with('callproc', 'foo', ['bar']) @testing.gen_test @@ -218,5 +218,17 @@ class SessionPublicMethodTests(testing.AsyncTestCase): future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) - result = yield obj.query('SELECT 1') + 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(KeyError): + yield obj.query('SELECT * FROM foo WHERE bar=%(baz)s', {}) + + @testing.gen_test + def test_query_error_index_error(self): + obj = tornado_session.TornadoSession(io_loop=self.io_loop) + with self.assertRaises(IndexError): + yield obj.query('SELECT * FROM foo WHERE bar=%s', [])
14
Add a bare exception around invoking psycopg2 methods
2
.py
py
bsd-3-clause
gmr/queries
1102
<NME> tornado_session_tests.py <BEF> """ Tests for functionality in the tornado_session module """ import unittest import mock # Out of order import to ensure psycopg2cffi is registered from queries import pool, tornado_session from psycopg2 import extras from tornado import concurrent, gen, ioloop, testing class ResultsTests(unittest.TestCase): def setUp(self): self.cursor = mock.Mock() self.fd = 10 self.cleanup = mock.Mock() self.obj = tornado_session.Results(self.cursor, self.cleanup, self.fd) def test_cursor_is_assigned(self): self.assertEqual(self.obj.cursor, self.cursor) def test_fd_is_assigned(self): self.assertEqual(self.obj._fd, self.fd) def test_cleanup_is_assigned(self): self.assertEqual(self.obj._cleanup, self.cleanup) @gen.coroutine def test_free_invokes_cleanup(self): yield self.obj.free() self.cleanup.assert_called_once_with(self.cursor, self.fd) class SessionInitTests(unittest.TestCase): def setUp(self): self.obj = tornado_session.TornadoSession() def test_creates_empty_callback_dict(self): self.assertDictEqual(self.obj._futures, {}) def test_creates_empty_connections_dict(self): self.assertDictEqual(self.obj._connections, {}) def test_sets_default_cursor_factory(self): self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor) def test_sets_tornado_ioloop_instance(self): self.assertEqual(self.obj._ioloop, ioloop.IOLoop.instance()) def test_sets_poolmananger_instance(self): self.assertEqual(self.obj._pool_manager, pool.PoolManager.instance()) def test_sets_uri(self): self.assertEqual(self.obj._uri, tornado_session.session.DEFAULT_URI) def test_creates_pool_in_manager(self): self.assertIn(self.obj.pid, self.obj._pool_manager._pools) def test_connection_is_none(self): self.assertIsNone(self.obj.connection) def test_cursor_is_none(self): self.assertIsNone(self.obj.cursor) class SessionConnectTests(testing.AsyncTestCase): def setUp(self): super(SessionConnectTests, self).setUp() self.conn = mock.Mock() self.conn.fileno = mock.Mock(return_value=10) self.obj = tornado_session.TornadoSession(io_loop=self.io_loop) def create_connection(future): future.set_result(self.conn) self.obj._create_connection = create_connection @testing.gen_test def test_connect_returns_new_connection(self): conn = yield self.obj._connect() self.assertEqual(conn, self.conn) @testing.gen_test def test_connect_returns_pooled_connection(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) second_result = yield self.obj._connect() self.assertEqual(second_result, conn) @testing.gen_test def test_connect_gets_pooled_connection(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) with mock.patch.object(self.obj._pool_manager, 'get') as get: with mock.patch.object(self.io_loop, 'add_handler'): yield self.obj._connect() get.assert_called_once_with(self.obj.pid, self.obj) @testing.gen_test def test_connect_pooled_connection_invokes_add_handler(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) with mock.patch.object(self.obj._pool_manager, 'get') as get: get.return_value = self.conn with mock.patch.object(self.io_loop, 'add_handler') as add_handler: yield self.obj._connect() add_handler.assert_called_once_with(self.conn.fileno(), self.obj._on_io_events, ioloop.IOLoop.WRITE) def test_psycopg2_connect_invokes_psycopg2_connect(self): with mock.patch('psycopg2.connect') as connect: self.obj._psycopg2_connect({}) connect.assert_called_once_with(**{'async': True}) def test_on_io_events_returns_if_fd_not_present(self): with mock.patch.object(self.obj, '_poll_connection') as poll: self.obj._on_io_events(1337, ioloop.IOLoop.WRITE) poll.assert_not_called() def test_on_io_events_calls_poll_connection(self): with mock.patch.object(self.obj, '_poll_connection') as poll: self.obj._connections[1337] = True self.obj._on_io_events(1337, ioloop.IOLoop.WRITE) poll.assert_called_once_with(1337) def test_exec_cleanup_closes_cursor(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() cursor = mock.Mock() cursor.close = mock.Mock() self.obj._exec_cleanup(cursor, 14) cursor.close.assert_called_once_with() def test_exec_cleanup_frees_connection(self): with mock.patch.object(self.obj._pool_manager, 'free') as pm_free: with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = conn = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) pm_free.assert_called_once_with(self.obj.pid, conn) def test_exec_cleanup_remove_handler_invoked(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler') as rh: self.obj._connections[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) rh.assert_called_once_with(14) def test_exec_removes_connection(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) self.assertNotIn(14, self.obj._connections) def test_exec_removes_future(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() self.obj._futures[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) self.assertNotIn(14, self.obj._futures) def test_pool_manager_add_failures_are_propagated(self): futures = [] def add_future(future, callback): futures.append((future, callback)) obj = tornado_session.TornadoSession() obj._ioloop = mock.Mock() obj._ioloop.add_future = add_future future = concurrent.Future() with mock.patch.object(obj._pool_manager, 'add') as add_method: add_method.side_effect = pool.PoolFullError(mock.Mock()) obj._create_connection(future) self.assertEqual(len(futures), 1) connected_future, callback = futures.pop() connected_future.set_result(True) callback(connected_future) self.assertIs(future.exception(), add_method.side_effect) class SessionPublicMethodTests(testing.AsyncTestCase): @testing.gen_test def test_callproc_invokes_execute(self): with mock.patch('queries.tornado_session.TornadoSession._execute') as \ _execute: future = concurrent.Future() future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) yield obj.callproc('foo', ['bar']) _execute.assert_called_once_with('callproc', 'foo', ['bar']) future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) result = yield obj.callproc('foo', ['bar']) _execute.assert_called_once_with('callproc', 'foo', ['bar']) @testing.gen_test obj = tornado_session.TornadoSession(io_loop=self.io_loop) yield obj.query('SELECT 1') _execute.assert_called_once_with('execute', 'SELECT 1', None) future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) result = yield obj.query('SELECT 1') _execute.assert_called_once_with('execute', 'SELECT 1', None) <MSG> Add a bare exception around invoking psycopg2 methods <DFF> @@ -207,7 +207,7 @@ class SessionPublicMethodTests(testing.AsyncTestCase): future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) - result = yield obj.callproc('foo', ['bar']) + yield obj.callproc('foo', ['bar']) _execute.assert_called_once_with('callproc', 'foo', ['bar']) @testing.gen_test @@ -218,5 +218,17 @@ class SessionPublicMethodTests(testing.AsyncTestCase): future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) - result = yield obj.query('SELECT 1') + 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(KeyError): + yield obj.query('SELECT * FROM foo WHERE bar=%(baz)s', {}) + + @testing.gen_test + def test_query_error_index_error(self): + obj = tornado_session.TornadoSession(io_loop=self.io_loop) + with self.assertRaises(IndexError): + yield obj.query('SELECT * FROM foo WHERE bar=%s', [])
14
Add a bare exception around invoking psycopg2 methods
2
.py
py
bsd-3-clause
gmr/queries
1103
<NME> LICENSE <BEF> Copyright (c) 2014 - 2019 Gavin M. Roy All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the queries nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. <MSG> Adjust copyright date in license <DFF> @@ -1,4 +1,4 @@ -Copyright (c) 2014 - 2019 Gavin M. Roy +Copyright (c) 2014 - 2021 Gavin M. Roy All rights reserved. Redistribution and use in source and binary forms, with or without modification,
1
Adjust copyright date in license
1
LICENSE
bsd-3-clause
gmr/queries
1104
<NME> LICENSE <BEF> Copyright (c) 2014 - 2019 Gavin M. Roy All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the queries nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. <MSG> Adjust copyright date in license <DFF> @@ -1,4 +1,4 @@ -Copyright (c) 2014 - 2019 Gavin M. Roy +Copyright (c) 2014 - 2021 Gavin M. Roy All rights reserved. Redistribution and use in source and binary forms, with or without modification,
1
Adjust copyright date in license
1
LICENSE
bsd-3-clause
gmr/queries
1105
<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. """ __version__ = '1.10.4' version = __version__ import logging 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 from psycopg2 import ProgrammingError from psycopg2.extensions import QueryCanceledError from psycopg2.extensions import TransactionRollbackError __version__ = '2.1.0' version = __version__ # Add a Null logging handler to prevent logging output when un-configured logging.getLogger('queries').addHandler(logging.NullHandler()) <MSG> Bump for the next version <DFF> @@ -8,7 +8,7 @@ The core `queries.Queries` class will automatically register support for UUIDs, Unicode and Unicode arrays. """ -__version__ = '1.10.4' +__version__ = '1.2.0' version = __version__ import logging
1
Bump for the next version
1
.py
py
bsd-3-clause
gmr/queries
1106
<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. """ __version__ = '1.10.4' version = __version__ import logging 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 from psycopg2 import ProgrammingError from psycopg2.extensions import QueryCanceledError from psycopg2.extensions import TransactionRollbackError __version__ = '2.1.0' version = __version__ # Add a Null logging handler to prevent logging output when un-configured logging.getLogger('queries').addHandler(logging.NullHandler()) <MSG> Bump for the next version <DFF> @@ -8,7 +8,7 @@ The core `queries.Queries` class will automatically register support for UUIDs, Unicode and Unicode arrays. """ -__version__ = '1.10.4' +__version__ = '1.2.0' version = __version__ import logging
1
Bump for the next version
1
.py
py
bsd-3-clause
gmr/queries
1107
<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 """ _conn = None _cursor = None _cursor_factory = None _from_pool = False _tpc_id = None _uri = None _use_pool = True 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 self._cursor = self._get_cursor() self._autocommit() 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: PgSQL """ 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() @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 close(self): """Explicitly close the connection and remove it from the connection 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. """ return self._conn.notices 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) @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 # Querying, executing, copying, etc def callproc(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. .. code:: python 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 """ self._cursor.callproc(name, parameters) try: for record in self._cursor: yield record except psycopg2.ProgrammingError: return def query(self, sql, parameters=None): """A generator to issue a query on the server, mogrifying the """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() except psycopg2.ProgrammingError: return # Listen Notify def listen(self, channel, callback=None): pass def notifications(self): pass # TPC Transaction Functionality def tx_begin(self): """Begin a new transaction""" # Ensure that auto-commit is off if self._conn.autocommit: self._conn.autocommit = False def tx_commit(self): self._conn.commit() def tx_rollback(self): self._conn.rollback() @property def tx_status(self): """Return the transaction status for the current connection. Values should be one of: - queries.Session.TX_IDLE: Idle without an active session - queries.Session.TX_ACTIVE: A command is currently in progress - queries.Session.TX_INTRANS: Idle in a valid transaction - queries.Session.TX_INERROR: Idle in a failed transaction - queries.Session.TX_UNKNOWN: Connection error :rtype: int """ return self._conn.get_transaction_status() # Internal methods def _autocommit(self): """Set the isolation level automatically to commit after every query""" 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 """ return self._conn.cursor(cursor_factory=self._cursor_factory) @property def pid(self): """Return a pool ID to be used with connection pooling :rtype: str """ return str(hashlib.md5(self._uri.encode('utf-8')).hexdigest()) def _psycopg2_connect(self, kwargs): """Return a psycopg2 connection for the specified kwargs. Extend for use in async session adapters. """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> Re-organize the Session class, update callproc to have an arg called args <DFF> @@ -53,8 +53,6 @@ class Session(object): """ _conn = None _cursor = None - _cursor_factory = None - _from_pool = False _tpc_id = None _uri = None _use_pool = True @@ -90,38 +88,43 @@ class Session(object): self._cursor = self._get_cursor() self._autocommit() - def __del__(self): - """When deleting the context, ensure the instance is removed from - caches, etc. + @property + def backend_pid(self): + """Return the backend process ID of the PostgreSQL server that this + session is connected to. + + :rtype: int """ - self._cleanup() + return self._conn.get_backend_pid() - def __enter__(self): - """For use as a context manager, return a handle to this object - instance. + def callproc(self, name, args=None): + """Call a stored procedure on the server and return an iterator of the + result set for easy access to the data. - :rtype: PgSQL + .. code:: python - """ - return self + for row in session.callproc('now'): + print row - def __exit__(self, exc_type, exc_val, exc_tb): - """When leaving the context, ensure the instance is removed from - caches, etc. + To return the full set of rows in a single call, wrap the method with + list: - """ - self._cleanup() + .. code:: python - @property - def backend_pid(self): - """Return the backend process ID of the PostgreSQL server that this - session is connected to. + rows = list(session.callproc('now')) - :rtype: int + :param str name: The procedure name + :param list args: The list of arguments to pass in + :return: iterator """ - return self._conn.get_backend_pid() + self._cursor.callproc(name, args) + try: + for record in self._cursor: + yield record + except psycopg2.ProgrammingError: + return def close(self): """Explicitly close the connection and remove it from the connection @@ -176,62 +179,16 @@ class Session(object): """ return self._conn.notices - 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) @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 - - # Querying, executing, copying, etc - - def callproc(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. - - .. code:: python - - 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')) + def pid(self): + """Return the pool ID used for connection pooling - :param str name: The procedure name - :param list parameters: The list of parameters to pass in - :return: iterator + :rtype: str """ - self._cursor.callproc(name, parameters) - try: - for record in self._cursor: - yield record - except psycopg2.ProgrammingError: - return + return str(hashlib.md5(self._uri.encode('utf-8')).hexdigest()) def query(self, sql, parameters=None): """A generator to issue a query on the server, mogrifying the @@ -263,46 +220,55 @@ class Session(object): except psycopg2.ProgrammingError: return - # Listen Notify + 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. - def listen(self, channel, callback=None): - pass + :param str value: The encoding value to use - def notifications(self): - pass + """ + if self._conn.encoding != value: + self._conn.set_client_encoding(value) - # TPC Transaction Functionality + @property + def status(self): + """Return the current connection status as an integer value. - def tx_begin(self): - """Begin a new transaction""" - # Ensure that auto-commit is off - if self._conn.autocommit: - self._conn.autocommit = False + The status should match one of the following constants: - def tx_commit(self): - self._conn.commit() + - queries.Session.INTRANS: Connection established, in transaction + - queries.Session.PREPARED: Prepared for second phase of transaction + - queries.Session.READY: Connected, no active transaction - def tx_rollback(self): - self._conn.rollback() + :rtype: int - @property - def tx_status(self): - """Return the transaction status for the current connection. + """ + if self._conn.status == psycopg2.extensions.STATUS_BEGIN: + return self.READY + return self._conn.status - Values should be one of: + def __del__(self): + """When deleting the context, ensure the instance is removed from + caches, etc. - - queries.Session.TX_IDLE: Idle without an active session - - queries.Session.TX_ACTIVE: A command is currently in progress - - queries.Session.TX_INTRANS: Idle in a valid transaction - - queries.Session.TX_INERROR: Idle in a failed transaction - - queries.Session.TX_UNKNOWN: Connection error + """ + self._cleanup() - :rtype: int + def __enter__(self): + """For use as a context manager, return a handle to this object + instance. + + :rtype: PgSQL """ - return self._conn.get_transaction_status() + return self - # Internal methods + 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""" @@ -363,15 +329,6 @@ class Session(object): """ return self._conn.cursor(cursor_factory=self._cursor_factory) - @property - def pid(self): - """Return a pool ID to be used with connection pooling - - :rtype: str - - """ - return str(hashlib.md5(self._uri.encode('utf-8')).hexdigest()) - def _psycopg2_connect(self, kwargs): """Return a psycopg2 connection for the specified kwargs. Extend for use in async session adapters.
66
Re-organize the Session class, update callproc to have an arg called args
109
.py
py
bsd-3-clause
gmr/queries
1108
<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 """ _conn = None _cursor = None _cursor_factory = None _from_pool = False _tpc_id = None _uri = None _use_pool = True 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 self._cursor = self._get_cursor() self._autocommit() 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: PgSQL """ 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() @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 close(self): """Explicitly close the connection and remove it from the connection 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. """ return self._conn.notices 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) @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 # Querying, executing, copying, etc def callproc(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. .. code:: python 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 """ self._cursor.callproc(name, parameters) try: for record in self._cursor: yield record except psycopg2.ProgrammingError: return def query(self, sql, parameters=None): """A generator to issue a query on the server, mogrifying the """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() except psycopg2.ProgrammingError: return # Listen Notify def listen(self, channel, callback=None): pass def notifications(self): pass # TPC Transaction Functionality def tx_begin(self): """Begin a new transaction""" # Ensure that auto-commit is off if self._conn.autocommit: self._conn.autocommit = False def tx_commit(self): self._conn.commit() def tx_rollback(self): self._conn.rollback() @property def tx_status(self): """Return the transaction status for the current connection. Values should be one of: - queries.Session.TX_IDLE: Idle without an active session - queries.Session.TX_ACTIVE: A command is currently in progress - queries.Session.TX_INTRANS: Idle in a valid transaction - queries.Session.TX_INERROR: Idle in a failed transaction - queries.Session.TX_UNKNOWN: Connection error :rtype: int """ return self._conn.get_transaction_status() # Internal methods def _autocommit(self): """Set the isolation level automatically to commit after every query""" 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 """ return self._conn.cursor(cursor_factory=self._cursor_factory) @property def pid(self): """Return a pool ID to be used with connection pooling :rtype: str """ return str(hashlib.md5(self._uri.encode('utf-8')).hexdigest()) def _psycopg2_connect(self, kwargs): """Return a psycopg2 connection for the specified kwargs. Extend for use in async session adapters. """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> Re-organize the Session class, update callproc to have an arg called args <DFF> @@ -53,8 +53,6 @@ class Session(object): """ _conn = None _cursor = None - _cursor_factory = None - _from_pool = False _tpc_id = None _uri = None _use_pool = True @@ -90,38 +88,43 @@ class Session(object): self._cursor = self._get_cursor() self._autocommit() - def __del__(self): - """When deleting the context, ensure the instance is removed from - caches, etc. + @property + def backend_pid(self): + """Return the backend process ID of the PostgreSQL server that this + session is connected to. + + :rtype: int """ - self._cleanup() + return self._conn.get_backend_pid() - def __enter__(self): - """For use as a context manager, return a handle to this object - instance. + def callproc(self, name, args=None): + """Call a stored procedure on the server and return an iterator of the + result set for easy access to the data. - :rtype: PgSQL + .. code:: python - """ - return self + for row in session.callproc('now'): + print row - def __exit__(self, exc_type, exc_val, exc_tb): - """When leaving the context, ensure the instance is removed from - caches, etc. + To return the full set of rows in a single call, wrap the method with + list: - """ - self._cleanup() + .. code:: python - @property - def backend_pid(self): - """Return the backend process ID of the PostgreSQL server that this - session is connected to. + rows = list(session.callproc('now')) - :rtype: int + :param str name: The procedure name + :param list args: The list of arguments to pass in + :return: iterator """ - return self._conn.get_backend_pid() + self._cursor.callproc(name, args) + try: + for record in self._cursor: + yield record + except psycopg2.ProgrammingError: + return def close(self): """Explicitly close the connection and remove it from the connection @@ -176,62 +179,16 @@ class Session(object): """ return self._conn.notices - 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) @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 - - # Querying, executing, copying, etc - - def callproc(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. - - .. code:: python - - 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')) + def pid(self): + """Return the pool ID used for connection pooling - :param str name: The procedure name - :param list parameters: The list of parameters to pass in - :return: iterator + :rtype: str """ - self._cursor.callproc(name, parameters) - try: - for record in self._cursor: - yield record - except psycopg2.ProgrammingError: - return + return str(hashlib.md5(self._uri.encode('utf-8')).hexdigest()) def query(self, sql, parameters=None): """A generator to issue a query on the server, mogrifying the @@ -263,46 +220,55 @@ class Session(object): except psycopg2.ProgrammingError: return - # Listen Notify + 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. - def listen(self, channel, callback=None): - pass + :param str value: The encoding value to use - def notifications(self): - pass + """ + if self._conn.encoding != value: + self._conn.set_client_encoding(value) - # TPC Transaction Functionality + @property + def status(self): + """Return the current connection status as an integer value. - def tx_begin(self): - """Begin a new transaction""" - # Ensure that auto-commit is off - if self._conn.autocommit: - self._conn.autocommit = False + The status should match one of the following constants: - def tx_commit(self): - self._conn.commit() + - queries.Session.INTRANS: Connection established, in transaction + - queries.Session.PREPARED: Prepared for second phase of transaction + - queries.Session.READY: Connected, no active transaction - def tx_rollback(self): - self._conn.rollback() + :rtype: int - @property - def tx_status(self): - """Return the transaction status for the current connection. + """ + if self._conn.status == psycopg2.extensions.STATUS_BEGIN: + return self.READY + return self._conn.status - Values should be one of: + def __del__(self): + """When deleting the context, ensure the instance is removed from + caches, etc. - - queries.Session.TX_IDLE: Idle without an active session - - queries.Session.TX_ACTIVE: A command is currently in progress - - queries.Session.TX_INTRANS: Idle in a valid transaction - - queries.Session.TX_INERROR: Idle in a failed transaction - - queries.Session.TX_UNKNOWN: Connection error + """ + self._cleanup() - :rtype: int + def __enter__(self): + """For use as a context manager, return a handle to this object + instance. + + :rtype: PgSQL """ - return self._conn.get_transaction_status() + return self - # Internal methods + 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""" @@ -363,15 +329,6 @@ class Session(object): """ return self._conn.cursor(cursor_factory=self._cursor_factory) - @property - def pid(self): - """Return a pool ID to be used with connection pooling - - :rtype: str - - """ - return str(hashlib.md5(self._uri.encode('utf-8')).hexdigest()) - def _psycopg2_connect(self, kwargs): """Return a psycopg2 connection for the specified kwargs. Extend for use in async session adapters.
66
Re-organize the Session class, update callproc to have an arg called args
109
.py
py
bsd-3-clause
gmr/queries
1109
<NME> index.rst <BEF> Queries: PostgreSQL Simplified ============================== *Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for interacting with PostgreSQL. |Version| |License| |PythonVersions| The popular psycopg2_ package is a full-featured python client. Unfortunately as a developer, you're often repeating the same steps to get started with your applications that use it. Queries aims to reduce the complexity of psycopg2 while adding additional features to make writing PostgreSQL client applications both fast and easy. *Key features include*: - Simplified API - Support of Python 2.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_ :py:class:`~psycopg2.extensions.connection` and :py:class:`~psycopg2.extensions.cursor` objects - Internal connection pooling Installation ------------ Queries can be installed via the `Python Package Index <https://pypi.python.org/pypi/queries>`_ and can be installed by running :command:`easy_install queries` or :command:`pip install queries` When installing Queries, ``pip`` or ``easy_install`` will automatically install the proper dependencies for your platform. Contents -------- .. toctree:: :maxdepth: 1 usage session results tornado_session pool examples/index.rst history Issues ------ Please report any issues to the Github repo at `https://github.com/gmr/queries/issues <https://github.com/gmr/queries/issues>`_ Source ------ Queries source is available on Github at `https://github.com/gmr/queries <https://github.com/gmr/queries>`_ |Status| Inspiration ----------- Queries is inspired by `Kenneth Reitz's <https://github.com/kennethreitz/>`_ awesome work on `requests <http://docs.python-requests.org/en/latest/>`_. Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` .. _pypi: https://pypi.python.org/pypi/queries .. _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 .. |License| image:: https://img.shields.io/github/license/gmr/queries.svg? :target: https://github.com/gmr/queries <MSG> Remove broken badges <DFF> @@ -3,7 +3,7 @@ Queries: PostgreSQL Simplified *Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for interacting with PostgreSQL. -|Version| |License| |PythonVersions| +|Version| |License| 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 @@ -53,8 +53,6 @@ Source ------ Queries source is available on Github at `https://github.com/gmr/queries <https://github.com/gmr/queries>`_ -|Status| - Inspiration ----------- Queries is inspired by `Kenneth Reitz's <https://github.com/kennethreitz/>`_ awesome
1
Remove broken badges
3
.rst
rst
bsd-3-clause
gmr/queries
1110
<NME> index.rst <BEF> Queries: PostgreSQL Simplified ============================== *Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for interacting with PostgreSQL. |Version| |License| |PythonVersions| The popular psycopg2_ package is a full-featured python client. Unfortunately as a developer, you're often repeating the same steps to get started with your applications that use it. Queries aims to reduce the complexity of psycopg2 while adding additional features to make writing PostgreSQL client applications both fast and easy. *Key features include*: - Simplified API - Support of Python 2.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_ :py:class:`~psycopg2.extensions.connection` and :py:class:`~psycopg2.extensions.cursor` objects - Internal connection pooling Installation ------------ Queries can be installed via the `Python Package Index <https://pypi.python.org/pypi/queries>`_ and can be installed by running :command:`easy_install queries` or :command:`pip install queries` When installing Queries, ``pip`` or ``easy_install`` will automatically install the proper dependencies for your platform. Contents -------- .. toctree:: :maxdepth: 1 usage session results tornado_session pool examples/index.rst history Issues ------ Please report any issues to the Github repo at `https://github.com/gmr/queries/issues <https://github.com/gmr/queries/issues>`_ Source ------ Queries source is available on Github at `https://github.com/gmr/queries <https://github.com/gmr/queries>`_ |Status| Inspiration ----------- Queries is inspired by `Kenneth Reitz's <https://github.com/kennethreitz/>`_ awesome work on `requests <http://docs.python-requests.org/en/latest/>`_. Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` .. _pypi: https://pypi.python.org/pypi/queries .. _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 .. |License| image:: https://img.shields.io/github/license/gmr/queries.svg? :target: https://github.com/gmr/queries <MSG> Remove broken badges <DFF> @@ -3,7 +3,7 @@ Queries: PostgreSQL Simplified *Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for interacting with PostgreSQL. -|Version| |License| |PythonVersions| +|Version| |License| 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 @@ -53,8 +53,6 @@ Source ------ Queries source is available on Github at `https://github.com/gmr/queries <https://github.com/gmr/queries>`_ -|Status| - Inspiration ----------- Queries is inspired by `Kenneth Reitz's <https://github.com/kennethreitz/>`_ awesome
1
Remove broken badges
3
.rst
rst
bsd-3-clause
gmr/queries
1111
<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='gavinmroy@gmail.com', 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.8.0', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="gavinmroy@gmail.com", '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> Fix cffi handling <DFF> @@ -29,7 +29,7 @@ classifiers = ['Development Status :: 5 - Production/Stable', 'Topic :: Software Development :: Libraries'] setup(name='queries', - version='1.8.0', + version='1.8.1', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="gavinmroy@gmail.com",
1
Fix cffi handling
1
.py
py
bsd-3-clause
gmr/queries
1112
<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='gavinmroy@gmail.com', 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.8.0', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="gavinmroy@gmail.com", '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> Fix cffi handling <DFF> @@ -29,7 +29,7 @@ classifiers = ['Development Status :: 5 - Production/Stable', 'Topic :: Software Development :: Libraries'] setup(name='queries', - version='1.8.0', + version='1.8.1', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="gavinmroy@gmail.com",
1
Fix cffi handling
1
.py
py
bsd-3-clause
gmr/queries
1113
<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.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 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> Remove Python 3.2 support <DFF> @@ -20,7 +20,6 @@ classifiers = ['Development Status :: 5 - Production/Stable', '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 :: 3.5',
0
Remove Python 3.2 support
1
.py
py
bsd-3-clause
gmr/queries
1114
<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.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 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> Remove Python 3.2 support <DFF> @@ -20,7 +20,6 @@ classifiers = ['Development Status :: 5 - Production/Stable', '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 :: 3.5',
0
Remove Python 3.2 support
1
.py
py
bsd-3-clause
gmr/queries
1115
<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__) from queries import PYPY class SessionTests(unittest.TestCase): URI = 'pgsql://foo:bar@localhost:5432/foo' def setUp(self): self.conn = mock.Mock() self._connect = mock.Mock(return_value=self.conn) self.cursor = mock.Mock() self._get_cursor = mock.Mock(return_value=self.cursor) self._autocommit = mock.Mock() with mock.patch.multiple('queries.session.Session', _connect=self._connect, _get_cursor=self._get_cursor, _autocommit=self._autocommit): pool.PoolManager.create = self.pm_create = mock.Mock() pool.PoolManager.is_full = self.pm_is_full = mock.PropertyMock() pool.PoolManager.remove_connection = self.pm_rem_conn = mock.Mock() self.obj = session.Session(self.URI) def test_init_gets_poolmanager_instance(self): instance = pool.PoolManager.instance() self.assertEqual(self.obj._pool_manager, instance) def test_init_sets_uri(self): self.assertEqual(self.obj._uri, self.URI) def test_init_invokes_poolmanager_create(self): self.obj._pool_manager.create.assert_called_once_with( self.obj.pid, pool.DEFAULT_IDLE_TTL, pool.DEFAULT_MAX_SIZE) def test_init_invokes_connection(self): self._connect.assert_called_once_with() def test_init_sets_cursorfactory(self): self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor) def test_init_gets_cursor(self): self._get_cursor.assert_called_once_with(self.conn) def test_init_sets_autocommit(self): self._autocommit.assert_called_once_with() def test_backend_pid_invokes_conn_backend_pid(self): self.conn.get_backend_pid = get_backend_pid = mock.Mock() def test_callproc_invokes_cursor_callproc(self): get_backend_pid.assert_called_once_with() def test_callproc_invokes_cursor_callproc(self): self.cursor.callproc = mock.Mock() args = ('foo', ['bar', 'baz']) self.obj.callproc(*args) self.cursor.callproc.assert_called_once_with(*args) def test_callproc_returns_results(self): self.cursor.callproc = mock.Mock() args = ('foo', ['bar', 'baz']) self.assertIsInstance(self.obj.callproc(*args), results.Results) def test_close_removes_connection(self): self.obj.close() def test_close_removes_connection(self): self.obj.close() self.pm_rem_conn.assert_called_once_with(self.obj.pid, self.conn) def test_close_unassigns_connection(self): self.obj.close() 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.connection, self.conn) def test_cursor_property_returns_correct_value(self): self.assertEqual(self.obj.cursor, self.cursor) def test_encoding_property_value(self): self.conn.encoding = 'UTF-8' 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) self.assertEqual(self.obj.pid, expectation) def test_query_invokes_cursor_execute(self): self.cursor.execute = mock.Mock() args = ('SELECT * FROM foo', ['bar', 'baz']) self.obj.query(*args) self.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') 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 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.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_connect_invokes_pool_manager_get(self): pool.PoolManager.clean = clean = mock.Mock() self.obj._cleanup() clean.assert_called_once_with(self.obj.pid) <MSG> Rework and complete session tests <DFF> @@ -19,50 +19,57 @@ from queries import session from queries import PYPY -class SessionTests(unittest.TestCase): +class SessionTestCase(unittest.TestCase): URI = 'pgsql://foo:bar@localhost:5432/foo' - - def setUp(self): + @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._connect = mock.Mock(return_value=self.conn) - self.cursor = mock.Mock() - self._get_cursor = mock.Mock(return_value=self.cursor) - self._autocommit = mock.Mock() - with mock.patch.multiple('queries.session.Session', - _connect=self._connect, - _get_cursor=self._get_cursor, - _autocommit=self._autocommit): - pool.PoolManager.create = self.pm_create = mock.Mock() - pool.PoolManager.is_full = self.pm_is_full = mock.PropertyMock() - pool.PoolManager.remove_connection = self.pm_rem_conn = mock.Mock() - self.obj = session.Session(self.URI) - - def test_init_gets_poolmanager_instance(self): - instance = pool.PoolManager.instance() - self.assertEqual(self.obj._pool_manager, instance) + 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) def test_init_sets_uri(self): self.assertEqual(self.obj._uri, self.URI) - def test_init_invokes_poolmanager_create(self): - self.obj._pool_manager.create.assert_called_once_with( - self.obj.pid, - pool.DEFAULT_IDLE_TTL, - pool.DEFAULT_MAX_SIZE) + def test_init_creates_new_pool(self): + self.assertIn(self.obj.pid, self.obj._pool_manager) - def test_init_invokes_connection(self): - self._connect.assert_called_once_with() + 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._get_cursor.assert_called_once_with(self.conn) + self.conn.cursor.assert_called_once_with( + name=None, cursor_factory=extras.RealDictCursor) def test_init_sets_autocommit(self): - self._autocommit.assert_called_once_with() + self.assertTrue(self.conn.autocommit) def test_backend_pid_invokes_conn_backend_pid(self): self.conn.get_backend_pid = get_backend_pid = mock.Mock() @@ -70,13 +77,13 @@ class SessionTests(unittest.TestCase): get_backend_pid.assert_called_once_with() def test_callproc_invokes_cursor_callproc(self): - self.cursor.callproc = mock.Mock() + self.obj._cursor.callproc = mock.Mock() args = ('foo', ['bar', 'baz']) self.obj.callproc(*args) - self.cursor.callproc.assert_called_once_with(*args) + self.obj._cursor.callproc.assert_called_once_with(*args) def test_callproc_returns_results(self): - self.cursor.callproc = mock.Mock() + self.obj._cursor.callproc = mock.Mock() args = ('foo', ['bar', 'baz']) self.assertIsInstance(self.obj.callproc(*args), results.Results) @@ -86,7 +93,8 @@ class SessionTests(unittest.TestCase): def test_close_removes_connection(self): self.obj.close() - self.pm_rem_conn.assert_called_once_with(self.obj.pid, self.conn) + self.assertNotIn(self.conn, + self.obj._pool_manager._pools[self.obj.pid]) def test_close_unassigns_connection(self): self.obj.close() @@ -100,7 +108,7 @@ class SessionTests(unittest.TestCase): self.assertEqual(self.obj.connection, self.conn) def test_cursor_property_returns_correct_value(self): - self.assertEqual(self.obj.cursor, self.cursor) + self.assertEqual(self.obj.cursor, self.obj._cursor) def test_encoding_property_value(self): self.conn.encoding = 'UTF-8' @@ -115,10 +123,10 @@ class SessionTests(unittest.TestCase): self.assertEqual(self.obj.pid, expectation) def test_query_invokes_cursor_execute(self): - self.cursor.execute = mock.Mock() + self.obj._cursor.callproc = mock.Mock() args = ('SELECT * FROM foo', ['bar', 'baz']) self.obj.query(*args) - self.cursor.execute.assert_called_once_with(*args) + self.obj._cursor.execute.assert_called_once_with(*args) def test_set_encoding_sets_encoding_if_different(self): self.conn.encoding = 'LATIN-1' @@ -161,23 +169,24 @@ class SessionTests(unittest.TestCase): self.assertTrue(self.conn.autocommit) def test_cleanup_closes_cursor(self): - self.cursor.close = closeit = mock.Mock() + 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.cursor.close = mock.Mock() + self.obj._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) + 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_connecto_to_none(self): + def test_cleanup_sets_connect_to_none(self): self.obj._cleanup() self.assertIsNone(self.obj._conn) @@ -185,3 +194,41 @@ class SessionTests(unittest.TestCase): pool.PoolManager.clean = clean = mock.Mock() self.obj._cleanup() clean.assert_called_once_with(self.obj.pid) + + 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(PYPY, 'connection.reset is PYPY only behavior') + def test_connection_reset_in_pypy(self): + self.conn.reset.assert_called_once_with()
88
Rework and complete session tests
41
.py
py
bsd-3-clause
gmr/queries
1116
<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__) from queries import PYPY class SessionTests(unittest.TestCase): URI = 'pgsql://foo:bar@localhost:5432/foo' def setUp(self): self.conn = mock.Mock() self._connect = mock.Mock(return_value=self.conn) self.cursor = mock.Mock() self._get_cursor = mock.Mock(return_value=self.cursor) self._autocommit = mock.Mock() with mock.patch.multiple('queries.session.Session', _connect=self._connect, _get_cursor=self._get_cursor, _autocommit=self._autocommit): pool.PoolManager.create = self.pm_create = mock.Mock() pool.PoolManager.is_full = self.pm_is_full = mock.PropertyMock() pool.PoolManager.remove_connection = self.pm_rem_conn = mock.Mock() self.obj = session.Session(self.URI) def test_init_gets_poolmanager_instance(self): instance = pool.PoolManager.instance() self.assertEqual(self.obj._pool_manager, instance) def test_init_sets_uri(self): self.assertEqual(self.obj._uri, self.URI) def test_init_invokes_poolmanager_create(self): self.obj._pool_manager.create.assert_called_once_with( self.obj.pid, pool.DEFAULT_IDLE_TTL, pool.DEFAULT_MAX_SIZE) def test_init_invokes_connection(self): self._connect.assert_called_once_with() def test_init_sets_cursorfactory(self): self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor) def test_init_gets_cursor(self): self._get_cursor.assert_called_once_with(self.conn) def test_init_sets_autocommit(self): self._autocommit.assert_called_once_with() def test_backend_pid_invokes_conn_backend_pid(self): self.conn.get_backend_pid = get_backend_pid = mock.Mock() def test_callproc_invokes_cursor_callproc(self): get_backend_pid.assert_called_once_with() def test_callproc_invokes_cursor_callproc(self): self.cursor.callproc = mock.Mock() args = ('foo', ['bar', 'baz']) self.obj.callproc(*args) self.cursor.callproc.assert_called_once_with(*args) def test_callproc_returns_results(self): self.cursor.callproc = mock.Mock() args = ('foo', ['bar', 'baz']) self.assertIsInstance(self.obj.callproc(*args), results.Results) def test_close_removes_connection(self): self.obj.close() def test_close_removes_connection(self): self.obj.close() self.pm_rem_conn.assert_called_once_with(self.obj.pid, self.conn) def test_close_unassigns_connection(self): self.obj.close() 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.connection, self.conn) def test_cursor_property_returns_correct_value(self): self.assertEqual(self.obj.cursor, self.cursor) def test_encoding_property_value(self): self.conn.encoding = 'UTF-8' 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) self.assertEqual(self.obj.pid, expectation) def test_query_invokes_cursor_execute(self): self.cursor.execute = mock.Mock() args = ('SELECT * FROM foo', ['bar', 'baz']) self.obj.query(*args) self.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') 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 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.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_connect_invokes_pool_manager_get(self): pool.PoolManager.clean = clean = mock.Mock() self.obj._cleanup() clean.assert_called_once_with(self.obj.pid) <MSG> Rework and complete session tests <DFF> @@ -19,50 +19,57 @@ from queries import session from queries import PYPY -class SessionTests(unittest.TestCase): +class SessionTestCase(unittest.TestCase): URI = 'pgsql://foo:bar@localhost:5432/foo' - - def setUp(self): + @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._connect = mock.Mock(return_value=self.conn) - self.cursor = mock.Mock() - self._get_cursor = mock.Mock(return_value=self.cursor) - self._autocommit = mock.Mock() - with mock.patch.multiple('queries.session.Session', - _connect=self._connect, - _get_cursor=self._get_cursor, - _autocommit=self._autocommit): - pool.PoolManager.create = self.pm_create = mock.Mock() - pool.PoolManager.is_full = self.pm_is_full = mock.PropertyMock() - pool.PoolManager.remove_connection = self.pm_rem_conn = mock.Mock() - self.obj = session.Session(self.URI) - - def test_init_gets_poolmanager_instance(self): - instance = pool.PoolManager.instance() - self.assertEqual(self.obj._pool_manager, instance) + 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) def test_init_sets_uri(self): self.assertEqual(self.obj._uri, self.URI) - def test_init_invokes_poolmanager_create(self): - self.obj._pool_manager.create.assert_called_once_with( - self.obj.pid, - pool.DEFAULT_IDLE_TTL, - pool.DEFAULT_MAX_SIZE) + def test_init_creates_new_pool(self): + self.assertIn(self.obj.pid, self.obj._pool_manager) - def test_init_invokes_connection(self): - self._connect.assert_called_once_with() + 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._get_cursor.assert_called_once_with(self.conn) + self.conn.cursor.assert_called_once_with( + name=None, cursor_factory=extras.RealDictCursor) def test_init_sets_autocommit(self): - self._autocommit.assert_called_once_with() + self.assertTrue(self.conn.autocommit) def test_backend_pid_invokes_conn_backend_pid(self): self.conn.get_backend_pid = get_backend_pid = mock.Mock() @@ -70,13 +77,13 @@ class SessionTests(unittest.TestCase): get_backend_pid.assert_called_once_with() def test_callproc_invokes_cursor_callproc(self): - self.cursor.callproc = mock.Mock() + self.obj._cursor.callproc = mock.Mock() args = ('foo', ['bar', 'baz']) self.obj.callproc(*args) - self.cursor.callproc.assert_called_once_with(*args) + self.obj._cursor.callproc.assert_called_once_with(*args) def test_callproc_returns_results(self): - self.cursor.callproc = mock.Mock() + self.obj._cursor.callproc = mock.Mock() args = ('foo', ['bar', 'baz']) self.assertIsInstance(self.obj.callproc(*args), results.Results) @@ -86,7 +93,8 @@ class SessionTests(unittest.TestCase): def test_close_removes_connection(self): self.obj.close() - self.pm_rem_conn.assert_called_once_with(self.obj.pid, self.conn) + self.assertNotIn(self.conn, + self.obj._pool_manager._pools[self.obj.pid]) def test_close_unassigns_connection(self): self.obj.close() @@ -100,7 +108,7 @@ class SessionTests(unittest.TestCase): self.assertEqual(self.obj.connection, self.conn) def test_cursor_property_returns_correct_value(self): - self.assertEqual(self.obj.cursor, self.cursor) + self.assertEqual(self.obj.cursor, self.obj._cursor) def test_encoding_property_value(self): self.conn.encoding = 'UTF-8' @@ -115,10 +123,10 @@ class SessionTests(unittest.TestCase): self.assertEqual(self.obj.pid, expectation) def test_query_invokes_cursor_execute(self): - self.cursor.execute = mock.Mock() + self.obj._cursor.callproc = mock.Mock() args = ('SELECT * FROM foo', ['bar', 'baz']) self.obj.query(*args) - self.cursor.execute.assert_called_once_with(*args) + self.obj._cursor.execute.assert_called_once_with(*args) def test_set_encoding_sets_encoding_if_different(self): self.conn.encoding = 'LATIN-1' @@ -161,23 +169,24 @@ class SessionTests(unittest.TestCase): self.assertTrue(self.conn.autocommit) def test_cleanup_closes_cursor(self): - self.cursor.close = closeit = mock.Mock() + 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.cursor.close = mock.Mock() + self.obj._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) + 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_connecto_to_none(self): + def test_cleanup_sets_connect_to_none(self): self.obj._cleanup() self.assertIsNone(self.obj._conn) @@ -185,3 +194,41 @@ class SessionTests(unittest.TestCase): pool.PoolManager.clean = clean = mock.Mock() self.obj._cleanup() clean.assert_called_once_with(self.obj.pid) + + 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(PYPY, 'connection.reset is PYPY only behavior') + def test_connection_reset_in_pypy(self): + self.conn.reset.assert_called_once_with()
88
Rework and complete session tests
41
.py
py
bsd-3-clause
gmr/queries
1117
<NME> README.rst <BEF> Queries: PostgreSQL Simplified ============================== *Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for *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. However there are multiple steps, which are often repeated, to get to the point where you can execute queries on the PostgreSQL server. Queries aims to reduce the complexity 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. - 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()) ... {'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> Clean it up a bit more [ci skip] <DFF> @@ -4,9 +4,9 @@ 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. However there are -multiple steps, which are often repeated, to get to the point where you can -execute queries on the PostgreSQL server. Queries aims to reduce the complexity +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.
3
Clean it up a bit more
3
.rst
rst
bsd-3-clause
gmr/queries
1118
<NME> README.rst <BEF> Queries: PostgreSQL Simplified ============================== *Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for *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. However there are multiple steps, which are often repeated, to get to the point where you can execute queries on the PostgreSQL server. Queries aims to reduce the complexity 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. - 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()) ... {'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> Clean it up a bit more [ci skip] <DFF> @@ -4,9 +4,9 @@ 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. However there are -multiple steps, which are often repeated, to get to the point where you can -execute queries on the PostgreSQL server. Queries aims to reduce the complexity +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.
3
Clean it up a bit more
3
.rst
rst
bsd-3-clause
gmr/queries
1119
<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 from psycopg2 import extensions from psycopg2 import extras from tornado import concurrent from tornado import gen from tornado import ioloop 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 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`` def validate(self): """Validate the session can connect or has open connections to PostgreSQL :rtype: bool """ future = concurrent.TracebackFuture() def on_connected(cf): if cf.exception(): future.set_exception(cf.exception()) return connection = cf.result() fd = connection.fileno() # The connection would have been added to the pool manager, free it self._pool_manager.free(self.pid, connection) self._ioloop.remove_handler(fd) if fd in self._connections: del self._connections[fd] if fd in self._futures: del self._futures[fd] # Return the success in validating the connection future.set_result(True) # Grab a connection to PostgreSQL self._ioloop.add_future(self._connect(), on_connected) # Return the future for the query result return future 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): if fd in self._futures: del self._futures[fd] 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: 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> Remove/deprecate TornadoSession.validate <DFF> @@ -25,19 +25,14 @@ Example Use: import logging import socket -from psycopg2 import extensions -from psycopg2 import extras - -from tornado import concurrent -from tornado import gen -from tornado import ioloop import psycopg2 +from psycopg2 import extras, extensions +from tornado import concurrent, ioloop 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 @@ -239,38 +234,17 @@ class TornadoSession(session.Session): def validate(self): """Validate the session can connect or has open connections to - PostgreSQL + 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 """ - future = concurrent.TracebackFuture() - - def on_connected(cf): - if cf.exception(): - future.set_exception(cf.exception()) - return - - connection = cf.result() - fd = connection.fileno() - - # The connection would have been added to the pool manager, free it - self._pool_manager.free(self.pid, connection) - self._ioloop.remove_handler(fd) - - if fd in self._connections: - del self._connections[fd] - if fd in self._futures: - del self._futures[fd] - - # Return the success in validating the connection - future.set_result(True) - - # Grab a connection to PostgreSQL - self._ioloop.add_future(self._connect(), on_connected) - - # Return the future for the query result - return future + raise DeprecationWarning('All functionality removed from this method') def _connect(self): """Connect to PostgreSQL, either by reusing a connection from the pool @@ -460,11 +434,11 @@ class TornadoSession(session.Session): if fd in self._futures: del self._futures[fd] - def _on_io_events(self, fd=None, events=None): + 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 + :param int _events: The events raised """ if fd not in self._connections:
11
Remove/deprecate TornadoSession.validate
37
.py
py
bsd-3-clause
gmr/queries
1120
<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 from psycopg2 import extensions from psycopg2 import extras from tornado import concurrent from tornado import gen from tornado import ioloop 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 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`` def validate(self): """Validate the session can connect or has open connections to PostgreSQL :rtype: bool """ future = concurrent.TracebackFuture() def on_connected(cf): if cf.exception(): future.set_exception(cf.exception()) return connection = cf.result() fd = connection.fileno() # The connection would have been added to the pool manager, free it self._pool_manager.free(self.pid, connection) self._ioloop.remove_handler(fd) if fd in self._connections: del self._connections[fd] if fd in self._futures: del self._futures[fd] # Return the success in validating the connection future.set_result(True) # Grab a connection to PostgreSQL self._ioloop.add_future(self._connect(), on_connected) # Return the future for the query result return future 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): if fd in self._futures: del self._futures[fd] 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: 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> Remove/deprecate TornadoSession.validate <DFF> @@ -25,19 +25,14 @@ Example Use: import logging import socket -from psycopg2 import extensions -from psycopg2 import extras - -from tornado import concurrent -from tornado import gen -from tornado import ioloop import psycopg2 +from psycopg2 import extras, extensions +from tornado import concurrent, ioloop 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 @@ -239,38 +234,17 @@ class TornadoSession(session.Session): def validate(self): """Validate the session can connect or has open connections to - PostgreSQL + 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 """ - future = concurrent.TracebackFuture() - - def on_connected(cf): - if cf.exception(): - future.set_exception(cf.exception()) - return - - connection = cf.result() - fd = connection.fileno() - - # The connection would have been added to the pool manager, free it - self._pool_manager.free(self.pid, connection) - self._ioloop.remove_handler(fd) - - if fd in self._connections: - del self._connections[fd] - if fd in self._futures: - del self._futures[fd] - - # Return the success in validating the connection - future.set_result(True) - - # Grab a connection to PostgreSQL - self._ioloop.add_future(self._connect(), on_connected) - - # Return the future for the query result - return future + raise DeprecationWarning('All functionality removed from this method') def _connect(self): """Connect to PostgreSQL, either by reusing a connection from the pool @@ -460,11 +434,11 @@ class TornadoSession(session.Session): if fd in self._futures: del self._futures[fd] - def _on_io_events(self, fd=None, events=None): + 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 + :param int _events: The events raised """ if fd not in self._connections:
11
Remove/deprecate TornadoSession.validate
37
.py
py
bsd-3-clause
gmr/queries
1121
<NME> pool_tests.py <BEF> """ Tests for functionality in the pool module """ import time import unittest import uuid import unittest2 as unittest except ImportError: import unittest from queries import pool from queries.pool import CLIENTS, LAST, TTL class ConnectionPoolTests(unittest.TestCase): def setUp(self): pool.add_connection('cc0', self.__class__) def tearDown(self): for key in ['cc0', 'cc1', 'cc2', 'cc3', 'cc4']: if key in pool.CONNECTIONS: del pool.CONNECTIONS[key] def test_add_connection_adds_value(self): """Connection should already exist in the connection pool""" self.assertIn('cc0', pool.CONNECTIONS) def test_get_connection_returns_proper_value(self): """Fetching connection from pool returns proper value""" self.assertEqual(pool.get_connection('cc0'), self.__class__) def test_get_connection_increments_counter(self): """Fetching connection from pool increments client counter""" value = pool.CONNECTIONS.get('cc0', {}).get(CLIENTS, 0) pool.get_connection('cc0') self.assertEqual(pool.CONNECTIONS['cc0'][CLIENTS], value + 1) def test_add_connection_new(self): """Adding a new connection to the pool returns True""" self.assertTrue(pool.add_connection('cc1', True)) def test_add_connection_existing(self): """Adding an existing connection to the pool returns False""" pool.add_connection('cc2', True) self.assertFalse(pool.add_connection('cc2', True)) def test_new_then_freed_connection_has_no_clients(self): """Freeing connection with one client should decrement counter""" pool.add_connection('cc3', True) pool.free_connection('cc3') self.assertEqual(pool.CONNECTIONS['cc3'][CLIENTS], 0) def test_free_connection(self): """Freeing connection should update last timestamp""" pool.add_connection('cc4', True) pool.free_connection('cc4') self.assertAlmostEqual(pool.CONNECTIONS['cc4'][LAST], int(time.time())) def test_remove_connection(self): """Freeing connection should update last timestamp""" pool.add_connection('cc5', True) pool.remove_connection('cc5') self.assertNotIn('cc5', pool.CONNECTIONS) class ConnectionPoolExpirationTests(unittest.TestCase): def setUp(self): pool.add_connection('cce_test', self.__class__) def test_pool_expiration(self): """Check that unused connection expires""" return_value = time.time() - TTL - 1 with mock.patch('time.time') as ptime: ptime.return_value = return_value pool.free_connection('cce_test') pool.check_for_unused_expired_connections() self.assertNotIn('cce_test', pool.CONNECTIONS) self.assertRaises(pool.ConnectionNotFoundError, obj.lock, mock.Mock(), mock.Mock()) def test_lock_resets_idle_start(self): with mock.patch('queries.pool.Connection.lock'): obj = pool.Pool(str(uuid.uuid4())) obj.idle_start = time.time() psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.lock(psycopg2_conn, mock.Mock()) self.assertIsNone(obj.idle_start) def test_remove_removes_connection(self): with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.remove(psycopg2_conn) self.assertNotIn(psycopg2_conn, obj) def test_remove_closes_connection(self): close_method = mock.Mock() with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False, close=close_method): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.remove(psycopg2_conn) close_method.assert_called_once_with() def test_remove_raises_when_connection_not_found(self): obj = pool.Pool(str(uuid.uuid4())) self.assertRaises(pool.ConnectionNotFoundError, obj.remove, mock.Mock()) def test_remove_raises_when_connection_is_busy(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() psycopg2_conn.closed = False obj.add(psycopg2_conn) self.assertRaises(pool.ConnectionBusyError, obj.remove, psycopg2_conn) def test__connection_returns_handle(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) self.assertEqual( obj.connection_handle(psycopg2_conn).handle, psycopg2_conn) def test_shutdown_raises_when_executing(self): psycopg2_conn = mock_connection() psycopg2_conn.isexecuting.return_value = True obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertRaises(pool.ConnectionBusyError, obj.shutdown) <MSG> Update connection pool and tests <DFF> @@ -8,73 +8,226 @@ try: import unittest2 as unittest except ImportError: import unittest +import uuid +import weakref from queries import pool -from queries.pool import CLIENTS, LAST, TTL -class ConnectionPoolTests(unittest.TestCase): +class AddConnectionTests(unittest.TestCase): def setUp(self): - pool.add_connection('cc0', self.__class__) + self.connection = mock.Mock('psycopg2._psycopg.connection') + self.pid = str(uuid.uuid4()) + pool.add_connection(self.pid, self, self.connection) - def tearDown(self): - for key in ['cc0', 'cc1', 'cc2', 'cc3', 'cc4']: - if key in pool.CONNECTIONS: - del pool.CONNECTIONS[key] + def test_pool_id_is_in_pools(self): + """Ensure the pool.Pools dict has an entry for pid""" + self.assertIn(self.pid, pool.Pools) - def test_add_connection_adds_value(self): - """Connection should already exist in the connection pool""" - self.assertIn('cc0', pool.CONNECTIONS) + def test_session_ref_is_in_pool(self): + """Ensure that the session weakref is in the pool""" + self.assertIn(weakref.ref(self), pool.Pools[self.pid].sessions) - def test_get_connection_returns_proper_value(self): - """Fetching connection from pool returns proper value""" - self.assertEqual(pool.get_connection('cc0'), self.__class__) + def test_connection_is_in_pool(self): + """Ensure that the session weakref is in the pool""" + self.assertIn(self.connection, pool.Pools[self.pid].connections) - def test_get_connection_increments_counter(self): - """Fetching connection from pool increments client counter""" - value = pool.CONNECTIONS.get('cc0', {}).get(CLIENTS, 0) - pool.get_connection('cc0') - self.assertEqual(pool.CONNECTIONS['cc0'][CLIENTS], value + 1) + def test_last_used_is_zero_for_pool(self): + """Ensure that the last_used value is 0 for pool""" + self.assertEqual(pool.Pools[self.pid].last_use, 0) - def test_add_connection_new(self): - """Adding a new connection to the pool returns True""" - self.assertTrue(pool.add_connection('cc1', True)) + def test_max_connection_reached_raises_exception(self): + """Ensure that a ValueError is raised with too many connections""" + for iteration in range(0, pool.MAX_CONNECTIONS): + conn = 'conn%i' % iteration + pool.add_connection(self.pid, self, conn) + self.assertRaises(ValueError, pool.add_connection, + self.pid, self, 'ERROR') - def test_add_connection_existing(self): - """Adding an existing connection to the pool returns False""" - pool.add_connection('cc2', True) - self.assertFalse(pool.add_connection('cc2', True)) + def test_count_of_session_references(self): + """Ensure a single session is only added once to the pool sessions""" + for iteration in range(0, pool.MAX_CONNECTIONS): + conn = 'conn%i' % iteration + pool.add_connection(self.pid, self, conn) + self.assertEqual(len(pool.Pools[self.pid].sessions), 1) - def test_new_then_freed_connection_has_no_clients(self): - """Freeing connection with one client should decrement counter""" - pool.add_connection('cc3', True) - pool.free_connection('cc3') - self.assertEqual(pool.CONNECTIONS['cc3'][CLIENTS], 0) - def test_free_connection(self): - """Freeing connection should update last timestamp""" - pool.add_connection('cc4', True) - pool.free_connection('cc4') - self.assertAlmostEqual(pool.CONNECTIONS['cc4'][LAST], int(time.time())) +class CleanPoolTests(unittest.TestCase): - def test_remove_connection(self): - """Freeing connection should update last timestamp""" - pool.add_connection('cc5', True) - pool.remove_connection('cc5') - self.assertNotIn('cc5', pool.CONNECTIONS) + def setUp(self): + self.cclose = mock.Mock() + self.connection = mock.Mock('psycopg2._psycopg.connection') + self.connection.close = self.cclose + self.pid = str(uuid.uuid4()) + self.session = mock.Mock('queries.session.Session') + pool.add_connection(self.pid, self.session, self.connection) + + def test_idle_pool_removed(self): + """Ensure an idle pool is removed""" + pool.Pools[self.pid] = \ + pool.Pools[self.pid]._replace(sessions=set(), + last_use=int(time.time()-pool.TTL-2)) + pool.clean_pools() + self.assertNotIn(self.pid, pool.Pools) + + def test_idle_connections_closed(self): + """Ensure a connection in an idle pool is closed""" + pool.Pools[self.pid] = \ + pool.Pools[self.pid]._replace(sessions=set(), + last_use=int(time.time()-pool.TTL-2)) + pool.clean_pools() + self.cclose.assert_called_once_with() + + +class ConnectionInPoolTests(unittest.TestCase): + + def setUp(self): + self.connection = mock.Mock('psycopg2._psycopg.connection') + self.pid = str(uuid.uuid4()) + pool.add_connection(self.pid, self, self.connection) + + def test_has_pool_returns_true(self): + """Ensure that connection_in_pool returns True""" + self.assertTrue(pool.connection_in_pool(self.pid, self.connection)) + + def test_has_pool_returns_false(self): + """Ensure that connection_in_pool returns False""" + self.assertFalse(pool.connection_in_pool(self.pid, self)) + + +class GetConnectionTests(unittest.TestCase): + + def setUp(self): + self.connection = mock.Mock('psycopg2._psycopg.connection') + self.connection.isexecuting = mock.Mock() + self.pid = str(uuid.uuid4()) + pool.add_connection(self.pid, self, self.connection) + + def test_when_is_executing(self): + """When connection is executing get_connection return None""" + self.connection.isexecuting.return_value = True + self.assertIsNone(pool.get_connection(self.pid)) + + def test_when_is_idle(self): + """When connection is executing get_connection returns connection""" + self.connection.isexecuting.return_value = False + self.assertEqual(pool.get_connection(self.pid), self.connection) -class ConnectionPoolExpirationTests(unittest.TestCase): +class HasIdleConnectionTests(unittest.TestCase): def setUp(self): - pool.add_connection('cce_test', self.__class__) - - def test_pool_expiration(self): - """Check that unused connection expires""" - return_value = time.time() - TTL - 1 - with mock.patch('time.time') as ptime: - ptime.return_value = return_value - pool.free_connection('cce_test') - pool.check_for_unused_expired_connections() - self.assertNotIn('cce_test', pool.CONNECTIONS) \ No newline at end of file + self.connection = mock.Mock('psycopg2._psycopg.connection') + self.connection.isexecuting = mock.Mock() + self.pid = str(uuid.uuid4()) + pool.add_connection(self.pid, self, self.connection) + + def test_when_is_executing(self): + """When connection is executing has_idle_connection return False""" + self.connection.isexecuting.return_value = True + self.assertFalse(pool.has_idle_connection(self.pid)) + + def test_when_is_idle(self): + """When connection is executing has_idle_connection return False""" + self.connection.isexecuting.return_value = False + self.assertTrue(pool.has_idle_connection(self.pid)) + + +class HasPoolTests(unittest.TestCase): + + def setUp(self): + self.connection = mock.Mock('psycopg2._psycopg.connection') + self.pid = str(uuid.uuid4()) + pool.add_connection(self.pid, self, self.connection) + + def test_has_pool_returns_true(self): + """Ensure that has_pool returns True when pool exists""" + self.assertTrue(pool.has_pool(self.pid)) + + def test_has_pool_returns_false(self): + """Ensure that has_pool returns False when pool doesnt exist""" + self.assertFalse(pool.has_pool(self)) + + +class RemoveConnectionTests(unittest.TestCase): + + def setUp(self): + self.connection = mock.Mock('psycopg2._psycopg.connection') + self.pid = str(uuid.uuid4()) + pool.add_connection(self.pid, self, self.connection) + + def test_remove_connection_removes_connection(self): + """Ensure a removed connection is not in pool""" + pool.remove_connection(self.pid, self.connection) + self.assertNotIn(self.connection, pool.Pools[self.pid].connections) + + def test_empty_pool_removed(self): + """Ensure a removed connection is not in pool""" + pool.remove_connection(self.pid, self.connection) + pool.clean_pools() + self.assertNotIn(self.pid, pool.Pools) + + def test_invalid_connection_fails_silently(self): + """Ensure that passing an invalid pid doesnt raise an exception""" + pool.remove_connection(self.pid, self) + + def test_invalid_pid_fails_silently(self): + """Ensure passing an invalid pid doesnt not raise exception""" + pool.remove_connection(self.connection, self) + + +class RemoveSessionTests(unittest.TestCase): + + def setUp(self): + self.session = mock.Mock('queries.session.Session') + self.connection = mock.Mock('psycopg2._psycopg.connection') + self.connection.close = mock.Mock() + self.pid = str(uuid.uuid4()) + pool.add_connection(self.pid, self.session, self.connection) + + def test_remove_sets_last_use(self): + """Ensure that last_use is set for a pool when last session removed""" + pool.remove_session(self.pid, self.session) + self.assertEqual(pool.Pools[self.pid].last_use, int(time.time())) + + def test_remove_session_removes_session(self): + """Ensure a removed session's weakref is not in pool""" + pool.remove_session(self.pid, self.session) + self.assertNotIn(weakref.ref(self), pool.Pools[self.pid].sessions) + + def test_dead_weakref_removed(self): + """Ensure a deleted session obj is not in the pool""" + del self.session + pool.clean_pools() + self.assertEqual(len(pool.Pools[self.pid].sessions), 0) + + def test_dead_weakref_removed_but_pool_not_removed(self): + """Ensure a pool with no remaining sessions is not removed""" + del self.session + pool.clean_pools() + self.assertIn(self.pid, pool.Pools) + + def test_invalid_session_fails_silently(self): + """Ensure that passing an invalid pid doesnt raise an exception""" + pool.remove_session(self.pid, self.connection) + + def test_invalid_pid_fails_silently(self): + """Ensure passing an invalid pid doesnt not raise exception""" + pool.remove_session(self.connection, self.session) + + +class SessionInPoolTests(unittest.TestCase): + + def setUp(self): + self.connection = mock.Mock('psycopg2._psycopg.connection') + self.pid = str(uuid.uuid4()) + pool.add_connection(self.pid, self, self.connection) + + def test_has_pool_returns_true(self): + """Ensure that session_in_pool returns True when session exists""" + self.assertTrue(pool.session_in_pool(self.pid, self)) + + def test_has_pool_returns_false(self): + """Ensure that session_in_pool returns False when it doesnt exist""" + self.assertFalse(pool.session_in_pool(self.pid, self.connection))
204
Update connection pool and tests
51
.py
py
bsd-3-clause
gmr/queries
1122
<NME> pool_tests.py <BEF> """ Tests for functionality in the pool module """ import time import unittest import uuid import unittest2 as unittest except ImportError: import unittest from queries import pool from queries.pool import CLIENTS, LAST, TTL class ConnectionPoolTests(unittest.TestCase): def setUp(self): pool.add_connection('cc0', self.__class__) def tearDown(self): for key in ['cc0', 'cc1', 'cc2', 'cc3', 'cc4']: if key in pool.CONNECTIONS: del pool.CONNECTIONS[key] def test_add_connection_adds_value(self): """Connection should already exist in the connection pool""" self.assertIn('cc0', pool.CONNECTIONS) def test_get_connection_returns_proper_value(self): """Fetching connection from pool returns proper value""" self.assertEqual(pool.get_connection('cc0'), self.__class__) def test_get_connection_increments_counter(self): """Fetching connection from pool increments client counter""" value = pool.CONNECTIONS.get('cc0', {}).get(CLIENTS, 0) pool.get_connection('cc0') self.assertEqual(pool.CONNECTIONS['cc0'][CLIENTS], value + 1) def test_add_connection_new(self): """Adding a new connection to the pool returns True""" self.assertTrue(pool.add_connection('cc1', True)) def test_add_connection_existing(self): """Adding an existing connection to the pool returns False""" pool.add_connection('cc2', True) self.assertFalse(pool.add_connection('cc2', True)) def test_new_then_freed_connection_has_no_clients(self): """Freeing connection with one client should decrement counter""" pool.add_connection('cc3', True) pool.free_connection('cc3') self.assertEqual(pool.CONNECTIONS['cc3'][CLIENTS], 0) def test_free_connection(self): """Freeing connection should update last timestamp""" pool.add_connection('cc4', True) pool.free_connection('cc4') self.assertAlmostEqual(pool.CONNECTIONS['cc4'][LAST], int(time.time())) def test_remove_connection(self): """Freeing connection should update last timestamp""" pool.add_connection('cc5', True) pool.remove_connection('cc5') self.assertNotIn('cc5', pool.CONNECTIONS) class ConnectionPoolExpirationTests(unittest.TestCase): def setUp(self): pool.add_connection('cce_test', self.__class__) def test_pool_expiration(self): """Check that unused connection expires""" return_value = time.time() - TTL - 1 with mock.patch('time.time') as ptime: ptime.return_value = return_value pool.free_connection('cce_test') pool.check_for_unused_expired_connections() self.assertNotIn('cce_test', pool.CONNECTIONS) self.assertRaises(pool.ConnectionNotFoundError, obj.lock, mock.Mock(), mock.Mock()) def test_lock_resets_idle_start(self): with mock.patch('queries.pool.Connection.lock'): obj = pool.Pool(str(uuid.uuid4())) obj.idle_start = time.time() psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.lock(psycopg2_conn, mock.Mock()) self.assertIsNone(obj.idle_start) def test_remove_removes_connection(self): with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.remove(psycopg2_conn) self.assertNotIn(psycopg2_conn, obj) def test_remove_closes_connection(self): close_method = mock.Mock() with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False, close=close_method): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.remove(psycopg2_conn) close_method.assert_called_once_with() def test_remove_raises_when_connection_not_found(self): obj = pool.Pool(str(uuid.uuid4())) self.assertRaises(pool.ConnectionNotFoundError, obj.remove, mock.Mock()) def test_remove_raises_when_connection_is_busy(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() psycopg2_conn.closed = False obj.add(psycopg2_conn) self.assertRaises(pool.ConnectionBusyError, obj.remove, psycopg2_conn) def test__connection_returns_handle(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) self.assertEqual( obj.connection_handle(psycopg2_conn).handle, psycopg2_conn) def test_shutdown_raises_when_executing(self): psycopg2_conn = mock_connection() psycopg2_conn.isexecuting.return_value = True obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertRaises(pool.ConnectionBusyError, obj.shutdown) <MSG> Update connection pool and tests <DFF> @@ -8,73 +8,226 @@ try: import unittest2 as unittest except ImportError: import unittest +import uuid +import weakref from queries import pool -from queries.pool import CLIENTS, LAST, TTL -class ConnectionPoolTests(unittest.TestCase): +class AddConnectionTests(unittest.TestCase): def setUp(self): - pool.add_connection('cc0', self.__class__) + self.connection = mock.Mock('psycopg2._psycopg.connection') + self.pid = str(uuid.uuid4()) + pool.add_connection(self.pid, self, self.connection) - def tearDown(self): - for key in ['cc0', 'cc1', 'cc2', 'cc3', 'cc4']: - if key in pool.CONNECTIONS: - del pool.CONNECTIONS[key] + def test_pool_id_is_in_pools(self): + """Ensure the pool.Pools dict has an entry for pid""" + self.assertIn(self.pid, pool.Pools) - def test_add_connection_adds_value(self): - """Connection should already exist in the connection pool""" - self.assertIn('cc0', pool.CONNECTIONS) + def test_session_ref_is_in_pool(self): + """Ensure that the session weakref is in the pool""" + self.assertIn(weakref.ref(self), pool.Pools[self.pid].sessions) - def test_get_connection_returns_proper_value(self): - """Fetching connection from pool returns proper value""" - self.assertEqual(pool.get_connection('cc0'), self.__class__) + def test_connection_is_in_pool(self): + """Ensure that the session weakref is in the pool""" + self.assertIn(self.connection, pool.Pools[self.pid].connections) - def test_get_connection_increments_counter(self): - """Fetching connection from pool increments client counter""" - value = pool.CONNECTIONS.get('cc0', {}).get(CLIENTS, 0) - pool.get_connection('cc0') - self.assertEqual(pool.CONNECTIONS['cc0'][CLIENTS], value + 1) + def test_last_used_is_zero_for_pool(self): + """Ensure that the last_used value is 0 for pool""" + self.assertEqual(pool.Pools[self.pid].last_use, 0) - def test_add_connection_new(self): - """Adding a new connection to the pool returns True""" - self.assertTrue(pool.add_connection('cc1', True)) + def test_max_connection_reached_raises_exception(self): + """Ensure that a ValueError is raised with too many connections""" + for iteration in range(0, pool.MAX_CONNECTIONS): + conn = 'conn%i' % iteration + pool.add_connection(self.pid, self, conn) + self.assertRaises(ValueError, pool.add_connection, + self.pid, self, 'ERROR') - def test_add_connection_existing(self): - """Adding an existing connection to the pool returns False""" - pool.add_connection('cc2', True) - self.assertFalse(pool.add_connection('cc2', True)) + def test_count_of_session_references(self): + """Ensure a single session is only added once to the pool sessions""" + for iteration in range(0, pool.MAX_CONNECTIONS): + conn = 'conn%i' % iteration + pool.add_connection(self.pid, self, conn) + self.assertEqual(len(pool.Pools[self.pid].sessions), 1) - def test_new_then_freed_connection_has_no_clients(self): - """Freeing connection with one client should decrement counter""" - pool.add_connection('cc3', True) - pool.free_connection('cc3') - self.assertEqual(pool.CONNECTIONS['cc3'][CLIENTS], 0) - def test_free_connection(self): - """Freeing connection should update last timestamp""" - pool.add_connection('cc4', True) - pool.free_connection('cc4') - self.assertAlmostEqual(pool.CONNECTIONS['cc4'][LAST], int(time.time())) +class CleanPoolTests(unittest.TestCase): - def test_remove_connection(self): - """Freeing connection should update last timestamp""" - pool.add_connection('cc5', True) - pool.remove_connection('cc5') - self.assertNotIn('cc5', pool.CONNECTIONS) + def setUp(self): + self.cclose = mock.Mock() + self.connection = mock.Mock('psycopg2._psycopg.connection') + self.connection.close = self.cclose + self.pid = str(uuid.uuid4()) + self.session = mock.Mock('queries.session.Session') + pool.add_connection(self.pid, self.session, self.connection) + + def test_idle_pool_removed(self): + """Ensure an idle pool is removed""" + pool.Pools[self.pid] = \ + pool.Pools[self.pid]._replace(sessions=set(), + last_use=int(time.time()-pool.TTL-2)) + pool.clean_pools() + self.assertNotIn(self.pid, pool.Pools) + + def test_idle_connections_closed(self): + """Ensure a connection in an idle pool is closed""" + pool.Pools[self.pid] = \ + pool.Pools[self.pid]._replace(sessions=set(), + last_use=int(time.time()-pool.TTL-2)) + pool.clean_pools() + self.cclose.assert_called_once_with() + + +class ConnectionInPoolTests(unittest.TestCase): + + def setUp(self): + self.connection = mock.Mock('psycopg2._psycopg.connection') + self.pid = str(uuid.uuid4()) + pool.add_connection(self.pid, self, self.connection) + + def test_has_pool_returns_true(self): + """Ensure that connection_in_pool returns True""" + self.assertTrue(pool.connection_in_pool(self.pid, self.connection)) + + def test_has_pool_returns_false(self): + """Ensure that connection_in_pool returns False""" + self.assertFalse(pool.connection_in_pool(self.pid, self)) + + +class GetConnectionTests(unittest.TestCase): + + def setUp(self): + self.connection = mock.Mock('psycopg2._psycopg.connection') + self.connection.isexecuting = mock.Mock() + self.pid = str(uuid.uuid4()) + pool.add_connection(self.pid, self, self.connection) + + def test_when_is_executing(self): + """When connection is executing get_connection return None""" + self.connection.isexecuting.return_value = True + self.assertIsNone(pool.get_connection(self.pid)) + + def test_when_is_idle(self): + """When connection is executing get_connection returns connection""" + self.connection.isexecuting.return_value = False + self.assertEqual(pool.get_connection(self.pid), self.connection) -class ConnectionPoolExpirationTests(unittest.TestCase): +class HasIdleConnectionTests(unittest.TestCase): def setUp(self): - pool.add_connection('cce_test', self.__class__) - - def test_pool_expiration(self): - """Check that unused connection expires""" - return_value = time.time() - TTL - 1 - with mock.patch('time.time') as ptime: - ptime.return_value = return_value - pool.free_connection('cce_test') - pool.check_for_unused_expired_connections() - self.assertNotIn('cce_test', pool.CONNECTIONS) \ No newline at end of file + self.connection = mock.Mock('psycopg2._psycopg.connection') + self.connection.isexecuting = mock.Mock() + self.pid = str(uuid.uuid4()) + pool.add_connection(self.pid, self, self.connection) + + def test_when_is_executing(self): + """When connection is executing has_idle_connection return False""" + self.connection.isexecuting.return_value = True + self.assertFalse(pool.has_idle_connection(self.pid)) + + def test_when_is_idle(self): + """When connection is executing has_idle_connection return False""" + self.connection.isexecuting.return_value = False + self.assertTrue(pool.has_idle_connection(self.pid)) + + +class HasPoolTests(unittest.TestCase): + + def setUp(self): + self.connection = mock.Mock('psycopg2._psycopg.connection') + self.pid = str(uuid.uuid4()) + pool.add_connection(self.pid, self, self.connection) + + def test_has_pool_returns_true(self): + """Ensure that has_pool returns True when pool exists""" + self.assertTrue(pool.has_pool(self.pid)) + + def test_has_pool_returns_false(self): + """Ensure that has_pool returns False when pool doesnt exist""" + self.assertFalse(pool.has_pool(self)) + + +class RemoveConnectionTests(unittest.TestCase): + + def setUp(self): + self.connection = mock.Mock('psycopg2._psycopg.connection') + self.pid = str(uuid.uuid4()) + pool.add_connection(self.pid, self, self.connection) + + def test_remove_connection_removes_connection(self): + """Ensure a removed connection is not in pool""" + pool.remove_connection(self.pid, self.connection) + self.assertNotIn(self.connection, pool.Pools[self.pid].connections) + + def test_empty_pool_removed(self): + """Ensure a removed connection is not in pool""" + pool.remove_connection(self.pid, self.connection) + pool.clean_pools() + self.assertNotIn(self.pid, pool.Pools) + + def test_invalid_connection_fails_silently(self): + """Ensure that passing an invalid pid doesnt raise an exception""" + pool.remove_connection(self.pid, self) + + def test_invalid_pid_fails_silently(self): + """Ensure passing an invalid pid doesnt not raise exception""" + pool.remove_connection(self.connection, self) + + +class RemoveSessionTests(unittest.TestCase): + + def setUp(self): + self.session = mock.Mock('queries.session.Session') + self.connection = mock.Mock('psycopg2._psycopg.connection') + self.connection.close = mock.Mock() + self.pid = str(uuid.uuid4()) + pool.add_connection(self.pid, self.session, self.connection) + + def test_remove_sets_last_use(self): + """Ensure that last_use is set for a pool when last session removed""" + pool.remove_session(self.pid, self.session) + self.assertEqual(pool.Pools[self.pid].last_use, int(time.time())) + + def test_remove_session_removes_session(self): + """Ensure a removed session's weakref is not in pool""" + pool.remove_session(self.pid, self.session) + self.assertNotIn(weakref.ref(self), pool.Pools[self.pid].sessions) + + def test_dead_weakref_removed(self): + """Ensure a deleted session obj is not in the pool""" + del self.session + pool.clean_pools() + self.assertEqual(len(pool.Pools[self.pid].sessions), 0) + + def test_dead_weakref_removed_but_pool_not_removed(self): + """Ensure a pool with no remaining sessions is not removed""" + del self.session + pool.clean_pools() + self.assertIn(self.pid, pool.Pools) + + def test_invalid_session_fails_silently(self): + """Ensure that passing an invalid pid doesnt raise an exception""" + pool.remove_session(self.pid, self.connection) + + def test_invalid_pid_fails_silently(self): + """Ensure passing an invalid pid doesnt not raise exception""" + pool.remove_session(self.connection, self.session) + + +class SessionInPoolTests(unittest.TestCase): + + def setUp(self): + self.connection = mock.Mock('psycopg2._psycopg.connection') + self.pid = str(uuid.uuid4()) + pool.add_connection(self.pid, self, self.connection) + + def test_has_pool_returns_true(self): + """Ensure that session_in_pool returns True when session exists""" + self.assertTrue(pool.session_in_pool(self.pid, self)) + + def test_has_pool_returns_false(self): + """Ensure that session_in_pool returns False when it doesnt exist""" + self.assertFalse(pool.session_in_pool(self.pid, self.connection))
204
Update connection pool and tests
51
.py
py
bsd-3-clause
gmr/queries
1123
<NME> pool_connection_tests.py <BEF> """ Tests for Connection class in the pool module """ import unittest import weakref import mock from queries import pool class ConnectionTests(unittest.TestCase): def setUp(self): self.handle = mock.Mock() self.handle.close = mock.Mock() self.handle.closed = True self.handle.isexecuting = mock.Mock(return_value=False) self.connection = pool.Connection(self.handle) self.connection.used_by = None def test_handle_should_match(self): self.assertEqual(self.handle, self.connection.handle) def test_busy_isexecuting_is_false(self): self.assertFalse(self.connection.busy) def test_busy_isexecuting_is_true(self): self.handle.isexecuting.return_value = True self.assertTrue(self.connection.busy) def test_busy_is_used(self): self.handle.isexecuting.return_value = False self.connection.used_by = mock.Mock() self.assertTrue(self.connection.busy) def test_executing_is_true(self): self.handle.isexecuting.return_value = True self.assertTrue(self.connection.executing) def test_executing_is_false(self): self.handle.isexecuting.return_value = False self.assertFalse(self.connection.executing) def test_locked_is_true(self): self.connection.used_by = mock.Mock() self.assertTrue(self.connection.locked) def test_locked_is_false(self): self.connection.used_by = None self.assertFalse(self.connection.locked) def test_closed_is_true(self): self.handle.closed = True self.assertTrue(self.connection.closed) def test_closed_is_false(self): self.handle.closed = False self.assertFalse(self.connection.closed) def test_close_raises_when_busy(self): self.handle.isexecuting.return_value = True self.handle.closed = False self.assertRaises(pool.ConnectionBusyError, self.connection.close) def test_close_invokes_handle_close(self): self.handle.isexecuting.return_value = False self.connection.used_by = None self.connection.close() self.assertEqual(len(self.handle.close.mock_calls), 1) def test_free_raises_when_busy(self): self.handle.isexecuting.return_value = True self.assertRaises(pool.ConnectionBusyError, self.connection.free) def test_free_resets_used_by(self): self.handle.isexecuting.return_value = False self.connection.used_by = mock.Mock() self.connection.free() self.assertIsNone(self.connection.used_by) def test_id_value_matches(self): self.assertEqual(id(self.handle), self.connection.id) def test_lock_raises_when_busy(self): self.connection.used_by = mock.Mock() self.assertRaises(pool.ConnectionBusyError, self.connection.lock, mock.Mock()) def test_lock_session_used_by(self): session = mock.Mock() self.connection.lock(session) self.assertIn(self.connection.used_by, weakref.getweakrefs(session)) <MSG> Fix the broken connection.close() test <DFF> @@ -67,6 +67,7 @@ class ConnectionTests(unittest.TestCase): def test_close_invokes_handle_close(self): self.handle.isexecuting.return_value = False + self.handle.closed = False self.connection.used_by = None self.connection.close() self.assertEqual(len(self.handle.close.mock_calls), 1)
1
Fix the broken connection.close() test
0
.py
py
bsd-3-clause
gmr/queries
1124
<NME> pool_connection_tests.py <BEF> """ Tests for Connection class in the pool module """ import unittest import weakref import mock from queries import pool class ConnectionTests(unittest.TestCase): def setUp(self): self.handle = mock.Mock() self.handle.close = mock.Mock() self.handle.closed = True self.handle.isexecuting = mock.Mock(return_value=False) self.connection = pool.Connection(self.handle) self.connection.used_by = None def test_handle_should_match(self): self.assertEqual(self.handle, self.connection.handle) def test_busy_isexecuting_is_false(self): self.assertFalse(self.connection.busy) def test_busy_isexecuting_is_true(self): self.handle.isexecuting.return_value = True self.assertTrue(self.connection.busy) def test_busy_is_used(self): self.handle.isexecuting.return_value = False self.connection.used_by = mock.Mock() self.assertTrue(self.connection.busy) def test_executing_is_true(self): self.handle.isexecuting.return_value = True self.assertTrue(self.connection.executing) def test_executing_is_false(self): self.handle.isexecuting.return_value = False self.assertFalse(self.connection.executing) def test_locked_is_true(self): self.connection.used_by = mock.Mock() self.assertTrue(self.connection.locked) def test_locked_is_false(self): self.connection.used_by = None self.assertFalse(self.connection.locked) def test_closed_is_true(self): self.handle.closed = True self.assertTrue(self.connection.closed) def test_closed_is_false(self): self.handle.closed = False self.assertFalse(self.connection.closed) def test_close_raises_when_busy(self): self.handle.isexecuting.return_value = True self.handle.closed = False self.assertRaises(pool.ConnectionBusyError, self.connection.close) def test_close_invokes_handle_close(self): self.handle.isexecuting.return_value = False self.connection.used_by = None self.connection.close() self.assertEqual(len(self.handle.close.mock_calls), 1) def test_free_raises_when_busy(self): self.handle.isexecuting.return_value = True self.assertRaises(pool.ConnectionBusyError, self.connection.free) def test_free_resets_used_by(self): self.handle.isexecuting.return_value = False self.connection.used_by = mock.Mock() self.connection.free() self.assertIsNone(self.connection.used_by) def test_id_value_matches(self): self.assertEqual(id(self.handle), self.connection.id) def test_lock_raises_when_busy(self): self.connection.used_by = mock.Mock() self.assertRaises(pool.ConnectionBusyError, self.connection.lock, mock.Mock()) def test_lock_session_used_by(self): session = mock.Mock() self.connection.lock(session) self.assertIn(self.connection.used_by, weakref.getweakrefs(session)) <MSG> Fix the broken connection.close() test <DFF> @@ -67,6 +67,7 @@ class ConnectionTests(unittest.TestCase): def test_close_invokes_handle_close(self): self.handle.isexecuting.return_value = False + self.handle.closed = False self.connection.used_by = None self.connection.close() self.assertEqual(len(self.handle.close.mock_calls), 1)
1
Fix the broken connection.close() test
0
.py
py
bsd-3-clause
gmr/queries
1125
<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() class TornadoSession(session.Session): """Session class for Tornado asynchronous applications. Using 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()`. """ def __init__(self, uri=DEFAULT_URI, cursor_factory=extras.RealDictCursor, results = yield session.query('SELECT * FROM foo') for row in results print row results.free() :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 """ self._callbacks = dict() self._connections = dict() self._commands = dict() self._cursor_factory = cursor_factory results = yield session.query('SELECT * FROM foo LIMIT 1') print results.as_dict() self._use_pool = use_pool @gen.coroutine def callproc(self, name, parameters=None): # Grab a connection, either new or out of the pool connection, fd, status = self._connect() 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 # Get the cursor, execute the query and wait for the result cursor = self._get_cursor(connection) cursor.callproc(name, parameters) yield gen.Wait((self, fd)) # If there was an exception, cleanup, then raise it 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 # Return the result if there are any raise gen.Return(result) @gen.coroutine def query(self, sql, parameters=None): # Grab a connection, either new or out of the pool connection, fd, status = self._connect() :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) # Return the result if there are any raise gen.Return(result) def _connect(self): connection = super(TornadoSession, self)._connect() fd, status = connection.fileno(), connection.status else: try: # Add the connection to the pool LOGGER.debug('Connection established for %s', self.pid) self._pool_manager.add(self.pid, connection) except (ValueError, pool.PoolException) as err: LOGGER.exception('Failed to add %r to the pool', self.pid) self._cleanup_fd(fd) future.set_exception(err) return self._pool_manager.lock(self.pid, connection, self) # Added in because psycopg2cffi connects and leaves the # connection in a weird state: consts.STATUS_DATESTYLE, # returning from Connection._setup without setting the state # as const.STATUS_OK if utils.PYPY: connection.status = extensions.STATUS_READY # Register the custom data types self._register_unicode(connection) self._register_uuid(connection) # Set the future result future.set_result(connection) # Add a future that fires once connected self._futures[fd] = concurrent.Future() self._ioloop.add_future(self._futures[fd], on_connected) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) def _execute(self, method, query, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. This function reduces duplicate code for callproc and query by getting the class attribute for the method passed in as the function to call. :param str method: The method attribute to use :param str query: The SQL statement or Stored Procedure name :param list|dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ future = concurrent.Future() def on_connected(cf): """Invoked by the future returned by self._connect""" if cf.exception(): future.set_exception(cf.exception()) return # Get the psycopg2 connection object and cursor conn = cf.result() cursor = self._get_cursor(conn) def completed(qf): """Invoked by the IOLoop when the future has completed""" if qf.exception(): self._incr_exceptions(conn) err = qf.exception() LOGGER.debug('Cleaning cursor due to exception: %r', err) self._exec_cleanup(cursor, conn.fileno()) future.set_exception(err) else: self._incr_executions(conn) value = Results(cursor, self._exec_cleanup, conn.fileno()) future.set_result(value) # Setup a callback to wait on the query result self._futures[conn.fileno()] = concurrent.Future() # Add the future to the IOLoop self._ioloop.add_future(self._futures[conn.fileno()], completed) # Get the cursor, execute the query func = getattr(cursor, method) try: func(query, parameters) except Exception as error: future.set_exception(error) # Ensure the pool exists for the connection self._ensure_pool_exists() # Grab a connection to PostgreSQL self._ioloop.add_future(self._connect(), on_connected) # Return the future for the query result return future def _exec_cleanup(self, cursor, fd): """Close the cursor, remove any references to the fd in internal state and remove the fd from the ioloop. :param psycopg2.extensions.cursor cursor: The cursor to close :param int fd: The connection file descriptor """ LOGGER.debug('Closing cursor and cleaning %s', fd) try: cursor.close() except (psycopg2.Error, psycopg2.Warning) as error: LOGGER.debug('Error closing the cursor: %s', error) self._cleanup_fd(fd) # If the cleanup callback exists, remove it if self._cleanup_callback: self._ioloop.remove_timeout(self._cleanup_callback) # Create a new cleanup callback to clean the pool of idle connections self._cleanup_callback = self._ioloop.add_timeout( self._ioloop.time() + self._pool_idle_ttl + 1, self._pool_manager.clean, self.pid) def _cleanup_fd(self, fd, close=False): """Ensure the socket socket is removed from the IOLoop, the connection stack, and futures stack. :param int fd: The fd # to cleanup """ self._ioloop.remove_handler(fd) if fd in self._connections: try: self._pool_manager.free(self.pid, self._connections[fd]) except pool.ConnectionNotFoundError: pass if close: self._connections[fd].close() del self._connections[fd] if fd in self._futures: del self._futures[fd] def _incr_exceptions(self, conn): """Increment the number of exceptions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).exceptions += 1 def _incr_executions(self, conn): """Increment the number of executions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).executions += 1 def _on_io_events(self, fd=None, _events=None): """Invoked by Tornado's IOLoop when there are events for the fd :param int fd: The file descriptor for the event :param int _events: The events raised """ if fd not in self._connections: LOGGER.warning('Received IO event for non-existing connection') return self._poll_connection(fd) def _poll_connection(self, fd): """Check with psycopg2 to see what action to take. If the state is POLL_OK, we should have a pending callback for that fd. :param int fd: The socket fd for the postgresql connection """ try: state = self._connections[fd].poll() except (OSError, socket.error) as error: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.OperationalError('Connection error (%s)' % error) ) except (psycopg2.Error, psycopg2.Warning) as error: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception(error) else: if state == extensions.POLL_OK: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_result(True) elif state == extensions.POLL_WRITE: self._ioloop.update_handler(fd, ioloop.IOLoop.WRITE) elif state == extensions.POLL_READ: self._ioloop.update_handler(fd, ioloop.IOLoop.READ) elif state == extensions.POLL_ERROR: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.Error('Poll Error')) def _psycopg2_connect(self, kwargs): """Return a psycopg2 connection for the specified kwargs. Extend for use in async session adapters. :param dict kwargs: Keyword connection args :rtype: psycopg2.extensions.connection """ kwargs['async'] = True return psycopg2.connect(**kwargs) <MSG> Update docstrings <DFF> @@ -21,16 +21,36 @@ LOGGER = logging.getLogger(__name__) class TornadoSession(session.Session): - """Session class for Tornado asynchronous applications. Using + """Session class for Tornado asynchronous applications. Uses + ``tornado.gen.coroutine`` to wrap API methods for use in Tornado. - Unlike `queries.Session.query` and `queries.Session.callproc`, the - `TornadoSession.query` and `TornadoSession.callproc` methods are not + 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 + :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, @@ -42,10 +62,11 @@ class TornadoSession(session.Session): :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 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 @@ -55,8 +76,21 @@ class TornadoSession(session.Session): self._use_pool = use_pool @gen.coroutine - def callproc(self, name, 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, returning the results + as a list. If no results are returned, the method will return None + instead. + + .. 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 connection, fd, status = self._connect() @@ -75,7 +109,7 @@ class TornadoSession(session.Session): # Get the cursor, execute the query and wait for the result cursor = self._get_cursor(connection) - cursor.callproc(name, parameters) + cursor.callproc(name, args) yield gen.Wait((self, fd)) # If there was an exception, cleanup, then raise it @@ -96,9 +130,96 @@ class TornadoSession(session.Session): # Return the result if there are any raise gen.Return(result) + @gen.coroutine + def listen(self, channel, callback): + """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 + + """ + # 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) + + # Loop while we have listeners and a channel + 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): + """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', + {'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 connection, fd, status = self._connect() @@ -138,7 +259,42 @@ class TornadoSession(session.Session): # Return the result if there are any raise gen.Return(result) + @gen.coroutine + def unlisten(self, channel): + """Cancel a listening on a channel. + + ..code:: python + + yield self.session.unlisten('channel-name') + + :param str channel: The channel to stop listening on + + """ + if channel not in self._listeners: + raise ValueError("No listeners for specified channel") + + # Get the fd and cursor, then remove the listener + fd, cursor = self._listeners[channel] + del self._listeners[channel] + + # Call the callback waiting in the LISTEN loop + self._callbacks[fd]((self, fd)) + + # Create a callback, unlisten and wait for the result + self._callbacks[fd] = yield gen.Callback((self, fd)) + cursor.execute("UNLISTEN %s;" % channel) + yield gen.Wait((self, fd)) + + # 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. + + :rtype: tuple(psycopg2._psycopg.connection, int, int) + + """ connection = super(TornadoSession, self)._connect() fd, status = connection.fileno(), connection.status
163
Update docstrings
7
.py
py
bsd-3-clause
gmr/queries
1126
<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() class TornadoSession(session.Session): """Session class for Tornado asynchronous applications. Using 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()`. """ def __init__(self, uri=DEFAULT_URI, cursor_factory=extras.RealDictCursor, results = yield session.query('SELECT * FROM foo') for row in results print row results.free() :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 """ self._callbacks = dict() self._connections = dict() self._commands = dict() self._cursor_factory = cursor_factory results = yield session.query('SELECT * FROM foo LIMIT 1') print results.as_dict() self._use_pool = use_pool @gen.coroutine def callproc(self, name, parameters=None): # Grab a connection, either new or out of the pool connection, fd, status = self._connect() 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 # Get the cursor, execute the query and wait for the result cursor = self._get_cursor(connection) cursor.callproc(name, parameters) yield gen.Wait((self, fd)) # If there was an exception, cleanup, then raise it 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 # Return the result if there are any raise gen.Return(result) @gen.coroutine def query(self, sql, parameters=None): # Grab a connection, either new or out of the pool connection, fd, status = self._connect() :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) # Return the result if there are any raise gen.Return(result) def _connect(self): connection = super(TornadoSession, self)._connect() fd, status = connection.fileno(), connection.status else: try: # Add the connection to the pool LOGGER.debug('Connection established for %s', self.pid) self._pool_manager.add(self.pid, connection) except (ValueError, pool.PoolException) as err: LOGGER.exception('Failed to add %r to the pool', self.pid) self._cleanup_fd(fd) future.set_exception(err) return self._pool_manager.lock(self.pid, connection, self) # Added in because psycopg2cffi connects and leaves the # connection in a weird state: consts.STATUS_DATESTYLE, # returning from Connection._setup without setting the state # as const.STATUS_OK if utils.PYPY: connection.status = extensions.STATUS_READY # Register the custom data types self._register_unicode(connection) self._register_uuid(connection) # Set the future result future.set_result(connection) # Add a future that fires once connected self._futures[fd] = concurrent.Future() self._ioloop.add_future(self._futures[fd], on_connected) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) def _execute(self, method, query, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. This function reduces duplicate code for callproc and query by getting the class attribute for the method passed in as the function to call. :param str method: The method attribute to use :param str query: The SQL statement or Stored Procedure name :param list|dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ future = concurrent.Future() def on_connected(cf): """Invoked by the future returned by self._connect""" if cf.exception(): future.set_exception(cf.exception()) return # Get the psycopg2 connection object and cursor conn = cf.result() cursor = self._get_cursor(conn) def completed(qf): """Invoked by the IOLoop when the future has completed""" if qf.exception(): self._incr_exceptions(conn) err = qf.exception() LOGGER.debug('Cleaning cursor due to exception: %r', err) self._exec_cleanup(cursor, conn.fileno()) future.set_exception(err) else: self._incr_executions(conn) value = Results(cursor, self._exec_cleanup, conn.fileno()) future.set_result(value) # Setup a callback to wait on the query result self._futures[conn.fileno()] = concurrent.Future() # Add the future to the IOLoop self._ioloop.add_future(self._futures[conn.fileno()], completed) # Get the cursor, execute the query func = getattr(cursor, method) try: func(query, parameters) except Exception as error: future.set_exception(error) # Ensure the pool exists for the connection self._ensure_pool_exists() # Grab a connection to PostgreSQL self._ioloop.add_future(self._connect(), on_connected) # Return the future for the query result return future def _exec_cleanup(self, cursor, fd): """Close the cursor, remove any references to the fd in internal state and remove the fd from the ioloop. :param psycopg2.extensions.cursor cursor: The cursor to close :param int fd: The connection file descriptor """ LOGGER.debug('Closing cursor and cleaning %s', fd) try: cursor.close() except (psycopg2.Error, psycopg2.Warning) as error: LOGGER.debug('Error closing the cursor: %s', error) self._cleanup_fd(fd) # If the cleanup callback exists, remove it if self._cleanup_callback: self._ioloop.remove_timeout(self._cleanup_callback) # Create a new cleanup callback to clean the pool of idle connections self._cleanup_callback = self._ioloop.add_timeout( self._ioloop.time() + self._pool_idle_ttl + 1, self._pool_manager.clean, self.pid) def _cleanup_fd(self, fd, close=False): """Ensure the socket socket is removed from the IOLoop, the connection stack, and futures stack. :param int fd: The fd # to cleanup """ self._ioloop.remove_handler(fd) if fd in self._connections: try: self._pool_manager.free(self.pid, self._connections[fd]) except pool.ConnectionNotFoundError: pass if close: self._connections[fd].close() del self._connections[fd] if fd in self._futures: del self._futures[fd] def _incr_exceptions(self, conn): """Increment the number of exceptions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).exceptions += 1 def _incr_executions(self, conn): """Increment the number of executions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).executions += 1 def _on_io_events(self, fd=None, _events=None): """Invoked by Tornado's IOLoop when there are events for the fd :param int fd: The file descriptor for the event :param int _events: The events raised """ if fd not in self._connections: LOGGER.warning('Received IO event for non-existing connection') return self._poll_connection(fd) def _poll_connection(self, fd): """Check with psycopg2 to see what action to take. If the state is POLL_OK, we should have a pending callback for that fd. :param int fd: The socket fd for the postgresql connection """ try: state = self._connections[fd].poll() except (OSError, socket.error) as error: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.OperationalError('Connection error (%s)' % error) ) except (psycopg2.Error, psycopg2.Warning) as error: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception(error) else: if state == extensions.POLL_OK: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_result(True) elif state == extensions.POLL_WRITE: self._ioloop.update_handler(fd, ioloop.IOLoop.WRITE) elif state == extensions.POLL_READ: self._ioloop.update_handler(fd, ioloop.IOLoop.READ) elif state == extensions.POLL_ERROR: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.Error('Poll Error')) def _psycopg2_connect(self, kwargs): """Return a psycopg2 connection for the specified kwargs. Extend for use in async session adapters. :param dict kwargs: Keyword connection args :rtype: psycopg2.extensions.connection """ kwargs['async'] = True return psycopg2.connect(**kwargs) <MSG> Update docstrings <DFF> @@ -21,16 +21,36 @@ LOGGER = logging.getLogger(__name__) class TornadoSession(session.Session): - """Session class for Tornado asynchronous applications. Using + """Session class for Tornado asynchronous applications. Uses + ``tornado.gen.coroutine`` to wrap API methods for use in Tornado. - Unlike `queries.Session.query` and `queries.Session.callproc`, the - `TornadoSession.query` and `TornadoSession.callproc` methods are not + 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 + :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, @@ -42,10 +62,11 @@ class TornadoSession(session.Session): :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 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 @@ -55,8 +76,21 @@ class TornadoSession(session.Session): self._use_pool = use_pool @gen.coroutine - def callproc(self, name, 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, returning the results + as a list. If no results are returned, the method will return None + instead. + + .. 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 connection, fd, status = self._connect() @@ -75,7 +109,7 @@ class TornadoSession(session.Session): # Get the cursor, execute the query and wait for the result cursor = self._get_cursor(connection) - cursor.callproc(name, parameters) + cursor.callproc(name, args) yield gen.Wait((self, fd)) # If there was an exception, cleanup, then raise it @@ -96,9 +130,96 @@ class TornadoSession(session.Session): # Return the result if there are any raise gen.Return(result) + @gen.coroutine + def listen(self, channel, callback): + """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 + + """ + # 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) + + # Loop while we have listeners and a channel + 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): + """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', + {'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 connection, fd, status = self._connect() @@ -138,7 +259,42 @@ class TornadoSession(session.Session): # Return the result if there are any raise gen.Return(result) + @gen.coroutine + def unlisten(self, channel): + """Cancel a listening on a channel. + + ..code:: python + + yield self.session.unlisten('channel-name') + + :param str channel: The channel to stop listening on + + """ + if channel not in self._listeners: + raise ValueError("No listeners for specified channel") + + # Get the fd and cursor, then remove the listener + fd, cursor = self._listeners[channel] + del self._listeners[channel] + + # Call the callback waiting in the LISTEN loop + self._callbacks[fd]((self, fd)) + + # Create a callback, unlisten and wait for the result + self._callbacks[fd] = yield gen.Callback((self, fd)) + cursor.execute("UNLISTEN %s;" % channel) + yield gen.Wait((self, fd)) + + # 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. + + :rtype: tuple(psycopg2._psycopg.connection, int, int) + + """ connection = super(TornadoSession, self)._connect() fd, status = connection.fileno(), connection.status
163
Update docstrings
7
.py
py
bsd-3-clause
gmr/queries
1127
<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='gavinmroy@gmail.com', 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.8.4', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="gavinmroy@gmail.com", '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 metadata everywhere. First release this year? <DFF> @@ -29,7 +29,7 @@ classifiers = ['Development Status :: 5 - Production/Stable', 'Topic :: Software Development :: Libraries'] setup(name='queries', - version='1.8.4', + version='1.8.10', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="gavinmroy@gmail.com",
1
Bump metadata everywhere.
1
.py
py
bsd-3-clause
gmr/queries
1128
<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='gavinmroy@gmail.com', 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.8.4', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="gavinmroy@gmail.com", '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 metadata everywhere. First release this year? <DFF> @@ -29,7 +29,7 @@ classifiers = ['Development Status :: 5 - Production/Stable', 'Topic :: Software Development :: Libraries'] setup(name='queries', - version='1.8.4', + version='1.8.10', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="gavinmroy@gmail.com",
1
Bump metadata everywhere.
1
.py
py
bsd-3-clause
gmr/queries
1129
<NME> session_tests.py <BEF> """ Tests for functionality in the session module """ import hashlib import logging import unittest import unittest from queries import session # 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 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> Fix docstrings <DFF> @@ -9,3 +9,4 @@ except ImportError: import unittest from queries import session +
1
Fix docstrings
0
.py
py
bsd-3-clause
gmr/queries
1130
<NME> session_tests.py <BEF> """ Tests for functionality in the session module """ import hashlib import logging import unittest import unittest from queries import session # 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 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> Fix docstrings <DFF> @@ -9,3 +9,4 @@ except ImportError: import unittest from queries import session +
1
Fix docstrings
0
.py
py
bsd-3-clause
gmr/queries
1131
<NME> index.rst <BEF> ADDFILE <MSG> Base docs structure <DFF> @@ -0,0 +1,22 @@ +.. Queries documentation master file, created by + sphinx-quickstart on Fri Apr 25 10:36:39 2014. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to Queries's documentation! +=================================== + +Contents: + +.. toctree:: + :maxdepth: 2 + + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` +
22
Base docs structure
0
.rst
rst
bsd-3-clause
gmr/queries
1132
<NME> index.rst <BEF> ADDFILE <MSG> Base docs structure <DFF> @@ -0,0 +1,22 @@ +.. Queries documentation master file, created by + sphinx-quickstart on Fri Apr 25 10:36:39 2014. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to Queries's documentation! +=================================== + +Contents: + +.. toctree:: + :maxdepth: 2 + + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` +
22
Base docs structure
0
.rst
rst
bsd-3-clause
gmr/queries
1133
<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 "$DOCKER_COMPOSE_PREFIX" then CWD=${PWD##*/} DOCKER_COMPOSE_PREFIX=${CWD/_/} fi COMPOSE_ARGS="-p ${DOCKER_COMPOSE_PREFIX}" test -d build || mkdir build get_exposed_port() { docker-compose ${COMPOSE_ARGS} port $1 $2 | cut -d: -f2 } docker-compose ${COMPOSE_ARGS} down --volumes --remove-orphans docker-compose ${COMPOSE_ARGS} pull docker-compose ${COMPOSE_ARGS} up -d --no-recreate CONTAINER="${DOCKER_COMPOSE_PREFIX}_postgres_1" PORT=$(get_exposed_port postgres 5432) echo "Waiting for ${CONTAINER} \c" export PG until psql -U postgres -h ${DOCKER_IP} -p ${PORT} -c 'SELECT 1' > /dev/null 2> /dev/null; do echo ".\c" sleep 1 done echo " done" cat > build/test-environment<<EOF export DOCKER_COMPOSE_PREFIX=${DOCKER_COMPOSE_PREFIX} export PGHOST=${DOCKER_IP} export PGPORT=${PORT} EOF <MSG> Use COMPOSE_PROJECT_NAME in bootstrap https://docs.docker.com/compose/reference/envvars/#compose_project_name <DFF> @@ -10,27 +10,25 @@ else fi set -e -if test -z "$DOCKER_COMPOSE_PREFIX" +if test -z "$COMPOSE_PROJECT_NAME" then CWD=${PWD##*/} - DOCKER_COMPOSE_PREFIX=${CWD/_/} + export COMPOSE_PROJECT_NAME=${CWD/_/} fi -COMPOSE_ARGS="-p ${DOCKER_COMPOSE_PREFIX}" test -d build || mkdir build get_exposed_port() { - docker-compose ${COMPOSE_ARGS} port $1 $2 | cut -d: -f2 + docker-compose port $1 $2 | cut -d: -f2 } -docker-compose ${COMPOSE_ARGS} down --volumes --remove-orphans -docker-compose ${COMPOSE_ARGS} pull -docker-compose ${COMPOSE_ARGS} up -d --no-recreate +docker-compose down --volumes --remove-orphans +docker-compose pull +docker-compose up -d --no-recreate -CONTAINER="${DOCKER_COMPOSE_PREFIX}_postgres_1" PORT=$(get_exposed_port postgres 5432) -echo "Waiting for ${CONTAINER} \c" +echo "Waiting for postgres \c" export PG until psql -U postgres -h ${DOCKER_IP} -p ${PORT} -c 'SELECT 1' > /dev/null 2> /dev/null; do echo ".\c" @@ -39,7 +37,6 @@ done echo " done" cat > build/test-environment<<EOF -export DOCKER_COMPOSE_PREFIX=${DOCKER_COMPOSE_PREFIX} export PGHOST=${DOCKER_IP} export PGPORT=${PORT} EOF
7
Use COMPOSE_PROJECT_NAME in bootstrap https://docs.docker.com/compose/reference/envvars/#compose_project_name
10
bootstrap
bsd-3-clause
gmr/queries
1134
<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 "$DOCKER_COMPOSE_PREFIX" then CWD=${PWD##*/} DOCKER_COMPOSE_PREFIX=${CWD/_/} fi COMPOSE_ARGS="-p ${DOCKER_COMPOSE_PREFIX}" test -d build || mkdir build get_exposed_port() { docker-compose ${COMPOSE_ARGS} port $1 $2 | cut -d: -f2 } docker-compose ${COMPOSE_ARGS} down --volumes --remove-orphans docker-compose ${COMPOSE_ARGS} pull docker-compose ${COMPOSE_ARGS} up -d --no-recreate CONTAINER="${DOCKER_COMPOSE_PREFIX}_postgres_1" PORT=$(get_exposed_port postgres 5432) echo "Waiting for ${CONTAINER} \c" export PG until psql -U postgres -h ${DOCKER_IP} -p ${PORT} -c 'SELECT 1' > /dev/null 2> /dev/null; do echo ".\c" sleep 1 done echo " done" cat > build/test-environment<<EOF export DOCKER_COMPOSE_PREFIX=${DOCKER_COMPOSE_PREFIX} export PGHOST=${DOCKER_IP} export PGPORT=${PORT} EOF <MSG> Use COMPOSE_PROJECT_NAME in bootstrap https://docs.docker.com/compose/reference/envvars/#compose_project_name <DFF> @@ -10,27 +10,25 @@ else fi set -e -if test -z "$DOCKER_COMPOSE_PREFIX" +if test -z "$COMPOSE_PROJECT_NAME" then CWD=${PWD##*/} - DOCKER_COMPOSE_PREFIX=${CWD/_/} + export COMPOSE_PROJECT_NAME=${CWD/_/} fi -COMPOSE_ARGS="-p ${DOCKER_COMPOSE_PREFIX}" test -d build || mkdir build get_exposed_port() { - docker-compose ${COMPOSE_ARGS} port $1 $2 | cut -d: -f2 + docker-compose port $1 $2 | cut -d: -f2 } -docker-compose ${COMPOSE_ARGS} down --volumes --remove-orphans -docker-compose ${COMPOSE_ARGS} pull -docker-compose ${COMPOSE_ARGS} up -d --no-recreate +docker-compose down --volumes --remove-orphans +docker-compose pull +docker-compose up -d --no-recreate -CONTAINER="${DOCKER_COMPOSE_PREFIX}_postgres_1" PORT=$(get_exposed_port postgres 5432) -echo "Waiting for ${CONTAINER} \c" +echo "Waiting for postgres \c" export PG until psql -U postgres -h ${DOCKER_IP} -p ${PORT} -c 'SELECT 1' > /dev/null 2> /dev/null; do echo ".\c" @@ -39,7 +37,6 @@ done echo " done" cat > build/test-environment<<EOF -export DOCKER_COMPOSE_PREFIX=${DOCKER_COMPOSE_PREFIX} export PGHOST=${DOCKER_IP} export PGPORT=${PORT} EOF
7
Use COMPOSE_PROJECT_NAME in bootstrap https://docs.docker.com/compose/reference/envvars/#compose_project_name
10
bootstrap
bsd-3-clause
gmr/queries
1135
<NME> pool.py <BEF> """ Connection Pooling """ module and re-used when the Queries object is created. """ import logging import time LOGGER = logging.getLogger() # Time-to-live in the pool TTL = 60 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 global CONNECTIONS if uri not in CONNECTIONS: CONNECTIONS[uri] = {CLIENTS: 1, HANDLE: connection, LAST: 0} LOGGER.info('%s: added to module pool', uri) return True return False :raises: ConnectionBusyError """ LOGGER.debug('Connection %s closing', self.id) if self.busy and not self.closed: raise ConnectionBusyError(self) for uri in list(CONNECTIONS.keys()): if (not CONNECTIONS[uri][CLIENTS] and (time.time() > CONNECTIONS[uri][LAST] + TTL)): LOGGER.info('Removing expired connection: %s', uri) del CONNECTIONS[uri] @property def closed(self): """Return if the psycopg2 connection is closed. :rtype: bool """ check_for_unused_expired_connections() if uri in CONNECTIONS: LOGGER.debug('Returning cached connection and incrementing counter') CONNECTIONS[uri][CLIENTS] += 1 return CONNECTIONS[uri][HANDLE] return None by a session that still exists. :rtype: bool """ if self.handle.isexecuting(): return True elif self.used_by is None: """ global CONNECTIONS if uri in CONNECTIONS: LOGGER.debug('%s: decrementing client count', uri) CONNECTIONS[uri][CLIENTS] -= 1 if not CONNECTIONS[uri][CLIENTS]: LOGGER.debug('%s: updating last client time', uri) CONNECTIONS[uri][LAST] = int(time.time()) """ return self.handle.isexecuting() def free(self): """ global CONNECTIONS if uri in CONNECTIONS: LOGGER.debug('%s: decrementing client count', uri) del CONNECTIONS[uri] """ 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 :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> Remove logging <DFF> @@ -5,12 +5,8 @@ Implement basic connection pooling where connections are kept attached to this module and re-used when the Queries object is created. """ -import logging import time - -LOGGER = logging.getLogger() - # Time-to-live in the pool TTL = 60 @@ -33,7 +29,6 @@ def add_connection(uri, connection): global CONNECTIONS if uri not in CONNECTIONS: CONNECTIONS[uri] = {CLIENTS: 1, HANDLE: connection, LAST: 0} - LOGGER.info('%s: added to module pool', uri) return True return False @@ -47,7 +42,6 @@ def check_for_unused_expired_connections(): for uri in list(CONNECTIONS.keys()): if (not CONNECTIONS[uri][CLIENTS] and (time.time() > CONNECTIONS[uri][LAST] + TTL)): - LOGGER.info('Removing expired connection: %s', uri) del CONNECTIONS[uri] @@ -61,7 +55,6 @@ def get_connection(uri): """ check_for_unused_expired_connections() if uri in CONNECTIONS: - LOGGER.debug('Returning cached connection and incrementing counter') CONNECTIONS[uri][CLIENTS] += 1 return CONNECTIONS[uri][HANDLE] return None @@ -76,10 +69,8 @@ def free_connection(uri): """ global CONNECTIONS if uri in CONNECTIONS: - LOGGER.debug('%s: decrementing client count', uri) CONNECTIONS[uri][CLIENTS] -= 1 if not CONNECTIONS[uri][CLIENTS]: - LOGGER.debug('%s: updating last client time', uri) CONNECTIONS[uri][LAST] = int(time.time()) @@ -91,5 +82,4 @@ def remove_connection(uri): """ global CONNECTIONS if uri in CONNECTIONS: - LOGGER.debug('%s: decrementing client count', uri) del CONNECTIONS[uri]
0
Remove logging
10
.py
py
bsd-3-clause
gmr/queries
1136
<NME> pool.py <BEF> """ Connection Pooling """ module and re-used when the Queries object is created. """ import logging import time LOGGER = logging.getLogger() # Time-to-live in the pool TTL = 60 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 global CONNECTIONS if uri not in CONNECTIONS: CONNECTIONS[uri] = {CLIENTS: 1, HANDLE: connection, LAST: 0} LOGGER.info('%s: added to module pool', uri) return True return False :raises: ConnectionBusyError """ LOGGER.debug('Connection %s closing', self.id) if self.busy and not self.closed: raise ConnectionBusyError(self) for uri in list(CONNECTIONS.keys()): if (not CONNECTIONS[uri][CLIENTS] and (time.time() > CONNECTIONS[uri][LAST] + TTL)): LOGGER.info('Removing expired connection: %s', uri) del CONNECTIONS[uri] @property def closed(self): """Return if the psycopg2 connection is closed. :rtype: bool """ check_for_unused_expired_connections() if uri in CONNECTIONS: LOGGER.debug('Returning cached connection and incrementing counter') CONNECTIONS[uri][CLIENTS] += 1 return CONNECTIONS[uri][HANDLE] return None by a session that still exists. :rtype: bool """ if self.handle.isexecuting(): return True elif self.used_by is None: """ global CONNECTIONS if uri in CONNECTIONS: LOGGER.debug('%s: decrementing client count', uri) CONNECTIONS[uri][CLIENTS] -= 1 if not CONNECTIONS[uri][CLIENTS]: LOGGER.debug('%s: updating last client time', uri) CONNECTIONS[uri][LAST] = int(time.time()) """ return self.handle.isexecuting() def free(self): """ global CONNECTIONS if uri in CONNECTIONS: LOGGER.debug('%s: decrementing client count', uri) del CONNECTIONS[uri] """ 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 :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> Remove logging <DFF> @@ -5,12 +5,8 @@ Implement basic connection pooling where connections are kept attached to this module and re-used when the Queries object is created. """ -import logging import time - -LOGGER = logging.getLogger() - # Time-to-live in the pool TTL = 60 @@ -33,7 +29,6 @@ def add_connection(uri, connection): global CONNECTIONS if uri not in CONNECTIONS: CONNECTIONS[uri] = {CLIENTS: 1, HANDLE: connection, LAST: 0} - LOGGER.info('%s: added to module pool', uri) return True return False @@ -47,7 +42,6 @@ def check_for_unused_expired_connections(): for uri in list(CONNECTIONS.keys()): if (not CONNECTIONS[uri][CLIENTS] and (time.time() > CONNECTIONS[uri][LAST] + TTL)): - LOGGER.info('Removing expired connection: %s', uri) del CONNECTIONS[uri] @@ -61,7 +55,6 @@ def get_connection(uri): """ check_for_unused_expired_connections() if uri in CONNECTIONS: - LOGGER.debug('Returning cached connection and incrementing counter') CONNECTIONS[uri][CLIENTS] += 1 return CONNECTIONS[uri][HANDLE] return None @@ -76,10 +69,8 @@ def free_connection(uri): """ global CONNECTIONS if uri in CONNECTIONS: - LOGGER.debug('%s: decrementing client count', uri) CONNECTIONS[uri][CLIENTS] -= 1 if not CONNECTIONS[uri][CLIENTS]: - LOGGER.debug('%s: updating last client time', uri) CONNECTIONS[uri][LAST] = int(time.time()) @@ -91,5 +82,4 @@ def remove_connection(uri): """ global CONNECTIONS if uri in CONNECTIONS: - LOGGER.debug('%s: decrementing client count', uri) del CONNECTIONS[uri]
0
Remove logging
10
.py
py
bsd-3-clause
gmr/queries
1137
<NME> integration_tests.py <BEF> ADDFILE <MSG> Add integration tests <DFF> @@ -0,0 +1,79 @@ +import datetime +try: + import unittest2 as unittest +except ImportError: + import unittest + +import queries +from tornado import testing + + +class SessionIntegrationTests(unittest.TestCase): + + def setUp(self): + uri = queries.uri('localhost', 5432, 'postgres', 'postgres') + try: + self.session = queries.Session(uri, pool_max_size=10) + except queries.OperationalError as error: + raise unittest.SkipTest(str(error).split('\n')[0]) + + def test_query_returns_results_object(self): + self.assertIsInstance(self.session.query('SELECT 1 AS value'), + queries.Results) + + def test_query_result_value(self): + result = self.session.query('SELECT 1 AS value') + self.assertDictEqual(result.as_dict(), {'value': 1}) + + def test_query_multirow_result_has_at_least_three_rows(self): + result = self.session.query('SELECT * FROM pg_stat_database') + self.assertGreaterEqual(result.count(), 3) + + def test_callproc_returns_results_object(self): + timestamp = int(datetime.datetime.now().strftime('%s')) + self.assertIsInstance(self.session.callproc('to_timestamp', + [timestamp]), + queries.Results) + + def test_callproc_mod_result_value(self): + result = self.session.callproc('mod', [6, 4]) + self.assertEqual(6 % 4, result[0]['mod']) + + +class TornadoSessionIntegrationTests(testing.AsyncTestCase): + + def setUp(self): + self.io_loop = self.get_new_ioloop() + uri = queries.uri('localhost', 5432, 'postgres', 'postgres') + try: + self.session = queries.TornadoSession(uri, + pool_max_size=10, + io_loop=self.io_loop) + except queries.OperationalError as error: + raise unittest.SkipTest(str(error).split('\n')[0]) + + @testing.gen_test + def test_query_returns_results_object(self): + result = yield self.session.query('SELECT 1 AS value') + self.assertIsInstance(result, queries.Results) + + @testing.gen_test + def test_query_result_value(self): + result = yield self.session.query('SELECT 1 AS value') + self.assertDictEqual(result.as_dict(), {'value': 1}) + + @testing.gen_test + def test_query_multirow_result_has_at_least_three_rows(self): + result = yield self.session.query('SELECT * FROM pg_stat_database') + self.assertGreaterEqual(result.count(), 3) + + @testing.gen_test + def test_callproc_returns_results_object(self): + timestamp = int(datetime.datetime.now().strftime('%s')) + result = yield self.session.callproc('to_timestamp', [timestamp]) + self.assertIsInstance(result, queries.Results) + + @testing.gen_test + def test_callproc_mod_result_value(self): + result = yield self.session.callproc('mod', [6, 4]) + self.assertEqual(6 % 4, result[0]['mod'])
79
Add integration tests
0
.py
py
bsd-3-clause
gmr/queries
1138
<NME> integration_tests.py <BEF> ADDFILE <MSG> Add integration tests <DFF> @@ -0,0 +1,79 @@ +import datetime +try: + import unittest2 as unittest +except ImportError: + import unittest + +import queries +from tornado import testing + + +class SessionIntegrationTests(unittest.TestCase): + + def setUp(self): + uri = queries.uri('localhost', 5432, 'postgres', 'postgres') + try: + self.session = queries.Session(uri, pool_max_size=10) + except queries.OperationalError as error: + raise unittest.SkipTest(str(error).split('\n')[0]) + + def test_query_returns_results_object(self): + self.assertIsInstance(self.session.query('SELECT 1 AS value'), + queries.Results) + + def test_query_result_value(self): + result = self.session.query('SELECT 1 AS value') + self.assertDictEqual(result.as_dict(), {'value': 1}) + + def test_query_multirow_result_has_at_least_three_rows(self): + result = self.session.query('SELECT * FROM pg_stat_database') + self.assertGreaterEqual(result.count(), 3) + + def test_callproc_returns_results_object(self): + timestamp = int(datetime.datetime.now().strftime('%s')) + self.assertIsInstance(self.session.callproc('to_timestamp', + [timestamp]), + queries.Results) + + def test_callproc_mod_result_value(self): + result = self.session.callproc('mod', [6, 4]) + self.assertEqual(6 % 4, result[0]['mod']) + + +class TornadoSessionIntegrationTests(testing.AsyncTestCase): + + def setUp(self): + self.io_loop = self.get_new_ioloop() + uri = queries.uri('localhost', 5432, 'postgres', 'postgres') + try: + self.session = queries.TornadoSession(uri, + pool_max_size=10, + io_loop=self.io_loop) + except queries.OperationalError as error: + raise unittest.SkipTest(str(error).split('\n')[0]) + + @testing.gen_test + def test_query_returns_results_object(self): + result = yield self.session.query('SELECT 1 AS value') + self.assertIsInstance(result, queries.Results) + + @testing.gen_test + def test_query_result_value(self): + result = yield self.session.query('SELECT 1 AS value') + self.assertDictEqual(result.as_dict(), {'value': 1}) + + @testing.gen_test + def test_query_multirow_result_has_at_least_three_rows(self): + result = yield self.session.query('SELECT * FROM pg_stat_database') + self.assertGreaterEqual(result.count(), 3) + + @testing.gen_test + def test_callproc_returns_results_object(self): + timestamp = int(datetime.datetime.now().strftime('%s')) + result = yield self.session.callproc('to_timestamp', [timestamp]) + self.assertIsInstance(result, queries.Results) + + @testing.gen_test + def test_callproc_mod_result_value(self): + result = yield self.session.callproc('mod', [6, 4]) + self.assertEqual(6 % 4, result[0]['mod'])
79
Add integration tests
0
.py
py
bsd-3-clause
gmr/queries
1139
<NME> pool_exception_tests.py <BEF> ADDFILE <MSG> Add pool exception tests <DFF> @@ -0,0 +1,107 @@ +""" +Tests for Exceptions in queries.pool + +""" +import mock +try: + import unittest2 as unittest +except ImportError: + import unittest +import uuid + +from queries import pool + + +class ActiveConnectionErrorTestCase(unittest.TestCase): + + def setUp(self): + self.pid = uuid.uuid4() + self.connection = mock.Mock() + self.connection.id = uuid.uuid4() + self.exception = pool.ActiveConnectionError(self.pid, self.connection) + + def test_pid_is_assigned(self): + self.assertEqual(self.exception.pid, self.pid) + + def test_cid_is_assigned(self): + self.assertEqual(self.exception.cid, self.connection.id) + + def test_str_value(self): + expectation = 'Connection %s in pool %s is active' % \ + (self.connection.id, self.pid) + self.assertEqual(str(self.exception), expectation) + + +class ActivePoolErrorTestCase(unittest.TestCase): + + def setUp(self): + self.pid = uuid.uuid4() + self.exception = pool.ActivePoolError(self.pid) + + def test_pid_is_assigned(self): + self.assertEqual(self.exception.pid, self.pid) + + def test_str_value(self): + expectation = 'Pool %s has at least one active connection' % self.pid + self.assertEqual(str(self.exception), expectation) + + +class ConnectionBusyErrorTestCase(unittest.TestCase): + + def setUp(self): + self.cid = uuid.uuid4() + self.exception = pool.ConnectionBusyError(self.cid) + + def test_cid_is_assigned(self): + self.assertEqual(self.exception.cid, self.cid) + + def test_str_value(self): + expectation = 'Connection %s is busy' % self.cid + self.assertEqual(str(self.exception), expectation) + + +class ConnectionNotFoundErrorTestCase(unittest.TestCase): + + def setUp(self): + self.pid = uuid.uuid4() + self.cid = uuid.uuid4() + self.exception = pool.ConnectionNotFoundError(self.pid, self.cid) + + def test_cid_is_assigned(self): + self.assertEqual(self.exception.cid, self.cid) + + def test_pid_is_assigned(self): + self.assertEqual(self.exception.pid, self.pid) + + def test_str_value(self): + expectation = 'Connection %s not found in pool %s' % (self.cid, + self.pid) + self.assertEqual(str(self.exception), expectation) + + +class NoIdleConnectionsErrorTestCase(unittest.TestCase): + + def setUp(self): + self.pid = uuid.uuid4() + self.exception = pool.NoIdleConnectionsError(self.pid) + + def test_pid_is_assigned(self): + self.assertEqual(self.exception.pid, self.pid) + + def test_str_value(self): + expectation = 'Pool %s has no idle connections' % self.pid + self.assertEqual(str(self.exception), expectation) + + +class PoolFullErrorTestCase(unittest.TestCase): + + def setUp(self): + self.pid = uuid.uuid4() + self.exception = pool.PoolFullError(self.pid) + + def test_pid_is_assigned(self): + self.assertEqual(self.exception.pid, self.pid) + + def test_str_value(self): + expectation = 'Pool %s is at its maximum capacity' % self.pid + self.assertEqual(str(self.exception), expectation)
107
Add pool exception tests
0
.py
py
bsd-3-clause
gmr/queries
1140
<NME> pool_exception_tests.py <BEF> ADDFILE <MSG> Add pool exception tests <DFF> @@ -0,0 +1,107 @@ +""" +Tests for Exceptions in queries.pool + +""" +import mock +try: + import unittest2 as unittest +except ImportError: + import unittest +import uuid + +from queries import pool + + +class ActiveConnectionErrorTestCase(unittest.TestCase): + + def setUp(self): + self.pid = uuid.uuid4() + self.connection = mock.Mock() + self.connection.id = uuid.uuid4() + self.exception = pool.ActiveConnectionError(self.pid, self.connection) + + def test_pid_is_assigned(self): + self.assertEqual(self.exception.pid, self.pid) + + def test_cid_is_assigned(self): + self.assertEqual(self.exception.cid, self.connection.id) + + def test_str_value(self): + expectation = 'Connection %s in pool %s is active' % \ + (self.connection.id, self.pid) + self.assertEqual(str(self.exception), expectation) + + +class ActivePoolErrorTestCase(unittest.TestCase): + + def setUp(self): + self.pid = uuid.uuid4() + self.exception = pool.ActivePoolError(self.pid) + + def test_pid_is_assigned(self): + self.assertEqual(self.exception.pid, self.pid) + + def test_str_value(self): + expectation = 'Pool %s has at least one active connection' % self.pid + self.assertEqual(str(self.exception), expectation) + + +class ConnectionBusyErrorTestCase(unittest.TestCase): + + def setUp(self): + self.cid = uuid.uuid4() + self.exception = pool.ConnectionBusyError(self.cid) + + def test_cid_is_assigned(self): + self.assertEqual(self.exception.cid, self.cid) + + def test_str_value(self): + expectation = 'Connection %s is busy' % self.cid + self.assertEqual(str(self.exception), expectation) + + +class ConnectionNotFoundErrorTestCase(unittest.TestCase): + + def setUp(self): + self.pid = uuid.uuid4() + self.cid = uuid.uuid4() + self.exception = pool.ConnectionNotFoundError(self.pid, self.cid) + + def test_cid_is_assigned(self): + self.assertEqual(self.exception.cid, self.cid) + + def test_pid_is_assigned(self): + self.assertEqual(self.exception.pid, self.pid) + + def test_str_value(self): + expectation = 'Connection %s not found in pool %s' % (self.cid, + self.pid) + self.assertEqual(str(self.exception), expectation) + + +class NoIdleConnectionsErrorTestCase(unittest.TestCase): + + def setUp(self): + self.pid = uuid.uuid4() + self.exception = pool.NoIdleConnectionsError(self.pid) + + def test_pid_is_assigned(self): + self.assertEqual(self.exception.pid, self.pid) + + def test_str_value(self): + expectation = 'Pool %s has no idle connections' % self.pid + self.assertEqual(str(self.exception), expectation) + + +class PoolFullErrorTestCase(unittest.TestCase): + + def setUp(self): + self.pid = uuid.uuid4() + self.exception = pool.PoolFullError(self.pid) + + def test_pid_is_assigned(self): + self.assertEqual(self.exception.pid, self.pid) + + def test_str_value(self): + expectation = 'Pool %s is at its maximum capacity' % self.pid + self.assertEqual(str(self.exception), expectation)
107
Add pool exception tests
0
.py
py
bsd-3-clause
gmr/queries
1141
<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'} .. |Version| image:: https://badge.fury.io/py/queries.svg? :target: http://badge.fury.io/py/queries 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> Add pgsql_wrpaper note in README [ci-skip] <DFF> @@ -79,6 +79,11 @@ Using the Session object as a context manager: {'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
5
Add pgsql_wrpaper note in README
0
.rst
rst
bsd-3-clause
gmr/queries
1142
<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'} .. |Version| image:: https://badge.fury.io/py/queries.svg? :target: http://badge.fury.io/py/queries 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> Add pgsql_wrpaper note in README [ci-skip] <DFF> @@ -79,6 +79,11 @@ Using the Session object as a context manager: {'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
5
Add pgsql_wrpaper note in README
0
.rst
rst
bsd-3-clause
gmr/queries
1143
<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') maintainer_email="gavinmroy@gmail.com", url="https://github.com/gmr/queries", install_requires=install_requires, license=open('LICENSE').read(), package_data={'': ['LICENSE', 'README.md']}, py_modules=['pgsql_wrapper'], 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> Add extras_requires for tornado support <DFF> @@ -16,6 +16,7 @@ setup(name='queries', maintainer_email="gavinmroy@gmail.com", url="https://github.com/gmr/queries", install_requires=install_requires, + extras_require={'tornado': 'tornado'}, license=open('LICENSE').read(), package_data={'': ['LICENSE', 'README.md']}, py_modules=['pgsql_wrapper'],
1
Add extras_requires for tornado support
0
.py
py
bsd-3-clause
gmr/queries
1144
<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') maintainer_email="gavinmroy@gmail.com", url="https://github.com/gmr/queries", install_requires=install_requires, license=open('LICENSE').read(), package_data={'': ['LICENSE', 'README.md']}, py_modules=['pgsql_wrapper'], 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> Add extras_requires for tornado support <DFF> @@ -16,6 +16,7 @@ setup(name='queries', maintainer_email="gavinmroy@gmail.com", url="https://github.com/gmr/queries", install_requires=install_requires, + extras_require={'tornado': 'tornado'}, license=open('LICENSE').read(), package_data={'': ['LICENSE', 'README.md']}, py_modules=['pgsql_wrapper'],
1
Add extras_requires for tornado support
0
.py
py
bsd-3-clause
gmr/queries
1145
<NME> results.py <BEF> """ query or callproc Results """ import logging import psycopg2 LOGGER = logging.getLogger(__name__) class Results(object): """The :py:class:`Results` class contains the results returned from :py:meth:`Session.query <queries.Session.query>` and :py:meth:`Session.callproc <queries.Session.callproc>`. It is able to act as an iterator and provides many different methods for accessing the information about and results from a query. :param psycopg2.extensions.cursor cursor: The cursor for the results """ def __init__(self, cursor): self.cursor = cursor def __getitem__(self, item): """Fetch an individual row from the result set :rtype: mixed :raises: IndexError """ try: self.cursor.scroll(item, 'absolute') except psycopg2.ProgrammingError: raise IndexError('No such row') else: return self.cursor.fetchone() def __iter__(self): """Iterate through the result set :rtype: mixed """ if self.cursor.rowcount: self._rewind() for row in self.cursor: yield row def __len__(self): """Return the number of rows that were returned from the query :rtype: int """ return self.cursor.rowcount if self.cursor.rowcount >= 0 else 0 def __nonzero__(self): return bool(self.cursor.rowcount) def __bool__(self): return self.__nonzero__() def __repr__(self): return '<queries.%s rows=%s>' % (self.__class__.__name__, len(self)) def as_dict(self): """Return a single row result as a dictionary. If the results contain multiple rows, a :py:class:`ValueError` will be raised. :return: dict :raises: ValueError """ if not self.cursor.rowcount: return {} self._rewind() if self.cursor.rowcount == 1: return dict(self.cursor.fetchone()) else: raise ValueError('More than one row') def count(self): """Return the number of rows that were returned from the query :rtype: int """ return self.cursor.rowcount def free(self): connections. """ raise NotImplementedError def items(self): """Return all of the rows that are in the result set. """Return all of the rows that are in the result set. :rtype: list """ if not self.cursor.rowcount: return [] self.cursor.scroll(0, 'absolute') return self.cursor.fetchall() @property def rownumber(self): """Return the current offset of the result set :rtype: int """ return self.cursor.rownumber @property def query(self): """Return a read-only value of the query that was submitted to PostgreSQL. :rtype: str """ return self.cursor.query @property def status(self): """Return the status message returned by PostgreSQL after the query was executed. :rtype: str """ return self.cursor.statusmessage def _rewind(self): """Rewind the cursor to the first row""" self.cursor.scroll(0, 'absolute') <MSG> Dont raise NotImplementedError <DFF> @@ -92,7 +92,7 @@ class Results(object): connections. """ - raise NotImplementedError + LOGGER.debug('Invoking synchronous free has no effect') def items(self): """Return all of the rows that are in the result set.
1
Dont raise NotImplementedError
1
.py
py
bsd-3-clause
gmr/queries
1146
<NME> results.py <BEF> """ query or callproc Results """ import logging import psycopg2 LOGGER = logging.getLogger(__name__) class Results(object): """The :py:class:`Results` class contains the results returned from :py:meth:`Session.query <queries.Session.query>` and :py:meth:`Session.callproc <queries.Session.callproc>`. It is able to act as an iterator and provides many different methods for accessing the information about and results from a query. :param psycopg2.extensions.cursor cursor: The cursor for the results """ def __init__(self, cursor): self.cursor = cursor def __getitem__(self, item): """Fetch an individual row from the result set :rtype: mixed :raises: IndexError """ try: self.cursor.scroll(item, 'absolute') except psycopg2.ProgrammingError: raise IndexError('No such row') else: return self.cursor.fetchone() def __iter__(self): """Iterate through the result set :rtype: mixed """ if self.cursor.rowcount: self._rewind() for row in self.cursor: yield row def __len__(self): """Return the number of rows that were returned from the query :rtype: int """ return self.cursor.rowcount if self.cursor.rowcount >= 0 else 0 def __nonzero__(self): return bool(self.cursor.rowcount) def __bool__(self): return self.__nonzero__() def __repr__(self): return '<queries.%s rows=%s>' % (self.__class__.__name__, len(self)) def as_dict(self): """Return a single row result as a dictionary. If the results contain multiple rows, a :py:class:`ValueError` will be raised. :return: dict :raises: ValueError """ if not self.cursor.rowcount: return {} self._rewind() if self.cursor.rowcount == 1: return dict(self.cursor.fetchone()) else: raise ValueError('More than one row') def count(self): """Return the number of rows that were returned from the query :rtype: int """ return self.cursor.rowcount def free(self): connections. """ raise NotImplementedError def items(self): """Return all of the rows that are in the result set. """Return all of the rows that are in the result set. :rtype: list """ if not self.cursor.rowcount: return [] self.cursor.scroll(0, 'absolute') return self.cursor.fetchall() @property def rownumber(self): """Return the current offset of the result set :rtype: int """ return self.cursor.rownumber @property def query(self): """Return a read-only value of the query that was submitted to PostgreSQL. :rtype: str """ return self.cursor.query @property def status(self): """Return the status message returned by PostgreSQL after the query was executed. :rtype: str """ return self.cursor.statusmessage def _rewind(self): """Rewind the cursor to the first row""" self.cursor.scroll(0, 'absolute') <MSG> Dont raise NotImplementedError <DFF> @@ -92,7 +92,7 @@ class Results(object): connections. """ - raise NotImplementedError + LOGGER.debug('Invoking synchronous free has no effect') def items(self): """Return all of the rows that are in the result set.
1
Dont raise NotImplementedError
1
.py
py
bsd-3-clause
gmr/queries
1147
<NME> session_tests.py <BEF> """ Tests for functionality in the session module """ import mock try: import unittest2 as unittest except ImportError: import unittest from queries import session 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 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> Initial coverage of queries.Session <DFF> @@ -2,11 +2,130 @@ Tests for functionality in the session module """ +import hashlib import mock try: import unittest2 as unittest except ImportError: import unittest +from psycopg2 import extras +import psycopg2 + +from queries import pool +from queries import results from queries import session + +class SessionTests(unittest.TestCase): + + URI = 'pgsql://foo:bar@localhost:5432/foo' + + + def setUp(self): + self.conn = mock.Mock() + self._connect = mock.Mock(return_value=self.conn) + self.cursor = mock.Mock() + self._get_cursor = mock.Mock(return_value=self.cursor) + self._autocommit = mock.Mock() + with mock.patch.multiple('queries.session.Session', + _connect=self._connect, + _get_cursor=self._get_cursor, + _autocommit=self._autocommit): + pool.PoolManager.create = self.pm_create = mock.Mock() + pool.PoolManager.is_full = self.pm_is_full = mock.PropertyMock() + pool.PoolManager.remove_connection = self.pm_rem_conn = mock.Mock() + self.obj = session.Session(self.URI) + + def test_init_gets_poolmanager_instance(self): + instance = pool.PoolManager.instance() + self.assertEqual(self.obj._pool_manager, instance) + + def test_init_sets_uri(self): + self.assertEqual(self.obj._uri, self.URI) + + def test_init_invokes_poolmanager_create(self): + self.obj._pool_manager.create.assert_called_once_with( + self.obj.pid, + pool.DEFAULT_IDLE_TTL, + pool.DEFAULT_MAX_SIZE) + + def test_init_invokes_connection(self): + self._connect.assert_called_once_with() + + def test_init_sets_cursorfactory(self): + self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor) + + def test_init_gets_cursor(self): + self._get_cursor.assert_called_once_with(self.conn) + + def test_init_sets_autocommit(self): + self._autocommit.assert_called_once_with() + + def test_backend_pid_invokes_conn_backend_pid(self): + self.conn.get_backend_pid = get_backend_pid = mock.Mock() + val = self.obj.backend_pid + get_backend_pid.assert_called_once_with() + + def test_callproc_invokes_cursor_callproc(self): + self.cursor.callproc = mock.Mock() + args = ('foo', ['bar', 'baz']) + self.obj.callproc(*args) + self.cursor.callproc.assert_called_once_with(*args) + + def test_callproc_returns_results(self): + self.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.pm_rem_conn.assert_called_once_with(self.obj.pid, self.conn) + + 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.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 = str(hashlib.md5(self.URI.encode('utf-8')).hexdigest()) + self.assertEqual(self.obj.pid, expectation) + + def test_query_invokes_cursor_execute(self): + self.cursor.execute = mock.Mock() + args = ('SELECT * FROM foo', ['bar', 'baz']) + self.obj.query(*args) + self.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)
119
Initial coverage of queries.Session
0
.py
py
bsd-3-clause
gmr/queries
1148
<NME> session_tests.py <BEF> """ Tests for functionality in the session module """ import mock try: import unittest2 as unittest except ImportError: import unittest from queries import session 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 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> Initial coverage of queries.Session <DFF> @@ -2,11 +2,130 @@ Tests for functionality in the session module """ +import hashlib import mock try: import unittest2 as unittest except ImportError: import unittest +from psycopg2 import extras +import psycopg2 + +from queries import pool +from queries import results from queries import session + +class SessionTests(unittest.TestCase): + + URI = 'pgsql://foo:bar@localhost:5432/foo' + + + def setUp(self): + self.conn = mock.Mock() + self._connect = mock.Mock(return_value=self.conn) + self.cursor = mock.Mock() + self._get_cursor = mock.Mock(return_value=self.cursor) + self._autocommit = mock.Mock() + with mock.patch.multiple('queries.session.Session', + _connect=self._connect, + _get_cursor=self._get_cursor, + _autocommit=self._autocommit): + pool.PoolManager.create = self.pm_create = mock.Mock() + pool.PoolManager.is_full = self.pm_is_full = mock.PropertyMock() + pool.PoolManager.remove_connection = self.pm_rem_conn = mock.Mock() + self.obj = session.Session(self.URI) + + def test_init_gets_poolmanager_instance(self): + instance = pool.PoolManager.instance() + self.assertEqual(self.obj._pool_manager, instance) + + def test_init_sets_uri(self): + self.assertEqual(self.obj._uri, self.URI) + + def test_init_invokes_poolmanager_create(self): + self.obj._pool_manager.create.assert_called_once_with( + self.obj.pid, + pool.DEFAULT_IDLE_TTL, + pool.DEFAULT_MAX_SIZE) + + def test_init_invokes_connection(self): + self._connect.assert_called_once_with() + + def test_init_sets_cursorfactory(self): + self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor) + + def test_init_gets_cursor(self): + self._get_cursor.assert_called_once_with(self.conn) + + def test_init_sets_autocommit(self): + self._autocommit.assert_called_once_with() + + def test_backend_pid_invokes_conn_backend_pid(self): + self.conn.get_backend_pid = get_backend_pid = mock.Mock() + val = self.obj.backend_pid + get_backend_pid.assert_called_once_with() + + def test_callproc_invokes_cursor_callproc(self): + self.cursor.callproc = mock.Mock() + args = ('foo', ['bar', 'baz']) + self.obj.callproc(*args) + self.cursor.callproc.assert_called_once_with(*args) + + def test_callproc_returns_results(self): + self.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.pm_rem_conn.assert_called_once_with(self.obj.pid, self.conn) + + 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.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 = str(hashlib.md5(self.URI.encode('utf-8')).hexdigest()) + self.assertEqual(self.obj.pid, expectation) + + def test_query_invokes_cursor_execute(self): + self.cursor.execute = mock.Mock() + args = ('SELECT * FROM foo', ['bar', 'baz']) + self.obj.query(*args) + self.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)
119
Initial coverage of queries.Session
0
.py
py
bsd-3-clause
gmr/queries
1149
<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: - if [[ $TRAVIS_PYTHON_VERSION != 'pypy' ]]; then pip install -r requirements.pip; fi - if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then pip install -r requirements.pypy; fi script: nosetests --with-coverage --cover-package=queries after_success: - coveralls install: - pip install awscli - pip install -r requires/testing.txt - python setup.py develop script: nosetests after_success: - aws s3 cp .coverage "s3://com-gavinroy-travis/queries/$TRAVIS_BUILD_NUMBER/.coverage.${TRAVIS_PYTHON_VERSION}" jobs: include: - python: 2.7 - python: 3.4 - python: 3.5 - python: 3.6 - python: 3.7 - python: 3.8 - stage: coverage if: repo = gmr/queries services: [] python: 3.7 install: - pip install awscli coverage codecov script: - mkdir coverage - aws s3 cp --recursive s3://com-gavinroy-travis/queries/$TRAVIS_BUILD_NUMBER/ coverage - cd coverage - coverage combine - cd .. - mv coverage/.coverage . - coverage report after_success: codecov - stage: deploy if: repo = gmr/queries python: 3.6 services: [] install: true script: true after_success: true deploy: distributions: sdist bdist_wheel provider: pypi user: crad on: tags: true all_branches: true password: secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= <MSG> Add verbose flag to see where pypy is hanging (on travis) <DFF> @@ -13,7 +13,7 @@ install: - if [[ $TRAVIS_PYTHON_VERSION != 'pypy' ]]; then pip install -r requirements.pip; fi - if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then pip install -r requirements.pypy; fi -script: nosetests --with-coverage --cover-package=queries +script: nosetests --with-coverage --cover-package=queries --verbose after_success: - coveralls \ No newline at end of file
1
Add verbose flag to see where pypy is hanging
1
.yml
travis
bsd-3-clause
gmr/queries
1150
<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: - if [[ $TRAVIS_PYTHON_VERSION != 'pypy' ]]; then pip install -r requirements.pip; fi - if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then pip install -r requirements.pypy; fi script: nosetests --with-coverage --cover-package=queries after_success: - coveralls install: - pip install awscli - pip install -r requires/testing.txt - python setup.py develop script: nosetests after_success: - aws s3 cp .coverage "s3://com-gavinroy-travis/queries/$TRAVIS_BUILD_NUMBER/.coverage.${TRAVIS_PYTHON_VERSION}" jobs: include: - python: 2.7 - python: 3.4 - python: 3.5 - python: 3.6 - python: 3.7 - python: 3.8 - stage: coverage if: repo = gmr/queries services: [] python: 3.7 install: - pip install awscli coverage codecov script: - mkdir coverage - aws s3 cp --recursive s3://com-gavinroy-travis/queries/$TRAVIS_BUILD_NUMBER/ coverage - cd coverage - coverage combine - cd .. - mv coverage/.coverage . - coverage report after_success: codecov - stage: deploy if: repo = gmr/queries python: 3.6 services: [] install: true script: true after_success: true deploy: distributions: sdist bdist_wheel provider: pypi user: crad on: tags: true all_branches: true password: secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= <MSG> Add verbose flag to see where pypy is hanging (on travis) <DFF> @@ -13,7 +13,7 @@ install: - if [[ $TRAVIS_PYTHON_VERSION != 'pypy' ]]; then pip install -r requirements.pip; fi - if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then pip install -r requirements.pypy; fi -script: nosetests --with-coverage --cover-package=queries +script: nosetests --with-coverage --cover-package=queries --verbose after_success: - coveralls \ No newline at end of file
1
Add verbose flag to see where pypy is hanging
1
.yml
travis
bsd-3-clause
gmr/queries
1151
<NME> utils.py <BEF> """ Utility functions for access to OS level info and URI parsing """ import collections import os # All systems do not support pwd module # 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 except ImportError: from urllib import unquote PARSED = collections.namedtuple('Parsed', 'scheme,netloc,path,params,query,fragment,' 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 if pwd is None: return getpass.getuser() else: return pwd.getpwuid(os.getuid())[0] def parse_qs(query_string): LOGGER.error('Could not get logged-in user: %s', error) def parse_qs(query_string): """Return the parsed query string in a python2/3 agnostic fashion :param str query_string: The URI query string :rtype: dict """ return _urlparse.parse_qs(query_string) def uri(host='localhost', port=5432, dbname='postgres', user='postgres', password=None): """Return a PostgreSQL connection URI for the specified values. :param str host: Host to connect to :param int port: Port to connect on :param str dbname: The database name :param str user: User to connect as :param str password: The password to use, None for no password :return str: The PostgreSQL connection URI """ 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> Handle an error where the logged in user cant be found <DFF> @@ -3,6 +3,7 @@ Utility functions for access to OS level info and URI parsing """ import collections +import logging import os # All systems do not support pwd module @@ -21,6 +22,7 @@ try: except ImportError: from urllib import unquote +LOGGER = logging.getLogger(__name__) PARSED = collections.namedtuple('Parsed', 'scheme,netloc,path,params,query,fragment,' @@ -57,7 +59,10 @@ def get_current_user(): if pwd is None: return getpass.getuser() else: - return pwd.getpwuid(os.getuid())[0] + 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):
6
Handle an error where the logged in user cant be found
1
.py
py
bsd-3-clause
gmr/queries
1152
<NME> utils.py <BEF> """ Utility functions for access to OS level info and URI parsing """ import collections import os # All systems do not support pwd module # 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 except ImportError: from urllib import unquote PARSED = collections.namedtuple('Parsed', 'scheme,netloc,path,params,query,fragment,' 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 if pwd is None: return getpass.getuser() else: return pwd.getpwuid(os.getuid())[0] def parse_qs(query_string): LOGGER.error('Could not get logged-in user: %s', error) def parse_qs(query_string): """Return the parsed query string in a python2/3 agnostic fashion :param str query_string: The URI query string :rtype: dict """ return _urlparse.parse_qs(query_string) def uri(host='localhost', port=5432, dbname='postgres', user='postgres', password=None): """Return a PostgreSQL connection URI for the specified values. :param str host: Host to connect to :param int port: Port to connect on :param str dbname: The database name :param str user: User to connect as :param str password: The password to use, None for no password :return str: The PostgreSQL connection URI """ 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> Handle an error where the logged in user cant be found <DFF> @@ -3,6 +3,7 @@ Utility functions for access to OS level info and URI parsing """ import collections +import logging import os # All systems do not support pwd module @@ -21,6 +22,7 @@ try: except ImportError: from urllib import unquote +LOGGER = logging.getLogger(__name__) PARSED = collections.namedtuple('Parsed', 'scheme,netloc,path,params,query,fragment,' @@ -57,7 +59,10 @@ def get_current_user(): if pwd is None: return getpass.getuser() else: - return pwd.getpwuid(os.getuid())[0] + 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):
6
Handle an error where the logged in user cant be found
1
.py
py
bsd-3-clause
gmr/queries
1153
<NME> README.rst <BEF> Queries: PostgreSQL Simplified ============================== *Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for interacting with PostgreSQL. The popular psycopg2_ package is a full-featured python client. Unfortunately as a developer, you're often repeating the same steps to get started with your applications that use it. Queries aims to reduce the complexity of psycopg2 while adding additional features to make writing PostgreSQL client applications both fast and easy. Check out the `Usage`_ section below to see how easy it can be. Key features include: - Simplified API - Support of Python 2.7+ and 3.4+ - PyPy support via psycopg2cffi_ - Asynchronous support for Tornado_ - Connection information provided by URI ------------ queries is available via pypi and can be installed with easy_install or pip: pip install queries Requirements ------------ 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> Formatting update [ci skip] <DFF> @@ -19,7 +19,9 @@ Installation ------------ queries is available via pypi and can be installed with easy_install or pip: -pip install queries +..code:: bash + + pip install queries Requirements ------------
3
Formatting update
1
.rst
rst
bsd-3-clause
gmr/queries
1154
<NME> README.rst <BEF> Queries: PostgreSQL Simplified ============================== *Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for interacting with PostgreSQL. The popular psycopg2_ package is a full-featured python client. Unfortunately as a developer, you're often repeating the same steps to get started with your applications that use it. Queries aims to reduce the complexity of psycopg2 while adding additional features to make writing PostgreSQL client applications both fast and easy. Check out the `Usage`_ section below to see how easy it can be. Key features include: - Simplified API - Support of Python 2.7+ and 3.4+ - PyPy support via psycopg2cffi_ - Asynchronous support for Tornado_ - Connection information provided by URI ------------ queries is available via pypi and can be installed with easy_install or pip: pip install queries Requirements ------------ 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> Formatting update [ci skip] <DFF> @@ -19,7 +19,9 @@ Installation ------------ queries is available via pypi and can be installed with easy_install or pip: -pip install queries +..code:: bash + + pip install queries Requirements ------------
3
Formatting update
1
.rst
rst
bsd-3-clause
gmr/queries
1155
<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='gavinmroy@gmail.com', url='https://github.com/gmr/queries', install_requires=install_requires, extras_require={'tornado': 'tornado<6'}, license='BSD', package_data={'': ['LICENSE', 'README.rst']}, packages=['queries'], classifiers=[ 'Topic :: Software Development :: Libraries'] setup(name='queries', version='1.7.2', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="gavinmroy@gmail.com", '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> Properly cast the environment variable as an integer <DFF> @@ -30,7 +30,7 @@ classifiers = ['Development Status :: 5 - Production/Stable', 'Topic :: Software Development :: Libraries'] setup(name='queries', - version='1.7.2', + version='1.7.3', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="gavinmroy@gmail.com",
1
Properly cast the environment variable as an integer
1
.py
py
bsd-3-clause
gmr/queries
1156
<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='gavinmroy@gmail.com', url='https://github.com/gmr/queries', install_requires=install_requires, extras_require={'tornado': 'tornado<6'}, license='BSD', package_data={'': ['LICENSE', 'README.rst']}, packages=['queries'], classifiers=[ 'Topic :: Software Development :: Libraries'] setup(name='queries', version='1.7.2', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="gavinmroy@gmail.com", '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> Properly cast the environment variable as an integer <DFF> @@ -30,7 +30,7 @@ classifiers = ['Development Status :: 5 - Production/Stable', 'Topic :: Software Development :: Libraries'] setup(name='queries', - version='1.7.2', + version='1.7.3', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="gavinmroy@gmail.com",
1
Properly cast the environment variable as an integer
1
.py
py
bsd-3-clause
gmr/queries
1157
<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. username is ``fred`` and you omit the URI when issuing ``queries.query`` the URI that is constructed would be ``pgsql://fred@localhost:5432/fred``. Here are a few examples of using the Queries simple API: 1. Executing a query and fetching data using the default URI: 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> Mention the queries.uri method [ci skip] <DFF> @@ -61,6 +61,15 @@ 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 ``pgsql://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") + 'pgsql://user:pass@server-name:5432/dbname' + Here are a few examples of using the Queries simple API: 1. Executing a query and fetching data using the default URI:
9
Mention the queries.uri method
0
.rst
rst
bsd-3-clause
gmr/queries
1158
<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. username is ``fred`` and you omit the URI when issuing ``queries.query`` the URI that is constructed would be ``pgsql://fred@localhost:5432/fred``. Here are a few examples of using the Queries simple API: 1. Executing a query and fetching data using the default URI: 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> Mention the queries.uri method [ci skip] <DFF> @@ -61,6 +61,15 @@ 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 ``pgsql://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") + 'pgsql://user:pass@server-name:5432/dbname' + Here are a few examples of using the Queries simple API: 1. Executing a query and fetching data using the default URI:
9
Mention the queries.uri method
0
.rst
rst
bsd-3-clause
gmr/queries
1159
<NME> setup.py <BEF> import os import platform import setuptools # PYPY vs cpython if platform.python_implementation() == 'PyPy': install_requires = ['psycopg2cffi>=2.7.2,<2.8'] else: install_requires = ['psycopg2>=2.5.1,<2.8'] # 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='gavinmroy@gmail.com', 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 :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Database', 'Topic :: Software Development :: Libraries'], zip_safe=True) <MSG> Widen pin (#36) and include 3.7, 3.8 in support classifiers <DFF> @@ -5,9 +5,9 @@ import setuptools # PYPY vs cpython if platform.python_implementation() == 'PyPy': - install_requires = ['psycopg2cffi>=2.7.2,<2.8'] + install_requires = ['psycopg2cffi>=2.7.2,<2.9'] else: - install_requires = ['psycopg2>=2.5.1,<2.8'] + install_requires = ['psycopg2>=2.5.1,<2.9'] # Install tornado if generating docs on readthedocs if os.environ.get('READTHEDOCS', None) == 'True': @@ -37,6 +37,8 @@ setuptools.setup( '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',
4
Widen pin (#36) and include 3.7, 3.8 in support classifiers
2
.py
py
bsd-3-clause
gmr/queries
1160
<NME> setup.py <BEF> import os import platform import setuptools # PYPY vs cpython if platform.python_implementation() == 'PyPy': install_requires = ['psycopg2cffi>=2.7.2,<2.8'] else: install_requires = ['psycopg2>=2.5.1,<2.8'] # 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='gavinmroy@gmail.com', 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 :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Database', 'Topic :: Software Development :: Libraries'], zip_safe=True) <MSG> Widen pin (#36) and include 3.7, 3.8 in support classifiers <DFF> @@ -5,9 +5,9 @@ import setuptools # PYPY vs cpython if platform.python_implementation() == 'PyPy': - install_requires = ['psycopg2cffi>=2.7.2,<2.8'] + install_requires = ['psycopg2cffi>=2.7.2,<2.9'] else: - install_requires = ['psycopg2>=2.5.1,<2.8'] + install_requires = ['psycopg2>=2.5.1,<2.9'] # Install tornado if generating docs on readthedocs if os.environ.get('READTHEDOCS', None) == 'True': @@ -37,6 +37,8 @@ setuptools.setup( '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',
4
Widen pin (#36) and include 3.7, 3.8 in support classifiers
2
.py
py
bsd-3-clause
gmr/queries
1161
<NME> .travis.yml <BEF> sudo: false language: python 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: pypy - python: pypy3 - stage: upload coverage if: repo IS gmr/queries services: [] python: 3.6 install: - pip install awscli coverage codecov script: - 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> Add Python3.7 to tests <DFF> @@ -1,3 +1,4 @@ +dist: xenial sudo: false language: python @@ -33,12 +34,13 @@ jobs: - python: 3.4 - python: 3.5 - python: 3.6 + - python: 3.7 - python: pypy - python: pypy3 - stage: upload coverage if: repo IS gmr/queries services: [] - python: 3.6 + python: 3.7 install: - pip install awscli coverage codecov script:
3
Add Python3.7 to tests
1
.yml
travis
bsd-3-clause
gmr/queries
1162
<NME> .travis.yml <BEF> sudo: false language: python 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: pypy - python: pypy3 - stage: upload coverage if: repo IS gmr/queries services: [] python: 3.6 install: - pip install awscli coverage codecov script: - 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> Add Python3.7 to tests <DFF> @@ -1,3 +1,4 @@ +dist: xenial sudo: false language: python @@ -33,12 +34,13 @@ jobs: - python: 3.4 - python: 3.5 - python: 3.6 + - python: 3.7 - python: pypy - python: pypy3 - stage: upload coverage if: repo IS gmr/queries services: [] - python: 3.6 + python: 3.7 install: - pip install awscli coverage codecov script:
3
Add Python3.7 to tests
1
.yml
travis
bsd-3-clause
gmr/queries
1163
<NME> session_tests.py <BEF> """ Tests for functionality in the session module """ import hashlib import mock import platform import unittest # Out of order import to ensure psycopg2cffi is registered from queries import pool, results, session, utils from psycopg2 import extras import psycopg2 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() val = 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 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(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> Flake8 cleanup of tests <DFF> @@ -3,15 +3,17 @@ Tests for functionality in the session module """ import hashlib -import mock -import platform +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 psycopg2 import extras -import psycopg2 +LOGGER = logging.getLogger(__name__) class SessionTestCase(unittest.TestCase): @@ -68,7 +70,7 @@ class SessionTestCase(unittest.TestCase): def test_backend_pid_invokes_conn_backend_pid(self): self.conn.get_backend_pid = get_backend_pid = mock.Mock() - val = self.obj.backend_pid + LOGGER.debug('ValueL %s', self.obj.backend_pid) get_backend_pid.assert_called_once_with() def test_callproc_invokes_cursor_callproc(self): @@ -114,8 +116,9 @@ class SessionTestCase(unittest.TestCase): 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() + 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): @@ -156,7 +159,7 @@ class SessionTestCase(unittest.TestCase): _connect=mock.Mock(), _get_cursor=mock.Mock(), _autocommit=mock.Mock()): - with session.Session(self.URI) as sess: + with session.Session(self.URI): pass cleanup.assert_called_once_with()
11
Flake8 cleanup of tests
8
.py
py
bsd-3-clause
gmr/queries
1164
<NME> session_tests.py <BEF> """ Tests for functionality in the session module """ import hashlib import mock import platform import unittest # Out of order import to ensure psycopg2cffi is registered from queries import pool, results, session, utils from psycopg2 import extras import psycopg2 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() val = 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 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(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> Flake8 cleanup of tests <DFF> @@ -3,15 +3,17 @@ Tests for functionality in the session module """ import hashlib -import mock -import platform +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 psycopg2 import extras -import psycopg2 +LOGGER = logging.getLogger(__name__) class SessionTestCase(unittest.TestCase): @@ -68,7 +70,7 @@ class SessionTestCase(unittest.TestCase): def test_backend_pid_invokes_conn_backend_pid(self): self.conn.get_backend_pid = get_backend_pid = mock.Mock() - val = self.obj.backend_pid + LOGGER.debug('ValueL %s', self.obj.backend_pid) get_backend_pid.assert_called_once_with() def test_callproc_invokes_cursor_callproc(self): @@ -114,8 +116,9 @@ class SessionTestCase(unittest.TestCase): 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() + 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): @@ -156,7 +159,7 @@ class SessionTestCase(unittest.TestCase): _connect=mock.Mock(), _get_cursor=mock.Mock(), _autocommit=mock.Mock()): - with session.Session(self.URI) as sess: + with session.Session(self.URI): pass cleanup.assert_called_once_with()
11
Flake8 cleanup of tests
8
.py
py
bsd-3-clause
gmr/queries
1165
<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 |Version| |Downloads| |Status| Installation ------------ queries is available via pypi and can be installed with easy_install or pip: 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: >>> import pprint >>> import queries >>> >>> for row in queries.query('SELECT * FROM foo'): ... pprint.pprint(row) ... {'id': 1, 'name': u'Gavin'} {'id': 2, 'name': u'Bob'} {'id': 3, 'name': u'Joe'} Iterate over a stored procedure: .. code:: python 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 docs [ci skip] <DFF> @@ -15,6 +15,10 @@ connection. |Version| |Downloads| |Status| +Documentation +------------- +Documentation is available at https://queries.readthedocs.org + Installation ------------ queries is available via pypi and can be installed with easy_install or pip: @@ -40,14 +44,14 @@ the current user with a database matching the username: >>> import pprint >>> import queries >>> - >>> for row in queries.query('SELECT * FROM foo'): + >>> for row in queries.query('SELECT * FROM names'): ... pprint.pprint(row) ... - {'id': 1, 'name': u'Gavin'} - {'id': 2, 'name': u'Bob'} - {'id': 3, 'name': u'Joe'} + {'id': 1, 'name': u'Jacob'} + {'id': 2, 'name': u'Mason'} + {'id': 3, 'name': u'Ethan'} -Iterate over a stored procedure: +Iterate over the results from calling a stored procedure: .. code:: python
9
Update docs
5
.rst
rst
bsd-3-clause
gmr/queries
1166
<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 |Version| |Downloads| |Status| Installation ------------ queries is available via pypi and can be installed with easy_install or pip: 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: >>> import pprint >>> import queries >>> >>> for row in queries.query('SELECT * FROM foo'): ... pprint.pprint(row) ... {'id': 1, 'name': u'Gavin'} {'id': 2, 'name': u'Bob'} {'id': 3, 'name': u'Joe'} Iterate over a stored procedure: .. code:: python 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 docs [ci skip] <DFF> @@ -15,6 +15,10 @@ connection. |Version| |Downloads| |Status| +Documentation +------------- +Documentation is available at https://queries.readthedocs.org + Installation ------------ queries is available via pypi and can be installed with easy_install or pip: @@ -40,14 +44,14 @@ the current user with a database matching the username: >>> import pprint >>> import queries >>> - >>> for row in queries.query('SELECT * FROM foo'): + >>> for row in queries.query('SELECT * FROM names'): ... pprint.pprint(row) ... - {'id': 1, 'name': u'Gavin'} - {'id': 2, 'name': u'Bob'} - {'id': 3, 'name': u'Joe'} + {'id': 1, 'name': u'Jacob'} + {'id': 2, 'name': u'Mason'} + {'id': 3, 'name': u'Ethan'} -Iterate over a stored procedure: +Iterate over the results from calling a stored procedure: .. code:: python
9
Update docs
5
.rst
rst
bsd-3-clause
gmr/queries
1167
<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.0.1', description='Simplified PostgreSQL client built upon Psycopg2', long_description=open('README.rst').read(), maintainer='Gavin M. Roy', maintainer_email='gavinmroy@gmail.com', 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 version for release <DFF> @@ -15,7 +15,7 @@ if os.environ.get('READTHEDOCS', None) == 'True': setuptools.setup( name='queries', - version='2.0.1', + version='2.1.0', description='Simplified PostgreSQL client built upon Psycopg2', long_description=open('README.rst').read(), maintainer='Gavin M. Roy',
1
Bump the version for release
1
.py
py
bsd-3-clause
gmr/queries
1168
<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.0.1', description='Simplified PostgreSQL client built upon Psycopg2', long_description=open('README.rst').read(), maintainer='Gavin M. Roy', maintainer_email='gavinmroy@gmail.com', 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 version for release <DFF> @@ -15,7 +15,7 @@ if os.environ.get('READTHEDOCS', None) == 'True': setuptools.setup( name='queries', - version='2.0.1', + version='2.1.0', description='Simplified PostgreSQL client built upon Psycopg2', long_description=open('README.rst').read(), maintainer='Gavin M. Roy',
1
Bump the version for release
1
.py
py
bsd-3-clause
gmr/queries
1169
<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'" 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, returning the results as a list. If no results are returned, the method will return None instead. :param str name: The stored procedure name :param list args: An optional list of procedure arguments :rtype: list or None """ # Grab a connection, either new or out of the pool 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() try: result = cursor.fetchall() except psycopg2.ProgrammingError: result = None # Close the cursor and cleanup the references for this request self._exec_cleanup(cursor, fd) :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): @gen.coroutine 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 list. :param str sql: The SQL statement :param dict parameters: A dictionary of query parameters :rtype: list or None """ # 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. 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 = None # 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 unlisten(self, channel): 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> Make query and callproc return a tuple of (rows, data) <DFF> @@ -83,12 +83,11 @@ class TornadoSession(session.Session): 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, returning the results - as a list. If no results are returned, the method will return None - instead. + as a tuple of row count and result set. :param str name: The stored procedure name :param list args: An optional list of procedure arguments - :rtype: list or None + :rtype: list """ # Grab a connection, either new or out of the pool @@ -122,7 +121,7 @@ class TornadoSession(session.Session): try: result = cursor.fetchall() except psycopg2.ProgrammingError: - result = None + result = [] # Close the cursor and cleanup the references for this request self._exec_cleanup(cursor, fd) @@ -182,11 +181,12 @@ class TornadoSession(session.Session): @gen.coroutine 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 list. + parameters against the sql statement and yielding the results as a + tuple of row count and result set. :param str sql: The SQL statement :param dict parameters: A dictionary of query parameters - :rtype: list or None + :return tuple: (row_count, rows) """ # Grab a connection, either new or out of the pool @@ -216,17 +216,20 @@ class TornadoSession(session.Session): 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 = None + 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) + raise gen.Return((row_count, result)) @gen.coroutine def unlisten(self, channel):
11
Make query and callproc return a tuple of (rows, data)
8
.py
py
bsd-3-clause
gmr/queries
1170
<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'" 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, returning the results as a list. If no results are returned, the method will return None instead. :param str name: The stored procedure name :param list args: An optional list of procedure arguments :rtype: list or None """ # Grab a connection, either new or out of the pool 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() try: result = cursor.fetchall() except psycopg2.ProgrammingError: result = None # Close the cursor and cleanup the references for this request self._exec_cleanup(cursor, fd) :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): @gen.coroutine 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 list. :param str sql: The SQL statement :param dict parameters: A dictionary of query parameters :rtype: list or None """ # 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. 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 = None # 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 unlisten(self, channel): 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> Make query and callproc return a tuple of (rows, data) <DFF> @@ -83,12 +83,11 @@ class TornadoSession(session.Session): 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, returning the results - as a list. If no results are returned, the method will return None - instead. + as a tuple of row count and result set. :param str name: The stored procedure name :param list args: An optional list of procedure arguments - :rtype: list or None + :rtype: list """ # Grab a connection, either new or out of the pool @@ -122,7 +121,7 @@ class TornadoSession(session.Session): try: result = cursor.fetchall() except psycopg2.ProgrammingError: - result = None + result = [] # Close the cursor and cleanup the references for this request self._exec_cleanup(cursor, fd) @@ -182,11 +181,12 @@ class TornadoSession(session.Session): @gen.coroutine 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 list. + parameters against the sql statement and yielding the results as a + tuple of row count and result set. :param str sql: The SQL statement :param dict parameters: A dictionary of query parameters - :rtype: list or None + :return tuple: (row_count, rows) """ # Grab a connection, either new or out of the pool @@ -216,17 +216,20 @@ class TornadoSession(session.Session): 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 = None + 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) + raise gen.Return((row_count, result)) @gen.coroutine def unlisten(self, channel):
11
Make query and callproc return a tuple of (rows, data)
8
.py
py
bsd-3-clause
gmr/queries
1171
<NME> .travis.yml <BEF> sudo: false language: python dist: xenial env: - pypy - 3.2 - 3.3 - 3.4 install: - if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then pip install psycopg2ct; fi - 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: 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> Comment out Python 3.4 <DFF> @@ -6,7 +6,7 @@ python: - pypy - 3.2 - 3.3 - - 3.4 +# - 3.4 install: - if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then pip install psycopg2ct; fi
1
Comment out Python 3.4
1
.yml
travis
bsd-3-clause
gmr/queries
1172
<NME> .travis.yml <BEF> sudo: false language: python dist: xenial env: - pypy - 3.2 - 3.3 - 3.4 install: - if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then pip install psycopg2ct; fi - 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: 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> Comment out Python 3.4 <DFF> @@ -6,7 +6,7 @@ python: - pypy - 3.2 - 3.3 - - 3.4 +# - 3.4 install: - if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then pip install psycopg2ct; fi
1
Comment out Python 3.4
1
.yml
travis
bsd-3-clause
gmr/queries
1173
<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 Examples -------- Executing a query and fetching data: .. code:: python import queries uri = 'pgsql://postgres@localhost/postgres' for row in queries.execute(uri, 'SELECT 1 as value'): print(data['value']) Using the Session object as a context manager: .. code:: python import queries with queries.Session('pgsql://postgres@localhost/postgres') as session: for row in session.Query('SELECT * FROM table'): print row Creating a Session object for transactional behavior: .. code:: python import queries uri = 'pgsql://postgres@localhost/postgres' pgsql = queries.Session(uri) pgsql.prepare() pgsql.callproc('SELECT foo FROM bar()') pgsql.commit() .. |Version| image:: https://badge.fury.io/py/queries.svg? 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> Updated examples <DFF> @@ -30,41 +30,48 @@ Requirements Examples -------- -Executing a query and fetching data: +Executing a query and fetching data, connecting by default to `localhost` as +the current user with a database matching the username: .. code:: python - import queries + >>> import pprint + >>> import queries + >>> + >>> for row in queries.query('SELECT * FROM foo'): + ... pprint.pprint(row) + ... + {'id': 1, 'name': u'Gavin'} + {'id': 2, 'name': u'Bob'} + {'id': 3, 'name': u'Joe'} - uri = 'pgsql://postgres@localhost/postgres' - for row in queries.execute(uri, 'SELECT 1 as value'): - print(data['value']) - -Using the Session object as a context manager: +Iterate over a stored procedure: .. code:: python - import queries - - with queries.Session('pgsql://postgres@localhost/postgres') as session: - for row in session.Query('SELECT * FROM table'): - print row + >>> import pprint + >>> import queries + >>> + >>> for row in queries.callproc('now'): + ... pprint.pprint(row) + ... + {'now': datetime.datetime(2014, 4, 25, 12, 52, 0, 133279, + tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=-240, name=None))} -Creating a Session object for transactional behavior: +Using the Session object as a context manager: .. code:: python - import queries - - uri = 'pgsql://postgres@localhost/postgres' - pgsql = queries.Session(uri) - pgsql.prepare() - pgsql.callproc('SELECT foo FROM bar()') - pgsql.commit() - - - - + >>> import pprint + >>> import queries + >>> + >>> with queries.Session() as s: + ... for row in s.query('SELECT * FROM names'): + ... pprint.pprint(row) + ... + {'id': 1, 'name': u'Jacob'} + {'id': 2, 'name': u'Mason'} + {'id': 3, 'name': u'Ethan'} .. |Version| image:: https://badge.fury.io/py/queries.svg?
31
Updated examples
24
.rst
rst
bsd-3-clause
gmr/queries
1174
<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 Examples -------- Executing a query and fetching data: .. code:: python import queries uri = 'pgsql://postgres@localhost/postgres' for row in queries.execute(uri, 'SELECT 1 as value'): print(data['value']) Using the Session object as a context manager: .. code:: python import queries with queries.Session('pgsql://postgres@localhost/postgres') as session: for row in session.Query('SELECT * FROM table'): print row Creating a Session object for transactional behavior: .. code:: python import queries uri = 'pgsql://postgres@localhost/postgres' pgsql = queries.Session(uri) pgsql.prepare() pgsql.callproc('SELECT foo FROM bar()') pgsql.commit() .. |Version| image:: https://badge.fury.io/py/queries.svg? 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> Updated examples <DFF> @@ -30,41 +30,48 @@ Requirements Examples -------- -Executing a query and fetching data: +Executing a query and fetching data, connecting by default to `localhost` as +the current user with a database matching the username: .. code:: python - import queries + >>> import pprint + >>> import queries + >>> + >>> for row in queries.query('SELECT * FROM foo'): + ... pprint.pprint(row) + ... + {'id': 1, 'name': u'Gavin'} + {'id': 2, 'name': u'Bob'} + {'id': 3, 'name': u'Joe'} - uri = 'pgsql://postgres@localhost/postgres' - for row in queries.execute(uri, 'SELECT 1 as value'): - print(data['value']) - -Using the Session object as a context manager: +Iterate over a stored procedure: .. code:: python - import queries - - with queries.Session('pgsql://postgres@localhost/postgres') as session: - for row in session.Query('SELECT * FROM table'): - print row + >>> import pprint + >>> import queries + >>> + >>> for row in queries.callproc('now'): + ... pprint.pprint(row) + ... + {'now': datetime.datetime(2014, 4, 25, 12, 52, 0, 133279, + tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=-240, name=None))} -Creating a Session object for transactional behavior: +Using the Session object as a context manager: .. code:: python - import queries - - uri = 'pgsql://postgres@localhost/postgres' - pgsql = queries.Session(uri) - pgsql.prepare() - pgsql.callproc('SELECT foo FROM bar()') - pgsql.commit() - - - - + >>> import pprint + >>> import queries + >>> + >>> with queries.Session() as s: + ... for row in s.query('SELECT * FROM names'): + ... pprint.pprint(row) + ... + {'id': 1, 'name': u'Jacob'} + {'id': 2, 'name': u'Mason'} + {'id': 3, 'name': u'Ethan'} .. |Version| image:: https://badge.fury.io/py/queries.svg?
31
Updated examples
24
.rst
rst
bsd-3-clause
gmr/queries
1175
<NME> results_tests.py <BEF> """ Tests for functionality in the results module """ import logging import unittest except ImportError: import unittest from queries import results def test_rownumber_value(self): self.cursor.rownumber = 10 self.assertEqual(self.obj.rownumber, 10) def test_query_value(self): self.cursor.query = 'SELECT * FROM foo' self.assertEqual(self.obj.query, 'SELECT * FROM foo') def test_status_value(self): self.cursor.statusmessage = 'Status message' self.assertEqual(self.obj.status, 'Status message') def test_rewind_invokes_scroll(self): self.cursor.scroll = mock.Mock() self.obj._rewind() self.cursor.scroll.assert_called_once_with(0, 'absolute') <MSG> Add Results coverage <DFF> @@ -8,4 +8,122 @@ try: except ImportError: import unittest +import psycopg2 + from queries import results + + +class ResultsTestCase(unittest.TestCase): + + def setUp(self): + self.cursor = mock.MagicMock() + self.obj = results.Results(self.cursor) + + def test_cursor_is_assigned(self): + self.assertEqual(self.obj.cursor, self.cursor) + + def test_getitem_invokes_scroll(self): + self.cursor.scroll = mock.Mock() + self.cursor.fetchone = mock.Mock() + _row = self.obj[1] + self.cursor.scroll.assert_called_once_with(1, 'absolute') + + def test_getitem_raises_index_error(self): + self.cursor.scroll = mock.Mock(side_effect=psycopg2.ProgrammingError) + self.cursor.fetchone = mock.Mock() + def get_row(): + return self.obj[1] + self.assertRaises(IndexError, get_row) + + def test_getitem_invokes_fetchone(self): + self.cursor.scroll = mock.Mock() + self.cursor.fetchone = mock.Mock() + _row = self.obj[1] + self.cursor.fetchone.assert_called_once_with() + + def test_iter_rewinds(self): + self.cursor.__iter__ = mock.Mock(return_value=iter([1, 2, 3])) + with mock.patch.object(self.obj, '_rewind') as rewind: + [x for x in self.obj] + rewind.assert_called_once_with() + + def test_iter_iters(self): + self.cursor.__iter__ = mock.Mock(return_value=iter([1, 2, 3])) + with mock.patch.object(self.obj, '_rewind') as rewind: + self.assertEqual([x for x in self.obj], [1, 2, 3]) + + def test_rowcount_value(self): + self.cursor.rowcount = 128 + self.assertEqual(len(self.obj), 128) + + def test_nonzero_false(self): + self.cursor.rowcount = 0 + self.assertFalse(bool(self.obj)) + + def test_nonzero_true(self): + self.cursor.rowcount = 128 + self.assertTrue(bool(self.obj)) + + def test_repr_str(self): + self.cursor.rowcount = 128 + self.assertEqual(str(self.obj), '<queries.Results rows=128>') + + def test_as_dict_no_rows(self): + self.cursor.rowcount = 0 + self.assertDictEqual(self.obj.as_dict(), {}) + + def test_as_dict_rewinds(self): + expectation = {'foo': 'bar', 'baz': 'qux'} + self.cursor.rowcount = 1 + self.cursor.fetchone = mock.Mock(return_value=expectation) + with mock.patch.object(self.obj, '_rewind') as rewind: + result = self.obj.as_dict() + rewind.assert_called_once_with() + + def test_as_dict_value(self): + expectation = {'foo': 'bar', 'baz': 'qux'} + self.cursor.rowcount = 1 + self.cursor.fetchone = mock.Mock(return_value=expectation) + with mock.patch.object(self.obj, '_rewind') as rewind: + self.assertDictEqual(self.obj.as_dict(), expectation) + + def test_as_dict_with_multiple_rows_raises(self): + self.cursor.rowcount = 2 + with mock.patch.object(self.obj, '_rewind') as rewind: + self.assertRaises(ValueError, self.obj.as_dict) + + def test_count_returns_rowcount(self): + self.cursor.rowcount = 2 + self.assertEqual(self.obj.count(), 2) + + def test_free_raises_exception(self): + self.assertRaises(NotImplementedError, self.obj.free) + + def test_items_invokes_scroll(self): + self.cursor.scroll = mock.Mock() + self.cursor.fetchall = mock.Mock() + self.obj.items() + self.cursor.scroll.assert_called_once_with(0, 'absolute') + + def test_items_invokes_fetchall(self): + self.cursor.scroll = mock.Mock() + self.cursor.fetchall = mock.Mock() + self.obj.items() + self.cursor.fetchall.assert_called_once_with() + + def test_rownumber_value(self): + self.cursor.rownumber = 10 + self.assertEqual(self.obj.rownumber, 10) + + def test_query_value(self): + self.cursor.query = 'SELECT * FROM foo' + self.assertEqual(self.obj.query, 'SELECT * FROM foo') + + def test_status_value(self): + self.cursor.statusmessage = 'Status message' + self.assertEqual(self.obj.status, 'Status message') + + def test_rewind_invokes_scroll(self): + self.cursor.scroll = mock.Mock() + self.obj._rewind() + self.cursor.scroll.assert_called_once_with(0, 'absolute')
118
Add Results coverage
0
.py
py
bsd-3-clause
gmr/queries
1176
<NME> results_tests.py <BEF> """ Tests for functionality in the results module """ import logging import unittest except ImportError: import unittest from queries import results def test_rownumber_value(self): self.cursor.rownumber = 10 self.assertEqual(self.obj.rownumber, 10) def test_query_value(self): self.cursor.query = 'SELECT * FROM foo' self.assertEqual(self.obj.query, 'SELECT * FROM foo') def test_status_value(self): self.cursor.statusmessage = 'Status message' self.assertEqual(self.obj.status, 'Status message') def test_rewind_invokes_scroll(self): self.cursor.scroll = mock.Mock() self.obj._rewind() self.cursor.scroll.assert_called_once_with(0, 'absolute') <MSG> Add Results coverage <DFF> @@ -8,4 +8,122 @@ try: except ImportError: import unittest +import psycopg2 + from queries import results + + +class ResultsTestCase(unittest.TestCase): + + def setUp(self): + self.cursor = mock.MagicMock() + self.obj = results.Results(self.cursor) + + def test_cursor_is_assigned(self): + self.assertEqual(self.obj.cursor, self.cursor) + + def test_getitem_invokes_scroll(self): + self.cursor.scroll = mock.Mock() + self.cursor.fetchone = mock.Mock() + _row = self.obj[1] + self.cursor.scroll.assert_called_once_with(1, 'absolute') + + def test_getitem_raises_index_error(self): + self.cursor.scroll = mock.Mock(side_effect=psycopg2.ProgrammingError) + self.cursor.fetchone = mock.Mock() + def get_row(): + return self.obj[1] + self.assertRaises(IndexError, get_row) + + def test_getitem_invokes_fetchone(self): + self.cursor.scroll = mock.Mock() + self.cursor.fetchone = mock.Mock() + _row = self.obj[1] + self.cursor.fetchone.assert_called_once_with() + + def test_iter_rewinds(self): + self.cursor.__iter__ = mock.Mock(return_value=iter([1, 2, 3])) + with mock.patch.object(self.obj, '_rewind') as rewind: + [x for x in self.obj] + rewind.assert_called_once_with() + + def test_iter_iters(self): + self.cursor.__iter__ = mock.Mock(return_value=iter([1, 2, 3])) + with mock.patch.object(self.obj, '_rewind') as rewind: + self.assertEqual([x for x in self.obj], [1, 2, 3]) + + def test_rowcount_value(self): + self.cursor.rowcount = 128 + self.assertEqual(len(self.obj), 128) + + def test_nonzero_false(self): + self.cursor.rowcount = 0 + self.assertFalse(bool(self.obj)) + + def test_nonzero_true(self): + self.cursor.rowcount = 128 + self.assertTrue(bool(self.obj)) + + def test_repr_str(self): + self.cursor.rowcount = 128 + self.assertEqual(str(self.obj), '<queries.Results rows=128>') + + def test_as_dict_no_rows(self): + self.cursor.rowcount = 0 + self.assertDictEqual(self.obj.as_dict(), {}) + + def test_as_dict_rewinds(self): + expectation = {'foo': 'bar', 'baz': 'qux'} + self.cursor.rowcount = 1 + self.cursor.fetchone = mock.Mock(return_value=expectation) + with mock.patch.object(self.obj, '_rewind') as rewind: + result = self.obj.as_dict() + rewind.assert_called_once_with() + + def test_as_dict_value(self): + expectation = {'foo': 'bar', 'baz': 'qux'} + self.cursor.rowcount = 1 + self.cursor.fetchone = mock.Mock(return_value=expectation) + with mock.patch.object(self.obj, '_rewind') as rewind: + self.assertDictEqual(self.obj.as_dict(), expectation) + + def test_as_dict_with_multiple_rows_raises(self): + self.cursor.rowcount = 2 + with mock.patch.object(self.obj, '_rewind') as rewind: + self.assertRaises(ValueError, self.obj.as_dict) + + def test_count_returns_rowcount(self): + self.cursor.rowcount = 2 + self.assertEqual(self.obj.count(), 2) + + def test_free_raises_exception(self): + self.assertRaises(NotImplementedError, self.obj.free) + + def test_items_invokes_scroll(self): + self.cursor.scroll = mock.Mock() + self.cursor.fetchall = mock.Mock() + self.obj.items() + self.cursor.scroll.assert_called_once_with(0, 'absolute') + + def test_items_invokes_fetchall(self): + self.cursor.scroll = mock.Mock() + self.cursor.fetchall = mock.Mock() + self.obj.items() + self.cursor.fetchall.assert_called_once_with() + + def test_rownumber_value(self): + self.cursor.rownumber = 10 + self.assertEqual(self.obj.rownumber, 10) + + def test_query_value(self): + self.cursor.query = 'SELECT * FROM foo' + self.assertEqual(self.obj.query, 'SELECT * FROM foo') + + def test_status_value(self): + self.cursor.statusmessage = 'Status message' + self.assertEqual(self.obj.status, 'Status message') + + def test_rewind_invokes_scroll(self): + self.cursor.scroll = mock.Mock() + self.obj._rewind() + self.cursor.scroll.assert_called_once_with(0, 'absolute')
118
Add Results coverage
0
.py
py
bsd-3-clause
gmr/queries
1177
<NME> index.rst <BEF> Queries: PostgreSQL Simplified ============================== *Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for interacting with PostgreSQL. |Version| |Downloads| |License| |PythonVersions| The popular psycopg2_ package is a full-featured python client. Unfortunately as a developer, you're often repeating the same steps to get started with your applications that use it. Queries aims to reduce the complexity of psycopg2 while adding additional features to make writing PostgreSQL client applications both fast and easy. *Key features include*: - Simplified API - Support of Python 2.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_ :py:class:`~psycopg2.extensions.connection` and :py:class:`~psycopg2.extensions.cursor` objects - Internal connection pooling Installation ------------ Queries can be installed via the `Python Package Index <https://pypi.python.org/pypi/queries>`_ and can be installed by running :command:`easy_install queries` or :command:`pip install queries` When installing Queries, ``pip`` or ``easy_install`` will automatically install the proper dependencies for your platform. Contents -------- .. toctree:: :maxdepth: 1 usage session results tornado_session pool examples/index.rst history Issues ------ Please report any issues to the Github repo at `https://github.com/gmr/queries/issues <https://github.com/gmr/queries/issues>`_ Source ------ Queries source is available on Github at `https://github.com/gmr/queries <https://github.com/gmr/queries>`_ Inspiration ----------- Queries is inspired by `Kenneth Reitz's <https://github.com/kennethreitz/>`_ awesome work on `requests <http://docs.python-requests.org/en/latest/>`_. Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` .. _pypi: https://pypi.python.org/pypi/queries .. _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 .. |License| image:: https://img.shields.io/github/license/gmr/queries.svg? :target: https://github.com/gmr/queries <MSG> Remove the downloads badge <DFF> @@ -3,7 +3,7 @@ Queries: PostgreSQL Simplified *Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for interacting with PostgreSQL. -|Version| |Downloads| |License| |PythonVersions| +|Version| |License| |PythonVersions| The popular psycopg2_ package is a full-featured python client. Unfortunately as a developer, you're often repeating the same steps to get started with your
1
Remove the downloads badge
1
.rst
rst
bsd-3-clause
gmr/queries
1178
<NME> index.rst <BEF> Queries: PostgreSQL Simplified ============================== *Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for interacting with PostgreSQL. |Version| |Downloads| |License| |PythonVersions| The popular psycopg2_ package is a full-featured python client. Unfortunately as a developer, you're often repeating the same steps to get started with your applications that use it. Queries aims to reduce the complexity of psycopg2 while adding additional features to make writing PostgreSQL client applications both fast and easy. *Key features include*: - Simplified API - Support of Python 2.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_ :py:class:`~psycopg2.extensions.connection` and :py:class:`~psycopg2.extensions.cursor` objects - Internal connection pooling Installation ------------ Queries can be installed via the `Python Package Index <https://pypi.python.org/pypi/queries>`_ and can be installed by running :command:`easy_install queries` or :command:`pip install queries` When installing Queries, ``pip`` or ``easy_install`` will automatically install the proper dependencies for your platform. Contents -------- .. toctree:: :maxdepth: 1 usage session results tornado_session pool examples/index.rst history Issues ------ Please report any issues to the Github repo at `https://github.com/gmr/queries/issues <https://github.com/gmr/queries/issues>`_ Source ------ Queries source is available on Github at `https://github.com/gmr/queries <https://github.com/gmr/queries>`_ Inspiration ----------- Queries is inspired by `Kenneth Reitz's <https://github.com/kennethreitz/>`_ awesome work on `requests <http://docs.python-requests.org/en/latest/>`_. Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` .. _pypi: https://pypi.python.org/pypi/queries .. _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 .. |License| image:: https://img.shields.io/github/license/gmr/queries.svg? :target: https://github.com/gmr/queries <MSG> Remove the downloads badge <DFF> @@ -3,7 +3,7 @@ Queries: PostgreSQL Simplified *Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for interacting with PostgreSQL. -|Version| |Downloads| |License| |PythonVersions| +|Version| |License| |PythonVersions| The popular psycopg2_ package is a full-featured python client. Unfortunately as a developer, you're often repeating the same steps to get started with your
1
Remove the downloads badge
1
.rst
rst
bsd-3-clause
gmr/queries
1179
<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='gavinmroy@gmail.com', url='https://github.com/gmr/queries', install_requires=install_requires, extras_require={'tornado': 'tornado<6'}, license='BSD', package_data={'': ['LICENSE', 'README.rst']}, 'Topic :: Software Development :: Libraries'] setup(name='queries', version='1.10.0', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="gavinmroy@gmail.com", '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 version for release <DFF> @@ -28,7 +28,7 @@ classifiers = ['Development Status :: 5 - Production/Stable', 'Topic :: Software Development :: Libraries'] setup(name='queries', - version='1.10.0', + version='1.10.1', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="gavinmroy@gmail.com",
1
Bump the version for release
1
.py
py
bsd-3-clause
gmr/queries
1180
<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='gavinmroy@gmail.com', url='https://github.com/gmr/queries', install_requires=install_requires, extras_require={'tornado': 'tornado<6'}, license='BSD', package_data={'': ['LICENSE', 'README.rst']}, 'Topic :: Software Development :: Libraries'] setup(name='queries', version='1.10.0', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="gavinmroy@gmail.com", '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 version for release <DFF> @@ -28,7 +28,7 @@ classifiers = ['Development Status :: 5 - Production/Stable', 'Topic :: Software Development :: Libraries'] setup(name='queries', - version='1.10.0', + version='1.10.1', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="gavinmroy@gmail.com",
1
Bump the version for release
1
.py
py
bsd-3-clause
gmr/queries
1181
<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("pgsql://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 ``pgsql://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") 'pgsql://user:pass@server-name:5432/dbname' Using the queries.Session class ^^^^^^^^^^^^^^^^^^^^^ Currently Queries uses the following environment variables for tweaking various configuration values. The supported ones are: * ``QUERIES_MAX_POOL_SIZE`` - Modify the maximum size of the connection pool (default: 1) Using the queries.Session class ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To execute queries or call stored procedures, you start by creating an instance of the ``queries.Session`` class. It can act as a context manager, meaning you can use it with the ``with`` keyword and it will take care of cleaning up after itself. For more information on the ``with`` keyword and context managers, see PEP343_. In addition to both the ``queries.Session.query`` and ``queries.Session.callproc`` methods that are similar to the simple API methods, the ``queries.Session`` class provides access to the psycopg2 connection and cursor objects. **Using queries.Session.query** The following example shows how a ``queries.Session`` object can be used as a context manager to query the database table: .. code:: python >>> import pprint >>> import queries >>> >>> with queries.Session() as session: ... for row in session.query('SELECT * FROM names'): ... pprint.pprint(row) ... {'id': 1, 'name': u'Jacob'} {'id': 2, 'name': u'Mason'} {'id': 3, 'name': u'Ethan'} **Using queries.Session.callproc** This example uses ``queries.Session.callproc`` to execute a stored procedure and then pretty-prints the single row results as a dictionary: .. code:: python >>> import pprint >>> import queries >>> with queries.Session() as session: ... results = session.callproc('chr', [65]) ... pprint.pprint(results.as_dict()) ... {'chr': u'A'} **Asynchronous Queries with Tornado** In addition to providing a Pythonic, synchronous client API for PostgreSQL, Queries provides a very similar asynchronous API for use with Tornado. The only major difference API difference between ``queries.TornadoSession`` and ``queries.Session`` is the ``TornadoSession.query`` and ``TornadoSession.callproc`` methods return the entire result set instead of acting as an iterator over the results. The following example uses ``TornadoSession.query`` in an asynchronous Tornado_ web application to send a JSON payload with the query result set. .. code:: python from tornado import gen, ioloop, web import queries class MainHandler(web.RequestHandler): def initialize(self): self.session = queries.TornadoSession() @gen.coroutine def get(self): results = yield self.session.query('SELECT * FROM names') self.finish({'data': results.items()}) results.free() application = web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) ioloop.IOLoop.instance().start() Inspiration ----------- Queries is inspired by `Kenneth Reitz's <https://github.com/kennethreitz/>`_ awesome work on `requests <http://docs.python-requests.org/en/latest/>`_. History ------- Queries is a fork and enhancement of pgsql_wrapper_, which can be found in the main GitHub repository of Queries as tags prior to version 1.2.0. .. _pypi: https://pypi.python.org/pypi/queries .. _psycopg2: https://pypi.python.org/pypi/psycopg2 .. _documentation: https://queries.readthedocs.org .. _URI: http://www.postgresql.org/docs/9.3/static/libpq-connect.html#LIBPQ-CONNSTRING .. _pgsql_wrapper: https://pypi.python.org/pypi/pgsql_wrapper .. _Tornado: http://tornadoweb.org .. _PEP343: http://legacy.python.org/dev/peps/pep-0343/ .. _psycopg2cffi: https://pypi.python.org/pypi/psycopg2cffi .. |Version| image:: https://img.shields.io/pypi/v/queries.svg? :target: https://pypi.python.org/pypi/queries .. |Status| image:: https://img.shields.io/travis/gmr/queries.svg? :target: https://travis-ci.org/gmr/queries .. |Coverage| image:: https://img.shields.io/codecov/c/github/gmr/queries.svg? :target: https://codecov.io/github/gmr/queries?branch=master .. |License| image:: https://img.shields.io/github/license/gmr/queries.svg? :target: https://github.com/gmr/queries <MSG> Fix the URI scheme in README <DFF> @@ -43,7 +43,7 @@ a session: .. code:: python - session = queries.Session("pgsql://postgres@localhost:5432/postgres") + 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. @@ -53,7 +53,7 @@ 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 ``pgsql://fred@localhost:5432/fred``. +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 @@ -62,7 +62,7 @@ methods. .. code:: python >>> queries.uri("server-name", 5432, "dbname", "user", "pass") - 'pgsql://user:pass@server-name:5432/dbname' + 'postgresql://user:pass@server-name:5432/dbname' Using the queries.Session class
3
Fix the URI scheme in README
3
.rst
rst
bsd-3-clause
gmr/queries
1182
<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("pgsql://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 ``pgsql://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") 'pgsql://user:pass@server-name:5432/dbname' Using the queries.Session class ^^^^^^^^^^^^^^^^^^^^^ Currently Queries uses the following environment variables for tweaking various configuration values. The supported ones are: * ``QUERIES_MAX_POOL_SIZE`` - Modify the maximum size of the connection pool (default: 1) Using the queries.Session class ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To execute queries or call stored procedures, you start by creating an instance of the ``queries.Session`` class. It can act as a context manager, meaning you can use it with the ``with`` keyword and it will take care of cleaning up after itself. For more information on the ``with`` keyword and context managers, see PEP343_. In addition to both the ``queries.Session.query`` and ``queries.Session.callproc`` methods that are similar to the simple API methods, the ``queries.Session`` class provides access to the psycopg2 connection and cursor objects. **Using queries.Session.query** The following example shows how a ``queries.Session`` object can be used as a context manager to query the database table: .. code:: python >>> import pprint >>> import queries >>> >>> with queries.Session() as session: ... for row in session.query('SELECT * FROM names'): ... pprint.pprint(row) ... {'id': 1, 'name': u'Jacob'} {'id': 2, 'name': u'Mason'} {'id': 3, 'name': u'Ethan'} **Using queries.Session.callproc** This example uses ``queries.Session.callproc`` to execute a stored procedure and then pretty-prints the single row results as a dictionary: .. code:: python >>> import pprint >>> import queries >>> with queries.Session() as session: ... results = session.callproc('chr', [65]) ... pprint.pprint(results.as_dict()) ... {'chr': u'A'} **Asynchronous Queries with Tornado** In addition to providing a Pythonic, synchronous client API for PostgreSQL, Queries provides a very similar asynchronous API for use with Tornado. The only major difference API difference between ``queries.TornadoSession`` and ``queries.Session`` is the ``TornadoSession.query`` and ``TornadoSession.callproc`` methods return the entire result set instead of acting as an iterator over the results. The following example uses ``TornadoSession.query`` in an asynchronous Tornado_ web application to send a JSON payload with the query result set. .. code:: python from tornado import gen, ioloop, web import queries class MainHandler(web.RequestHandler): def initialize(self): self.session = queries.TornadoSession() @gen.coroutine def get(self): results = yield self.session.query('SELECT * FROM names') self.finish({'data': results.items()}) results.free() application = web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) ioloop.IOLoop.instance().start() Inspiration ----------- Queries is inspired by `Kenneth Reitz's <https://github.com/kennethreitz/>`_ awesome work on `requests <http://docs.python-requests.org/en/latest/>`_. History ------- Queries is a fork and enhancement of pgsql_wrapper_, which can be found in the main GitHub repository of Queries as tags prior to version 1.2.0. .. _pypi: https://pypi.python.org/pypi/queries .. _psycopg2: https://pypi.python.org/pypi/psycopg2 .. _documentation: https://queries.readthedocs.org .. _URI: http://www.postgresql.org/docs/9.3/static/libpq-connect.html#LIBPQ-CONNSTRING .. _pgsql_wrapper: https://pypi.python.org/pypi/pgsql_wrapper .. _Tornado: http://tornadoweb.org .. _PEP343: http://legacy.python.org/dev/peps/pep-0343/ .. _psycopg2cffi: https://pypi.python.org/pypi/psycopg2cffi .. |Version| image:: https://img.shields.io/pypi/v/queries.svg? :target: https://pypi.python.org/pypi/queries .. |Status| image:: https://img.shields.io/travis/gmr/queries.svg? :target: https://travis-ci.org/gmr/queries .. |Coverage| image:: https://img.shields.io/codecov/c/github/gmr/queries.svg? :target: https://codecov.io/github/gmr/queries?branch=master .. |License| image:: https://img.shields.io/github/license/gmr/queries.svg? :target: https://github.com/gmr/queries <MSG> Fix the URI scheme in README <DFF> @@ -43,7 +43,7 @@ a session: .. code:: python - session = queries.Session("pgsql://postgres@localhost:5432/postgres") + 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. @@ -53,7 +53,7 @@ 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 ``pgsql://fred@localhost:5432/fred``. +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 @@ -62,7 +62,7 @@ methods. .. code:: python >>> queries.uri("server-name", 5432, "dbname", "user", "pass") - 'pgsql://user:pass@server-name:5432/dbname' + 'postgresql://user:pass@server-name:5432/dbname' Using the queries.Session class
3
Fix the URI scheme in README
3
.rst
rst
bsd-3-clause
gmr/queries
1183
<NME> utils_tests.py <BEF> """ Tests for functionality in the utils module """ import platform import unittest import mock import queries from queries import utils class GetCurrentUserTests(unittest.TestCase): @mock.patch('pwd.getpwuid') def test_get_current_user(self, getpwuid): """get_current_user returns value from pwd.getpwuid""" getpwuid.return_value = ['mocky'] self.assertEqual(utils.get_current_user(), 'mocky') class PYPYDetectionTests(unittest.TestCase): def test_pypy_flag(self): """PYPY flag is set properly""" self.assertEqual(queries.utils.PYPY, platform.python_implementation() == 'PyPy') class URICreationTests(unittest.TestCase): def test_uri_with_password(self): expectation = 'postgresql://foo:bar@baz:5433/qux' self.assertEqual(queries.uri('baz', 5433, 'qux', 'foo', 'bar'), expectation) def test_uri_without_password(self): expectation = 'postgresql://foo@baz:5433/qux' self.assertEqual(queries.uri('baz', 5433, 'qux', 'foo'), expectation) def test_default_uri(self): expectation = 'postgresql://postgres@localhost:5432/postgres' self.assertEqual(queries.uri(), expectation) class 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_invalid(self): """invalid query argument should not be in kwargs""" self.assertNotIn('invaid', utils.uri_to_kwargs(self.URI)) '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> Support Unix socket connections in URI parsing As detailed in http://www.postgresql.org/docs/9.3/static/libpq-connect.html#AEN39029 Address issue #1 <DFF> @@ -82,3 +82,15 @@ class URIToKWargsTestCase(unittest.TestCase): 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/') + +
12
Support Unix socket connections in URI parsing
0
.py
py
bsd-3-clause
gmr/queries
1184
<NME> utils_tests.py <BEF> """ Tests for functionality in the utils module """ import platform import unittest import mock import queries from queries import utils class GetCurrentUserTests(unittest.TestCase): @mock.patch('pwd.getpwuid') def test_get_current_user(self, getpwuid): """get_current_user returns value from pwd.getpwuid""" getpwuid.return_value = ['mocky'] self.assertEqual(utils.get_current_user(), 'mocky') class PYPYDetectionTests(unittest.TestCase): def test_pypy_flag(self): """PYPY flag is set properly""" self.assertEqual(queries.utils.PYPY, platform.python_implementation() == 'PyPy') class URICreationTests(unittest.TestCase): def test_uri_with_password(self): expectation = 'postgresql://foo:bar@baz:5433/qux' self.assertEqual(queries.uri('baz', 5433, 'qux', 'foo', 'bar'), expectation) def test_uri_without_password(self): expectation = 'postgresql://foo@baz:5433/qux' self.assertEqual(queries.uri('baz', 5433, 'qux', 'foo'), expectation) def test_default_uri(self): expectation = 'postgresql://postgres@localhost:5432/postgres' self.assertEqual(queries.uri(), expectation) class 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_invalid(self): """invalid query argument should not be in kwargs""" self.assertNotIn('invaid', utils.uri_to_kwargs(self.URI)) '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> Support Unix socket connections in URI parsing As detailed in http://www.postgresql.org/docs/9.3/static/libpq-connect.html#AEN39029 Address issue #1 <DFF> @@ -82,3 +82,15 @@ class URIToKWargsTestCase(unittest.TestCase): 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/') + +
12
Support Unix socket connections in URI parsing
0
.py
py
bsd-3-clause
gmr/queries
1185
<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> Merge pull request #20 from dave-shawley/propagate-exceptions 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
Merge pull request #20 from dave-shawley/propagate-exceptions
0
.py
py
bsd-3-clause
gmr/queries
1186
<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> Merge pull request #20 from dave-shawley/propagate-exceptions 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
Merge pull request #20 from dave-shawley/propagate-exceptions
0
.py
py
bsd-3-clause
gmr/queries
1187
<NME> pool_tests.py <BEF> """ Tests for functionality in the pool module """ import time import unittest import uuid import mock from queries import pool MAX_POOL_SIZE = 100 def mock_connection(): conn = mock.MagicMock('psycopg2.extensions.connection') conn.close = mock.Mock() conn.closed = True conn.isexecuting = mock.Mock(return_value=False) return conn class PoolTests(unittest.TestCase): def test_id_is_set(self): pool_id = str(uuid.uuid4()) obj = pool.Pool(pool_id) self.assertEqual(obj._id, pool_id) def test_id_property(self): pool_id = str(uuid.uuid4()) obj = pool.Pool(pool_id) self.assertEqual(obj.id, pool_id) def test_idle_ttl_is_default(self): obj = pool.Pool(str(uuid.uuid4())) self.assertEqual(obj.idle_ttl, pool.DEFAULT_IDLE_TTL) def test_max_connection_reached_raises_exception(self): """Ensure that a ValueError is raised with too many connections""" for iteration in range(0, pool.MAX_CONNECTIONS): conn = 'conn%i' % iteration pool.add_connection(self.pid, self, conn) self.assertRaises(ValueError, pool.add_connection, def test_count_of_session_references(self): """Ensure a single session is only added once to the pool sessions""" for iteration in range(0, pool.MAX_CONNECTIONS): conn = 'conn%i' % iteration pool.add_connection(self.pid, self, conn) self.assertEqual(len(pool.Pools[self.pid].sessions), 1) self.assertEqual(obj.idle_ttl, 10) def test_max_size_assignment(self): obj = pool.Pool(str(uuid.uuid4())) obj.set_max_size(10) self.assertEqual(obj.max_size, 10) def test_pool_doesnt_contain_connection(self): obj = pool.Pool(str(uuid.uuid4())) self.assertNotIn('foo', obj) def test_default_connection_count(self): obj = pool.Pool(str(uuid.uuid4())) self.assertEqual(len(obj), 0) def test_add_new_connection(self): psycopg2_conn = mock.Mock() obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertIn(psycopg2_conn, obj) def test_connection_count_after_add(self): psycopg2_conn = mock.Mock() obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertEqual(len(obj), 1) def test_add_existing_connection_raises_on_second_add(self): psycopg2_conn = mock.Mock() obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertRaises(ValueError, obj.add, psycopg2_conn) def test_add_when_pool_is_full_raises(self): obj = pool.Pool(str(uuid.uuid4()), max_size=1) obj.add(mock.Mock()) mock_conn = mock.Mock() self.assertRaises(pool.PoolFullError, obj.add, mock_conn) def test_closed_conn_invokes_remove_on_clean(self): psycopg2_conn = mock.Mock() psycopg2_conn.closed = True obj = pool.Pool(str(uuid.uuid4())) obj.remove = mock.Mock() obj.add(psycopg2_conn) obj.clean() obj.remove.assert_called_once_with(psycopg2_conn) def test_clean_closes_all_when_idle(self): obj = pool.Pool(str(uuid.uuid4()), idle_ttl=10) obj.idle_start = time.time() - 20 obj.close = mock.Mock() obj.clean() obj.close.assert_called_once_with() def test_close_close_removes_all(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) obj.remove = mock.Mock() psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] obj.close() psycopg2_calls = [mock.call(c) for c in psycopg2_conns] obj.remove.assert_has_calls(psycopg2_calls) def test_free_invokes_connection_free(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) self._connection = obj.connection_handle conn = self._connection(psycopg2_conn) conn.free = mock.Mock() obj.free(psycopg2_conn) conn.free.assert_called_once_with() def test_free_raises_not_found_exception(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) conn = obj.connection_handle(psycopg2_conn) conn.free = mock.Mock() obj.free(psycopg2_conn) conn.free.assert_called_once_with() def test_free_resets_idle_start(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): [obj.add(conn) for conn in psycopg2_conns] for psycopg2_conn in psycopg2_conns: conn = obj.connection_handle(psycopg2_conn) conn.free = mock.Mock() obj.free(psycopg2_conns[1]) self.assertAlmostEqual(int(obj.idle_start), int(time.time())) def test_free_raises_on_not_found(self): obj = pool.Pool(str(uuid.uuid4())) self.assertRaises(pool.ConnectionNotFoundError, obj.free, mock.Mock()) def test_get_returns_first_psycopg2_conn(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] session = mock.Mock() self.assertEqual(obj.get(session), psycopg2_conns[0]) def test_get_locks_first_psycopg2_conn(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] lock = mock.Mock() with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False, lock=lock): session = mock.Mock() obj.get(session) lock.assert_called_once_with(session) def test_get_resets_idle_start_to_none(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): session = mock.Mock() obj.idle_start = time.time() obj.get(session) self.assertIsNone(obj.idle_start) def test_get_raises_when_no_idle_connections(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] session = mock.Mock() self.assertRaises(pool.NoIdleConnectionsError, obj.get, session) def test_idle_connections(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): self.assertListEqual([c.handle for c in obj.idle_connections], psycopg2_conns) def test_idle_duration_when_none(self): obj = pool.Pool(str(uuid.uuid4())) obj.idle_start = None self.assertEqual(obj.idle_duration, 0) def test_idle_duration_when_set(self): obj = pool.Pool(str(uuid.uuid4())) obj.idle_start = time.time() - 5 self.assertAlmostEqual(int(obj.idle_duration), 5) def test_is_full_property_when_full(self): obj = pool.Pool(str(uuid.uuid4()), max_size=2) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] self.assertTrue(obj.is_full) def test_is_full_property_when_not_full(self): obj = pool.Pool(str(uuid.uuid4()), max_size=3) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] self.assertFalse(obj.is_full) def test_connection_lock_is_called_when_lock_is(self): with mock.patch('queries.pool.Connection.lock') as lock: obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) session = mock.Mock() obj.lock(psycopg2_conn, session) lock.assert_called_once_with(session) def test_locks_raises_when_connection_not_found(self): obj = pool.Pool(str(uuid.uuid4())) self.assertRaises(pool.ConnectionNotFoundError, obj.lock, mock.Mock(), mock.Mock()) def test_lock_resets_idle_start(self): with mock.patch('queries.pool.Connection.lock'): obj = pool.Pool(str(uuid.uuid4())) obj.idle_start = time.time() psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.lock(psycopg2_conn, mock.Mock()) self.assertIsNone(obj.idle_start) def test_remove_removes_connection(self): with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.remove(psycopg2_conn) self.assertNotIn(psycopg2_conn, obj) def test_remove_closes_connection(self): close_method = mock.Mock() with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False, close=close_method): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.remove(psycopg2_conn) close_method.assert_called_once_with() def test_remove_raises_when_connection_not_found(self): obj = pool.Pool(str(uuid.uuid4())) self.assertRaises(pool.ConnectionNotFoundError, obj.remove, mock.Mock()) def test_remove_raises_when_connection_is_busy(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() psycopg2_conn.closed = False obj.add(psycopg2_conn) self.assertRaises(pool.ConnectionBusyError, obj.remove, psycopg2_conn) def test__connection_returns_handle(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) self.assertEqual( obj.connection_handle(psycopg2_conn).handle, psycopg2_conn) def test_shutdown_raises_when_executing(self): psycopg2_conn = mock_connection() psycopg2_conn.isexecuting.return_value = True obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertRaises(pool.ConnectionBusyError, obj.shutdown) <MSG> Rename the max pool size constant <DFF> @@ -40,7 +40,7 @@ class AddConnectionTests(unittest.TestCase): def test_max_connection_reached_raises_exception(self): """Ensure that a ValueError is raised with too many connections""" - for iteration in range(0, pool.MAX_CONNECTIONS): + for iteration in range(0, pool.MAX_SIZE): conn = 'conn%i' % iteration pool.add_connection(self.pid, self, conn) self.assertRaises(ValueError, pool.add_connection, @@ -48,7 +48,7 @@ class AddConnectionTests(unittest.TestCase): def test_count_of_session_references(self): """Ensure a single session is only added once to the pool sessions""" - for iteration in range(0, pool.MAX_CONNECTIONS): + for iteration in range(0, pool.MAX_SIZE): conn = 'conn%i' % iteration pool.add_connection(self.pid, self, conn) self.assertEqual(len(pool.Pools[self.pid].sessions), 1)
2
Rename the max pool size constant
2
.py
py
bsd-3-clause
gmr/queries
1188
<NME> pool_tests.py <BEF> """ Tests for functionality in the pool module """ import time import unittest import uuid import mock from queries import pool MAX_POOL_SIZE = 100 def mock_connection(): conn = mock.MagicMock('psycopg2.extensions.connection') conn.close = mock.Mock() conn.closed = True conn.isexecuting = mock.Mock(return_value=False) return conn class PoolTests(unittest.TestCase): def test_id_is_set(self): pool_id = str(uuid.uuid4()) obj = pool.Pool(pool_id) self.assertEqual(obj._id, pool_id) def test_id_property(self): pool_id = str(uuid.uuid4()) obj = pool.Pool(pool_id) self.assertEqual(obj.id, pool_id) def test_idle_ttl_is_default(self): obj = pool.Pool(str(uuid.uuid4())) self.assertEqual(obj.idle_ttl, pool.DEFAULT_IDLE_TTL) def test_max_connection_reached_raises_exception(self): """Ensure that a ValueError is raised with too many connections""" for iteration in range(0, pool.MAX_CONNECTIONS): conn = 'conn%i' % iteration pool.add_connection(self.pid, self, conn) self.assertRaises(ValueError, pool.add_connection, def test_count_of_session_references(self): """Ensure a single session is only added once to the pool sessions""" for iteration in range(0, pool.MAX_CONNECTIONS): conn = 'conn%i' % iteration pool.add_connection(self.pid, self, conn) self.assertEqual(len(pool.Pools[self.pid].sessions), 1) self.assertEqual(obj.idle_ttl, 10) def test_max_size_assignment(self): obj = pool.Pool(str(uuid.uuid4())) obj.set_max_size(10) self.assertEqual(obj.max_size, 10) def test_pool_doesnt_contain_connection(self): obj = pool.Pool(str(uuid.uuid4())) self.assertNotIn('foo', obj) def test_default_connection_count(self): obj = pool.Pool(str(uuid.uuid4())) self.assertEqual(len(obj), 0) def test_add_new_connection(self): psycopg2_conn = mock.Mock() obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertIn(psycopg2_conn, obj) def test_connection_count_after_add(self): psycopg2_conn = mock.Mock() obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertEqual(len(obj), 1) def test_add_existing_connection_raises_on_second_add(self): psycopg2_conn = mock.Mock() obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertRaises(ValueError, obj.add, psycopg2_conn) def test_add_when_pool_is_full_raises(self): obj = pool.Pool(str(uuid.uuid4()), max_size=1) obj.add(mock.Mock()) mock_conn = mock.Mock() self.assertRaises(pool.PoolFullError, obj.add, mock_conn) def test_closed_conn_invokes_remove_on_clean(self): psycopg2_conn = mock.Mock() psycopg2_conn.closed = True obj = pool.Pool(str(uuid.uuid4())) obj.remove = mock.Mock() obj.add(psycopg2_conn) obj.clean() obj.remove.assert_called_once_with(psycopg2_conn) def test_clean_closes_all_when_idle(self): obj = pool.Pool(str(uuid.uuid4()), idle_ttl=10) obj.idle_start = time.time() - 20 obj.close = mock.Mock() obj.clean() obj.close.assert_called_once_with() def test_close_close_removes_all(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) obj.remove = mock.Mock() psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] obj.close() psycopg2_calls = [mock.call(c) for c in psycopg2_conns] obj.remove.assert_has_calls(psycopg2_calls) def test_free_invokes_connection_free(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) self._connection = obj.connection_handle conn = self._connection(psycopg2_conn) conn.free = mock.Mock() obj.free(psycopg2_conn) conn.free.assert_called_once_with() def test_free_raises_not_found_exception(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) conn = obj.connection_handle(psycopg2_conn) conn.free = mock.Mock() obj.free(psycopg2_conn) conn.free.assert_called_once_with() def test_free_resets_idle_start(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): [obj.add(conn) for conn in psycopg2_conns] for psycopg2_conn in psycopg2_conns: conn = obj.connection_handle(psycopg2_conn) conn.free = mock.Mock() obj.free(psycopg2_conns[1]) self.assertAlmostEqual(int(obj.idle_start), int(time.time())) def test_free_raises_on_not_found(self): obj = pool.Pool(str(uuid.uuid4())) self.assertRaises(pool.ConnectionNotFoundError, obj.free, mock.Mock()) def test_get_returns_first_psycopg2_conn(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] session = mock.Mock() self.assertEqual(obj.get(session), psycopg2_conns[0]) def test_get_locks_first_psycopg2_conn(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] lock = mock.Mock() with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False, lock=lock): session = mock.Mock() obj.get(session) lock.assert_called_once_with(session) def test_get_resets_idle_start_to_none(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): session = mock.Mock() obj.idle_start = time.time() obj.get(session) self.assertIsNone(obj.idle_start) def test_get_raises_when_no_idle_connections(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] session = mock.Mock() self.assertRaises(pool.NoIdleConnectionsError, obj.get, session) def test_idle_connections(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): self.assertListEqual([c.handle for c in obj.idle_connections], psycopg2_conns) def test_idle_duration_when_none(self): obj = pool.Pool(str(uuid.uuid4())) obj.idle_start = None self.assertEqual(obj.idle_duration, 0) def test_idle_duration_when_set(self): obj = pool.Pool(str(uuid.uuid4())) obj.idle_start = time.time() - 5 self.assertAlmostEqual(int(obj.idle_duration), 5) def test_is_full_property_when_full(self): obj = pool.Pool(str(uuid.uuid4()), max_size=2) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] self.assertTrue(obj.is_full) def test_is_full_property_when_not_full(self): obj = pool.Pool(str(uuid.uuid4()), max_size=3) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] self.assertFalse(obj.is_full) def test_connection_lock_is_called_when_lock_is(self): with mock.patch('queries.pool.Connection.lock') as lock: obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) session = mock.Mock() obj.lock(psycopg2_conn, session) lock.assert_called_once_with(session) def test_locks_raises_when_connection_not_found(self): obj = pool.Pool(str(uuid.uuid4())) self.assertRaises(pool.ConnectionNotFoundError, obj.lock, mock.Mock(), mock.Mock()) def test_lock_resets_idle_start(self): with mock.patch('queries.pool.Connection.lock'): obj = pool.Pool(str(uuid.uuid4())) obj.idle_start = time.time() psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.lock(psycopg2_conn, mock.Mock()) self.assertIsNone(obj.idle_start) def test_remove_removes_connection(self): with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.remove(psycopg2_conn) self.assertNotIn(psycopg2_conn, obj) def test_remove_closes_connection(self): close_method = mock.Mock() with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False, close=close_method): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.remove(psycopg2_conn) close_method.assert_called_once_with() def test_remove_raises_when_connection_not_found(self): obj = pool.Pool(str(uuid.uuid4())) self.assertRaises(pool.ConnectionNotFoundError, obj.remove, mock.Mock()) def test_remove_raises_when_connection_is_busy(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() psycopg2_conn.closed = False obj.add(psycopg2_conn) self.assertRaises(pool.ConnectionBusyError, obj.remove, psycopg2_conn) def test__connection_returns_handle(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) self.assertEqual( obj.connection_handle(psycopg2_conn).handle, psycopg2_conn) def test_shutdown_raises_when_executing(self): psycopg2_conn = mock_connection() psycopg2_conn.isexecuting.return_value = True obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertRaises(pool.ConnectionBusyError, obj.shutdown) <MSG> Rename the max pool size constant <DFF> @@ -40,7 +40,7 @@ class AddConnectionTests(unittest.TestCase): def test_max_connection_reached_raises_exception(self): """Ensure that a ValueError is raised with too many connections""" - for iteration in range(0, pool.MAX_CONNECTIONS): + for iteration in range(0, pool.MAX_SIZE): conn = 'conn%i' % iteration pool.add_connection(self.pid, self, conn) self.assertRaises(ValueError, pool.add_connection, @@ -48,7 +48,7 @@ class AddConnectionTests(unittest.TestCase): def test_count_of_session_references(self): """Ensure a single session is only added once to the pool sessions""" - for iteration in range(0, pool.MAX_CONNECTIONS): + for iteration in range(0, pool.MAX_SIZE): conn = 'conn%i' % iteration pool.add_connection(self.pid, self, conn) self.assertEqual(len(pool.Pools[self.pid].sessions), 1)
2
Rename the max pool size constant
2
.py
py
bsd-3-clause
gmr/queries
1189
<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' Using the queries.Session class ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To execute queries or call stored procedures, you start by creating an instance of the :py:class:`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 :pep:`343`. In addition to both the :py:meth:`queries.Session.query` and :py:meth:`queries.Session.callproc` methods that are similar to the simple API methods, the :py:class:`queries.Session` class provides access to the psycopg2 :py:class:`~psycopg2.extensions.connection` and :py:class:`~psycopg2.extensions.cursor` objects. It also provides methods for managing transactions and to the `LISTEN/NOTIFY <http://www.postgresql.org/docs/9.3/static/sql-listen.html>`_ functionality provided by PostgreSQL. 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 .. _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 .. |Version| image:: https://badge.fury.io/py/queries.svg? :target: http://badge.fury.io/py/queries .. _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> More README updates <DFF> @@ -68,16 +68,14 @@ methods. Using the queries.Session class ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To execute queries or call stored procedures, you start by creating an instance of the -:py:class:`queries.Session` class. It can act as a context manager, meaning you can +``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 :pep:`343`. - -In addition to both the :py:meth:`queries.Session.query` and -:py:meth:`queries.Session.callproc` methods that -are similar to the simple API methods, the :py:class:`queries.Session` class provides -access to the psycopg2 :py:class:`~psycopg2.extensions.connection` and -:py:class:`~psycopg2.extensions.cursor` objects. It also provides methods for -managing transactions and to the +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. It also provides +methods for managing transactions and to the `LISTEN/NOTIFY <http://www.postgresql.org/docs/9.3/static/sql-listen.html>`_ functionality provided by PostgreSQL. @@ -164,6 +162,7 @@ main GitHub repository of Queries as tags prior to version 1.2.0. .. _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/ .. |Version| image:: https://badge.fury.io/py/queries.svg? :target: http://badge.fury.io/py/queries
8
More README updates
9
.rst
rst
bsd-3-clause
gmr/queries
1190
<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' Using the queries.Session class ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To execute queries or call stored procedures, you start by creating an instance of the :py:class:`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 :pep:`343`. In addition to both the :py:meth:`queries.Session.query` and :py:meth:`queries.Session.callproc` methods that are similar to the simple API methods, the :py:class:`queries.Session` class provides access to the psycopg2 :py:class:`~psycopg2.extensions.connection` and :py:class:`~psycopg2.extensions.cursor` objects. It also provides methods for managing transactions and to the `LISTEN/NOTIFY <http://www.postgresql.org/docs/9.3/static/sql-listen.html>`_ functionality provided by PostgreSQL. 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 .. _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 .. |Version| image:: https://badge.fury.io/py/queries.svg? :target: http://badge.fury.io/py/queries .. _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> More README updates <DFF> @@ -68,16 +68,14 @@ methods. Using the queries.Session class ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To execute queries or call stored procedures, you start by creating an instance of the -:py:class:`queries.Session` class. It can act as a context manager, meaning you can +``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 :pep:`343`. - -In addition to both the :py:meth:`queries.Session.query` and -:py:meth:`queries.Session.callproc` methods that -are similar to the simple API methods, the :py:class:`queries.Session` class provides -access to the psycopg2 :py:class:`~psycopg2.extensions.connection` and -:py:class:`~psycopg2.extensions.cursor` objects. It also provides methods for -managing transactions and to the +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. It also provides +methods for managing transactions and to the `LISTEN/NOTIFY <http://www.postgresql.org/docs/9.3/static/sql-listen.html>`_ functionality provided by PostgreSQL. @@ -164,6 +162,7 @@ main GitHub repository of Queries as tags prior to version 1.2.0. .. _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/ .. |Version| image:: https://badge.fury.io/py/queries.svg? :target: http://badge.fury.io/py/queries
8
More README updates
9
.rst
rst
bsd-3-clause
gmr/queries
1191
<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. allows for multiple modules in the same interpreter to use the same PostgreSQL connection. Installation ------------ pgsql_wrapper is available via pypi and can be installed with easy_install or pip: - 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 Example ------- import pgsql_wrapper HOST = 'localhost' 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: connection.cursor.execute('SELECT 1 as value') data = connection.cursor.fetchone() print data['value'] 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> Add badges, code highlighting <DFF> @@ -12,6 +12,8 @@ Without requiring any additional code, the module level caching of connections allows for multiple modules in the same interpreter to use the same PostgreSQL connection. +|Version| |Downloads| |Status| + Installation ------------ pgsql_wrapper is available via pypi and can be installed with easy_install or pip: @@ -27,6 +29,8 @@ Requirements Example ------- +.. code:: python + import pgsql_wrapper HOST = 'localhost' @@ -39,3 +43,14 @@ Example connection.cursor.execute('SELECT 1 as value') data = connection.cursor.fetchone() print data['value'] + + + +.. |Version| image:: https://badge.fury.io/py/pgsql_wrapper.svg? + :target: http://badge.fury.io/py/pgsql_wrapper + +.. |Status| image:: https://travis-ci.org/gmr/pgsql_wrapper.svg?branch=master + :target: https://travis-ci.org/gmr/pgsql_wrapper + +.. |Downloads| image:: https://pypip.in/d/pgsql_wrapper/badge.svg? + :target: https://pypi.python.org/pypi/pgsql_wrapper \ No newline at end of file
15
Add badges, code highlighting
0
.rst
rst
bsd-3-clause
gmr/queries
1192
<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. allows for multiple modules in the same interpreter to use the same PostgreSQL connection. Installation ------------ pgsql_wrapper is available via pypi and can be installed with easy_install or pip: - 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 Example ------- import pgsql_wrapper HOST = 'localhost' 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: connection.cursor.execute('SELECT 1 as value') data = connection.cursor.fetchone() print data['value'] 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> Add badges, code highlighting <DFF> @@ -12,6 +12,8 @@ Without requiring any additional code, the module level caching of connections allows for multiple modules in the same interpreter to use the same PostgreSQL connection. +|Version| |Downloads| |Status| + Installation ------------ pgsql_wrapper is available via pypi and can be installed with easy_install or pip: @@ -27,6 +29,8 @@ Requirements Example ------- +.. code:: python + import pgsql_wrapper HOST = 'localhost' @@ -39,3 +43,14 @@ Example connection.cursor.execute('SELECT 1 as value') data = connection.cursor.fetchone() print data['value'] + + + +.. |Version| image:: https://badge.fury.io/py/pgsql_wrapper.svg? + :target: http://badge.fury.io/py/pgsql_wrapper + +.. |Status| image:: https://travis-ci.org/gmr/pgsql_wrapper.svg?branch=master + :target: https://travis-ci.org/gmr/pgsql_wrapper + +.. |Downloads| image:: https://pypip.in/d/pgsql_wrapper/badge.svg? + :target: https://pypi.python.org/pypi/pgsql_wrapper \ No newline at end of file
15
Add badges, code highlighting
0
.rst
rst
bsd-3-clause
gmr/queries
1193
<NME> pool_tests.py <BEF> """ Tests for functionality in the pool module """ import time import unittest import uuid import mock from queries import pool MAX_POOL_SIZE = 100 MAX_POOL_SIZE = 100 class PoolTests(unittest.TestCase): def test_id_is_set(self): def test_id_property(self): pool_id = str(uuid.uuid4()) obj = pool.Pool(pool_id) self.assertEqual(obj.id, pool_id) def test_idle_ttl_is_default(self): obj = pool.Pool(str(uuid.uuid4())) self.assertEqual(obj.idle_ttl, pool.DEFAULT_IDLE_TTL) def test_max_size_is_default(self): obj = pool.Pool(str(uuid.uuid4())) self.assertEqual(obj.max_size, pool.DEFAULT_MAX_SIZE) def test_idle_ttl_constructor_assignment(self): obj = pool.Pool(str(uuid.uuid4()), 10) self.assertEqual(obj.idle_ttl, 10) def test_max_size_constructor_assignment(self): obj = pool.Pool(str(uuid.uuid4()), max_size=10) self.assertEqual(obj.max_size, 10) def test_idle_ttl_assignment(self): obj = pool.Pool(str(uuid.uuid4())) obj.set_idle_ttl(10) self.assertEqual(obj.idle_ttl, 10) def test_max_size_assignment(self): obj = pool.Pool(str(uuid.uuid4())) obj.set_max_size(10) self.assertEqual(obj.max_size, 10) def test_pool_doesnt_contain_connection(self): obj = pool.Pool(str(uuid.uuid4())) self.assertNotIn('foo', obj) def test_default_connection_count(self): obj = pool.Pool(str(uuid.uuid4())) self.assertEqual(len(obj), 0) def test_add_new_connection(self): psycopg2_conn = mock.Mock() obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertIn(psycopg2_conn, obj) def test_connection_count_after_add(self): psycopg2_conn = mock.Mock() obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertEqual(len(obj), 1) def test_add_existing_connection_raises_on_second_add(self): psycopg2_conn = mock.Mock() obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertRaises(ValueError, obj.add, psycopg2_conn) def test_add_when_pool_is_full_raises(self): obj = pool.Pool(str(uuid.uuid4()), max_size=1) obj.add(mock.Mock()) mock_conn = mock.Mock() self.assertRaises(pool.PoolFullError, obj.add, mock_conn) def test_closed_conn_invokes_remove_on_clean(self): psycopg2_conn = mock.Mock() psycopg2_conn.closed = True obj = pool.Pool(str(uuid.uuid4())) obj.remove = mock.Mock() obj.add(psycopg2_conn) obj.clean() obj.remove.assert_called_once_with(psycopg2_conn) def test_clean_closes_all_when_idle(self): obj = pool.Pool(str(uuid.uuid4()), idle_ttl=10) obj.idle_start = time.time() - 20 obj.close = mock.Mock() obj.clean() obj.close.assert_called_once_with() def test_close_close_removes_all(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) obj.remove = mock.Mock() psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] obj.close() psycopg2_calls = [mock.call(c) for c in psycopg2_conns] obj.remove.assert_has_calls(psycopg2_calls) def test_free_invokes_connection_free(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) self._connection = obj.connection_handle conn = self._connection(psycopg2_conn) conn.free = mock.Mock() obj.free(psycopg2_conn) conn.free.assert_called_once_with() def test_free_raises_not_found_exception(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) conn = obj.connection_handle(psycopg2_conn) conn.free = mock.Mock() obj.free(psycopg2_conn) conn.free.assert_called_once_with() def test_free_resets_idle_start(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): [obj.add(conn) for conn in psycopg2_conns] for psycopg2_conn in psycopg2_conns: conn = obj.connection_handle(psycopg2_conn) conn.free = mock.Mock() obj.free(psycopg2_conns[1]) self.assertAlmostEqual(int(obj.idle_start), int(time.time())) def test_free_raises_on_not_found(self): obj = pool.Pool(str(uuid.uuid4())) self.assertRaises(pool.ConnectionNotFoundError, obj.free, mock.Mock()) def test_get_returns_first_psycopg2_conn(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] session = mock.Mock() self.assertEqual(obj.get(session), psycopg2_conns[0]) def test_get_locks_first_psycopg2_conn(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] lock = mock.Mock() with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False, lock=lock): session = mock.Mock() obj.get(session) lock.assert_called_once_with(session) def test_get_resets_idle_start_to_none(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): session = mock.Mock() obj.idle_start = time.time() obj.get(session) self.assertIsNone(obj.idle_start) def test_get_raises_when_no_idle_connections(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] session = mock.Mock() self.assertRaises(pool.NoIdleConnectionsError, obj.get, session) def test_idle_connections(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): self.assertListEqual([c.handle for c in obj.idle_connections], psycopg2_conns) def test_idle_duration_when_none(self): obj = pool.Pool(str(uuid.uuid4())) obj.idle_start = None self.assertEqual(obj.idle_duration, 0) def test_idle_duration_when_set(self): obj = pool.Pool(str(uuid.uuid4())) obj.idle_start = time.time() - 5 self.assertAlmostEqual(int(obj.idle_duration), 5) def test_is_full_property_when_full(self): obj = pool.Pool(str(uuid.uuid4()), max_size=2) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] self.assertTrue(obj.is_full) def test_is_full_property_when_not_full(self): obj = pool.Pool(str(uuid.uuid4()), max_size=3) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] self.assertFalse(obj.is_full) def test_connection_lock_is_called_when_lock_is(self): with mock.patch('queries.pool.Connection.lock') as lock: obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) session = mock.Mock() obj.lock(psycopg2_conn, session) lock.assert_called_once_with(session) def test_locks_raises_when_connection_not_found(self): obj = pool.Pool(str(uuid.uuid4())) self.assertRaises(pool.ConnectionNotFoundError, obj.lock, mock.Mock(), mock.Mock()) def test_lock_resets_idle_start(self): with mock.patch('queries.pool.Connection.lock'): obj = pool.Pool(str(uuid.uuid4())) obj.idle_start = time.time() psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.lock(psycopg2_conn, mock.Mock()) self.assertIsNone(obj.idle_start) def test_remove_removes_connection(self): with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.remove(psycopg2_conn) self.assertNotIn(psycopg2_conn, obj) def test_remove_closes_connection(self): close_method = mock.Mock() with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False, close=close_method): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.remove(psycopg2_conn) close_method.assert_called_once_with() def test_remove_raises_when_connection_not_found(self): obj = pool.Pool(str(uuid.uuid4())) self.assertRaises(pool.ConnectionNotFoundError, obj.remove, mock.Mock()) def test_remove_raises_when_connection_is_busy(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() psycopg2_conn.closed = False obj.add(psycopg2_conn) self.assertRaises(pool.ConnectionBusyError, obj.remove, psycopg2_conn) def test__connection_returns_handle(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) self.assertEqual(obj._connection(psycopg2_conn).handle, psycopg2_conn) <MSG> Add a test for Pool.shutdown & fix the bug it found pool.ConnectionBusyError requires a parameter <DFF> @@ -16,6 +16,14 @@ from queries import pool MAX_POOL_SIZE = 100 +def mock_connection(): + conn = mock.MagicMock('psycopg2.extensions.connection') + conn.close = mock.Mock() + conn.closed = True + conn.isexecuting = mock.Mock(return_value=False) + return conn + + class PoolTests(unittest.TestCase): def test_id_is_set(self): @@ -274,3 +282,11 @@ class PoolTests(unittest.TestCase): psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) self.assertEqual(obj._connection(psycopg2_conn).handle, psycopg2_conn) + + def test_shutdown_raises_when_executing(self): + psycopg2_conn = mock_connection() + psycopg2_conn.isexecuting.return_value = True + obj = pool.Pool(str(uuid.uuid4())) + obj.add(psycopg2_conn) + self.assertRaises(pool.ConnectionBusyError, obj.shutdown) +
16
Add a test for Pool.shutdown & fix the bug it found
0
.py
py
bsd-3-clause
gmr/queries
1194
<NME> pool_tests.py <BEF> """ Tests for functionality in the pool module """ import time import unittest import uuid import mock from queries import pool MAX_POOL_SIZE = 100 MAX_POOL_SIZE = 100 class PoolTests(unittest.TestCase): def test_id_is_set(self): def test_id_property(self): pool_id = str(uuid.uuid4()) obj = pool.Pool(pool_id) self.assertEqual(obj.id, pool_id) def test_idle_ttl_is_default(self): obj = pool.Pool(str(uuid.uuid4())) self.assertEqual(obj.idle_ttl, pool.DEFAULT_IDLE_TTL) def test_max_size_is_default(self): obj = pool.Pool(str(uuid.uuid4())) self.assertEqual(obj.max_size, pool.DEFAULT_MAX_SIZE) def test_idle_ttl_constructor_assignment(self): obj = pool.Pool(str(uuid.uuid4()), 10) self.assertEqual(obj.idle_ttl, 10) def test_max_size_constructor_assignment(self): obj = pool.Pool(str(uuid.uuid4()), max_size=10) self.assertEqual(obj.max_size, 10) def test_idle_ttl_assignment(self): obj = pool.Pool(str(uuid.uuid4())) obj.set_idle_ttl(10) self.assertEqual(obj.idle_ttl, 10) def test_max_size_assignment(self): obj = pool.Pool(str(uuid.uuid4())) obj.set_max_size(10) self.assertEqual(obj.max_size, 10) def test_pool_doesnt_contain_connection(self): obj = pool.Pool(str(uuid.uuid4())) self.assertNotIn('foo', obj) def test_default_connection_count(self): obj = pool.Pool(str(uuid.uuid4())) self.assertEqual(len(obj), 0) def test_add_new_connection(self): psycopg2_conn = mock.Mock() obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertIn(psycopg2_conn, obj) def test_connection_count_after_add(self): psycopg2_conn = mock.Mock() obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertEqual(len(obj), 1) def test_add_existing_connection_raises_on_second_add(self): psycopg2_conn = mock.Mock() obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertRaises(ValueError, obj.add, psycopg2_conn) def test_add_when_pool_is_full_raises(self): obj = pool.Pool(str(uuid.uuid4()), max_size=1) obj.add(mock.Mock()) mock_conn = mock.Mock() self.assertRaises(pool.PoolFullError, obj.add, mock_conn) def test_closed_conn_invokes_remove_on_clean(self): psycopg2_conn = mock.Mock() psycopg2_conn.closed = True obj = pool.Pool(str(uuid.uuid4())) obj.remove = mock.Mock() obj.add(psycopg2_conn) obj.clean() obj.remove.assert_called_once_with(psycopg2_conn) def test_clean_closes_all_when_idle(self): obj = pool.Pool(str(uuid.uuid4()), idle_ttl=10) obj.idle_start = time.time() - 20 obj.close = mock.Mock() obj.clean() obj.close.assert_called_once_with() def test_close_close_removes_all(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) obj.remove = mock.Mock() psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] obj.close() psycopg2_calls = [mock.call(c) for c in psycopg2_conns] obj.remove.assert_has_calls(psycopg2_calls) def test_free_invokes_connection_free(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) self._connection = obj.connection_handle conn = self._connection(psycopg2_conn) conn.free = mock.Mock() obj.free(psycopg2_conn) conn.free.assert_called_once_with() def test_free_raises_not_found_exception(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) conn = obj.connection_handle(psycopg2_conn) conn.free = mock.Mock() obj.free(psycopg2_conn) conn.free.assert_called_once_with() def test_free_resets_idle_start(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): [obj.add(conn) for conn in psycopg2_conns] for psycopg2_conn in psycopg2_conns: conn = obj.connection_handle(psycopg2_conn) conn.free = mock.Mock() obj.free(psycopg2_conns[1]) self.assertAlmostEqual(int(obj.idle_start), int(time.time())) def test_free_raises_on_not_found(self): obj = pool.Pool(str(uuid.uuid4())) self.assertRaises(pool.ConnectionNotFoundError, obj.free, mock.Mock()) def test_get_returns_first_psycopg2_conn(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] session = mock.Mock() self.assertEqual(obj.get(session), psycopg2_conns[0]) def test_get_locks_first_psycopg2_conn(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] lock = mock.Mock() with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False, lock=lock): session = mock.Mock() obj.get(session) lock.assert_called_once_with(session) def test_get_resets_idle_start_to_none(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): session = mock.Mock() obj.idle_start = time.time() obj.get(session) self.assertIsNone(obj.idle_start) def test_get_raises_when_no_idle_connections(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] session = mock.Mock() self.assertRaises(pool.NoIdleConnectionsError, obj.get, session) def test_idle_connections(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): self.assertListEqual([c.handle for c in obj.idle_connections], psycopg2_conns) def test_idle_duration_when_none(self): obj = pool.Pool(str(uuid.uuid4())) obj.idle_start = None self.assertEqual(obj.idle_duration, 0) def test_idle_duration_when_set(self): obj = pool.Pool(str(uuid.uuid4())) obj.idle_start = time.time() - 5 self.assertAlmostEqual(int(obj.idle_duration), 5) def test_is_full_property_when_full(self): obj = pool.Pool(str(uuid.uuid4()), max_size=2) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] self.assertTrue(obj.is_full) def test_is_full_property_when_not_full(self): obj = pool.Pool(str(uuid.uuid4()), max_size=3) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] self.assertFalse(obj.is_full) def test_connection_lock_is_called_when_lock_is(self): with mock.patch('queries.pool.Connection.lock') as lock: obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) session = mock.Mock() obj.lock(psycopg2_conn, session) lock.assert_called_once_with(session) def test_locks_raises_when_connection_not_found(self): obj = pool.Pool(str(uuid.uuid4())) self.assertRaises(pool.ConnectionNotFoundError, obj.lock, mock.Mock(), mock.Mock()) def test_lock_resets_idle_start(self): with mock.patch('queries.pool.Connection.lock'): obj = pool.Pool(str(uuid.uuid4())) obj.idle_start = time.time() psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.lock(psycopg2_conn, mock.Mock()) self.assertIsNone(obj.idle_start) def test_remove_removes_connection(self): with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.remove(psycopg2_conn) self.assertNotIn(psycopg2_conn, obj) def test_remove_closes_connection(self): close_method = mock.Mock() with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False, close=close_method): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.remove(psycopg2_conn) close_method.assert_called_once_with() def test_remove_raises_when_connection_not_found(self): obj = pool.Pool(str(uuid.uuid4())) self.assertRaises(pool.ConnectionNotFoundError, obj.remove, mock.Mock()) def test_remove_raises_when_connection_is_busy(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() psycopg2_conn.closed = False obj.add(psycopg2_conn) self.assertRaises(pool.ConnectionBusyError, obj.remove, psycopg2_conn) def test__connection_returns_handle(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) self.assertEqual(obj._connection(psycopg2_conn).handle, psycopg2_conn) <MSG> Add a test for Pool.shutdown & fix the bug it found pool.ConnectionBusyError requires a parameter <DFF> @@ -16,6 +16,14 @@ from queries import pool MAX_POOL_SIZE = 100 +def mock_connection(): + conn = mock.MagicMock('psycopg2.extensions.connection') + conn.close = mock.Mock() + conn.closed = True + conn.isexecuting = mock.Mock(return_value=False) + return conn + + class PoolTests(unittest.TestCase): def test_id_is_set(self): @@ -274,3 +282,11 @@ class PoolTests(unittest.TestCase): psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) self.assertEqual(obj._connection(psycopg2_conn).handle, psycopg2_conn) + + def test_shutdown_raises_when_executing(self): + psycopg2_conn = mock_connection() + psycopg2_conn.isexecuting.return_value = True + obj = pool.Pool(str(uuid.uuid4())) + obj.add(psycopg2_conn) + self.assertRaises(pool.ConnectionBusyError, obj.shutdown) +
16
Add a test for Pool.shutdown & fix the bug it found
0
.py
py
bsd-3-clause
gmr/queries
1195
<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 both 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 @gen.coroutine def get(self): results = yield self.session.query('SELECT * FROM names') self.finish({'data': data.items()}) results.free() application = web.Application([ @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> Merge pull request #3 from den-t/patch-1 Typos in README.rst <DFF> @@ -37,7 +37,7 @@ Queries is available via pypi_ and can be installed with easy_install or pip: Usage ----- -Queries provides both a session based API for interacting with PostgreSQL. +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: @@ -132,7 +132,7 @@ Tornado_ web application to send a JSON payload with the query result set. @gen.coroutine def get(self): results = yield self.session.query('SELECT * FROM names') - self.finish({'data': data.items()}) + self.finish({'data': results.items()}) results.free() application = web.Application([
2
Merge pull request #3 from den-t/patch-1
2
.rst
rst
bsd-3-clause
gmr/queries
1196
<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 both 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 @gen.coroutine def get(self): results = yield self.session.query('SELECT * FROM names') self.finish({'data': data.items()}) results.free() application = web.Application([ @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> Merge pull request #3 from den-t/patch-1 Typos in README.rst <DFF> @@ -37,7 +37,7 @@ Queries is available via pypi_ and can be installed with easy_install or pip: Usage ----- -Queries provides both a session based API for interacting with PostgreSQL. +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: @@ -132,7 +132,7 @@ Tornado_ web application to send a JSON payload with the query result set. @gen.coroutine def get(self): results = yield self.session.query('SELECT * FROM names') - self.finish({'data': data.items()}) + self.finish({'data': results.items()}) results.free() application = web.Application([
2
Merge pull request #3 from den-t/patch-1
2
.rst
rst
bsd-3-clause
gmr/queries
1197
<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'} 'password': 'bar', 'dbname': 'foo'} self.obj = session.Session(self.URI) def test_init_sets_uri(self): self.assertEqual(self.obj._uri, self.URI) 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 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_cleanup_cleans_pool_manager(self): pool.PoolManager.clean = clean = mock.Mock() self.obj._cleanup() clean.assert_called_once_with(self.obj.pid) 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> Update pool and session tests Reflecting default pool size and Session._cleanup changes <DFF> @@ -47,7 +47,7 @@ class SessionTestCase(unittest.TestCase): 'password': 'bar', 'dbname': 'foo'} - self.obj = session.Session(self.URI) + self.obj = session.Session(self.URI, pool_max_size=100) def test_init_sets_uri(self): self.assertEqual(self.obj._uri, self.URI) @@ -190,11 +190,6 @@ class SessionTestCase(unittest.TestCase): 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) - def test_connect_invokes_pool_manager_get(self): with mock.patch.object(self.obj._pool_manager, 'get') as get: self.obj._connect()
1
Update pool and session tests
6
.py
py
bsd-3-clause
gmr/queries
1198
<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'} 'password': 'bar', 'dbname': 'foo'} self.obj = session.Session(self.URI) def test_init_sets_uri(self): self.assertEqual(self.obj._uri, self.URI) 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 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_cleanup_cleans_pool_manager(self): pool.PoolManager.clean = clean = mock.Mock() self.obj._cleanup() clean.assert_called_once_with(self.obj.pid) 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> Update pool and session tests Reflecting default pool size and Session._cleanup changes <DFF> @@ -47,7 +47,7 @@ class SessionTestCase(unittest.TestCase): 'password': 'bar', 'dbname': 'foo'} - self.obj = session.Session(self.URI) + self.obj = session.Session(self.URI, pool_max_size=100) def test_init_sets_uri(self): self.assertEqual(self.obj._uri, self.URI) @@ -190,11 +190,6 @@ class SessionTestCase(unittest.TestCase): 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) - def test_connect_invokes_pool_manager_get(self): with mock.patch.object(self.obj._pool_manager, 'get') as get: self.obj._connect()
1
Update pool and session tests
6
.py
py
bsd-3-clause
gmr/queries
1199
<NME> index.rst <BEF> Queries: PostgreSQL Simplified ============================== *Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for interacting with PostgreSQL. |Version| |License| The popular psycopg2_ package is a full-featured python client. Unfortunately as a developer, you're often repeating the same steps to get started with your applications that use it. Queries aims to reduce the complexity of psycopg2 while adding additional features to make writing PostgreSQL client applications both fast and easy. *Key features include*: - Simplified API - Support of Python 2.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_ :py:class:`~psycopg2.extensions.connection` and :py:class:`~psycopg2.extensions.cursor` objects - Internal connection pooling Installation ------------ Queries can be installed via the `Python Package Index <https://pypi.python.org/pypi/queries>`_ and can be installed by running :command:`easy_install queries` or :command:`pip install queries` When installing Queries, ``pip`` or ``easy_install`` will automatically install the proper dependencies for your platform. Contents -------- .. toctree:: :maxdepth: 1 usage session results tornado_session pool examples/index.rst history Issues ------ Please report any issues to the Github repo at `https://github.com/gmr/queries/issues <https://github.com/gmr/queries/issues>`_ Issues ------ Please report any issues to the Github repo at `https://github.com/gmr/queries/issues <https://github.com/gmr/rabbitpy/queries>`_ Source ------ Queries is inspired by `Kenneth Reitz's <https://github.com/kennethreitz/>`_ awesome work on `requests <http://docs.python-requests.org/en/latest/>`_. Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` .. _pypi: https://pypi.python.org/pypi/queries .. _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 .. |License| image:: https://img.shields.io/github/license/gmr/queries.svg? :target: https://github.com/gmr/queries :target: https://travis-ci.org/gmr/queries .. |Downloads| image:: https://pypip.in/d/queries/badge.svg? :target: https://pypi.python.org/pypi/queries <MSG> Merge pull request #5 from jchassoul/patch-1 Update index.rst <DFF> @@ -51,7 +51,7 @@ Contents Issues ------ -Please report any issues to the Github repo at `https://github.com/gmr/queries/issues <https://github.com/gmr/rabbitpy/queries>`_ +Please report any issues to the Github repo at `https://github.com/gmr/queries/issues <https://github.com/gmr/queries/issues>`_ Source ------ @@ -84,4 +84,4 @@ Indices and tables :target: https://travis-ci.org/gmr/queries .. |Downloads| image:: https://pypip.in/d/queries/badge.svg? - :target: https://pypi.python.org/pypi/queries \ No newline at end of file + :target: https://pypi.python.org/pypi/queries
2
Merge pull request #5 from jchassoul/patch-1
2
.rst
rst
bsd-3-clause
gmr/queries