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
|
---|---|---|---|---|---|---|---|---|
1300 | <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> Merge pull request #30 from nvllsvm/devenv
boostrap updates
<DFF> @@ -10,36 +10,33 @@ 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
+mkdir -p 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 -t 0 --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"
+printf "Waiting for postgres "
export PG
-until psql -U postgres -h ${DOCKER_IP} -p ${PORT} -c 'SELECT 1' > /dev/null 2> /dev/null; do
- echo ".\c"
+until docker-compose exec postgres pg_isready -q; do
+ printf "."
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
| 10 | Merge pull request #30 from nvllsvm/devenv | 13 | bootstrap | bsd-3-clause | gmr/queries |
|
1301 | <NME> .travis.yml
<BEF> sudo: false
language: python
dist: xenial
env:
global:
- PATH=$HOME/.local/bin:$PATH
- AWS_DEFAULT_REGION=us-east-1
- 3.4
install:
- if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install -r requirements.txt; pip install psycopg2 unittest2; fi
- if [[ $TRAVIS_PYTHON_VERSION == '2.7' ]]; then pip install -r requirements.txt; pip install psycopg2; fi
- if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then pip install -r requirements.txt; pip install psycopg2ct; fi
- if [[ $TRAVIS_PYTHON_VERSION == '3.2' ]]; then pip install -r requirements.txt; pip install psycopg2; fi
- if [[ $TRAVIS_PYTHON_VERSION == '3.3' ]]; then pip install -r requirements.txt; pip install psycopg2; fi
- if [[ $TRAVIS_PYTHON_VERSION == '3.4' ]]; then pip install -r requirements.txt; pip install psycopg2; fi
script: nosetests --with-coverage --cover-package=queries
after_success:
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> Simplify the python version rules in travis install rules
<DFF> @@ -9,12 +9,9 @@ python:
- 3.4
install:
- - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install -r requirements.txt; pip install psycopg2 unittest2; fi
- - if [[ $TRAVIS_PYTHON_VERSION == '2.7' ]]; then pip install -r requirements.txt; pip install psycopg2; fi
+ - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install unittest2; fi
+ - if [[ $TRAVIS_PYTHON_VERSION != 'pypy' ]]; then pip install -r requirements.txt; pip install psycopg2; fi
- if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then pip install -r requirements.txt; pip install psycopg2ct; fi
- - if [[ $TRAVIS_PYTHON_VERSION == '3.2' ]]; then pip install -r requirements.txt; pip install psycopg2; fi
- - if [[ $TRAVIS_PYTHON_VERSION == '3.3' ]]; then pip install -r requirements.txt; pip install psycopg2; fi
- - if [[ $TRAVIS_PYTHON_VERSION == '3.4' ]]; then pip install -r requirements.txt; pip install psycopg2; fi
script: nosetests --with-coverage --cover-package=queries
after_success:
| 2 | Simplify the python version rules in travis install rules | 5 | .yml | travis | bsd-3-clause | gmr/queries |
1302 | <NME> .travis.yml
<BEF> sudo: false
language: python
dist: xenial
env:
global:
- PATH=$HOME/.local/bin:$PATH
- AWS_DEFAULT_REGION=us-east-1
- 3.4
install:
- if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install -r requirements.txt; pip install psycopg2 unittest2; fi
- if [[ $TRAVIS_PYTHON_VERSION == '2.7' ]]; then pip install -r requirements.txt; pip install psycopg2; fi
- if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then pip install -r requirements.txt; pip install psycopg2ct; fi
- if [[ $TRAVIS_PYTHON_VERSION == '3.2' ]]; then pip install -r requirements.txt; pip install psycopg2; fi
- if [[ $TRAVIS_PYTHON_VERSION == '3.3' ]]; then pip install -r requirements.txt; pip install psycopg2; fi
- if [[ $TRAVIS_PYTHON_VERSION == '3.4' ]]; then pip install -r requirements.txt; pip install psycopg2; fi
script: nosetests --with-coverage --cover-package=queries
after_success:
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> Simplify the python version rules in travis install rules
<DFF> @@ -9,12 +9,9 @@ python:
- 3.4
install:
- - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install -r requirements.txt; pip install psycopg2 unittest2; fi
- - if [[ $TRAVIS_PYTHON_VERSION == '2.7' ]]; then pip install -r requirements.txt; pip install psycopg2; fi
+ - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install unittest2; fi
+ - if [[ $TRAVIS_PYTHON_VERSION != 'pypy' ]]; then pip install -r requirements.txt; pip install psycopg2; fi
- if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then pip install -r requirements.txt; pip install psycopg2ct; fi
- - if [[ $TRAVIS_PYTHON_VERSION == '3.2' ]]; then pip install -r requirements.txt; pip install psycopg2; fi
- - if [[ $TRAVIS_PYTHON_VERSION == '3.3' ]]; then pip install -r requirements.txt; pip install psycopg2; fi
- - if [[ $TRAVIS_PYTHON_VERSION == '3.4' ]]; then pip install -r requirements.txt; pip install psycopg2; fi
script: nosetests --with-coverage --cover-package=queries
after_success:
| 2 | Simplify the python version rules in travis install rules | 5 | .yml | travis | bsd-3-clause | gmr/queries |
1303 | <NME> README.rst
<BEF> Queries: PostgreSQL Simplified
==============================
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.
Key features include:
allows for multiple modules in the same interpreter to use the same PostgreSQL
connection.
Queries provides a core
|Version| |Downloads| |Status|
Installation
- 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> Minor readme update
<DFF> @@ -3,7 +3,8 @@ 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.
+caching of connections and support for PyPy via psycopg2ct. Queries supports
+Python versions 2.6+ and 3.2+.
The core `queries.Queries` class will automatically register support for UUIDs,
Unicode and Unicode arrays.
@@ -12,8 +13,6 @@ Without requiring any additional code, queries offers connection pooling that
allows for multiple modules in the same interpreter to use the same PostgreSQL
connection.
-Queries provides a core
-
|Version| |Downloads| |Status|
Installation
| 2 | Minor readme update | 3 | .rst | rst | bsd-3-clause | gmr/queries |
1304 | <NME> README.rst
<BEF> Queries: PostgreSQL Simplified
==============================
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.
Key features include:
allows for multiple modules in the same interpreter to use the same PostgreSQL
connection.
Queries provides a core
|Version| |Downloads| |Status|
Installation
- 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> Minor readme update
<DFF> @@ -3,7 +3,8 @@ 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.
+caching of connections and support for PyPy via psycopg2ct. Queries supports
+Python versions 2.6+ and 3.2+.
The core `queries.Queries` class will automatically register support for UUIDs,
Unicode and Unicode arrays.
@@ -12,8 +13,6 @@ Without requiring any additional code, queries offers connection pooling that
allows for multiple modules in the same interpreter to use the same PostgreSQL
connection.
-Queries provides a core
-
|Version| |Downloads| |Status|
Installation
| 2 | Minor readme update | 3 | .rst | rst | bsd-3-clause | gmr/queries |
1305 | <NME> setup.cfg
<BEF> [nosetests]
with-coverage=1
cover-package=queries
cover-branches=1
cover-erase=1
logging-level = DEBUG
stop = 1
verbosity = 2
with-coverage = 1
detailed-errors = 1
<MSG> Update config
<DFF> @@ -1,5 +1,12 @@
+[flake8]
+exclude = .git,build,dist,docs,env
+
[nosetests]
-with-coverage=1
-cover-package=queries
-cover-branches=1
-cover-erase=1
+cover-branches = 1
+cover-erase = 1
+cover-html = 1
+cover-html-dir = build/coverage
+cover-package = queries
+logging-level = DEBUG
+verbosity = 2
+with-coverage = 1
| 11 | Update config | 4 | .cfg | cfg | bsd-3-clause | gmr/queries |
1306 | <NME> setup.cfg
<BEF> [nosetests]
with-coverage=1
cover-package=queries
cover-branches=1
cover-erase=1
logging-level = DEBUG
stop = 1
verbosity = 2
with-coverage = 1
detailed-errors = 1
<MSG> Update config
<DFF> @@ -1,5 +1,12 @@
+[flake8]
+exclude = .git,build,dist,docs,env
+
[nosetests]
-with-coverage=1
-cover-package=queries
-cover-branches=1
-cover-erase=1
+cover-branches = 1
+cover-erase = 1
+cover-html = 1
+cover-html-dir = build/coverage
+cover-package = queries
+logging-level = DEBUG
+verbosity = 2
+with-coverage = 1
| 11 | Update config | 4 | .cfg | cfg | bsd-3-clause | gmr/queries |
1307 | <NME> session_tests.py
<BEF> """
Tests for functionality in the session module
"""
import hashlib
import logging
import unittest
import mock
from psycopg2 import extras
import psycopg2
# Out of order import to ensure psycopg2cffi is registered
from queries import pool, results, session, utils
LOGGER = logging.getLogger(__name__)
class SessionTestCase(unittest.TestCase):
URI = 'postgresql://foo:bar@localhost:5432/foo'
@mock.patch('psycopg2.connect')
@mock.patch('psycopg2.extensions.register_type')
@mock.patch('psycopg2.extras.register_uuid')
@mock.patch('queries.utils.uri_to_kwargs')
def setUp(self, uri_to_kwargs, register_uuid, register_type, connect):
self.conn = mock.Mock()
self.conn.autocommit = False
self.conn.closed = False
self.conn.cursor = mock.Mock()
self.conn.isexecuting = mock.Mock(return_value=False)
self.conn.reset = mock.Mock()
self.conn.status = psycopg2.extensions.STATUS_BEGIN
self.psycopg2_connect = connect
self.psycopg2_connect.return_value = self.conn
self.psycopg2_register_type = register_type
self.psycopg2_register_uuid = register_uuid
self.uri_to_kwargs = uri_to_kwargs
self.uri_to_kwargs.return_value = {'host': 'localhost',
'port': 5432,
'user': 'foo',
'password': 'bar',
'dbname': 'foo'}
self.obj = session.Session(self.URI, pool_max_size=100)
def test_init_sets_uri(self):
self.assertEqual(self.obj._uri, self.URI)
def test_init_creates_new_pool(self):
self.assertIn(self.obj.pid, self.obj._pool_manager)
def test_init_creates_connection(self):
conns = \
[value.handle for key, value in
self.obj._pool_manager._pools[self.obj.pid].connections.items()]
self.assertIn(self.conn, conns)
def test_init_sets_cursorfactory(self):
self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor)
def test_init_gets_cursor(self):
self.conn.cursor.assert_called_once_with(
name=None, cursor_factory=extras.RealDictCursor)
def test_init_sets_autocommit(self):
self.assertTrue(self.conn.autocommit)
def test_backend_pid_invokes_conn_backend_pid(self):
self.conn.get_backend_pid = get_backend_pid = mock.Mock()
LOGGER.debug('ValueL %s', self.obj.backend_pid)
get_backend_pid.assert_called_once_with()
def test_callproc_invokes_cursor_callproc(self):
self.obj._cursor.callproc = mock.Mock()
args = ('foo', ['bar', 'baz'])
self.obj.callproc(*args)
self.obj._cursor.callproc.assert_called_once_with(*args)
def test_callproc_returns_results(self):
self.obj._cursor.callproc = mock.Mock()
args = ('foo', ['bar', 'baz'])
self.assertIsInstance(self.obj.callproc(*args), results.Results)
def test_close_raises_exception(self):
self.obj._conn = None
self.assertRaises(psycopg2.InterfaceError, self.obj.close)
def test_close_removes_connection(self):
self.obj.close()
self.assertNotIn(self.conn,
self.obj._pool_manager._pools[self.obj.pid])
def test_close_unassigns_connection(self):
self.obj.close()
self.assertIsNone(self.obj._conn)
def test_close_unassigns_cursor(self):
self.obj.close()
self.assertIsNone(self.obj._cursor)
def test_connection_property_returns_correct_value(self):
self.assertEqual(self.obj.connection, self.conn)
def test_cursor_property_returns_correct_value(self):
self.assertEqual(self.obj.cursor, self.obj._cursor)
def test_encoding_property_value(self):
self.conn.encoding = 'UTF-8'
self.assertEqual(self.obj.encoding, 'UTF-8')
def test_notices_value(self):
self.conn.notices = [1, 2, 3]
self.assertListEqual(self.obj.notices, [1, 2, 3])
def test_pid_value(self):
expectation = hashlib.md5(
':'.join([self.obj.__class__.__name__,
self.URI]).encode('utf-8')).hexdigest()
self.assertEqual(self.obj.pid, expectation)
def test_query_invokes_cursor_execute(self):
self.obj._cursor.callproc = mock.Mock()
args = ('SELECT * FROM foo', ['bar', 'baz'])
self.obj.query(*args)
self.obj._cursor.execute.assert_called_once_with(*args)
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()
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> Update tests
<DFF> @@ -165,7 +165,7 @@ class SessionTestCase(unittest.TestCase):
def test_autocommit_sets_attribute(self):
self.conn.autocommit = False
- self.obj._autocommit()
+ self.obj._autocommit(True)
self.assertTrue(self.conn.autocommit)
def test_cleanup_closes_cursor(self):
| 1 | Update tests | 1 | .py | py | bsd-3-clause | gmr/queries |
1308 | <NME> session_tests.py
<BEF> """
Tests for functionality in the session module
"""
import hashlib
import logging
import unittest
import mock
from psycopg2 import extras
import psycopg2
# Out of order import to ensure psycopg2cffi is registered
from queries import pool, results, session, utils
LOGGER = logging.getLogger(__name__)
class SessionTestCase(unittest.TestCase):
URI = 'postgresql://foo:bar@localhost:5432/foo'
@mock.patch('psycopg2.connect')
@mock.patch('psycopg2.extensions.register_type')
@mock.patch('psycopg2.extras.register_uuid')
@mock.patch('queries.utils.uri_to_kwargs')
def setUp(self, uri_to_kwargs, register_uuid, register_type, connect):
self.conn = mock.Mock()
self.conn.autocommit = False
self.conn.closed = False
self.conn.cursor = mock.Mock()
self.conn.isexecuting = mock.Mock(return_value=False)
self.conn.reset = mock.Mock()
self.conn.status = psycopg2.extensions.STATUS_BEGIN
self.psycopg2_connect = connect
self.psycopg2_connect.return_value = self.conn
self.psycopg2_register_type = register_type
self.psycopg2_register_uuid = register_uuid
self.uri_to_kwargs = uri_to_kwargs
self.uri_to_kwargs.return_value = {'host': 'localhost',
'port': 5432,
'user': 'foo',
'password': 'bar',
'dbname': 'foo'}
self.obj = session.Session(self.URI, pool_max_size=100)
def test_init_sets_uri(self):
self.assertEqual(self.obj._uri, self.URI)
def test_init_creates_new_pool(self):
self.assertIn(self.obj.pid, self.obj._pool_manager)
def test_init_creates_connection(self):
conns = \
[value.handle for key, value in
self.obj._pool_manager._pools[self.obj.pid].connections.items()]
self.assertIn(self.conn, conns)
def test_init_sets_cursorfactory(self):
self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor)
def test_init_gets_cursor(self):
self.conn.cursor.assert_called_once_with(
name=None, cursor_factory=extras.RealDictCursor)
def test_init_sets_autocommit(self):
self.assertTrue(self.conn.autocommit)
def test_backend_pid_invokes_conn_backend_pid(self):
self.conn.get_backend_pid = get_backend_pid = mock.Mock()
LOGGER.debug('ValueL %s', self.obj.backend_pid)
get_backend_pid.assert_called_once_with()
def test_callproc_invokes_cursor_callproc(self):
self.obj._cursor.callproc = mock.Mock()
args = ('foo', ['bar', 'baz'])
self.obj.callproc(*args)
self.obj._cursor.callproc.assert_called_once_with(*args)
def test_callproc_returns_results(self):
self.obj._cursor.callproc = mock.Mock()
args = ('foo', ['bar', 'baz'])
self.assertIsInstance(self.obj.callproc(*args), results.Results)
def test_close_raises_exception(self):
self.obj._conn = None
self.assertRaises(psycopg2.InterfaceError, self.obj.close)
def test_close_removes_connection(self):
self.obj.close()
self.assertNotIn(self.conn,
self.obj._pool_manager._pools[self.obj.pid])
def test_close_unassigns_connection(self):
self.obj.close()
self.assertIsNone(self.obj._conn)
def test_close_unassigns_cursor(self):
self.obj.close()
self.assertIsNone(self.obj._cursor)
def test_connection_property_returns_correct_value(self):
self.assertEqual(self.obj.connection, self.conn)
def test_cursor_property_returns_correct_value(self):
self.assertEqual(self.obj.cursor, self.obj._cursor)
def test_encoding_property_value(self):
self.conn.encoding = 'UTF-8'
self.assertEqual(self.obj.encoding, 'UTF-8')
def test_notices_value(self):
self.conn.notices = [1, 2, 3]
self.assertListEqual(self.obj.notices, [1, 2, 3])
def test_pid_value(self):
expectation = hashlib.md5(
':'.join([self.obj.__class__.__name__,
self.URI]).encode('utf-8')).hexdigest()
self.assertEqual(self.obj.pid, expectation)
def test_query_invokes_cursor_execute(self):
self.obj._cursor.callproc = mock.Mock()
args = ('SELECT * FROM foo', ['bar', 'baz'])
self.obj.query(*args)
self.obj._cursor.execute.assert_called_once_with(*args)
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()
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> Update tests
<DFF> @@ -165,7 +165,7 @@ class SessionTestCase(unittest.TestCase):
def test_autocommit_sets_attribute(self):
self.conn.autocommit = False
- self.obj._autocommit()
+ self.obj._autocommit(True)
self.assertTrue(self.conn.autocommit)
def test_cleanup_closes_cursor(self):
| 1 | Update tests | 1 | .py | py | bsd-3-clause | gmr/queries |
1309 | <NME> README.rst
<BEF> Queries: PostgreSQL Simplified
==============================
*Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for
interacting with PostgreSQL.
The popular psycopg2_ package is a full-featured python client. Unfortunately
as a developer, you're often repeating the same steps to get started with your
applications that use it. Queries aims to reduce the complexity of psycopg2
while adding additional features to make writing PostgreSQL client applications
both fast and easy. Check out the `Usage`_ section below to see how easy it can be.
Key features include:
- Simplified API
- Support of Python 2.7+ and 3.4+
- PyPy support via psycopg2cffi_
- Asynchronous support for Tornado_
- Connection information provided by URI
- Query results delivered as a generator based iterators
- Automatically registered data-type support for UUIDs, Unicode and Unicode Arrays
- Ability to directly access psycopg2 ``connection`` and ``cursor`` objects
- Internal connection pooling
|Version| |Status| |Coverage| |License|
Documentation
-------------
Documentation is available at https://queries.readthedocs.org
Installation
------------
Queries is available via pypi_ and can be installed with easy_install or pip:
.. code:: bash
pip install queries
Usage
-----
Queries provides a session based API for interacting with PostgreSQL.
Simply pass in the URI_ of the PostgreSQL server to connect to when creating
a session:
.. code:: python
session = queries.Session("postgresql://postgres@localhost:5432/postgres")
Queries built-in connection pooling will re-use connections when possible,
lowering the overhead of connecting and reconnecting.
When specifying a URI, if you omit the username and database name to connect
with, Queries will use the current OS username for both. You can also omit the
URI when connecting to connect to localhost on port 5432 as the current OS user,
connecting to a database named for the current user. For example, if your
username is ``fred`` and you omit the URI when issuing ``queries.query`` the URI
that is constructed would be ``postgresql://fred@localhost:5432/fred``.
If you'd rather use individual values for the connection, the queries.uri()
method provides a quick and easy way to create a URI to pass into the various
methods.
.. code:: python
>>> queries.uri("server-name", 5432, "dbname", "user", "pass")
'postgresql://user:pass@server-name:5432/dbname'
Environment Variables
^^^^^^^^^^^^^^^^^^^^^
Currently Queries uses the following environment variables for tweaking various
configuration values. The supported ones are:
* ``QUERIES_MAX_POOL_SIZE`` - Modify the maximum size of the connection pool (default: 1)
Using the queries.Session class
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
To execute queries or call stored procedures, you start by creating an instance of the
``queries.Session`` class. It can act as a context manager, meaning you can
use it with the ``with`` keyword and it will take care of cleaning up after itself. For
more information on the ``with`` keyword and context managers, see PEP343_.
In addition to both the ``queries.Session.query`` and ``queries.Session.callproc``
methods that are similar to the simple API methods, the ``queries.Session`` class
provides access to the psycopg2 connection and cursor objects.
**Using queries.Session.query**
The following example shows how a ``queries.Session`` object can be used
as a context manager to query the database table:
.. code:: python
>>> import pprint
>>> import queries
>>>
>>> with queries.Session() as session:
... for row in session.query('SELECT * FROM names'):
... pprint.pprint(row)
...
{'id': 1, 'name': u'Jacob'}
{'id': 2, 'name': u'Mason'}
{'id': 3, 'name': u'Ethan'}
**Using queries.Session.callproc**
This example uses ``queries.Session.callproc`` to execute a stored
procedure and then pretty-prints the single row results as a dictionary:
.. code:: python
>>> import pprint
>>> import queries
>>> with queries.Session() as session:
... results = session.callproc('chr', [65])
... pprint.pprint(results.as_dict())
...
{'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
.. _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
.. _Tornado: http://tornadoweb.org
.. _PEP343: http://legacy.python.org/dev/peps/pep-0343/
:target: https://travis-ci.org/gmr/queries
.. |Downloads| image:: https://pypip.in/d/queries/badge.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 PEP link
[ci skip]
<DFF> @@ -162,7 +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/
+.. _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
@@ -171,4 +171,4 @@ main GitHub repository of Queries as tags prior to version 1.2.0.
: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 | Fix the PEP link | 2 | .rst | rst | bsd-3-clause | gmr/queries |
1310 | <NME> README.rst
<BEF> Queries: PostgreSQL Simplified
==============================
*Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for
interacting with PostgreSQL.
The popular psycopg2_ package is a full-featured python client. Unfortunately
as a developer, you're often repeating the same steps to get started with your
applications that use it. Queries aims to reduce the complexity of psycopg2
while adding additional features to make writing PostgreSQL client applications
both fast and easy. Check out the `Usage`_ section below to see how easy it can be.
Key features include:
- Simplified API
- Support of Python 2.7+ and 3.4+
- PyPy support via psycopg2cffi_
- Asynchronous support for Tornado_
- Connection information provided by URI
- Query results delivered as a generator based iterators
- Automatically registered data-type support for UUIDs, Unicode and Unicode Arrays
- Ability to directly access psycopg2 ``connection`` and ``cursor`` objects
- Internal connection pooling
|Version| |Status| |Coverage| |License|
Documentation
-------------
Documentation is available at https://queries.readthedocs.org
Installation
------------
Queries is available via pypi_ and can be installed with easy_install or pip:
.. code:: bash
pip install queries
Usage
-----
Queries provides a session based API for interacting with PostgreSQL.
Simply pass in the URI_ of the PostgreSQL server to connect to when creating
a session:
.. code:: python
session = queries.Session("postgresql://postgres@localhost:5432/postgres")
Queries built-in connection pooling will re-use connections when possible,
lowering the overhead of connecting and reconnecting.
When specifying a URI, if you omit the username and database name to connect
with, Queries will use the current OS username for both. You can also omit the
URI when connecting to connect to localhost on port 5432 as the current OS user,
connecting to a database named for the current user. For example, if your
username is ``fred`` and you omit the URI when issuing ``queries.query`` the URI
that is constructed would be ``postgresql://fred@localhost:5432/fred``.
If you'd rather use individual values for the connection, the queries.uri()
method provides a quick and easy way to create a URI to pass into the various
methods.
.. code:: python
>>> queries.uri("server-name", 5432, "dbname", "user", "pass")
'postgresql://user:pass@server-name:5432/dbname'
Environment Variables
^^^^^^^^^^^^^^^^^^^^^
Currently Queries uses the following environment variables for tweaking various
configuration values. The supported ones are:
* ``QUERIES_MAX_POOL_SIZE`` - Modify the maximum size of the connection pool (default: 1)
Using the queries.Session class
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
To execute queries or call stored procedures, you start by creating an instance of the
``queries.Session`` class. It can act as a context manager, meaning you can
use it with the ``with`` keyword and it will take care of cleaning up after itself. For
more information on the ``with`` keyword and context managers, see PEP343_.
In addition to both the ``queries.Session.query`` and ``queries.Session.callproc``
methods that are similar to the simple API methods, the ``queries.Session`` class
provides access to the psycopg2 connection and cursor objects.
**Using queries.Session.query**
The following example shows how a ``queries.Session`` object can be used
as a context manager to query the database table:
.. code:: python
>>> import pprint
>>> import queries
>>>
>>> with queries.Session() as session:
... for row in session.query('SELECT * FROM names'):
... pprint.pprint(row)
...
{'id': 1, 'name': u'Jacob'}
{'id': 2, 'name': u'Mason'}
{'id': 3, 'name': u'Ethan'}
**Using queries.Session.callproc**
This example uses ``queries.Session.callproc`` to execute a stored
procedure and then pretty-prints the single row results as a dictionary:
.. code:: python
>>> import pprint
>>> import queries
>>> with queries.Session() as session:
... results = session.callproc('chr', [65])
... pprint.pprint(results.as_dict())
...
{'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
.. _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
.. _Tornado: http://tornadoweb.org
.. _PEP343: http://legacy.python.org/dev/peps/pep-0343/
:target: https://travis-ci.org/gmr/queries
.. |Downloads| image:: https://pypip.in/d/queries/badge.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 PEP link
[ci skip]
<DFF> @@ -162,7 +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/
+.. _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
@@ -171,4 +171,4 @@ main GitHub repository of Queries as tags prior to version 1.2.0.
: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 | Fix the PEP link | 2 | .rst | rst | bsd-3-clause | gmr/queries |
1311 | <NME> session.py
<BEF> """The Session class allows for a unified (and simplified) view of
interfacing with a PostgreSQL database server.
Connection details are passed in as a PostgreSQL URI and connections are pooled
by default, allowing for reuse of connections across modules in the Python
runtime without having to pass around the object handle.
While you can still access the raw `psycopg2` connection and cursor objects to
provide ultimate flexibility in how you use the queries.Session object, there
are convenience methods designed to simplify the interaction with PostgreSQL.
For `psycopg2` functionality outside of what is exposed in Session, simply
use the Session.connection or Session.cursor properties to gain access to
either object just as you would in a program using psycopg2 directly.
Example usage:
.. code:: python
import queries
with queries.Session('pgsql://postgres@localhost/postgres') as session:
for row in session.Query('SELECT * FROM table'):
print row
"""
import hashlib
import logging
import psycopg2
from psycopg2 import extensions, extras
from queries import pool, results, utils
LOGGER = logging.getLogger(__name__)
DEFAULT_ENCODING = 'UTF8'
DEFAULT_URI = 'postgresql://localhost:5432'
class Session(object):
"""The Session class allows for a unified (and simplified) view of
interfacing with a PostgreSQL database server. The Session object can
act as a context manager, providing automated cleanup and simple, Pythonic
way of interacting with the object.
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
"""
_conn = None
_cursor = None
_tpc_id = None
_uri = None
# Connection status constants
INTRANS = extensions.STATUS_IN_TRANSACTION
PREPARED = extensions.STATUS_PREPARED
READY = extensions.STATUS_READY
SETUP = extensions.STATUS_SETUP
# Transaction status constants
TX_ACTIVE = extensions.TRANSACTION_STATUS_ACTIVE
TX_IDLE = extensions.TRANSACTION_STATUS_IDLE
TX_INERROR = extensions.TRANSACTION_STATUS_INERROR
TX_INTRANS = extensions.TRANSACTION_STATUS_INTRANS
TX_UNKNOWN = extensions.TRANSACTION_STATUS_UNKNOWN
def __init__(self, uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
pool_max_size=pool.DEFAULT_MAX_SIZE,
autocommit=True):
"""Connect to a PostgreSQL server using the module wide connection and
set the isolation level.
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
"""
self._pool_manager = pool.PoolManager.instance()
self._uri = uri
# Ensure the pool exists in the pool manager
if self.pid not in self._pool_manager:
self._pool_manager.create(self.pid, pool_idle_ttl, pool_max_size)
self._conn = self._connect()
self._cursor_factory = cursor_factory
self._cursor = self._get_cursor(self._conn)
self._autocommit(autocommit)
@property
def backend_pid(self):
"""Return the backend process ID of the PostgreSQL server that this
session is connected to.
:rtype: int
"""
return self._conn.get_backend_pid()
def callproc(self, name, args=None):
"""Call a stored procedure on the server, returning the results in a
:py:class:`queries.Results` instance.
:param str name: The procedure name
:param list args: The list of arguments to pass in
:rtype: queries.Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
try:
self._cursor.callproc(name, args)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def close(self):
"""Explicitly close the connection and remove it from the connection
pool if pooling is enabled. If the connection is already closed
"""
if not self._conn:
raise psycopg2.InterfaceError('Connection not open')
self._pool_manager.free(self.pid, self._conn)
self._pool_manager.remove_connection(self.pid, self._conn)
self._pool_manager.remove_connection(self.pid, self._conn)
# Un-assign the connection and cursor
self._conn, self._cursor = None, None
@property
def connection(self):
"""Return the current open connection to PostgreSQL.
:rtype: psycopg2.extensions.connection
"""
return self._conn
@property
def cursor(self):
"""Return the current, active cursor for the open connection.
:rtype: psycopg2.extensions.cursor
"""
return self._cursor
@property
def encoding(self):
"""Return the current client encoding value.
:rtype: str
"""
return self._conn.encoding
@property
def notices(self):
"""Return a list of up to the last 50 server notices sent to the client.
:rtype: list
"""
return self._conn.notices
@property
def pid(self):
"""Return the pool ID used for connection pooling.
:rtype: str
"""
return hashlib.md5(':'.join([self.__class__.__name__,
self._uri]).encode('utf-8')).hexdigest()
def query(self, sql, parameters=None):
"""A generator to issue a query on the server, mogrifying the
parameters against the sql statement. Results are returned as a
:py:class:`queries.Results` object which can act as an iterator and
has multiple ways to access the result data.
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: queries.Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
try:
self._cursor.execute(sql, parameters)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def set_encoding(self, value=DEFAULT_ENCODING):
"""Set the client encoding for the session if the value specified
is different than the current client encoding.
:param str value: The encoding value to use
"""
if self._conn.encoding != value:
self._conn.set_client_encoding(value)
def __del__(self):
"""When deleting the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def __enter__(self):
"""For use as a context manager, return a handle to this object
instance.
:rtype: Session
"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""When leaving the context, ensure the instance is removed from
caches, etc.
def _cleanup(self):
"""Remove the connection from the stack, closing out the cursor"""
if self._cursor:
self._cursor.close()
self._cursor = None
if self._conn:
try:
pool.PoolManager.instance().free(self.pid, self._conn)
except pool.ConnectionNotFoundError:
"""Remove the connection from the stack, closing out the cursor"""
if self._cursor:
LOGGER.debug('Closing the cursor on %s', self.pid)
self._cursor.close()
self._cursor = None
if self._conn:
LOGGER.debug('Freeing %s in the pool', self.pid)
try:
pool.PoolManager.instance().free(self.pid, self._conn)
except pool.ConnectionNotFoundError:
pass
self._conn = None
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
if possible, or by creating the new connection.
# 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)
LOGGER.debug("Re-using connection for %s", self.pid)
except pool.NoIdleConnectionsError:
if self._pool_manager.is_full(self.pid):
raise
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
LOGGER.debug("Creating a new connection for %s", self.pid)
connection = self._psycopg2_connect(kwargs)
self._pool_manager.add(self.pid, connection)
self._pool_manager.lock(self.pid, connection, self)
# Added in because psycopg2ct connects and leaves the connection in
# a weird state: consts.STATUS_DATESTYLE, returning from
# Connection._setup without setting the state as const.STATUS_OK
if utils.PYPY:
connection.reset()
# Register the custom data types
self._register_unicode(connection)
self._register_uuid(connection)
return connection
def _get_cursor(self, connection, name=None):
"""Return a cursor for the given cursor_factory. Specify a name to
use server-side cursors.
:param connection: The connection to create a cursor on
:type connection: psycopg2.extensions.connection
:param str name: A cursor name for a server side cursor
:rtype: psycopg2.extensions.cursor
"""
cursor = connection.cursor(name=name,
cursor_factory=self._cursor_factory)
if name is not None:
cursor.scrollable = True
cursor.withhold = True
return cursor
def _incr_exceptions(self):
"""Increment the number of exceptions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).exceptions += 1
def _incr_executions(self):
"""Increment the number of executions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).executions += 1
def _psycopg2_connect(self, kwargs):
"""Return a psycopg2 connection for the specified kwargs. Extend for
use in async session adapters.
:param dict kwargs: Keyword connection args
:rtype: psycopg2.extensions.connection
"""
return psycopg2.connect(**kwargs)
@staticmethod
def _register_unicode(connection):
"""Register the cursor to be able to receive Unicode string.
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE,
connection)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY,
connection)
@staticmethod
def _register_uuid(connection):
"""Register the UUID extension from the psycopg2.extra module
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extras.register_uuid(conn_or_curs=connection)
@property
def _status(self):
"""Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queries.Session.READY: Connected, no active transaction
:rtype: int
"""
if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
return self.READY
return self._conn.status
<MSG> Increase logging usefulness
<DFF> @@ -136,7 +136,7 @@ class Session(object):
"""
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)
@@ -251,10 +251,12 @@ class Session(object):
def _cleanup(self):
"""Remove the connection from the stack, closing out the cursor"""
if self._cursor:
+ LOGGER.debug('Closing the cursor on %s', self.pid)
self._cursor.close()
self._cursor = None
if self._conn:
+ LOGGER.debug('Freeing %s in the pool', self.pid)
try:
pool.PoolManager.instance().free(self.pid, self._conn)
except pool.ConnectionNotFoundError:
@@ -279,7 +281,7 @@ class Session(object):
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
- LOGGER.debug("Creating a new connection for %s", self.pid)
+ LOGGER.info("Creating a new connection for %s", self.pid)
connection = self._psycopg2_connect(kwargs)
self._pool_manager.add(self.pid, connection)
| 4 | Increase logging usefulness | 2 | .py | py | bsd-3-clause | gmr/queries |
1312 | <NME> session.py
<BEF> """The Session class allows for a unified (and simplified) view of
interfacing with a PostgreSQL database server.
Connection details are passed in as a PostgreSQL URI and connections are pooled
by default, allowing for reuse of connections across modules in the Python
runtime without having to pass around the object handle.
While you can still access the raw `psycopg2` connection and cursor objects to
provide ultimate flexibility in how you use the queries.Session object, there
are convenience methods designed to simplify the interaction with PostgreSQL.
For `psycopg2` functionality outside of what is exposed in Session, simply
use the Session.connection or Session.cursor properties to gain access to
either object just as you would in a program using psycopg2 directly.
Example usage:
.. code:: python
import queries
with queries.Session('pgsql://postgres@localhost/postgres') as session:
for row in session.Query('SELECT * FROM table'):
print row
"""
import hashlib
import logging
import psycopg2
from psycopg2 import extensions, extras
from queries import pool, results, utils
LOGGER = logging.getLogger(__name__)
DEFAULT_ENCODING = 'UTF8'
DEFAULT_URI = 'postgresql://localhost:5432'
class Session(object):
"""The Session class allows for a unified (and simplified) view of
interfacing with a PostgreSQL database server. The Session object can
act as a context manager, providing automated cleanup and simple, Pythonic
way of interacting with the object.
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
"""
_conn = None
_cursor = None
_tpc_id = None
_uri = None
# Connection status constants
INTRANS = extensions.STATUS_IN_TRANSACTION
PREPARED = extensions.STATUS_PREPARED
READY = extensions.STATUS_READY
SETUP = extensions.STATUS_SETUP
# Transaction status constants
TX_ACTIVE = extensions.TRANSACTION_STATUS_ACTIVE
TX_IDLE = extensions.TRANSACTION_STATUS_IDLE
TX_INERROR = extensions.TRANSACTION_STATUS_INERROR
TX_INTRANS = extensions.TRANSACTION_STATUS_INTRANS
TX_UNKNOWN = extensions.TRANSACTION_STATUS_UNKNOWN
def __init__(self, uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
pool_max_size=pool.DEFAULT_MAX_SIZE,
autocommit=True):
"""Connect to a PostgreSQL server using the module wide connection and
set the isolation level.
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
"""
self._pool_manager = pool.PoolManager.instance()
self._uri = uri
# Ensure the pool exists in the pool manager
if self.pid not in self._pool_manager:
self._pool_manager.create(self.pid, pool_idle_ttl, pool_max_size)
self._conn = self._connect()
self._cursor_factory = cursor_factory
self._cursor = self._get_cursor(self._conn)
self._autocommit(autocommit)
@property
def backend_pid(self):
"""Return the backend process ID of the PostgreSQL server that this
session is connected to.
:rtype: int
"""
return self._conn.get_backend_pid()
def callproc(self, name, args=None):
"""Call a stored procedure on the server, returning the results in a
:py:class:`queries.Results` instance.
:param str name: The procedure name
:param list args: The list of arguments to pass in
:rtype: queries.Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
try:
self._cursor.callproc(name, args)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def close(self):
"""Explicitly close the connection and remove it from the connection
pool if pooling is enabled. If the connection is already closed
"""
if not self._conn:
raise psycopg2.InterfaceError('Connection not open')
self._pool_manager.free(self.pid, self._conn)
self._pool_manager.remove_connection(self.pid, self._conn)
self._pool_manager.remove_connection(self.pid, self._conn)
# Un-assign the connection and cursor
self._conn, self._cursor = None, None
@property
def connection(self):
"""Return the current open connection to PostgreSQL.
:rtype: psycopg2.extensions.connection
"""
return self._conn
@property
def cursor(self):
"""Return the current, active cursor for the open connection.
:rtype: psycopg2.extensions.cursor
"""
return self._cursor
@property
def encoding(self):
"""Return the current client encoding value.
:rtype: str
"""
return self._conn.encoding
@property
def notices(self):
"""Return a list of up to the last 50 server notices sent to the client.
:rtype: list
"""
return self._conn.notices
@property
def pid(self):
"""Return the pool ID used for connection pooling.
:rtype: str
"""
return hashlib.md5(':'.join([self.__class__.__name__,
self._uri]).encode('utf-8')).hexdigest()
def query(self, sql, parameters=None):
"""A generator to issue a query on the server, mogrifying the
parameters against the sql statement. Results are returned as a
:py:class:`queries.Results` object which can act as an iterator and
has multiple ways to access the result data.
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: queries.Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
try:
self._cursor.execute(sql, parameters)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def set_encoding(self, value=DEFAULT_ENCODING):
"""Set the client encoding for the session if the value specified
is different than the current client encoding.
:param str value: The encoding value to use
"""
if self._conn.encoding != value:
self._conn.set_client_encoding(value)
def __del__(self):
"""When deleting the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def __enter__(self):
"""For use as a context manager, return a handle to this object
instance.
:rtype: Session
"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""When leaving the context, ensure the instance is removed from
caches, etc.
def _cleanup(self):
"""Remove the connection from the stack, closing out the cursor"""
if self._cursor:
self._cursor.close()
self._cursor = None
if self._conn:
try:
pool.PoolManager.instance().free(self.pid, self._conn)
except pool.ConnectionNotFoundError:
"""Remove the connection from the stack, closing out the cursor"""
if self._cursor:
LOGGER.debug('Closing the cursor on %s', self.pid)
self._cursor.close()
self._cursor = None
if self._conn:
LOGGER.debug('Freeing %s in the pool', self.pid)
try:
pool.PoolManager.instance().free(self.pid, self._conn)
except pool.ConnectionNotFoundError:
pass
self._conn = None
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
if possible, or by creating the new connection.
# 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)
LOGGER.debug("Re-using connection for %s", self.pid)
except pool.NoIdleConnectionsError:
if self._pool_manager.is_full(self.pid):
raise
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
LOGGER.debug("Creating a new connection for %s", self.pid)
connection = self._psycopg2_connect(kwargs)
self._pool_manager.add(self.pid, connection)
self._pool_manager.lock(self.pid, connection, self)
# Added in because psycopg2ct connects and leaves the connection in
# a weird state: consts.STATUS_DATESTYLE, returning from
# Connection._setup without setting the state as const.STATUS_OK
if utils.PYPY:
connection.reset()
# Register the custom data types
self._register_unicode(connection)
self._register_uuid(connection)
return connection
def _get_cursor(self, connection, name=None):
"""Return a cursor for the given cursor_factory. Specify a name to
use server-side cursors.
:param connection: The connection to create a cursor on
:type connection: psycopg2.extensions.connection
:param str name: A cursor name for a server side cursor
:rtype: psycopg2.extensions.cursor
"""
cursor = connection.cursor(name=name,
cursor_factory=self._cursor_factory)
if name is not None:
cursor.scrollable = True
cursor.withhold = True
return cursor
def _incr_exceptions(self):
"""Increment the number of exceptions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).exceptions += 1
def _incr_executions(self):
"""Increment the number of executions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).executions += 1
def _psycopg2_connect(self, kwargs):
"""Return a psycopg2 connection for the specified kwargs. Extend for
use in async session adapters.
:param dict kwargs: Keyword connection args
:rtype: psycopg2.extensions.connection
"""
return psycopg2.connect(**kwargs)
@staticmethod
def _register_unicode(connection):
"""Register the cursor to be able to receive Unicode string.
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE,
connection)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY,
connection)
@staticmethod
def _register_uuid(connection):
"""Register the UUID extension from the psycopg2.extra module
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extras.register_uuid(conn_or_curs=connection)
@property
def _status(self):
"""Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queries.Session.READY: Connected, no active transaction
:rtype: int
"""
if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
return self.READY
return self._conn.status
<MSG> Increase logging usefulness
<DFF> @@ -136,7 +136,7 @@ class Session(object):
"""
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)
@@ -251,10 +251,12 @@ class Session(object):
def _cleanup(self):
"""Remove the connection from the stack, closing out the cursor"""
if self._cursor:
+ LOGGER.debug('Closing the cursor on %s', self.pid)
self._cursor.close()
self._cursor = None
if self._conn:
+ LOGGER.debug('Freeing %s in the pool', self.pid)
try:
pool.PoolManager.instance().free(self.pid, self._conn)
except pool.ConnectionNotFoundError:
@@ -279,7 +281,7 @@ class Session(object):
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
- LOGGER.debug("Creating a new connection for %s", self.pid)
+ LOGGER.info("Creating a new connection for %s", self.pid)
connection = self._psycopg2_connect(kwargs)
self._pool_manager.add(self.pid, connection)
| 4 | Increase logging usefulness | 2 | .py | py | bsd-3-clause | gmr/queries |
1313 | <NME> pool_connection_tests.py
<BEF> ADDFILE
<MSG> Move pool.Connection tests into own file
<DFF> @@ -0,0 +1,80 @@
+"""
+Tests for Connection class in the pool module
+
+"""
+import mock
+try:
+ import unittest2 as unittest
+except ImportError:
+ import unittest
+import weakref
+
+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_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.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.handle.close.assertCalledOnce()
+
+ 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))
| 80 | Move pool.Connection tests into own file | 0 | .py | py | bsd-3-clause | gmr/queries |
1314 | <NME> pool_connection_tests.py
<BEF> ADDFILE
<MSG> Move pool.Connection tests into own file
<DFF> @@ -0,0 +1,80 @@
+"""
+Tests for Connection class in the pool module
+
+"""
+import mock
+try:
+ import unittest2 as unittest
+except ImportError:
+ import unittest
+import weakref
+
+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_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.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.handle.close.assertCalledOnce()
+
+ 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))
| 80 | Move pool.Connection tests into own file | 0 | .py | py | bsd-3-clause | gmr/queries |
1315 | <NME> tornado_session.rst
<BEF> .. py:module:: queries.tornado_session
TornadoSession Asynchronous API
===============================
Use a Queries Session asynchronously within the `Tornado <http://www.tornadoweb.org>`_ framework.
The :py:class:`TornadoSession <queries.TornadoSession>` class is optimized for
asynchronous concurrency. Each call to
:py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` or
:py:meth:`TornadoSession.query <queries.TornadoSession.query>` grabs a free
connection from the connection pool and requires that the results that are r
returned as a
:py:class:`Results <queries.tornado_session.Results>` object are freed via the
:py:meth:`Results.free <queries.tornado_session.Results.free>` method. Doing
so will release the free the `Results` object data and release the lock on
the connection so that other queries are able to use the connection.
Example Use
-----------
The following :py:class:`~tornado.web.RequestHandler` example will return a
JSON document containing the query results.
.. code:: python
import queries
from tornado import gen, web
class ExampleHandler(web.RequestHandler):
def initialize(self):
self.session = queries.TornadoSession()
@gen.coroutine
def get(self):
result = yield self.session.query('SELECT * FROM names')
self.finish({'data': result.items()})
result.free()
Class Documentation
-------------------
.. autoclass:: queries.TornadoSession
:members:
.. autoclass:: queries.tornado_session.Results
:members:
.. autoclass:: queries.tornado_session.Results
:members:
:inherited-members:
<MSG> Update the TornadoSession docs [skip ci]
<DFF> @@ -38,8 +38,9 @@ See the :doc:`examples/index` for more :py:meth:`~queries.TornadoSession` exampl
Class Documentation
-------------------
-.. autoclass:: queries.TornadoSession
+.. autoclass:: queries.tornado_session.TornadoSession
:members:
+ :inherited-members:
.. autoclass:: queries.tornado_session.Results
:members:
| 2 | Update the TornadoSession docs [skip ci] | 1 | .rst | rst | bsd-3-clause | gmr/queries |
1316 | <NME> tornado_session.rst
<BEF> .. py:module:: queries.tornado_session
TornadoSession Asynchronous API
===============================
Use a Queries Session asynchronously within the `Tornado <http://www.tornadoweb.org>`_ framework.
The :py:class:`TornadoSession <queries.TornadoSession>` class is optimized for
asynchronous concurrency. Each call to
:py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` or
:py:meth:`TornadoSession.query <queries.TornadoSession.query>` grabs a free
connection from the connection pool and requires that the results that are r
returned as a
:py:class:`Results <queries.tornado_session.Results>` object are freed via the
:py:meth:`Results.free <queries.tornado_session.Results.free>` method. Doing
so will release the free the `Results` object data and release the lock on
the connection so that other queries are able to use the connection.
Example Use
-----------
The following :py:class:`~tornado.web.RequestHandler` example will return a
JSON document containing the query results.
.. code:: python
import queries
from tornado import gen, web
class ExampleHandler(web.RequestHandler):
def initialize(self):
self.session = queries.TornadoSession()
@gen.coroutine
def get(self):
result = yield self.session.query('SELECT * FROM names')
self.finish({'data': result.items()})
result.free()
Class Documentation
-------------------
.. autoclass:: queries.TornadoSession
:members:
.. autoclass:: queries.tornado_session.Results
:members:
.. autoclass:: queries.tornado_session.Results
:members:
:inherited-members:
<MSG> Update the TornadoSession docs [skip ci]
<DFF> @@ -38,8 +38,9 @@ See the :doc:`examples/index` for more :py:meth:`~queries.TornadoSession` exampl
Class Documentation
-------------------
-.. autoclass:: queries.TornadoSession
+.. autoclass:: queries.tornado_session.TornadoSession
:members:
+ :inherited-members:
.. autoclass:: queries.tornado_session.Results
:members:
| 2 | Update the TornadoSession docs [skip ci] | 1 | .rst | rst | bsd-3-clause | gmr/queries |
1317 | <NME> setup.py
<BEF> import os
import os
import platform
# Include the proper requirements
if platform.python_implementation() == 'PyPy':
install_requires = ['psycopg2cffi>=2.7.2,<3']
else:
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=[
'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> More python2.6 cleanup, move __init__ stuff to utils
<DFF> @@ -2,7 +2,7 @@ from setuptools import setup
import os
import platform
-# Include the proper requirements
+# PYPY vs cpython
if platform.python_implementation() == 'PyPy':
install_requires = ['psycopg2cffi>=2.7.2,<3']
else:
| 1 | More python2.6 cleanup, move __init__ stuff to utils | 1 | .py | py | bsd-3-clause | gmr/queries |
1318 | <NME> setup.py
<BEF> import os
import os
import platform
# Include the proper requirements
if platform.python_implementation() == 'PyPy':
install_requires = ['psycopg2cffi>=2.7.2,<3']
else:
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=[
'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> More python2.6 cleanup, move __init__ stuff to utils
<DFF> @@ -2,7 +2,7 @@ from setuptools import setup
import os
import platform
-# Include the proper requirements
+# PYPY vs cpython
if platform.python_implementation() == 'PyPy':
install_requires = ['psycopg2cffi>=2.7.2,<3']
else:
| 1 | More python2.6 cleanup, move __init__ stuff to utils | 1 | .py | py | bsd-3-clause | gmr/queries |
1319 | <NME> .travis.yml
<BEF> sudo: false
language: python
dist: xenial
env:
global:
- PATH=$HOME/.local/bin:$PATH
- AWS_DEFAULT_REGION=us-east-1
- secure: "inURdx4ldkJqQXL1TyvKImC3EnL5TixC1DlNMBYi5ttygwAk+mSSSw8Yc7klB6D1m6q79xUlHRk06vbz23CsXTM4AClC5Emrk6XN2GlUKl5WI+z+A2skI59buEhLWe7e2KzhB/AVx2E3TfKa0oY7raM0UUnaOkpV1Cj+mHKPIT0="
- secure: "H32DV3713a6UUuEJujrG7SfUX4/5WrwQy/3DxeptC6L7YPlTYxHBdEsccTfN5z806EheIl4BdIoxoDtq7PU/tWQoG1Lp2ze60mpwrniHajhFnjk7zP6pHvkhGLr8flhSmAb6CQBreNFOHTLWBMGPfi7k1Q9Td9MHbRo/FsTxqsM="
stages:
- test
- name: coverage
- name: deploy
if: tag IS present
install:
- pip install awscli
- pip install -r requires/testing.txt
stages:
- test
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> Attempt to fix the travis job
<DFF> @@ -18,6 +18,7 @@ env:
install:
- pip install awscli
- pip install -r requires/testing.txt
+ - python setup.py develop
stages:
- test
| 1 | Attempt to fix the travis job | 0 | .yml | travis | bsd-3-clause | gmr/queries |
1320 | <NME> .travis.yml
<BEF> sudo: false
language: python
dist: xenial
env:
global:
- PATH=$HOME/.local/bin:$PATH
- AWS_DEFAULT_REGION=us-east-1
- secure: "inURdx4ldkJqQXL1TyvKImC3EnL5TixC1DlNMBYi5ttygwAk+mSSSw8Yc7klB6D1m6q79xUlHRk06vbz23CsXTM4AClC5Emrk6XN2GlUKl5WI+z+A2skI59buEhLWe7e2KzhB/AVx2E3TfKa0oY7raM0UUnaOkpV1Cj+mHKPIT0="
- secure: "H32DV3713a6UUuEJujrG7SfUX4/5WrwQy/3DxeptC6L7YPlTYxHBdEsccTfN5z806EheIl4BdIoxoDtq7PU/tWQoG1Lp2ze60mpwrniHajhFnjk7zP6pHvkhGLr8flhSmAb6CQBreNFOHTLWBMGPfi7k1Q9Td9MHbRo/FsTxqsM="
stages:
- test
- name: coverage
- name: deploy
if: tag IS present
install:
- pip install awscli
- pip install -r requires/testing.txt
stages:
- test
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> Attempt to fix the travis job
<DFF> @@ -18,6 +18,7 @@ env:
install:
- pip install awscli
- pip install -r requires/testing.txt
+ - python setup.py develop
stages:
- test
| 1 | Attempt to fix the travis job | 0 | .yml | travis | bsd-3-clause | gmr/queries |
1321 | <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(
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
url='https://github.com/gmr/queries',
install_requires=install_requires,
extras_require={'tornado': 'tornado<6'},
license='BSD',
'Topic :: Software Development :: Libraries']
setup(name='queries',
version='1.10.4',
description="Simplified PostgreSQL client built upon Psycopg2",
maintainer="Gavin M. Roy",
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.rst']},
packages=['queries'],
classifiers=classifiers,
'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, remove Python 2.6
<DFF> @@ -17,7 +17,6 @@ classifiers = ['Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
- 'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
@@ -28,14 +27,14 @@ classifiers = ['Development Status :: 5 - Production/Stable',
'Topic :: Software Development :: Libraries']
setup(name='queries',
- version='1.10.4',
+ version='2.0.0',
description="Simplified PostgreSQL client built upon Psycopg2",
maintainer="Gavin M. Roy",
maintainer_email="gavinmroy@gmail.com",
url="https://github.com/gmr/queries",
install_requires=install_requires,
extras_require={'tornado': 'tornado'},
- license=open('LICENSE').read(),
+ license='BSD',
package_data={'': ['LICENSE', 'README.rst']},
packages=['queries'],
classifiers=classifiers,
| 2 | Bump the version, remove Python 2.6 | 3 | .py | py | bsd-3-clause | gmr/queries |
1322 | <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(
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
url='https://github.com/gmr/queries',
install_requires=install_requires,
extras_require={'tornado': 'tornado<6'},
license='BSD',
'Topic :: Software Development :: Libraries']
setup(name='queries',
version='1.10.4',
description="Simplified PostgreSQL client built upon Psycopg2",
maintainer="Gavin M. Roy",
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.rst']},
packages=['queries'],
classifiers=classifiers,
'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, remove Python 2.6
<DFF> @@ -17,7 +17,6 @@ classifiers = ['Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
- 'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
@@ -28,14 +27,14 @@ classifiers = ['Development Status :: 5 - Production/Stable',
'Topic :: Software Development :: Libraries']
setup(name='queries',
- version='1.10.4',
+ version='2.0.0',
description="Simplified PostgreSQL client built upon Psycopg2",
maintainer="Gavin M. Roy",
maintainer_email="gavinmroy@gmail.com",
url="https://github.com/gmr/queries",
install_requires=install_requires,
extras_require={'tornado': 'tornado'},
- license=open('LICENSE').read(),
+ license='BSD',
package_data={'': ['LICENSE', 'README.rst']},
packages=['queries'],
classifiers=classifiers,
| 2 | Bump the version, remove Python 2.6 | 3 | .py | py | bsd-3-clause | gmr/queries |
1323 | <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 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_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 \
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
result = yield obj.query('SELECT 1')
_execute.assert_called_once_with('execute', 'SELECT 1', None)
_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> Clean up stack and exception handling
- Add a new TornadoSession.validate() method
- Add new doc examples
- Raise a psycopg2.OperationalError when it can not connect or has been disconnected
<DFF> @@ -47,11 +47,11 @@ 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_callback_dict(self):
+ # self.assertDictEqual(self.obj._futures, {})
- def test_creates_empty_connections_dict(self):
- self.assertDictEqual(self.obj._connections, {})
+ # 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)
@@ -199,3 +199,17 @@ class SessionPublicMethodTests(testing.AsyncTestCase):
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
result = yield obj.query('SELECT 1')
_execute.assert_called_once_with('execute', 'SELECT 1', None)
+
+ @testing.gen_test
+ def test_validate_invokes_connect(self):
+ with mock.patch('queries.tornado_session.TornadoSession._connect') as \
+ _connect:
+ with mock.patch('queries.pool.PoolManager.free'):
+ future = concurrent.Future()
+ connection = mock.Mock()
+ connection.fileno = mock.Mock(return_value=10)
+ future.set_result(connection)
+ _connect.return_value = future
+ obj = tornado_session.TornadoSession(io_loop=self.io_loop)
+ result = yield obj.validate()
+ _connect.assert_called_once_with()
| 18 | Clean up stack and exception handling | 4 | .py | py | bsd-3-clause | gmr/queries |
1324 | <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 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_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 \
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
result = yield obj.query('SELECT 1')
_execute.assert_called_once_with('execute', 'SELECT 1', None)
_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> Clean up stack and exception handling
- Add a new TornadoSession.validate() method
- Add new doc examples
- Raise a psycopg2.OperationalError when it can not connect or has been disconnected
<DFF> @@ -47,11 +47,11 @@ 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_callback_dict(self):
+ # self.assertDictEqual(self.obj._futures, {})
- def test_creates_empty_connections_dict(self):
- self.assertDictEqual(self.obj._connections, {})
+ # 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)
@@ -199,3 +199,17 @@ class SessionPublicMethodTests(testing.AsyncTestCase):
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
result = yield obj.query('SELECT 1')
_execute.assert_called_once_with('execute', 'SELECT 1', None)
+
+ @testing.gen_test
+ def test_validate_invokes_connect(self):
+ with mock.patch('queries.tornado_session.TornadoSession._connect') as \
+ _connect:
+ with mock.patch('queries.pool.PoolManager.free'):
+ future = concurrent.Future()
+ connection = mock.Mock()
+ connection.fileno = mock.Mock(return_value=10)
+ future.set_result(connection)
+ _connect.return_value = future
+ obj = tornado_session.TornadoSession(io_loop=self.io_loop)
+ result = yield obj.validate()
+ _connect.assert_called_once_with()
| 18 | Clean up stack and exception handling | 4 | .py | py | bsd-3-clause | gmr/queries |
1325 | <NME> pool_manager_tests.py
<BEF> """
Tests for Manager class in the pool module
"""
import unittest
import uuid
import mock
from queries import pool
from queries import pool
class ManagerTests(unittest.TestCase):
def setUp(self):
self.manager = pool.PoolManager.instance()
def test_singleton_behavior(self):
self.assertEqual(pool.PoolManager.instance(), self.manager)
def test_has_pool_true(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.assertIn(pid, self.manager)
def test_adding_to_pool(self):
pid = str(uuid.uuid4())
def test_adding_to_pool(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
psycopg2_conn = mock.Mock()
self.manager.add(pid, psycopg2_conn)
self.assertIn(psycopg2_conn, self.manager._pools[pid])
psycopg2_conn = mock.Mock()
self.assertRaises(KeyError, self.manager.add, pid, psycopg2_conn)
def test_ensures_pool_exists_raises_key_error(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager._ensure_pool_exists, pid)
def test_clean_ensures_pool_exists_catches_key_error(self):
pid = str(uuid.uuid4())
self.assertIsNone(self.manager.clean(pid))
def test_clean_invokes_pool_clean(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool') as Pool:
self.manager._pools[pid] = Pool()
self.manager._pools[pid].clean = clean = mock.Mock()
self.manager.clean(pid)
clean.assert_called_once_with()
def test_clean_removes_pool(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool') as Pool:
self.manager._pools[pid] = Pool()
self.manager.clean(pid)
def test_create_prevents_duplicate_pool_id(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool') as Pool:
self.manager._pools[pid] = Pool()
self.assertRaises(KeyError, self.manager.create, pid, 10, 10, Pool)
def test_create_created_default_pool_type(self):
def test_create_passes_in_idle_ttl(self):
pid = str(uuid.uuid4())
self.manager.create(pid, 12)
self.assertEqual(self.manager._pools[pid].idle_ttl, 12)
def test_create_passes_in_max_size(self):
pid = str(uuid.uuid4())
self.manager.create(pid, 10, 16)
self.assertEqual(self.manager._pools[pid].max_size, 16)
def test_get_ensures_pool_exists(self):
pid = str(uuid.uuid4())
session = mock.Mock()
self.assertRaises(KeyError, self.manager.get, pid, session)
def test_get_invokes_pool_get(self):
pid = str(uuid.uuid4())
session = mock.Mock()
self.manager.create(pid)
self.manager._pools[pid].get = get = mock.Mock()
self.manager.get(pid, session)
get.assert_called_once_with(session)
def test_free_ensures_pool_exists(self):
pid = str(uuid.uuid4())
psycopg2_conn = mock_connection()
self.assertRaises(KeyError, self.manager.free, pid, psycopg2_conn)
def test_free_invokes_pool_free(self):
pid = str(uuid.uuid4())
psycopg2_conn = mock_connection()
self.manager.create(pid)
self.manager._pools[pid].free = free = mock.Mock()
self.manager.free(pid, psycopg2_conn)
def test_free_ensures_pool_exists(self):
pid = str(uuid.uuid4())
psycopg2_conn = mock.Mock()
self.assertRaises(KeyError, self.manager.free, pid, psycopg2_conn)
def test_free_invokes_pool_free(self):
pid = str(uuid.uuid4())
psycopg2_conn = mock.Mock()
self.manager.create(pid)
self.manager._pools[pid].free = free = mock.Mock()
self.manager.free(pid, psycopg2_conn)
self.manager.create(pid)
self.assertFalse(self.manager.has_connection(pid, mock.Mock()))
def test_has_connection_returns_true(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
psycopg2_conn = mock_connection()
self.manager.add(pid, psycopg2_conn)
self.assertTrue(self.manager.has_connection(pid, psycopg2_conn))
self.manager.remove(pid)
def test_has_idle_connection_returns_false(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
with mock.patch('queries.pool.Pool.idle_connections',
def test_has_connection_returns_true(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
psycopg2_conn = mock.Mock()
self.manager._pools[pid].connections[id(psycopg2_conn)] = psycopg2_conn
self.assertTrue(self.manager.has_connection(pid, psycopg2_conn))
def test_has_idle_connection_returns_false(self):
pid = str(uuid.uuid4())
self.assertTrue(self.manager.has_idle_connection(pid))
def test_is_full_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.is_full, pid)
def test_is_full_invokes_pool_is_full(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
with mock.patch('queries.pool.Pool.is_full',
new_callable=mock.PropertyMock) as is_full:
self.manager.is_full(pid)
is_full.assert_called_once_with()
def test_lock_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.lock, pid, None, None)
def test_lock_invokes_pool_lock(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].lock = lock = mock.Mock()
psycopg2_conn = mock.Mock()
session = mock.Mock()
self.manager.lock(pid, psycopg2_conn, session)
lock.assert_called_once_with(psycopg2_conn, session)
def test_remove_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.remove, pid)
def test_remove_invokes_pool_close(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].close = method = mock.Mock()
self.manager.remove(pid)
method.assert_called_once_with()
def test_remove_deletes_pool(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].close = mock.Mock()
self.manager.remove(pid)
self.assertNotIn(pid, self.manager._pools)
def test_remove_connection_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.remove_connection, pid, None)
def test_remove_connection_invokes_pool_remove(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].remove = remove = mock.Mock()
psycopg2_conn = mock.Mock()
self.manager.remove_connection(pid, psycopg2_conn)
remove.assert_called_once_with(psycopg2_conn)
def test_size_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.size, pid)
def test_size_returns_pool_length(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.assertEqual(self.manager.size(pid), len(self.manager._pools[pid]))
def test_set_idle_ttl_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.set_idle_ttl, pid, None)
def test_set_idle_ttl_invokes_pool_set_idle_ttl(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].set_idle_ttl = set_idle_ttl = mock.Mock()
self.manager.set_idle_ttl(pid, 256)
set_idle_ttl.assert_called_once_with(256)
def test_set_max_size_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.set_idle_ttl, pid, None)
def test_set_max_size_invokes_pool_set_max_size(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].set_max_size = set_max_size = mock.Mock()
self.manager.set_max_size(pid, 128)
set_max_size.assert_called_once_with(128)
def test_shutdown_closes_all(self):
pid1, pid2 = str(uuid.uuid4()), str(uuid.uuid4())
self.manager.create(pid1)
self.manager._pools[pid1].shutdown = method1 = mock.Mock()
self.manager.create(pid2)
self.manager._pools[pid2].shutdown = method2 = mock.Mock()
self.manager.shutdown()
method1.assert_called_once_with()
self.manager._pools[pid].set_max_size = set_max_size = mock.Mock()
self.manager.set_max_size(pid, 128)
set_max_size.assert_called_once_with(128)
<MSG> Add queries.pool.PoolManager.shutdown()
- Adds a single place that closes all open connections
- Update tests to behave a bit better
- Micro-optimization on ``foo = {}`` instead of ``foo = dict()``
<DFF> @@ -12,11 +12,22 @@ import uuid
from queries import pool
+def mock_connection():
+ conn = mock.MagicMock('psycopg2.extensions.connection')
+ conn.close = mock.Mock()
+ conn.closed = True
+ conn.isexecuting = mock.Mock(return_value=False)
+ return conn
+
+
class ManagerTests(unittest.TestCase):
def setUp(self):
self.manager = pool.PoolManager.instance()
+ def tearDown(self):
+ self.manager.shutdown()
+
def test_singleton_behavior(self):
self.assertEqual(pool.PoolManager.instance(), self.manager)
@@ -31,7 +42,7 @@ class ManagerTests(unittest.TestCase):
def test_adding_to_pool(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
- psycopg2_conn = mock.Mock()
+ psycopg2_conn = mock_connection()
self.manager.add(pid, psycopg2_conn)
self.assertIn(psycopg2_conn, self.manager._pools[pid])
@@ -62,7 +73,7 @@ class ManagerTests(unittest.TestCase):
def test_create_prevents_duplicate_pool_id(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool') as Pool:
- self.manager._pools[pid] = Pool()
+ self.manager.create(pid, 10, 10, Pool)
self.assertRaises(KeyError, self.manager.create, pid, 10, 10, Pool)
def test_create_created_default_pool_type(self):
@@ -104,12 +115,12 @@ class ManagerTests(unittest.TestCase):
def test_free_ensures_pool_exists(self):
pid = str(uuid.uuid4())
- psycopg2_conn = mock.Mock()
+ psycopg2_conn = mock_connection()
self.assertRaises(KeyError, self.manager.free, pid, psycopg2_conn)
def test_free_invokes_pool_free(self):
pid = str(uuid.uuid4())
- psycopg2_conn = mock.Mock()
+ psycopg2_conn = mock_connection()
self.manager.create(pid)
self.manager._pools[pid].free = free = mock.Mock()
self.manager.free(pid, psycopg2_conn)
@@ -131,9 +142,10 @@ class ManagerTests(unittest.TestCase):
def test_has_connection_returns_true(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
- psycopg2_conn = mock.Mock()
- self.manager._pools[pid].connections[id(psycopg2_conn)] = psycopg2_conn
+ psycopg2_conn = mock_connection()
+ self.manager.add(pid, psycopg2_conn)
self.assertTrue(self.manager.has_connection(pid, psycopg2_conn))
+ self.manager.remove(pid)
def test_has_idle_connection_returns_false(self):
pid = str(uuid.uuid4())
@@ -236,3 +248,13 @@ class ManagerTests(unittest.TestCase):
self.manager._pools[pid].set_max_size = set_max_size = mock.Mock()
self.manager.set_max_size(pid, 128)
set_max_size.assert_called_once_with(128)
+
+ def test_shutdown_closes_all(self):
+ pid1, pid2 = str(uuid.uuid4()), str(uuid.uuid4())
+ self.manager.create(pid1)
+ self.manager._pools[pid1].shutdown = method1 = mock.Mock()
+ self.manager.create(pid2)
+ self.manager._pools[pid2].shutdown = method2 = mock.Mock()
+ self.manager.shutdown()
+ method1.assert_called_once_with()
+ method2.assert_called_once_with()
| 28 | Add queries.pool.PoolManager.shutdown() | 6 | .py | py | bsd-3-clause | gmr/queries |
1326 | <NME> pool_manager_tests.py
<BEF> """
Tests for Manager class in the pool module
"""
import unittest
import uuid
import mock
from queries import pool
from queries import pool
class ManagerTests(unittest.TestCase):
def setUp(self):
self.manager = pool.PoolManager.instance()
def test_singleton_behavior(self):
self.assertEqual(pool.PoolManager.instance(), self.manager)
def test_has_pool_true(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.assertIn(pid, self.manager)
def test_adding_to_pool(self):
pid = str(uuid.uuid4())
def test_adding_to_pool(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
psycopg2_conn = mock.Mock()
self.manager.add(pid, psycopg2_conn)
self.assertIn(psycopg2_conn, self.manager._pools[pid])
psycopg2_conn = mock.Mock()
self.assertRaises(KeyError, self.manager.add, pid, psycopg2_conn)
def test_ensures_pool_exists_raises_key_error(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager._ensure_pool_exists, pid)
def test_clean_ensures_pool_exists_catches_key_error(self):
pid = str(uuid.uuid4())
self.assertIsNone(self.manager.clean(pid))
def test_clean_invokes_pool_clean(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool') as Pool:
self.manager._pools[pid] = Pool()
self.manager._pools[pid].clean = clean = mock.Mock()
self.manager.clean(pid)
clean.assert_called_once_with()
def test_clean_removes_pool(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool') as Pool:
self.manager._pools[pid] = Pool()
self.manager.clean(pid)
def test_create_prevents_duplicate_pool_id(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool') as Pool:
self.manager._pools[pid] = Pool()
self.assertRaises(KeyError, self.manager.create, pid, 10, 10, Pool)
def test_create_created_default_pool_type(self):
def test_create_passes_in_idle_ttl(self):
pid = str(uuid.uuid4())
self.manager.create(pid, 12)
self.assertEqual(self.manager._pools[pid].idle_ttl, 12)
def test_create_passes_in_max_size(self):
pid = str(uuid.uuid4())
self.manager.create(pid, 10, 16)
self.assertEqual(self.manager._pools[pid].max_size, 16)
def test_get_ensures_pool_exists(self):
pid = str(uuid.uuid4())
session = mock.Mock()
self.assertRaises(KeyError, self.manager.get, pid, session)
def test_get_invokes_pool_get(self):
pid = str(uuid.uuid4())
session = mock.Mock()
self.manager.create(pid)
self.manager._pools[pid].get = get = mock.Mock()
self.manager.get(pid, session)
get.assert_called_once_with(session)
def test_free_ensures_pool_exists(self):
pid = str(uuid.uuid4())
psycopg2_conn = mock_connection()
self.assertRaises(KeyError, self.manager.free, pid, psycopg2_conn)
def test_free_invokes_pool_free(self):
pid = str(uuid.uuid4())
psycopg2_conn = mock_connection()
self.manager.create(pid)
self.manager._pools[pid].free = free = mock.Mock()
self.manager.free(pid, psycopg2_conn)
def test_free_ensures_pool_exists(self):
pid = str(uuid.uuid4())
psycopg2_conn = mock.Mock()
self.assertRaises(KeyError, self.manager.free, pid, psycopg2_conn)
def test_free_invokes_pool_free(self):
pid = str(uuid.uuid4())
psycopg2_conn = mock.Mock()
self.manager.create(pid)
self.manager._pools[pid].free = free = mock.Mock()
self.manager.free(pid, psycopg2_conn)
self.manager.create(pid)
self.assertFalse(self.manager.has_connection(pid, mock.Mock()))
def test_has_connection_returns_true(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
psycopg2_conn = mock_connection()
self.manager.add(pid, psycopg2_conn)
self.assertTrue(self.manager.has_connection(pid, psycopg2_conn))
self.manager.remove(pid)
def test_has_idle_connection_returns_false(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
with mock.patch('queries.pool.Pool.idle_connections',
def test_has_connection_returns_true(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
psycopg2_conn = mock.Mock()
self.manager._pools[pid].connections[id(psycopg2_conn)] = psycopg2_conn
self.assertTrue(self.manager.has_connection(pid, psycopg2_conn))
def test_has_idle_connection_returns_false(self):
pid = str(uuid.uuid4())
self.assertTrue(self.manager.has_idle_connection(pid))
def test_is_full_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.is_full, pid)
def test_is_full_invokes_pool_is_full(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
with mock.patch('queries.pool.Pool.is_full',
new_callable=mock.PropertyMock) as is_full:
self.manager.is_full(pid)
is_full.assert_called_once_with()
def test_lock_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.lock, pid, None, None)
def test_lock_invokes_pool_lock(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].lock = lock = mock.Mock()
psycopg2_conn = mock.Mock()
session = mock.Mock()
self.manager.lock(pid, psycopg2_conn, session)
lock.assert_called_once_with(psycopg2_conn, session)
def test_remove_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.remove, pid)
def test_remove_invokes_pool_close(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].close = method = mock.Mock()
self.manager.remove(pid)
method.assert_called_once_with()
def test_remove_deletes_pool(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].close = mock.Mock()
self.manager.remove(pid)
self.assertNotIn(pid, self.manager._pools)
def test_remove_connection_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.remove_connection, pid, None)
def test_remove_connection_invokes_pool_remove(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].remove = remove = mock.Mock()
psycopg2_conn = mock.Mock()
self.manager.remove_connection(pid, psycopg2_conn)
remove.assert_called_once_with(psycopg2_conn)
def test_size_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.size, pid)
def test_size_returns_pool_length(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.assertEqual(self.manager.size(pid), len(self.manager._pools[pid]))
def test_set_idle_ttl_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.set_idle_ttl, pid, None)
def test_set_idle_ttl_invokes_pool_set_idle_ttl(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].set_idle_ttl = set_idle_ttl = mock.Mock()
self.manager.set_idle_ttl(pid, 256)
set_idle_ttl.assert_called_once_with(256)
def test_set_max_size_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.set_idle_ttl, pid, None)
def test_set_max_size_invokes_pool_set_max_size(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].set_max_size = set_max_size = mock.Mock()
self.manager.set_max_size(pid, 128)
set_max_size.assert_called_once_with(128)
def test_shutdown_closes_all(self):
pid1, pid2 = str(uuid.uuid4()), str(uuid.uuid4())
self.manager.create(pid1)
self.manager._pools[pid1].shutdown = method1 = mock.Mock()
self.manager.create(pid2)
self.manager._pools[pid2].shutdown = method2 = mock.Mock()
self.manager.shutdown()
method1.assert_called_once_with()
self.manager._pools[pid].set_max_size = set_max_size = mock.Mock()
self.manager.set_max_size(pid, 128)
set_max_size.assert_called_once_with(128)
<MSG> Add queries.pool.PoolManager.shutdown()
- Adds a single place that closes all open connections
- Update tests to behave a bit better
- Micro-optimization on ``foo = {}`` instead of ``foo = dict()``
<DFF> @@ -12,11 +12,22 @@ import uuid
from queries import pool
+def mock_connection():
+ conn = mock.MagicMock('psycopg2.extensions.connection')
+ conn.close = mock.Mock()
+ conn.closed = True
+ conn.isexecuting = mock.Mock(return_value=False)
+ return conn
+
+
class ManagerTests(unittest.TestCase):
def setUp(self):
self.manager = pool.PoolManager.instance()
+ def tearDown(self):
+ self.manager.shutdown()
+
def test_singleton_behavior(self):
self.assertEqual(pool.PoolManager.instance(), self.manager)
@@ -31,7 +42,7 @@ class ManagerTests(unittest.TestCase):
def test_adding_to_pool(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
- psycopg2_conn = mock.Mock()
+ psycopg2_conn = mock_connection()
self.manager.add(pid, psycopg2_conn)
self.assertIn(psycopg2_conn, self.manager._pools[pid])
@@ -62,7 +73,7 @@ class ManagerTests(unittest.TestCase):
def test_create_prevents_duplicate_pool_id(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool') as Pool:
- self.manager._pools[pid] = Pool()
+ self.manager.create(pid, 10, 10, Pool)
self.assertRaises(KeyError, self.manager.create, pid, 10, 10, Pool)
def test_create_created_default_pool_type(self):
@@ -104,12 +115,12 @@ class ManagerTests(unittest.TestCase):
def test_free_ensures_pool_exists(self):
pid = str(uuid.uuid4())
- psycopg2_conn = mock.Mock()
+ psycopg2_conn = mock_connection()
self.assertRaises(KeyError, self.manager.free, pid, psycopg2_conn)
def test_free_invokes_pool_free(self):
pid = str(uuid.uuid4())
- psycopg2_conn = mock.Mock()
+ psycopg2_conn = mock_connection()
self.manager.create(pid)
self.manager._pools[pid].free = free = mock.Mock()
self.manager.free(pid, psycopg2_conn)
@@ -131,9 +142,10 @@ class ManagerTests(unittest.TestCase):
def test_has_connection_returns_true(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
- psycopg2_conn = mock.Mock()
- self.manager._pools[pid].connections[id(psycopg2_conn)] = psycopg2_conn
+ psycopg2_conn = mock_connection()
+ self.manager.add(pid, psycopg2_conn)
self.assertTrue(self.manager.has_connection(pid, psycopg2_conn))
+ self.manager.remove(pid)
def test_has_idle_connection_returns_false(self):
pid = str(uuid.uuid4())
@@ -236,3 +248,13 @@ class ManagerTests(unittest.TestCase):
self.manager._pools[pid].set_max_size = set_max_size = mock.Mock()
self.manager.set_max_size(pid, 128)
set_max_size.assert_called_once_with(128)
+
+ def test_shutdown_closes_all(self):
+ pid1, pid2 = str(uuid.uuid4()), str(uuid.uuid4())
+ self.manager.create(pid1)
+ self.manager._pools[pid1].shutdown = method1 = mock.Mock()
+ self.manager.create(pid2)
+ self.manager._pools[pid2].shutdown = method2 = mock.Mock()
+ self.manager.shutdown()
+ method1.assert_called_once_with()
+ method2.assert_called_once_with()
| 28 | Add queries.pool.PoolManager.shutdown() | 6 | .py | py | bsd-3-clause | gmr/queries |
1327 | <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 __nonzero__(self):
return bool(self.cursor.rowcount)
def __repr__(self):
return '<queries.%s rows=%s>' % (self.__class__.__name__, len(self))
multiple rows, a :py:class:`ValueError` will be raised.
:return: dict
:raises: ValueError
"""
if not self.cursor.rowcount:
return {}
self._rewind()
if self.cursor.rowcount == 1:
return dict(self.cursor.fetchone())
else:
raise ValueError('More than one row')
def count(self):
"""Return the number of rows that were returned from the query
:rtype: int
"""
return self.cursor.rowcount
def free(self):
"""Used in asynchronous sessions for freeing results and their locked
connections.
"""
LOGGER.debug('Invoking synchronous free has no effect')
def items(self):
"""Return all of the rows that are in the result set.
:rtype: list
"""
if not self.cursor.rowcount:
return []
self.cursor.scroll(0, 'absolute')
return self.cursor.fetchall()
@property
def rownumber(self):
"""Return the current offset of the result set
:rtype: int
"""
return self.cursor.rownumber
@property
def query(self):
"""Return a read-only value of the query that was submitted to
PostgreSQL.
:rtype: str
"""
return self.cursor.query
@property
def status(self):
"""Return the status message returned by PostgreSQL after the query
was executed.
:rtype: str
"""
return self.cursor.statusmessage
def _rewind(self):
"""Rewind the cursor to the first row"""
self.cursor.scroll(0, 'absolute')
<MSG> Results: add __bool__ method.
Python 3 dropped __nonzero__ in preference to __bool__. The code was
only working because they fall back to __len__ if __bool__ is not
implemented. This commit adds a __bool__ implementation that simply
calls __nonzero__.
<DFF> @@ -59,6 +59,9 @@ class Results(object):
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))
| 3 | Results: add __bool__ method. | 0 | .py | py | bsd-3-clause | gmr/queries |
1328 | <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 __nonzero__(self):
return bool(self.cursor.rowcount)
def __repr__(self):
return '<queries.%s rows=%s>' % (self.__class__.__name__, len(self))
multiple rows, a :py:class:`ValueError` will be raised.
:return: dict
:raises: ValueError
"""
if not self.cursor.rowcount:
return {}
self._rewind()
if self.cursor.rowcount == 1:
return dict(self.cursor.fetchone())
else:
raise ValueError('More than one row')
def count(self):
"""Return the number of rows that were returned from the query
:rtype: int
"""
return self.cursor.rowcount
def free(self):
"""Used in asynchronous sessions for freeing results and their locked
connections.
"""
LOGGER.debug('Invoking synchronous free has no effect')
def items(self):
"""Return all of the rows that are in the result set.
:rtype: list
"""
if not self.cursor.rowcount:
return []
self.cursor.scroll(0, 'absolute')
return self.cursor.fetchall()
@property
def rownumber(self):
"""Return the current offset of the result set
:rtype: int
"""
return self.cursor.rownumber
@property
def query(self):
"""Return a read-only value of the query that was submitted to
PostgreSQL.
:rtype: str
"""
return self.cursor.query
@property
def status(self):
"""Return the status message returned by PostgreSQL after the query
was executed.
:rtype: str
"""
return self.cursor.statusmessage
def _rewind(self):
"""Rewind the cursor to the first row"""
self.cursor.scroll(0, 'absolute')
<MSG> Results: add __bool__ method.
Python 3 dropped __nonzero__ in preference to __bool__. The code was
only working because they fall back to __len__ if __bool__ is not
implemented. This commit adds a __bool__ implementation that simply
calls __nonzero__.
<DFF> @@ -59,6 +59,9 @@ class Results(object):
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))
| 3 | Results: add __bool__ method. | 0 | .py | py | bsd-3-clause | gmr/queries |
1329 | <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 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_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)
conn = yield self.obj._connect()
self.obj._pool_manager.add(self.obj.pid, conn)
with mock.patch.object(self.obj._pool_manager, 'get') as get:
with mock.patch.object(self.io_loop, 'add_handler') as add_handler:
second_result = yield self.obj._connect()
get.assert_called_once_with(self.obj.pid, self.obj)
@testing.gen_test
yield self.obj._connect()
add_handler.assert_called_once_with(self.conn.fileno(),
self.obj._on_io_events,
with mock.patch.object(self.obj._pool_manager, 'get') as get:
get.return_value = self.conn
with mock.patch.object(self.io_loop, 'add_handler') as add_handler:
second_result = yield self.obj._connect()
add_handler.assert_called_once_with(self.conn.fileno(),
self.obj._on_io_events,
ioloop.IOLoop.WRITE)
def test_on_io_events_returns_if_fd_not_present(self):
with mock.patch.object(self.obj, '_poll_connection') as poll:
self.obj._on_io_events(1337, ioloop.IOLoop.WRITE)
poll.assert_not_called()
def test_on_io_events_calls_poll_connection(self):
with mock.patch.object(self.obj, '_poll_connection') as poll:
self.obj._connections[1337] = True
self.obj._on_io_events(1337, ioloop.IOLoop.WRITE)
poll.assert_called_once_with(1337)
def test_exec_cleanup_closes_cursor(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = mock.Mock()
cursor = mock.Mock()
cursor.close = mock.Mock()
self.obj._exec_cleanup(cursor, 14)
cursor.close.assert_called_once_with()
def test_exec_cleanup_frees_connection(self):
with mock.patch.object(self.obj._pool_manager, 'free') as pm_free:
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = conn = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
pm_free.assert_called_once_with(self.obj.pid, conn)
def test_exec_cleanup_remove_handler_invoked(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler') as rh:
self.obj._connections[14] = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
rh.assert_called_once_with(14)
def test_exec_removes_connection(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
self.assertNotIn(14, self.obj._connections)
def test_exec_removes_future(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = mock.Mock()
self.obj._futures[14] = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
self.assertNotIn(14, self.obj._futures)
def test_pool_manager_add_failures_are_propagated(self):
futures = []
def add_future(future, callback):
futures.append((future, callback))
obj = tornado_session.TornadoSession()
obj._ioloop = mock.Mock()
obj._ioloop.add_future = add_future
future = concurrent.Future()
with mock.patch.object(obj._pool_manager, 'add') as add_method:
add_method.side_effect = pool.PoolFullError(mock.Mock())
obj._create_connection(future)
self.assertEqual(len(futures), 1)
connected_future, callback = futures.pop()
connected_future.set_result(True)
callback(connected_future)
self.assertIs(future.exception(), add_method.side_effect)
class SessionPublicMethodTests(testing.AsyncTestCase):
@testing.gen_test
def test_callproc_invokes_execute(self):
with mock.patch('queries.tornado_session.TornadoSession._execute') as \
_execute:
future = concurrent.Future()
future.set_result(True)
_execute.return_value = future
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
yield obj.callproc('foo', ['bar'])
_execute.assert_called_once_with('callproc', 'foo', ['bar'])
@testing.gen_test
def test_query_invokes_execute(self):
with mock.patch('queries.tornado_session.TornadoSession._execute') as \
_execute:
future = concurrent.Future()
future.set_result(True)
_execute.return_value = future
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
yield obj.query('SELECT 1')
_execute.assert_called_once_with('execute', 'SELECT 1', None)
"""
@testing.gen_test
def test_query_error_key_error(self):
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
with self.assertRaises(Exception):
yield obj.query('SELECT * FROM foo WHERE bar=%(baz)s', {})
@testing.gen_test
def test_query_error_index_error(self):
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
with self.assertRaises(Exception):
r = yield obj.query('SELECT * FROM foo WHERE bar=%s', [])
"""
future.set_result(connection)
_connect.return_value = future
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
result = yield obj.validate()
_connect.assert_called_once_with()
<MSG> Test cleanup
<DFF> @@ -47,11 +47,11 @@ 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_callback_dict(self):
+ self.assertDictEqual(self.obj._futures, {})
- # def test_creates_empty_connections_dict(self):
- # self.assertDictEqual(self.obj._connections, {})
+ 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)
@@ -105,8 +105,8 @@ class SessionConnectTests(testing.AsyncTestCase):
conn = yield self.obj._connect()
self.obj._pool_manager.add(self.obj.pid, conn)
with mock.patch.object(self.obj._pool_manager, 'get') as get:
- with mock.patch.object(self.io_loop, 'add_handler') as add_handler:
- second_result = yield self.obj._connect()
+ 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
@@ -116,7 +116,7 @@ class SessionConnectTests(testing.AsyncTestCase):
with mock.patch.object(self.obj._pool_manager, 'get') as get:
get.return_value = self.conn
with mock.patch.object(self.io_loop, 'add_handler') as add_handler:
- second_result = yield self.obj._connect()
+ yield self.obj._connect()
add_handler.assert_called_once_with(self.conn.fileno(),
self.obj._on_io_events,
ioloop.IOLoop.WRITE)
@@ -232,5 +232,5 @@ class SessionPublicMethodTests(testing.AsyncTestCase):
future.set_result(connection)
_connect.return_value = future
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
- result = yield obj.validate()
+ yield obj.validate()
_connect.assert_called_once_with()
| 8 | Test cleanup | 8 | .py | py | bsd-3-clause | gmr/queries |
1330 | <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 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_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)
conn = yield self.obj._connect()
self.obj._pool_manager.add(self.obj.pid, conn)
with mock.patch.object(self.obj._pool_manager, 'get') as get:
with mock.patch.object(self.io_loop, 'add_handler') as add_handler:
second_result = yield self.obj._connect()
get.assert_called_once_with(self.obj.pid, self.obj)
@testing.gen_test
yield self.obj._connect()
add_handler.assert_called_once_with(self.conn.fileno(),
self.obj._on_io_events,
with mock.patch.object(self.obj._pool_manager, 'get') as get:
get.return_value = self.conn
with mock.patch.object(self.io_loop, 'add_handler') as add_handler:
second_result = yield self.obj._connect()
add_handler.assert_called_once_with(self.conn.fileno(),
self.obj._on_io_events,
ioloop.IOLoop.WRITE)
def test_on_io_events_returns_if_fd_not_present(self):
with mock.patch.object(self.obj, '_poll_connection') as poll:
self.obj._on_io_events(1337, ioloop.IOLoop.WRITE)
poll.assert_not_called()
def test_on_io_events_calls_poll_connection(self):
with mock.patch.object(self.obj, '_poll_connection') as poll:
self.obj._connections[1337] = True
self.obj._on_io_events(1337, ioloop.IOLoop.WRITE)
poll.assert_called_once_with(1337)
def test_exec_cleanup_closes_cursor(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = mock.Mock()
cursor = mock.Mock()
cursor.close = mock.Mock()
self.obj._exec_cleanup(cursor, 14)
cursor.close.assert_called_once_with()
def test_exec_cleanup_frees_connection(self):
with mock.patch.object(self.obj._pool_manager, 'free') as pm_free:
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = conn = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
pm_free.assert_called_once_with(self.obj.pid, conn)
def test_exec_cleanup_remove_handler_invoked(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler') as rh:
self.obj._connections[14] = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
rh.assert_called_once_with(14)
def test_exec_removes_connection(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
self.assertNotIn(14, self.obj._connections)
def test_exec_removes_future(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = mock.Mock()
self.obj._futures[14] = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
self.assertNotIn(14, self.obj._futures)
def test_pool_manager_add_failures_are_propagated(self):
futures = []
def add_future(future, callback):
futures.append((future, callback))
obj = tornado_session.TornadoSession()
obj._ioloop = mock.Mock()
obj._ioloop.add_future = add_future
future = concurrent.Future()
with mock.patch.object(obj._pool_manager, 'add') as add_method:
add_method.side_effect = pool.PoolFullError(mock.Mock())
obj._create_connection(future)
self.assertEqual(len(futures), 1)
connected_future, callback = futures.pop()
connected_future.set_result(True)
callback(connected_future)
self.assertIs(future.exception(), add_method.side_effect)
class SessionPublicMethodTests(testing.AsyncTestCase):
@testing.gen_test
def test_callproc_invokes_execute(self):
with mock.patch('queries.tornado_session.TornadoSession._execute') as \
_execute:
future = concurrent.Future()
future.set_result(True)
_execute.return_value = future
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
yield obj.callproc('foo', ['bar'])
_execute.assert_called_once_with('callproc', 'foo', ['bar'])
@testing.gen_test
def test_query_invokes_execute(self):
with mock.patch('queries.tornado_session.TornadoSession._execute') as \
_execute:
future = concurrent.Future()
future.set_result(True)
_execute.return_value = future
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
yield obj.query('SELECT 1')
_execute.assert_called_once_with('execute', 'SELECT 1', None)
"""
@testing.gen_test
def test_query_error_key_error(self):
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
with self.assertRaises(Exception):
yield obj.query('SELECT * FROM foo WHERE bar=%(baz)s', {})
@testing.gen_test
def test_query_error_index_error(self):
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
with self.assertRaises(Exception):
r = yield obj.query('SELECT * FROM foo WHERE bar=%s', [])
"""
future.set_result(connection)
_connect.return_value = future
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
result = yield obj.validate()
_connect.assert_called_once_with()
<MSG> Test cleanup
<DFF> @@ -47,11 +47,11 @@ 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_callback_dict(self):
+ self.assertDictEqual(self.obj._futures, {})
- # def test_creates_empty_connections_dict(self):
- # self.assertDictEqual(self.obj._connections, {})
+ 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)
@@ -105,8 +105,8 @@ class SessionConnectTests(testing.AsyncTestCase):
conn = yield self.obj._connect()
self.obj._pool_manager.add(self.obj.pid, conn)
with mock.patch.object(self.obj._pool_manager, 'get') as get:
- with mock.patch.object(self.io_loop, 'add_handler') as add_handler:
- second_result = yield self.obj._connect()
+ 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
@@ -116,7 +116,7 @@ class SessionConnectTests(testing.AsyncTestCase):
with mock.patch.object(self.obj._pool_manager, 'get') as get:
get.return_value = self.conn
with mock.patch.object(self.io_loop, 'add_handler') as add_handler:
- second_result = yield self.obj._connect()
+ yield self.obj._connect()
add_handler.assert_called_once_with(self.conn.fileno(),
self.obj._on_io_events,
ioloop.IOLoop.WRITE)
@@ -232,5 +232,5 @@ class SessionPublicMethodTests(testing.AsyncTestCase):
future.set_result(connection)
_connect.return_value = future
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
- result = yield obj.validate()
+ yield obj.validate()
_connect.assert_called_once_with()
| 8 | Test cleanup | 8 | .py | py | bsd-3-clause | gmr/queries |
1331 | <NME> __init__.py
<BEF> """
Queries: PostgreSQL database access simplified
Queries is an opinionated wrapper for interfacing with PostgreSQL that offers
caching of connections and support for PyPy via psycopg2ct.
The core `queries.Queries` class will automatically register support for UUIDs,
Unicode and Unicode arrays.
"""
import logging
import sys
try:
import psycopg2cffi
import psycopg2cffi.extras
import psycopg2cffi.extensions
except ImportError:
pass
else:
sys.modules['psycopg2'] = psycopg2cffi
sys.modules['psycopg2.extras'] = psycopg2cffi.extras
sys.modules['psycopg2.extensions'] = psycopg2cffi.extensions
from queries.results import Results
from queries.session import Session
try:
from queries.tornado_session import TornadoSession
except ImportError: # pragma: nocover
TornadoSession = None
from queries.utils import uri
# For ease of access to different cursor types
from psycopg2.extras import DictCursor
from psycopg2.extras import NamedTupleCursor
from psycopg2.extras import RealDictCursor
from psycopg2.extras import LoggingCursor
from psycopg2.extras import MinTimeLoggingCursor
# Expose exceptions so clients do not need to import psycopg2 too
from psycopg2 import Warning
from psycopg2 import Error
from psycopg2 import DataError
from psycopg2 import DatabaseError
from psycopg2 import IntegrityError
from psycopg2 import InterfaceError
from psycopg2 import InternalError
from psycopg2 import NotSupportedError
from psycopg2 import OperationalError
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())
:return str: The PostgreSQL connection URI
"""
if password:
return 'postgresql://%s:%s@%s:%i/%s' % (user, password, host, port, dbname)
return 'postgresql://%s@%s:%i/%s' % (user, host, port, dbname)
# For ease of access to different cursor types
<MSG> Change how URIs are built with regard to port
<DFF> @@ -63,9 +63,11 @@ def uri(host='localhost', port=5432, dbname='postgres', user='postgres',
:return str: The PostgreSQL connection URI
"""
+ if port:
+ host = '%s:%s' % (host, port)
if password:
- return 'postgresql://%s:%s@%s:%i/%s' % (user, password, host, port, dbname)
- return 'postgresql://%s@%s:%i/%s' % (user, host, port, dbname)
+ return 'postgresql://%s:%s@%s/%s' % (user, password, host, dbname)
+ return 'postgresql://%s@%s/%s' % (user, host, dbname)
# For ease of access to different cursor types
| 4 | Change how URIs are built with regard to port | 2 | .py | py | bsd-3-clause | gmr/queries |
1332 | <NME> __init__.py
<BEF> """
Queries: PostgreSQL database access simplified
Queries is an opinionated wrapper for interfacing with PostgreSQL that offers
caching of connections and support for PyPy via psycopg2ct.
The core `queries.Queries` class will automatically register support for UUIDs,
Unicode and Unicode arrays.
"""
import logging
import sys
try:
import psycopg2cffi
import psycopg2cffi.extras
import psycopg2cffi.extensions
except ImportError:
pass
else:
sys.modules['psycopg2'] = psycopg2cffi
sys.modules['psycopg2.extras'] = psycopg2cffi.extras
sys.modules['psycopg2.extensions'] = psycopg2cffi.extensions
from queries.results import Results
from queries.session import Session
try:
from queries.tornado_session import TornadoSession
except ImportError: # pragma: nocover
TornadoSession = None
from queries.utils import uri
# For ease of access to different cursor types
from psycopg2.extras import DictCursor
from psycopg2.extras import NamedTupleCursor
from psycopg2.extras import RealDictCursor
from psycopg2.extras import LoggingCursor
from psycopg2.extras import MinTimeLoggingCursor
# Expose exceptions so clients do not need to import psycopg2 too
from psycopg2 import Warning
from psycopg2 import Error
from psycopg2 import DataError
from psycopg2 import DatabaseError
from psycopg2 import IntegrityError
from psycopg2 import InterfaceError
from psycopg2 import InternalError
from psycopg2 import NotSupportedError
from psycopg2 import OperationalError
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())
:return str: The PostgreSQL connection URI
"""
if password:
return 'postgresql://%s:%s@%s:%i/%s' % (user, password, host, port, dbname)
return 'postgresql://%s@%s:%i/%s' % (user, host, port, dbname)
# For ease of access to different cursor types
<MSG> Change how URIs are built with regard to port
<DFF> @@ -63,9 +63,11 @@ def uri(host='localhost', port=5432, dbname='postgres', user='postgres',
:return str: The PostgreSQL connection URI
"""
+ if port:
+ host = '%s:%s' % (host, port)
if password:
- return 'postgresql://%s:%s@%s:%i/%s' % (user, password, host, port, dbname)
- return 'postgresql://%s@%s:%i/%s' % (user, host, port, dbname)
+ return 'postgresql://%s:%s@%s/%s' % (user, password, host, dbname)
+ return 'postgresql://%s@%s/%s' % (user, host, dbname)
# For ease of access to different cursor types
| 4 | Change how URIs are built with regard to port | 2 | .py | py | bsd-3-clause | gmr/queries |
1333 | <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': None}
self._connect.assert_called_once_with(**expectation)
def test_psycopg2_register_json(self):
"""Ensure that the JSON extension was registered"""
self._reg_json.assert_called_once_with(conn_or_curs=self.client._conn)
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> psycopg2ct does not support JSON
<DFF> @@ -46,6 +46,7 @@ class SessionTests(unittest.TestCase):
'password': None}
self._connect.assert_called_once_with(**expectation)
+ @unittest.skipIf(PYPY, "Not supported in PyPy")
def test_psycopg2_register_json(self):
"""Ensure that the JSON extension was registered"""
self._reg_json.assert_called_once_with(conn_or_curs=self.client._conn)
| 1 | psycopg2ct does not support JSON | 0 | .py | py | bsd-3-clause | gmr/queries |
1334 | <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': None}
self._connect.assert_called_once_with(**expectation)
def test_psycopg2_register_json(self):
"""Ensure that the JSON extension was registered"""
self._reg_json.assert_called_once_with(conn_or_curs=self.client._conn)
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> psycopg2ct does not support JSON
<DFF> @@ -46,6 +46,7 @@ class SessionTests(unittest.TestCase):
'password': None}
self._connect.assert_called_once_with(**expectation)
+ @unittest.skipIf(PYPY, "Not supported in PyPy")
def test_psycopg2_register_json(self):
"""Ensure that the JSON extension was registered"""
self._reg_json.assert_called_once_with(conn_or_curs=self.client._conn)
| 1 | psycopg2ct does not support JSON | 0 | .py | py | bsd-3-clause | gmr/queries |
1335 | <NME> simple_tests.py
<BEF> ADDFILE
<MSG> Initial refactor
<DFF> @@ -0,0 +1,24 @@
+"""
+Queries Simple Method Tests
+
+"""
+try:
+ import unittest2 as unittest
+except ImportError:
+ import unittest
+
+from queries import simple
+
+
+class URITests(unittest.TestCase):
+
+ def test_uri_without_password(self):
+ """Validate URI method without password"""
+ expectation = 'pgsql://foo@bar:9999/baz'
+ self.assertEqual(simple.uri('bar', 9999, 'baz', 'foo'), expectation)
+
+ def test_uri_with_password(self):
+ """Validate URI method with a password"""
+ expectation = 'pgsql://foo:bar@baz:9999/qux'
+ self.assertEqual(simple.uri('baz', 9999, 'qux', 'foo', 'bar'),
+ expectation)
| 24 | Initial refactor | 0 | .py | py | bsd-3-clause | gmr/queries |
1336 | <NME> simple_tests.py
<BEF> ADDFILE
<MSG> Initial refactor
<DFF> @@ -0,0 +1,24 @@
+"""
+Queries Simple Method Tests
+
+"""
+try:
+ import unittest2 as unittest
+except ImportError:
+ import unittest
+
+from queries import simple
+
+
+class URITests(unittest.TestCase):
+
+ def test_uri_without_password(self):
+ """Validate URI method without password"""
+ expectation = 'pgsql://foo@bar:9999/baz'
+ self.assertEqual(simple.uri('bar', 9999, 'baz', 'foo'), expectation)
+
+ def test_uri_with_password(self):
+ """Validate URI method with a password"""
+ expectation = 'pgsql://foo:bar@baz:9999/qux'
+ self.assertEqual(simple.uri('baz', 9999, 'qux', 'foo', 'bar'),
+ expectation)
| 24 | Initial refactor | 0 | .py | py | bsd-3-clause | gmr/queries |
1337 | <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="
stages:
- test
- name: upload coverage
- name: deploy
services:
- postgres
- 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.6
- python: pypy
- python: pypy3
- stage: upload coverage
if: repo IS gmr/queries
services: []
python: 3.6
install:
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> More trying to get travis to work
<DFF> @@ -10,8 +10,9 @@ env:
stages:
- test
-- name: upload coverage
+- name: coverage
- name: deploy
+ if: tag IS present
services:
- postgres
@@ -34,8 +35,8 @@ jobs:
- python: 3.6
- python: pypy
- python: pypy3
- - stage: upload coverage
- if: repo IS gmr/queries
+ - stage: coverage
+ if: repo = gmr/queries
services: []
python: 3.6
install:
| 4 | More trying to get travis to work | 3 | .yml | travis | bsd-3-clause | gmr/queries |
1338 | <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="
stages:
- test
- name: upload coverage
- name: deploy
services:
- postgres
- 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.6
- python: pypy
- python: pypy3
- stage: upload coverage
if: repo IS gmr/queries
services: []
python: 3.6
install:
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> More trying to get travis to work
<DFF> @@ -10,8 +10,9 @@ env:
stages:
- test
-- name: upload coverage
+- name: coverage
- name: deploy
+ if: tag IS present
services:
- postgres
@@ -34,8 +35,8 @@ jobs:
- python: 3.6
- python: pypy
- python: pypy3
- - stage: upload coverage
- if: repo IS gmr/queries
+ - stage: coverage
+ if: repo = gmr/queries
services: []
python: 3.6
install:
| 4 | More trying to get travis to work | 3 | .yml | travis | bsd-3-clause | gmr/queries |
1339 | <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.10',
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 the version
<DFF> @@ -29,7 +29,7 @@ classifiers = ['Development Status :: 5 - Production/Stable',
'Topic :: Software Development :: Libraries']
setup(name='queries',
- version='1.8.10',
+ version='1.9.0',
description="Simplified PostgreSQL client built upon Psycopg2",
maintainer="Gavin M. Roy",
maintainer_email="gavinmroy@gmail.com",
| 1 | Bump the version | 1 | .py | py | bsd-3-clause | gmr/queries |
1340 | <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.10',
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 the version
<DFF> @@ -29,7 +29,7 @@ classifiers = ['Development Status :: 5 - Production/Stable',
'Topic :: Software Development :: Libraries']
setup(name='queries',
- version='1.8.10',
+ version='1.9.0',
description="Simplified PostgreSQL client built upon Psycopg2",
maintainer="Gavin M. Roy",
maintainer_email="gavinmroy@gmail.com",
| 1 | Bump the version | 1 | .py | py | bsd-3-clause | gmr/queries |
1341 | <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
pgsql.commit()
.. |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
>>> 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 the badges
<DFF> @@ -53,11 +53,11 @@ Creating a Postgres object for transactional behavior:
pgsql.commit()
-.. |Version| image:: https://badge.fury.io/py/pgsql_wrapper.svg?
- :target: http://badge.fury.io/py/pgsql_wrapper
+.. |Version| image:: https://badge.fury.io/py/queries.svg?
+ :target: http://badge.fury.io/py/queries
-.. |Status| image:: https://travis-ci.org/gmr/pgsql_wrapper.svg?branch=master
- :target: https://travis-ci.org/gmr/pgsql_wrapper
+.. |Status| image:: https://travis-ci.org/gmr/queries.svg?branch=master
+ :target: https://travis-ci.org/gmr/queries
-.. |Downloads| image:: https://pypip.in/d/pgsql_wrapper/badge.svg?
- :target: https://pypi.python.org/pypi/pgsql_wrapper
\ No newline at end of file
+.. |Downloads| image:: https://pypip.in/d/queries/badge.svg?
+ :target: https://pypi.python.org/pypi/queries
\ No newline at end of file
| 6 | Update the badges | 6 | .rst | rst | bsd-3-clause | gmr/queries |
1342 | <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
pgsql.commit()
.. |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
>>> 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 the badges
<DFF> @@ -53,11 +53,11 @@ Creating a Postgres object for transactional behavior:
pgsql.commit()
-.. |Version| image:: https://badge.fury.io/py/pgsql_wrapper.svg?
- :target: http://badge.fury.io/py/pgsql_wrapper
+.. |Version| image:: https://badge.fury.io/py/queries.svg?
+ :target: http://badge.fury.io/py/queries
-.. |Status| image:: https://travis-ci.org/gmr/pgsql_wrapper.svg?branch=master
- :target: https://travis-ci.org/gmr/pgsql_wrapper
+.. |Status| image:: https://travis-ci.org/gmr/queries.svg?branch=master
+ :target: https://travis-ci.org/gmr/queries
-.. |Downloads| image:: https://pypip.in/d/pgsql_wrapper/badge.svg?
- :target: https://pypi.python.org/pypi/pgsql_wrapper
\ No newline at end of file
+.. |Downloads| image:: https://pypip.in/d/queries/badge.svg?
+ :target: https://pypi.python.org/pypi/queries
\ No newline at end of file
| 6 | Update the badges | 6 | .rst | rst | bsd-3-clause | gmr/queries |
1343 | <NME> session_tests.py
<BEF> """
Tests for functionality in the session module
"""
import hashlib
import logging
import unittest
import mock
from psycopg2 import extras
import psycopg2
# Out of order import to ensure psycopg2cffi is registered
from queries import pool, results, session, utils
LOGGER = logging.getLogger(__name__)
class SessionTestCase(unittest.TestCase):
URI = 'postgresql://foo:bar@localhost:5432/foo'
@mock.patch('psycopg2.connect')
@mock.patch('psycopg2.extensions.register_type')
@mock.patch('psycopg2.extras.register_uuid')
@mock.patch('queries.utils.uri_to_kwargs')
def setUp(self, uri_to_kwargs, register_uuid, register_type, connect):
self.conn = mock.Mock()
self.conn.autocommit = False
self.conn.closed = False
self.conn.cursor = mock.Mock()
self.conn.isexecuting = mock.Mock(return_value=False)
self.conn.reset = mock.Mock()
self.conn.status = psycopg2.extensions.STATUS_BEGIN
self.psycopg2_connect = connect
self.psycopg2_connect.return_value = self.conn
self.psycopg2_register_type = register_type
self.psycopg2_register_uuid = register_uuid
self.uri_to_kwargs = uri_to_kwargs
self.uri_to_kwargs.return_value = {'host': 'localhost',
'port': 5432,
'user': 'foo',
'password': 'bar',
'dbname': 'foo'}
self.obj = session.Session(self.URI, pool_max_size=100)
def test_init_sets_uri(self):
self.assertEqual(self.obj._uri, self.URI)
def test_init_creates_new_pool(self):
self.assertIn(self.obj.pid, self.obj._pool_manager)
def test_init_creates_connection(self):
conns = \
[value.handle for key, value in
self.obj._pool_manager._pools[self.obj.pid].connections.items()]
self.assertIn(self.conn, conns)
def test_init_sets_cursorfactory(self):
self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor)
def test_init_gets_cursor(self):
self.conn.cursor.assert_called_once_with(
name=None, cursor_factory=extras.RealDictCursor)
def test_init_sets_autocommit(self):
self.assertTrue(self.conn.autocommit)
def test_backend_pid_invokes_conn_backend_pid(self):
self.conn.get_backend_pid = get_backend_pid = mock.Mock()
LOGGER.debug('ValueL %s', self.obj.backend_pid)
get_backend_pid.assert_called_once_with()
def test_callproc_invokes_cursor_callproc(self):
self.obj._cursor.callproc = mock.Mock()
args = ('foo', ['bar', 'baz'])
self.obj.callproc(*args)
self.obj._cursor.callproc.assert_called_once_with(*args)
def test_callproc_returns_results(self):
self.obj._cursor.callproc = mock.Mock()
args = ('foo', ['bar', 'baz'])
self.assertIsInstance(self.obj.callproc(*args), results.Results)
def test_close_raises_exception(self):
self.obj._conn = None
self.assertRaises(psycopg2.InterfaceError, self.obj.close)
def test_close_removes_connection(self):
self.obj.close()
self.assertNotIn(self.conn,
self.obj._pool_manager._pools[self.obj.pid])
def test_close_unassigns_connection(self):
self.obj.close()
self.assertIsNone(self.obj._conn)
def test_close_unassigns_cursor(self):
self.obj.close()
self.assertIsNone(self.obj._cursor)
def test_connection_property_returns_correct_value(self):
self.assertEqual(self.obj.connection, self.conn)
def test_cursor_property_returns_correct_value(self):
self.assertEqual(self.obj.cursor, self.obj._cursor)
def test_encoding_property_value(self):
self.conn.encoding = 'UTF-8'
self.assertEqual(self.obj.encoding, 'UTF-8')
def test_notices_value(self):
self.conn.notices = [1, 2, 3]
self.assertListEqual(self.obj.notices, [1, 2, 3])
def test_pid_value(self):
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.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> Dont let Session and TornadoSession share connections
<DFF> @@ -119,7 +119,8 @@ class SessionTestCase(unittest.TestCase):
self.assertListEqual(self.obj.notices, [1, 2, 3])
def test_pid_value(self):
- expectation = str(hashlib.md5(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):
| 2 | Dont let Session and TornadoSession share connections | 1 | .py | py | bsd-3-clause | gmr/queries |
1344 | <NME> session_tests.py
<BEF> """
Tests for functionality in the session module
"""
import hashlib
import logging
import unittest
import mock
from psycopg2 import extras
import psycopg2
# Out of order import to ensure psycopg2cffi is registered
from queries import pool, results, session, utils
LOGGER = logging.getLogger(__name__)
class SessionTestCase(unittest.TestCase):
URI = 'postgresql://foo:bar@localhost:5432/foo'
@mock.patch('psycopg2.connect')
@mock.patch('psycopg2.extensions.register_type')
@mock.patch('psycopg2.extras.register_uuid')
@mock.patch('queries.utils.uri_to_kwargs')
def setUp(self, uri_to_kwargs, register_uuid, register_type, connect):
self.conn = mock.Mock()
self.conn.autocommit = False
self.conn.closed = False
self.conn.cursor = mock.Mock()
self.conn.isexecuting = mock.Mock(return_value=False)
self.conn.reset = mock.Mock()
self.conn.status = psycopg2.extensions.STATUS_BEGIN
self.psycopg2_connect = connect
self.psycopg2_connect.return_value = self.conn
self.psycopg2_register_type = register_type
self.psycopg2_register_uuid = register_uuid
self.uri_to_kwargs = uri_to_kwargs
self.uri_to_kwargs.return_value = {'host': 'localhost',
'port': 5432,
'user': 'foo',
'password': 'bar',
'dbname': 'foo'}
self.obj = session.Session(self.URI, pool_max_size=100)
def test_init_sets_uri(self):
self.assertEqual(self.obj._uri, self.URI)
def test_init_creates_new_pool(self):
self.assertIn(self.obj.pid, self.obj._pool_manager)
def test_init_creates_connection(self):
conns = \
[value.handle for key, value in
self.obj._pool_manager._pools[self.obj.pid].connections.items()]
self.assertIn(self.conn, conns)
def test_init_sets_cursorfactory(self):
self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor)
def test_init_gets_cursor(self):
self.conn.cursor.assert_called_once_with(
name=None, cursor_factory=extras.RealDictCursor)
def test_init_sets_autocommit(self):
self.assertTrue(self.conn.autocommit)
def test_backend_pid_invokes_conn_backend_pid(self):
self.conn.get_backend_pid = get_backend_pid = mock.Mock()
LOGGER.debug('ValueL %s', self.obj.backend_pid)
get_backend_pid.assert_called_once_with()
def test_callproc_invokes_cursor_callproc(self):
self.obj._cursor.callproc = mock.Mock()
args = ('foo', ['bar', 'baz'])
self.obj.callproc(*args)
self.obj._cursor.callproc.assert_called_once_with(*args)
def test_callproc_returns_results(self):
self.obj._cursor.callproc = mock.Mock()
args = ('foo', ['bar', 'baz'])
self.assertIsInstance(self.obj.callproc(*args), results.Results)
def test_close_raises_exception(self):
self.obj._conn = None
self.assertRaises(psycopg2.InterfaceError, self.obj.close)
def test_close_removes_connection(self):
self.obj.close()
self.assertNotIn(self.conn,
self.obj._pool_manager._pools[self.obj.pid])
def test_close_unassigns_connection(self):
self.obj.close()
self.assertIsNone(self.obj._conn)
def test_close_unassigns_cursor(self):
self.obj.close()
self.assertIsNone(self.obj._cursor)
def test_connection_property_returns_correct_value(self):
self.assertEqual(self.obj.connection, self.conn)
def test_cursor_property_returns_correct_value(self):
self.assertEqual(self.obj.cursor, self.obj._cursor)
def test_encoding_property_value(self):
self.conn.encoding = 'UTF-8'
self.assertEqual(self.obj.encoding, 'UTF-8')
def test_notices_value(self):
self.conn.notices = [1, 2, 3]
self.assertListEqual(self.obj.notices, [1, 2, 3])
def test_pid_value(self):
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.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> Dont let Session and TornadoSession share connections
<DFF> @@ -119,7 +119,8 @@ class SessionTestCase(unittest.TestCase):
self.assertListEqual(self.obj.notices, [1, 2, 3])
def test_pid_value(self):
- expectation = str(hashlib.md5(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):
| 2 | Dont let Session and TornadoSession share connections | 1 | .py | py | bsd-3-clause | gmr/queries |
1345 | <NME> session.py
<BEF> """The Session class allows for a unified (and simplified) view of
interfacing with a PostgreSQL database server.
Connection details are passed in as a PostgreSQL URI and connections are pooled
by default, allowing for reuse of connections across modules in the Python
runtime without having to pass around the object handle.
While you can still access the raw `psycopg2` connection and cursor objects to
provide ultimate flexibility in how you use the queries.Session object, there
are convenience methods designed to simplify the interaction with PostgreSQL.
For `psycopg2` functionality outside of what is exposed in Session, simply
use the Session.connection or Session.cursor properties to gain access to
either object just as you would in a program using psycopg2 directly.
Example usage:
.. code:: python
import queries
with queries.Session('pgsql://postgres@localhost/postgres') as session:
for row in session.Query('SELECT * FROM table'):
print row
"""
import hashlib
import logging
import psycopg2
from psycopg2 import extensions, extras
from queries import pool, results, utils
LOGGER = logging.getLogger(__name__)
DEFAULT_ENCODING = 'UTF8'
DEFAULT_URI = 'postgresql://localhost:5432'
class Session(object):
"""The Session class allows for a unified (and simplified) view of
interfacing with a PostgreSQL database server. The Session object can
act as a context manager, providing automated cleanup and simple, Pythonic
way of interacting with the object.
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
"""
_conn = None
_cursor = None
_tpc_id = None
_uri = None
# Connection status constants
INTRANS = extensions.STATUS_IN_TRANSACTION
PREPARED = extensions.STATUS_PREPARED
READY = extensions.STATUS_READY
SETUP = extensions.STATUS_SETUP
# Transaction status constants
TX_ACTIVE = extensions.TRANSACTION_STATUS_ACTIVE
TX_IDLE = extensions.TRANSACTION_STATUS_IDLE
TX_INERROR = extensions.TRANSACTION_STATUS_INERROR
TX_INTRANS = extensions.TRANSACTION_STATUS_INTRANS
TX_UNKNOWN = extensions.TRANSACTION_STATUS_UNKNOWN
def __init__(self, uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
pool_max_size=pool.DEFAULT_MAX_SIZE,
autocommit=True):
"""Connect to a PostgreSQL server using the module wide connection and
set the isolation level.
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
"""
self._pool_manager = pool.PoolManager.instance()
self._uri = uri
# Ensure the pool exists in the pool manager
if self.pid not in self._pool_manager:
caches, etc.
"""
#self._cleanup()
pass
def __enter__(self):
"""For use as a context manager, return a handle to this object
@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()
caches, etc.
"""
#self._cleanup()
pass
@property
def backend_pid(self):
:rtype: queries.Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
try:
self._cursor.callproc(name, args)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def close(self):
"""Explicitly close the connection and remove it from the connection
pool if pooling is enabled. If the connection is already closed
:raises: psycopg2.InterfaceError
"""
if not self._conn:
raise psycopg2.InterfaceError('Connection not open')
LOGGER.info('Closing connection %r in %s', self._conn, self.pid)
self._pool_manager.free(self.pid, self._conn)
self._pool_manager.remove_connection(self.pid, self._conn)
# Un-assign the connection and cursor
self._conn, self._cursor = None, None
@property
def connection(self):
"""Return the current open connection to PostgreSQL.
:rtype: psycopg2.extensions.connection
"""
return self._conn
@property
def cursor(self):
"""Return the current, active cursor for the open connection.
:rtype: psycopg2.extensions.cursor
"""
return self._cursor
@property
def encoding(self):
"""Return the current client encoding value.
:rtype: str
"""
return self._conn.encoding
@property
def notices(self):
"""Return a list of up to the last 50 server notices sent to the client.
:rtype: list
"""
return self._conn.notices
@property
def pid(self):
"""Return the pool ID used for connection pooling.
:rtype: str
"""
return hashlib.md5(':'.join([self.__class__.__name__,
self._uri]).encode('utf-8')).hexdigest()
def query(self, sql, parameters=None):
"""A generator to issue a query on the server, mogrifying the
parameters against the sql statement. Results are returned as a
:py:class:`queries.Results` object which can act as an iterator and
has multiple ways to access the result data.
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: queries.Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
try:
self._cursor.execute(sql, parameters)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def set_encoding(self, value=DEFAULT_ENCODING):
"""Set the client encoding for the session if the value specified
is different than the current client encoding.
:param str value: The encoding value to use
"""
if self._conn.encoding != value:
self._conn.set_client_encoding(value)
def __del__(self):
"""When deleting the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def __enter__(self):
"""For use as a context manager, return a handle to this object
instance.
:rtype: Session
"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""When leaving the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def _autocommit(self, autocommit):
"""Set the isolation level automatically to commit or not after every query
:param autocommit: Boolean (Default - True)
"""
self._conn.autocommit = autocommit
def _cleanup(self):
"""Remove the connection from the stack, closing out the cursor"""
if self._cursor:
LOGGER.debug('Closing the cursor on %s', self.pid)
self._cursor.close()
self._cursor = None
if self._conn:
LOGGER.debug('Freeing %s in the pool', self.pid)
try:
pool.PoolManager.instance().free(self.pid, self._conn)
except pool.ConnectionNotFoundError:
pass
self._conn = None
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
if possible, or by creating the new connection.
:rtype: psycopg2.extensions.connection
:raises: pool.NoIdleConnectionsError
"""
# Attempt to get a cached connection from the connection pool
try:
connection = self._pool_manager.get(self.pid, self)
LOGGER.debug("Re-using connection for %s", self.pid)
except pool.NoIdleConnectionsError:
if self._pool_manager.is_full(self.pid):
raise
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
LOGGER.debug("Creating a new connection for %s", self.pid)
connection = self._psycopg2_connect(kwargs)
self._pool_manager.add(self.pid, connection)
self._pool_manager.lock(self.pid, connection, self)
# Added in because psycopg2ct connects and leaves the connection in
# a weird state: consts.STATUS_DATESTYLE, returning from
# Connection._setup without setting the state as const.STATUS_OK
if utils.PYPY:
connection.reset()
# Register the custom data types
self._register_unicode(connection)
self._register_uuid(connection)
return connection
def _get_cursor(self, connection, name=None):
"""Return a cursor for the given cursor_factory. Specify a name to
use server-side cursors.
:param connection: The connection to create a cursor on
:type connection: psycopg2.extensions.connection
:param str name: A cursor name for a server side cursor
:rtype: psycopg2.extensions.cursor
"""
cursor = connection.cursor(name=name,
cursor_factory=self._cursor_factory)
if name is not None:
cursor.scrollable = True
cursor.withhold = True
return cursor
def _incr_exceptions(self):
"""Increment the number of exceptions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).exceptions += 1
def _incr_executions(self):
"""Increment the number of executions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).executions += 1
def _psycopg2_connect(self, kwargs):
"""Return a psycopg2 connection for the specified kwargs. Extend for
use in async session adapters.
:param dict kwargs: Keyword connection args
:rtype: psycopg2.extensions.connection
"""
return psycopg2.connect(**kwargs)
@staticmethod
def _register_unicode(connection):
"""Register the cursor to be able to receive Unicode string.
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE,
connection)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY,
connection)
@staticmethod
def _register_uuid(connection):
"""Register the UUID extension from the psycopg2.extra module
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extras.register_uuid(conn_or_curs=connection)
@property
def _status(self):
"""Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queries.Session.READY: Connected, no active transaction
:rtype: int
"""
if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
return self.READY
return self._conn.status
<MSG> Move cleanup back after finding issue that they were commented out for
<DFF> @@ -89,8 +89,7 @@ class Session(object):
caches, etc.
"""
- #self._cleanup()
- pass
+ self._cleanup()
def __enter__(self):
"""For use as a context manager, return a handle to this object
@@ -106,8 +105,7 @@ class Session(object):
caches, etc.
"""
- #self._cleanup()
- pass
+ self._cleanup()
@property
def backend_pid(self):
| 2 | Move cleanup back after finding issue that they were commented out for | 4 | .py | py | bsd-3-clause | gmr/queries |
1346 | <NME> session.py
<BEF> """The Session class allows for a unified (and simplified) view of
interfacing with a PostgreSQL database server.
Connection details are passed in as a PostgreSQL URI and connections are pooled
by default, allowing for reuse of connections across modules in the Python
runtime without having to pass around the object handle.
While you can still access the raw `psycopg2` connection and cursor objects to
provide ultimate flexibility in how you use the queries.Session object, there
are convenience methods designed to simplify the interaction with PostgreSQL.
For `psycopg2` functionality outside of what is exposed in Session, simply
use the Session.connection or Session.cursor properties to gain access to
either object just as you would in a program using psycopg2 directly.
Example usage:
.. code:: python
import queries
with queries.Session('pgsql://postgres@localhost/postgres') as session:
for row in session.Query('SELECT * FROM table'):
print row
"""
import hashlib
import logging
import psycopg2
from psycopg2 import extensions, extras
from queries import pool, results, utils
LOGGER = logging.getLogger(__name__)
DEFAULT_ENCODING = 'UTF8'
DEFAULT_URI = 'postgresql://localhost:5432'
class Session(object):
"""The Session class allows for a unified (and simplified) view of
interfacing with a PostgreSQL database server. The Session object can
act as a context manager, providing automated cleanup and simple, Pythonic
way of interacting with the object.
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
"""
_conn = None
_cursor = None
_tpc_id = None
_uri = None
# Connection status constants
INTRANS = extensions.STATUS_IN_TRANSACTION
PREPARED = extensions.STATUS_PREPARED
READY = extensions.STATUS_READY
SETUP = extensions.STATUS_SETUP
# Transaction status constants
TX_ACTIVE = extensions.TRANSACTION_STATUS_ACTIVE
TX_IDLE = extensions.TRANSACTION_STATUS_IDLE
TX_INERROR = extensions.TRANSACTION_STATUS_INERROR
TX_INTRANS = extensions.TRANSACTION_STATUS_INTRANS
TX_UNKNOWN = extensions.TRANSACTION_STATUS_UNKNOWN
def __init__(self, uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
pool_max_size=pool.DEFAULT_MAX_SIZE,
autocommit=True):
"""Connect to a PostgreSQL server using the module wide connection and
set the isolation level.
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
"""
self._pool_manager = pool.PoolManager.instance()
self._uri = uri
# Ensure the pool exists in the pool manager
if self.pid not in self._pool_manager:
caches, etc.
"""
#self._cleanup()
pass
def __enter__(self):
"""For use as a context manager, return a handle to this object
@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()
caches, etc.
"""
#self._cleanup()
pass
@property
def backend_pid(self):
:rtype: queries.Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
try:
self._cursor.callproc(name, args)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def close(self):
"""Explicitly close the connection and remove it from the connection
pool if pooling is enabled. If the connection is already closed
:raises: psycopg2.InterfaceError
"""
if not self._conn:
raise psycopg2.InterfaceError('Connection not open')
LOGGER.info('Closing connection %r in %s', self._conn, self.pid)
self._pool_manager.free(self.pid, self._conn)
self._pool_manager.remove_connection(self.pid, self._conn)
# Un-assign the connection and cursor
self._conn, self._cursor = None, None
@property
def connection(self):
"""Return the current open connection to PostgreSQL.
:rtype: psycopg2.extensions.connection
"""
return self._conn
@property
def cursor(self):
"""Return the current, active cursor for the open connection.
:rtype: psycopg2.extensions.cursor
"""
return self._cursor
@property
def encoding(self):
"""Return the current client encoding value.
:rtype: str
"""
return self._conn.encoding
@property
def notices(self):
"""Return a list of up to the last 50 server notices sent to the client.
:rtype: list
"""
return self._conn.notices
@property
def pid(self):
"""Return the pool ID used for connection pooling.
:rtype: str
"""
return hashlib.md5(':'.join([self.__class__.__name__,
self._uri]).encode('utf-8')).hexdigest()
def query(self, sql, parameters=None):
"""A generator to issue a query on the server, mogrifying the
parameters against the sql statement. Results are returned as a
:py:class:`queries.Results` object which can act as an iterator and
has multiple ways to access the result data.
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: queries.Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
try:
self._cursor.execute(sql, parameters)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def set_encoding(self, value=DEFAULT_ENCODING):
"""Set the client encoding for the session if the value specified
is different than the current client encoding.
:param str value: The encoding value to use
"""
if self._conn.encoding != value:
self._conn.set_client_encoding(value)
def __del__(self):
"""When deleting the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def __enter__(self):
"""For use as a context manager, return a handle to this object
instance.
:rtype: Session
"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""When leaving the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def _autocommit(self, autocommit):
"""Set the isolation level automatically to commit or not after every query
:param autocommit: Boolean (Default - True)
"""
self._conn.autocommit = autocommit
def _cleanup(self):
"""Remove the connection from the stack, closing out the cursor"""
if self._cursor:
LOGGER.debug('Closing the cursor on %s', self.pid)
self._cursor.close()
self._cursor = None
if self._conn:
LOGGER.debug('Freeing %s in the pool', self.pid)
try:
pool.PoolManager.instance().free(self.pid, self._conn)
except pool.ConnectionNotFoundError:
pass
self._conn = None
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
if possible, or by creating the new connection.
:rtype: psycopg2.extensions.connection
:raises: pool.NoIdleConnectionsError
"""
# Attempt to get a cached connection from the connection pool
try:
connection = self._pool_manager.get(self.pid, self)
LOGGER.debug("Re-using connection for %s", self.pid)
except pool.NoIdleConnectionsError:
if self._pool_manager.is_full(self.pid):
raise
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
LOGGER.debug("Creating a new connection for %s", self.pid)
connection = self._psycopg2_connect(kwargs)
self._pool_manager.add(self.pid, connection)
self._pool_manager.lock(self.pid, connection, self)
# Added in because psycopg2ct connects and leaves the connection in
# a weird state: consts.STATUS_DATESTYLE, returning from
# Connection._setup without setting the state as const.STATUS_OK
if utils.PYPY:
connection.reset()
# Register the custom data types
self._register_unicode(connection)
self._register_uuid(connection)
return connection
def _get_cursor(self, connection, name=None):
"""Return a cursor for the given cursor_factory. Specify a name to
use server-side cursors.
:param connection: The connection to create a cursor on
:type connection: psycopg2.extensions.connection
:param str name: A cursor name for a server side cursor
:rtype: psycopg2.extensions.cursor
"""
cursor = connection.cursor(name=name,
cursor_factory=self._cursor_factory)
if name is not None:
cursor.scrollable = True
cursor.withhold = True
return cursor
def _incr_exceptions(self):
"""Increment the number of exceptions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).exceptions += 1
def _incr_executions(self):
"""Increment the number of executions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).executions += 1
def _psycopg2_connect(self, kwargs):
"""Return a psycopg2 connection for the specified kwargs. Extend for
use in async session adapters.
:param dict kwargs: Keyword connection args
:rtype: psycopg2.extensions.connection
"""
return psycopg2.connect(**kwargs)
@staticmethod
def _register_unicode(connection):
"""Register the cursor to be able to receive Unicode string.
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE,
connection)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY,
connection)
@staticmethod
def _register_uuid(connection):
"""Register the UUID extension from the psycopg2.extra module
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extras.register_uuid(conn_or_curs=connection)
@property
def _status(self):
"""Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queries.Session.READY: Connected, no active transaction
:rtype: int
"""
if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
return self.READY
return self._conn.status
<MSG> Move cleanup back after finding issue that they were commented out for
<DFF> @@ -89,8 +89,7 @@ class Session(object):
caches, etc.
"""
- #self._cleanup()
- pass
+ self._cleanup()
def __enter__(self):
"""For use as a context manager, return a handle to this object
@@ -106,8 +105,7 @@ class Session(object):
caches, etc.
"""
- #self._cleanup()
- pass
+ self._cleanup()
@property
def backend_pid(self):
| 2 | Move cleanup back after finding issue that they were commented out for | 4 | .py | py | bsd-3-clause | gmr/queries |
1347 | <NME> pool.py
<BEF> """
Connection Pooling
"""
import datetime
import logging
import os
import threading
import time
import weakref
import psycopg2
LOGGER = logging.getLogger(__name__)
DEFAULT_IDLE_TTL = 60
DEFAULT_MAX_SIZE = int(os.environ.get('QUERIES_MAX_POOL_SIZE', 1))
class Connection(object):
"""Contains the handle to the connection, the current state of the
connection and methods for manipulating the state of the connection.
"""
_lock = threading.Lock()
def __init__(self, handle):
self.handle = handle
self.used_by = None
self.executions = 0
self.exceptions = 0
def close(self):
"""Close the connection
:raises: ConnectionBusyError
"""
LOGGER.debug('Connection %s closing', self.id)
if self.busy and not self.closed:
raise ConnectionBusyError(self)
with self._lock:
if not self.handle.closed:
try:
self.handle.close()
except psycopg2.InterfaceError as error:
LOGGER.error('Error closing socket: %s', error)
@property
def closed(self):
"""Return if the psycopg2 connection is closed.
:rtype: bool
"""
return self.handle.closed != 0
@property
def busy(self):
"""Return if the connection is currently executing a query or is locked
by a session that still exists.
:rtype: bool
"""
if self.handle.isexecuting():
return True
elif self.used_by is None:
return False
return not self.used_by() is None
@property
def executing(self):
"""Return if the connection is currently executing a query
:rtype: bool
"""
return self.handle.isexecuting()
def free(self):
"""Remove the lock on the connection if the connection is not active
:raises: ConnectionBusyError
"""
LOGGER.debug('Connection %s freeing', self.id)
if self.handle.isexecuting():
raise ConnectionBusyError(self)
with self._lock:
self.used_by = None
LOGGER.debug('Connection %s freed', self.id)
@property
def id(self):
"""Return id of the psycopg2 connection object
:rtype: int
"""
return id(self.handle)
def lock(self, session):
"""Lock the connection, ensuring that it is not busy and storing
a weakref for the session.
:param queries.Session session: The session to lock the connection with
:raises: ConnectionBusyError
"""
if self.busy:
raise ConnectionBusyError(self)
with self._lock:
self.used_by = weakref.ref(session)
LOGGER.debug('Connection %s locked', self.id)
@property
def locked(self):
"""Return if the connection is currently exclusively locked
:rtype: bool
"""
return self.used_by is not None
class Pool(object):
"""A connection pool for gaining access to and managing connections"""
_lock = threading.Lock()
idle_start = None
idle_ttl = DEFAULT_IDLE_TTL
max_size = DEFAULT_MAX_SIZE
def __init__(self,
pool_id,
idle_ttl=DEFAULT_IDLE_TTL,
max_size=DEFAULT_MAX_SIZE,
time_method=None):
self.connections = {}
self._id = pool_id
self.idle_ttl = idle_ttl
self.max_size = max_size
self.time_method = time_method or time.time
def __contains__(self, connection):
"""Return True if the pool contains the connection"""
return id(connection) in self.connections
def __len__(self):
"""Return the number of connections in the pool"""
return len(self.connections)
def add(self, connection):
"""Add a new connection to the pool
:param connection: The connection to add to the pool
:type connection: psycopg2.extensions.connection
:raises: PoolFullError
"""
if id(connection) in self.connections:
raise ValueError('Connection already exists in pool')
if len(self.connections) == self.max_size:
LOGGER.warning('Race condition found when adding new connection')
try:
connection.close()
except (psycopg2.Error, psycopg2.Warning) as error:
LOGGER.error('Error closing the conn that cant be used: %s',
error)
raise PoolFullError(self)
with self._lock:
self.connections[id(connection)] = Connection(connection)
LOGGER.debug('Pool %s added connection %s', self.id, id(connection))
@property
def busy_connections(self):
"""Return a list of active/busy connections
:rtype: list
"""
return [c for c in self.connections.values()
if c.busy and not c.closed]
def clean(self):
"""Clean the pool by removing any closed connections and if the pool's
idle has exceeded its idle TTL, remove all connections.
"""
LOGGER.debug('Cleaning the pool')
for connection in [self.connections[k] for k in self.connections if
self.connections[k].closed]:
LOGGER.debug('Removing %s', connection.id)
self.remove(connection.handle)
if self.idle_duration > self.idle_ttl:
self.close()
LOGGER.debug('Pool %s cleaned', self.id)
def close(self):
"""Close the pool by closing and removing all of the connections"""
for cid in list(self.connections.keys()):
self.remove(self.connections[cid].handle)
LOGGER.debug('Pool %s closed', self.id)
@property
def closed_connections(self):
"""Return a list of closed connections
:rtype: list
"""
return [c for c in self.connections.values() if c.closed]
def connection_handle(self, connection):
"""Return a connection object for the given psycopg2 connection
:param connection: The connection to return a parent for
:type connection: psycopg2.extensions.connection
:rtype: Connection
"""
return self.connections[id(connection)]
@property
def executing_connections(self):
"""Return a list of connections actively executing queries
:rtype: list
"""
return [c for c in self.connections.values() if c.executing]
def free(self, connection):
"""Free the connection from use by the session that was using it.
:param connection: The connection to free
:type connection: psycopg2.extensions.connection
:raises: ConnectionNotFoundError
"""
LOGGER.debug('Pool %s freeing connection %s', self.id, id(connection))
try:
self.connection_handle(connection).free()
except KeyError:
raise ConnectionNotFoundError(self.id, id(connection))
if self.idle_connections == list(self.connections.values()):
with self._lock:
self.idle_start = self.time_method()
LOGGER.debug('Pool %s freed connection %s', self.id, id(connection))
def get(self, session):
"""Return an idle connection and assign the session to the connection
:param queries.Session session: The session to assign
:rtype: psycopg2.extensions.connection
:raises: NoIdleConnectionsError
"""
idle = self.idle_connections
if idle:
connection = idle.pop(0)
connection.lock(session)
if self.idle_start:
with self._lock:
self.idle_start = None
return connection.handle
raise NoIdleConnectionsError(self.id)
@property
def id(self):
"""Return the ID for this pool
:rtype: str
"""
return self._id
@property
def idle_connections(self):
"""Return a list of idle connections
:rtype: list
"""
return [c for c in self.connections.values()
if not c.busy and not c.closed]
@property
def idle_duration(self):
"""Return the number of seconds that the pool has had no active
connections.
:rtype: float
"""
if self.idle_start is None:
return 0
return self.time_method() - self.idle_start
@property
def is_full(self):
"""Return True if there are no more open slots for connections.
:rtype: bool
"""
return len(self.connections) >= self.max_size
def lock(self, connection, session):
"""Explicitly lock the specified connection
:type connection: psycopg2.extensions.connection
:param connection: The connection to lock
:param queries.Session session: The session to hold the lock
"""
cid = id(connection)
try:
self.connection_handle(connection).lock(session)
except KeyError:
raise ConnectionNotFoundError(self.id, cid)
else:
if self.idle_start:
with self._lock:
self.idle_start = None
LOGGER.debug('Pool %s locked connection %s', self.id, cid)
@property
def locked_connections(self):
"""Return a list of all locked connections
:rtype: list
"""
return [c for c in self.connections.values() if c.locked]
def remove(self, connection):
"""Remove the connection from the pool
:param connection: The connection to remove
:type connection: psycopg2.extensions.connection
:raises: ConnectionNotFoundError
:raises: ConnectionBusyError
"""
cid = id(connection)
if cid not in self.connections:
raise ConnectionNotFoundError(self.id, cid)
self.connection_handle(connection).close()
with self._lock:
del self.connections[cid]
LOGGER.debug('Pool %s removed connection %s', self.id, cid)
def report(self):
"""Return a report about the pool state and configuration.
:rtype: dict
"""
return {
'connections': {
'busy': len(self.busy_connections),
'closed': len(self.closed_connections),
'executing': len(self.executing_connections),
'idle': len(self.idle_connections),
'locked': len(self.busy_connections)
},
'exceptions': sum([c.exceptions
for c in self.connections.values()]),
'executions': sum([c.executions
for c in self.connections.values()]),
'full': self.is_full,
'idle': {
'duration': self.idle_duration,
'ttl': self.idle_ttl
},
'max_size': self.max_size
}
def shutdown(self):
"""Forcefully shutdown the entire pool, closing all non-executing
connections.
:raises: ConnectionBusyError
"""
with self._lock:
for cid in list(self.connections.keys()):
if self.connections[cid].executing:
raise ConnectionBusyError(cid)
if self.connections[cid].locked:
self.connections[cid].free()
self.connections[cid].close()
del self.connections[cid]
def set_idle_ttl(self, ttl):
"""Set the idle ttl
:param int ttl: The TTL when idle
"""
"""
with cls._lock:
cls._ensure_pool_exists(pid)
cls._pools[pid].clean()
cls._maybe_remove_pool(pid)
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> Catch KeyError in clean
<DFF> @@ -407,7 +407,11 @@ class PoolManager(object):
"""
with cls._lock:
- cls._ensure_pool_exists(pid)
+ 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)
| 5 | Catch KeyError in clean | 1 | .py | py | bsd-3-clause | gmr/queries |
1348 | <NME> pool.py
<BEF> """
Connection Pooling
"""
import datetime
import logging
import os
import threading
import time
import weakref
import psycopg2
LOGGER = logging.getLogger(__name__)
DEFAULT_IDLE_TTL = 60
DEFAULT_MAX_SIZE = int(os.environ.get('QUERIES_MAX_POOL_SIZE', 1))
class Connection(object):
"""Contains the handle to the connection, the current state of the
connection and methods for manipulating the state of the connection.
"""
_lock = threading.Lock()
def __init__(self, handle):
self.handle = handle
self.used_by = None
self.executions = 0
self.exceptions = 0
def close(self):
"""Close the connection
:raises: ConnectionBusyError
"""
LOGGER.debug('Connection %s closing', self.id)
if self.busy and not self.closed:
raise ConnectionBusyError(self)
with self._lock:
if not self.handle.closed:
try:
self.handle.close()
except psycopg2.InterfaceError as error:
LOGGER.error('Error closing socket: %s', error)
@property
def closed(self):
"""Return if the psycopg2 connection is closed.
:rtype: bool
"""
return self.handle.closed != 0
@property
def busy(self):
"""Return if the connection is currently executing a query or is locked
by a session that still exists.
:rtype: bool
"""
if self.handle.isexecuting():
return True
elif self.used_by is None:
return False
return not self.used_by() is None
@property
def executing(self):
"""Return if the connection is currently executing a query
:rtype: bool
"""
return self.handle.isexecuting()
def free(self):
"""Remove the lock on the connection if the connection is not active
:raises: ConnectionBusyError
"""
LOGGER.debug('Connection %s freeing', self.id)
if self.handle.isexecuting():
raise ConnectionBusyError(self)
with self._lock:
self.used_by = None
LOGGER.debug('Connection %s freed', self.id)
@property
def id(self):
"""Return id of the psycopg2 connection object
:rtype: int
"""
return id(self.handle)
def lock(self, session):
"""Lock the connection, ensuring that it is not busy and storing
a weakref for the session.
:param queries.Session session: The session to lock the connection with
:raises: ConnectionBusyError
"""
if self.busy:
raise ConnectionBusyError(self)
with self._lock:
self.used_by = weakref.ref(session)
LOGGER.debug('Connection %s locked', self.id)
@property
def locked(self):
"""Return if the connection is currently exclusively locked
:rtype: bool
"""
return self.used_by is not None
class Pool(object):
"""A connection pool for gaining access to and managing connections"""
_lock = threading.Lock()
idle_start = None
idle_ttl = DEFAULT_IDLE_TTL
max_size = DEFAULT_MAX_SIZE
def __init__(self,
pool_id,
idle_ttl=DEFAULT_IDLE_TTL,
max_size=DEFAULT_MAX_SIZE,
time_method=None):
self.connections = {}
self._id = pool_id
self.idle_ttl = idle_ttl
self.max_size = max_size
self.time_method = time_method or time.time
def __contains__(self, connection):
"""Return True if the pool contains the connection"""
return id(connection) in self.connections
def __len__(self):
"""Return the number of connections in the pool"""
return len(self.connections)
def add(self, connection):
"""Add a new connection to the pool
:param connection: The connection to add to the pool
:type connection: psycopg2.extensions.connection
:raises: PoolFullError
"""
if id(connection) in self.connections:
raise ValueError('Connection already exists in pool')
if len(self.connections) == self.max_size:
LOGGER.warning('Race condition found when adding new connection')
try:
connection.close()
except (psycopg2.Error, psycopg2.Warning) as error:
LOGGER.error('Error closing the conn that cant be used: %s',
error)
raise PoolFullError(self)
with self._lock:
self.connections[id(connection)] = Connection(connection)
LOGGER.debug('Pool %s added connection %s', self.id, id(connection))
@property
def busy_connections(self):
"""Return a list of active/busy connections
:rtype: list
"""
return [c for c in self.connections.values()
if c.busy and not c.closed]
def clean(self):
"""Clean the pool by removing any closed connections and if the pool's
idle has exceeded its idle TTL, remove all connections.
"""
LOGGER.debug('Cleaning the pool')
for connection in [self.connections[k] for k in self.connections if
self.connections[k].closed]:
LOGGER.debug('Removing %s', connection.id)
self.remove(connection.handle)
if self.idle_duration > self.idle_ttl:
self.close()
LOGGER.debug('Pool %s cleaned', self.id)
def close(self):
"""Close the pool by closing and removing all of the connections"""
for cid in list(self.connections.keys()):
self.remove(self.connections[cid].handle)
LOGGER.debug('Pool %s closed', self.id)
@property
def closed_connections(self):
"""Return a list of closed connections
:rtype: list
"""
return [c for c in self.connections.values() if c.closed]
def connection_handle(self, connection):
"""Return a connection object for the given psycopg2 connection
:param connection: The connection to return a parent for
:type connection: psycopg2.extensions.connection
:rtype: Connection
"""
return self.connections[id(connection)]
@property
def executing_connections(self):
"""Return a list of connections actively executing queries
:rtype: list
"""
return [c for c in self.connections.values() if c.executing]
def free(self, connection):
"""Free the connection from use by the session that was using it.
:param connection: The connection to free
:type connection: psycopg2.extensions.connection
:raises: ConnectionNotFoundError
"""
LOGGER.debug('Pool %s freeing connection %s', self.id, id(connection))
try:
self.connection_handle(connection).free()
except KeyError:
raise ConnectionNotFoundError(self.id, id(connection))
if self.idle_connections == list(self.connections.values()):
with self._lock:
self.idle_start = self.time_method()
LOGGER.debug('Pool %s freed connection %s', self.id, id(connection))
def get(self, session):
"""Return an idle connection and assign the session to the connection
:param queries.Session session: The session to assign
:rtype: psycopg2.extensions.connection
:raises: NoIdleConnectionsError
"""
idle = self.idle_connections
if idle:
connection = idle.pop(0)
connection.lock(session)
if self.idle_start:
with self._lock:
self.idle_start = None
return connection.handle
raise NoIdleConnectionsError(self.id)
@property
def id(self):
"""Return the ID for this pool
:rtype: str
"""
return self._id
@property
def idle_connections(self):
"""Return a list of idle connections
:rtype: list
"""
return [c for c in self.connections.values()
if not c.busy and not c.closed]
@property
def idle_duration(self):
"""Return the number of seconds that the pool has had no active
connections.
:rtype: float
"""
if self.idle_start is None:
return 0
return self.time_method() - self.idle_start
@property
def is_full(self):
"""Return True if there are no more open slots for connections.
:rtype: bool
"""
return len(self.connections) >= self.max_size
def lock(self, connection, session):
"""Explicitly lock the specified connection
:type connection: psycopg2.extensions.connection
:param connection: The connection to lock
:param queries.Session session: The session to hold the lock
"""
cid = id(connection)
try:
self.connection_handle(connection).lock(session)
except KeyError:
raise ConnectionNotFoundError(self.id, cid)
else:
if self.idle_start:
with self._lock:
self.idle_start = None
LOGGER.debug('Pool %s locked connection %s', self.id, cid)
@property
def locked_connections(self):
"""Return a list of all locked connections
:rtype: list
"""
return [c for c in self.connections.values() if c.locked]
def remove(self, connection):
"""Remove the connection from the pool
:param connection: The connection to remove
:type connection: psycopg2.extensions.connection
:raises: ConnectionNotFoundError
:raises: ConnectionBusyError
"""
cid = id(connection)
if cid not in self.connections:
raise ConnectionNotFoundError(self.id, cid)
self.connection_handle(connection).close()
with self._lock:
del self.connections[cid]
LOGGER.debug('Pool %s removed connection %s', self.id, cid)
def report(self):
"""Return a report about the pool state and configuration.
:rtype: dict
"""
return {
'connections': {
'busy': len(self.busy_connections),
'closed': len(self.closed_connections),
'executing': len(self.executing_connections),
'idle': len(self.idle_connections),
'locked': len(self.busy_connections)
},
'exceptions': sum([c.exceptions
for c in self.connections.values()]),
'executions': sum([c.executions
for c in self.connections.values()]),
'full': self.is_full,
'idle': {
'duration': self.idle_duration,
'ttl': self.idle_ttl
},
'max_size': self.max_size
}
def shutdown(self):
"""Forcefully shutdown the entire pool, closing all non-executing
connections.
:raises: ConnectionBusyError
"""
with self._lock:
for cid in list(self.connections.keys()):
if self.connections[cid].executing:
raise ConnectionBusyError(cid)
if self.connections[cid].locked:
self.connections[cid].free()
self.connections[cid].close()
del self.connections[cid]
def set_idle_ttl(self, ttl):
"""Set the idle ttl
:param int ttl: The TTL when idle
"""
"""
with cls._lock:
cls._ensure_pool_exists(pid)
cls._pools[pid].clean()
cls._maybe_remove_pool(pid)
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> Catch KeyError in clean
<DFF> @@ -407,7 +407,11 @@ class PoolManager(object):
"""
with cls._lock:
- cls._ensure_pool_exists(pid)
+ 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)
| 5 | Catch KeyError in clean | 1 | .py | py | bsd-3-clause | gmr/queries |
1349 | <NME> pool_manager_tests.py
<BEF> """
Tests for Manager class in the pool module
"""
import unittest
import uuid
import mock
from queries import pool
def mock_connection():
class ManagerTests(unittest.TestCase):
def setUp(self):
self.manager = pool.PoolManager.instance()
class ManagerTests(unittest.TestCase):
def setUp(self):
self.manager = pool.PoolManager.instance()
def tearDown(self):
self.manager.shutdown()
def test_singleton_behavior(self):
self.assertEqual(pool.PoolManager.instance(), self.manager)
def test_has_pool_false(self):
self.assertNotIn(mock.Mock(), self.manager)
def test_has_pool_true(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.assertIn(pid, self.manager)
def test_adding_to_pool(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
psycopg2_conn = mock_connection()
self.manager.add(pid, psycopg2_conn)
self.assertIn(psycopg2_conn, self.manager._pools[pid])
def test_adding_to_pool_ensures_pool_exists(self):
pid = str(uuid.uuid4())
psycopg2_conn = mock.Mock()
self.assertRaises(KeyError, self.manager.add, pid, psycopg2_conn)
def test_ensures_pool_exists_raises_key_error(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager._ensure_pool_exists, pid)
def test_clean_ensures_pool_exists_catches_key_error(self):
pid = str(uuid.uuid4())
self.assertIsNone(self.manager.clean(pid))
def test_clean_invokes_pool_clean(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool') as Pool:
self.manager._pools[pid] = Pool()
self.manager._pools[pid].clean = clean = mock.Mock()
self.manager.clean(pid)
clean.assert_called_once_with()
def test_clean_removes_pool(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool') as Pool:
self.manager._pools[pid] = Pool()
self.manager.clean(pid)
self.assertNotIn(pid, self.manager._pools)
def test_create_prevents_duplicate_pool_id(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool'):
self.manager.create(pid, 10, 10)
self.assertRaises(KeyError, self.manager.create, pid, 10, 10)
def test_create_passes_in_idle_ttl(self):
pid = str(uuid.uuid4())
self.manager.create(pid, 12)
self.assertEqual(self.manager._pools[pid].idle_ttl, 12)
def test_create_passes_in_max_size(self):
pid = str(uuid.uuid4())
self.manager.create(pid, 10, 16)
self.assertEqual(self.manager._pools[pid].max_size, 16)
def test_get_ensures_pool_exists(self):
pid = str(uuid.uuid4())
session = mock.Mock()
self.assertRaises(KeyError, self.manager.get, pid, session)
def test_get_invokes_pool_get(self):
pid = str(uuid.uuid4())
session = mock.Mock()
self.manager.create(pid)
self.manager._pools[pid].get = get = mock.Mock()
self.manager.get(pid, session)
get.assert_called_once_with(session)
def test_free_ensures_pool_exists(self):
pid = str(uuid.uuid4())
psycopg2_conn = mock_connection()
self.assertRaises(KeyError, self.manager.free, pid, psycopg2_conn)
def test_free_invokes_pool_free(self):
pid = str(uuid.uuid4())
psycopg2_conn = mock_connection()
self.manager.create(pid)
self.manager._pools[pid].free = free = mock.Mock()
self.manager.free(pid, psycopg2_conn)
free.assert_called_once_with(psycopg2_conn)
def test_has_connection_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.has_connection, pid, None)
def test_has_idle_connection_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.has_idle_connection, pid)
def test_has_connection_returns_false(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.assertFalse(self.manager.has_connection(pid, mock.Mock()))
def test_has_connection_returns_true(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
psycopg2_conn = mock_connection()
self.manager.add(pid, psycopg2_conn)
self.assertTrue(self.manager.has_connection(pid, psycopg2_conn))
self.manager.remove(pid)
def test_has_idle_connection_returns_false(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
with mock.patch('queries.pool.Pool.idle_connections',
new_callable=mock.PropertyMock) as idle_connections:
idle_connections.return_value = 0
self.assertFalse(self.manager.has_idle_connection(pid))
def test_has_idle_connection_returns_true(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
with mock.patch('queries.pool.Pool.idle_connections',
new_callable=mock.PropertyMock) as idle_connections:
idle_connections.return_value = 5
self.assertTrue(self.manager.has_idle_connection(pid))
def test_is_full_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.is_full, pid)
def test_is_full_invokes_pool_is_full(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
with mock.patch('queries.pool.Pool.is_full',
new_callable=mock.PropertyMock) as is_full:
self.manager.is_full(pid)
is_full.assert_called_once_with()
def test_lock_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.lock, pid, None, None)
def test_lock_invokes_pool_lock(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].lock = lock = mock.Mock()
psycopg2_conn = mock.Mock()
session = mock.Mock()
self.manager.lock(pid, psycopg2_conn, session)
lock.assert_called_once_with(psycopg2_conn, session)
def test_remove_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.remove, pid)
def test_remove_invokes_pool_close(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].close = method = mock.Mock()
self.manager.remove(pid)
method.assert_called_once_with()
def test_remove_deletes_pool(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].close = mock.Mock()
self.manager.remove(pid)
self.assertNotIn(pid, self.manager._pools)
def test_remove_connection_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.remove_connection, pid, None)
def test_remove_connection_invokes_pool_remove(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].remove = remove = mock.Mock()
psycopg2_conn = mock.Mock()
self.manager.remove_connection(pid, psycopg2_conn)
remove.assert_called_once_with(psycopg2_conn)
def test_size_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.size, pid)
def test_size_returns_pool_length(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.assertEqual(self.manager.size(pid), len(self.manager._pools[pid]))
def test_set_idle_ttl_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.set_idle_ttl, pid, None)
def test_set_idle_ttl_invokes_pool_set_idle_ttl(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].set_idle_ttl = set_idle_ttl = mock.Mock()
self.manager.set_idle_ttl(pid, 256)
set_idle_ttl.assert_called_once_with(256)
def test_set_max_size_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.set_idle_ttl, pid, None)
def test_set_max_size_invokes_pool_set_max_size(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].set_max_size = set_max_size = mock.Mock()
self.manager.set_max_size(pid, 128)
set_max_size.assert_called_once_with(128)
def test_shutdown_closes_all(self):
pid1, pid2 = str(uuid.uuid4()), str(uuid.uuid4())
self.manager.create(pid1)
self.manager._pools[pid1].shutdown = method1 = mock.Mock()
self.manager.create(pid2)
self.manager._pools[pid2].shutdown = method2 = mock.Mock()
self.manager.shutdown()
method1.assert_called_once_with()
method2.assert_called_once_with()
<MSG> Whitespace cleanup
<DFF> @@ -14,7 +14,6 @@ from queries import pool
class ManagerTests(unittest.TestCase):
-
def setUp(self):
self.manager = pool.PoolManager.instance()
| 0 | Whitespace cleanup | 1 | .py | py | bsd-3-clause | gmr/queries |
1350 | <NME> pool_manager_tests.py
<BEF> """
Tests for Manager class in the pool module
"""
import unittest
import uuid
import mock
from queries import pool
def mock_connection():
class ManagerTests(unittest.TestCase):
def setUp(self):
self.manager = pool.PoolManager.instance()
class ManagerTests(unittest.TestCase):
def setUp(self):
self.manager = pool.PoolManager.instance()
def tearDown(self):
self.manager.shutdown()
def test_singleton_behavior(self):
self.assertEqual(pool.PoolManager.instance(), self.manager)
def test_has_pool_false(self):
self.assertNotIn(mock.Mock(), self.manager)
def test_has_pool_true(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.assertIn(pid, self.manager)
def test_adding_to_pool(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
psycopg2_conn = mock_connection()
self.manager.add(pid, psycopg2_conn)
self.assertIn(psycopg2_conn, self.manager._pools[pid])
def test_adding_to_pool_ensures_pool_exists(self):
pid = str(uuid.uuid4())
psycopg2_conn = mock.Mock()
self.assertRaises(KeyError, self.manager.add, pid, psycopg2_conn)
def test_ensures_pool_exists_raises_key_error(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager._ensure_pool_exists, pid)
def test_clean_ensures_pool_exists_catches_key_error(self):
pid = str(uuid.uuid4())
self.assertIsNone(self.manager.clean(pid))
def test_clean_invokes_pool_clean(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool') as Pool:
self.manager._pools[pid] = Pool()
self.manager._pools[pid].clean = clean = mock.Mock()
self.manager.clean(pid)
clean.assert_called_once_with()
def test_clean_removes_pool(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool') as Pool:
self.manager._pools[pid] = Pool()
self.manager.clean(pid)
self.assertNotIn(pid, self.manager._pools)
def test_create_prevents_duplicate_pool_id(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool'):
self.manager.create(pid, 10, 10)
self.assertRaises(KeyError, self.manager.create, pid, 10, 10)
def test_create_passes_in_idle_ttl(self):
pid = str(uuid.uuid4())
self.manager.create(pid, 12)
self.assertEqual(self.manager._pools[pid].idle_ttl, 12)
def test_create_passes_in_max_size(self):
pid = str(uuid.uuid4())
self.manager.create(pid, 10, 16)
self.assertEqual(self.manager._pools[pid].max_size, 16)
def test_get_ensures_pool_exists(self):
pid = str(uuid.uuid4())
session = mock.Mock()
self.assertRaises(KeyError, self.manager.get, pid, session)
def test_get_invokes_pool_get(self):
pid = str(uuid.uuid4())
session = mock.Mock()
self.manager.create(pid)
self.manager._pools[pid].get = get = mock.Mock()
self.manager.get(pid, session)
get.assert_called_once_with(session)
def test_free_ensures_pool_exists(self):
pid = str(uuid.uuid4())
psycopg2_conn = mock_connection()
self.assertRaises(KeyError, self.manager.free, pid, psycopg2_conn)
def test_free_invokes_pool_free(self):
pid = str(uuid.uuid4())
psycopg2_conn = mock_connection()
self.manager.create(pid)
self.manager._pools[pid].free = free = mock.Mock()
self.manager.free(pid, psycopg2_conn)
free.assert_called_once_with(psycopg2_conn)
def test_has_connection_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.has_connection, pid, None)
def test_has_idle_connection_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.has_idle_connection, pid)
def test_has_connection_returns_false(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.assertFalse(self.manager.has_connection(pid, mock.Mock()))
def test_has_connection_returns_true(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
psycopg2_conn = mock_connection()
self.manager.add(pid, psycopg2_conn)
self.assertTrue(self.manager.has_connection(pid, psycopg2_conn))
self.manager.remove(pid)
def test_has_idle_connection_returns_false(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
with mock.patch('queries.pool.Pool.idle_connections',
new_callable=mock.PropertyMock) as idle_connections:
idle_connections.return_value = 0
self.assertFalse(self.manager.has_idle_connection(pid))
def test_has_idle_connection_returns_true(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
with mock.patch('queries.pool.Pool.idle_connections',
new_callable=mock.PropertyMock) as idle_connections:
idle_connections.return_value = 5
self.assertTrue(self.manager.has_idle_connection(pid))
def test_is_full_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.is_full, pid)
def test_is_full_invokes_pool_is_full(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
with mock.patch('queries.pool.Pool.is_full',
new_callable=mock.PropertyMock) as is_full:
self.manager.is_full(pid)
is_full.assert_called_once_with()
def test_lock_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.lock, pid, None, None)
def test_lock_invokes_pool_lock(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].lock = lock = mock.Mock()
psycopg2_conn = mock.Mock()
session = mock.Mock()
self.manager.lock(pid, psycopg2_conn, session)
lock.assert_called_once_with(psycopg2_conn, session)
def test_remove_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.remove, pid)
def test_remove_invokes_pool_close(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].close = method = mock.Mock()
self.manager.remove(pid)
method.assert_called_once_with()
def test_remove_deletes_pool(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].close = mock.Mock()
self.manager.remove(pid)
self.assertNotIn(pid, self.manager._pools)
def test_remove_connection_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.remove_connection, pid, None)
def test_remove_connection_invokes_pool_remove(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].remove = remove = mock.Mock()
psycopg2_conn = mock.Mock()
self.manager.remove_connection(pid, psycopg2_conn)
remove.assert_called_once_with(psycopg2_conn)
def test_size_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.size, pid)
def test_size_returns_pool_length(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.assertEqual(self.manager.size(pid), len(self.manager._pools[pid]))
def test_set_idle_ttl_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.set_idle_ttl, pid, None)
def test_set_idle_ttl_invokes_pool_set_idle_ttl(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].set_idle_ttl = set_idle_ttl = mock.Mock()
self.manager.set_idle_ttl(pid, 256)
set_idle_ttl.assert_called_once_with(256)
def test_set_max_size_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.set_idle_ttl, pid, None)
def test_set_max_size_invokes_pool_set_max_size(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].set_max_size = set_max_size = mock.Mock()
self.manager.set_max_size(pid, 128)
set_max_size.assert_called_once_with(128)
def test_shutdown_closes_all(self):
pid1, pid2 = str(uuid.uuid4()), str(uuid.uuid4())
self.manager.create(pid1)
self.manager._pools[pid1].shutdown = method1 = mock.Mock()
self.manager.create(pid2)
self.manager._pools[pid2].shutdown = method2 = mock.Mock()
self.manager.shutdown()
method1.assert_called_once_with()
method2.assert_called_once_with()
<MSG> Whitespace cleanup
<DFF> @@ -14,7 +14,6 @@ from queries import pool
class ManagerTests(unittest.TestCase):
-
def setUp(self):
self.manager = pool.PoolManager.instance()
| 0 | Whitespace cleanup | 1 | .py | py | bsd-3-clause | gmr/queries |
1351 | <NME> tornado_session_tests.py
<BEF> """
Tests for functionality in the tornado_session module
"""
import unittest
import mock
except ImportError:
import unittest
from queries import tornado_session
def setUp(self):
super(SessionConnectTests, self).setUp()
self.conn = mock.Mock()
self.conn.fileno = mock.Mock(return_value=10)
self.obj = tornado_session.TornadoSession(io_loop=self.io_loop)
def create_connection(future):
future.set_result(self.conn)
self.obj._create_connection = create_connection
@testing.gen_test
def test_connect_returns_new_connection(self):
conn = yield self.obj._connect()
self.assertEqual(conn, self.conn)
@testing.gen_test
def test_connect_returns_pooled_connection(self):
conn = yield self.obj._connect()
self.obj._pool_manager.add(self.obj.pid, conn)
second_result = yield self.obj._connect()
self.assertEqual(second_result, conn)
@testing.gen_test
def test_connect_gets_pooled_connection(self):
conn = yield self.obj._connect()
self.obj._pool_manager.add(self.obj.pid, conn)
with mock.patch.object(self.obj._pool_manager, 'get') as get:
with mock.patch.object(self.io_loop, 'add_handler'):
yield self.obj._connect()
get.assert_called_once_with(self.obj.pid, self.obj)
@testing.gen_test
def test_connect_pooled_connection_invokes_add_handler(self):
conn = yield self.obj._connect()
self.obj._pool_manager.add(self.obj.pid, conn)
with mock.patch.object(self.obj._pool_manager, 'get') as get:
get.return_value = self.conn
with mock.patch.object(self.io_loop, 'add_handler') as add_handler:
yield self.obj._connect()
add_handler.assert_called_once_with(self.conn.fileno(),
self.obj._on_io_events,
ioloop.IOLoop.WRITE)
def test_psycopg2_connect_invokes_psycopg2_connect(self):
with mock.patch('psycopg2.connect') as connect:
self.obj._psycopg2_connect({})
connect.assert_called_once_with(**{'async': True})
def test_on_io_events_returns_if_fd_not_present(self):
with mock.patch.object(self.obj, '_poll_connection') as poll:
self.obj._on_io_events(1337, ioloop.IOLoop.WRITE)
poll.assert_not_called()
def test_on_io_events_calls_poll_connection(self):
with mock.patch.object(self.obj, '_poll_connection') as poll:
self.obj._connections[1337] = True
self.obj._on_io_events(1337, ioloop.IOLoop.WRITE)
poll.assert_called_once_with(1337)
def test_exec_cleanup_closes_cursor(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = mock.Mock()
cursor = mock.Mock()
cursor.close = mock.Mock()
self.obj._exec_cleanup(cursor, 14)
cursor.close.assert_called_once_with()
def test_exec_cleanup_frees_connection(self):
with mock.patch.object(self.obj._pool_manager, 'free') as pm_free:
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = conn = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
pm_free.assert_called_once_with(self.obj.pid, conn)
def test_exec_cleanup_remove_handler_invoked(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler') as rh:
self.obj._connections[14] = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
rh.assert_called_once_with(14)
def test_exec_removes_connection(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
self.assertNotIn(14, self.obj._connections)
def test_exec_removes_future(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = mock.Mock()
self.obj._futures[14] = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
self.assertNotIn(14, self.obj._futures)
def test_pool_manager_add_failures_are_propagated(self):
futures = []
def add_future(future, callback):
futures.append((future, callback))
obj = tornado_session.TornadoSession()
obj._ioloop = mock.Mock()
obj._ioloop.add_future = add_future
future = concurrent.Future()
with mock.patch.object(obj._pool_manager, 'add') as add_method:
add_method.side_effect = pool.PoolFullError(mock.Mock())
obj._create_connection(future)
self.assertEqual(len(futures), 1)
connected_future, callback = futures.pop()
connected_future.set_result(True)
callback(connected_future)
self.assertIs(future.exception(), add_method.side_effect)
class SessionPublicMethodTests(testing.AsyncTestCase):
@testing.gen_test
def test_callproc_invokes_execute(self):
with mock.patch('queries.tornado_session.TornadoSession._execute') as \
_execute:
future = concurrent.Future()
future.set_result(True)
_execute.return_value = future
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
yield obj.callproc('foo', ['bar'])
_execute.assert_called_once_with('callproc', 'foo', ['bar'])
@testing.gen_test
def test_query_invokes_execute(self):
with mock.patch('queries.tornado_session.TornadoSession._execute') as \
_execute:
future = concurrent.Future()
future.set_result(True)
_execute.return_value = future
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
yield obj.query('SELECT 1')
_execute.assert_called_once_with('execute', 'SELECT 1', None)
"""
@testing.gen_test
def test_query_error_key_error(self):
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
with self.assertRaises(Exception):
yield obj.query('SELECT * FROM foo WHERE bar=%(baz)s', {})
@testing.gen_test
def test_query_error_index_error(self):
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
with self.assertRaises(Exception):
r = yield obj.query('SELECT * FROM foo WHERE bar=%s', [])
"""
<MSG> Initial TornadoSession tests
Still have coverage to add
<DFF> @@ -8,5 +8,65 @@ try:
except ImportError:
import unittest
+from psycopg2 import extras
+from tornado import gen
+from tornado import ioloop
+
+from queries import pool
from queries import tornado_session
+
+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._callbacks, {})
+
+ def test_creates_empty_connections_dict(self):
+ self.assertDictEqual(self.obj._connections, {})
+
+ def test_creates_empty_exceptions_dict(self):
+ self.assertDictEqual(self.obj._exceptions, {})
+
+ def test_creates_empty_listeners_dict(self):
+ self.assertDictEqual(self.obj._listeners, {})
+
+ 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.DEFAULT_URI)
+
+ def test_creates_pool_in_manager(self):
+ self.assertIn(self.obj.pid, self.obj._pool_manager._pools)
| 60 | Initial TornadoSession tests | 0 | .py | py | bsd-3-clause | gmr/queries |
1352 | <NME> tornado_session_tests.py
<BEF> """
Tests for functionality in the tornado_session module
"""
import unittest
import mock
except ImportError:
import unittest
from queries import tornado_session
def setUp(self):
super(SessionConnectTests, self).setUp()
self.conn = mock.Mock()
self.conn.fileno = mock.Mock(return_value=10)
self.obj = tornado_session.TornadoSession(io_loop=self.io_loop)
def create_connection(future):
future.set_result(self.conn)
self.obj._create_connection = create_connection
@testing.gen_test
def test_connect_returns_new_connection(self):
conn = yield self.obj._connect()
self.assertEqual(conn, self.conn)
@testing.gen_test
def test_connect_returns_pooled_connection(self):
conn = yield self.obj._connect()
self.obj._pool_manager.add(self.obj.pid, conn)
second_result = yield self.obj._connect()
self.assertEqual(second_result, conn)
@testing.gen_test
def test_connect_gets_pooled_connection(self):
conn = yield self.obj._connect()
self.obj._pool_manager.add(self.obj.pid, conn)
with mock.patch.object(self.obj._pool_manager, 'get') as get:
with mock.patch.object(self.io_loop, 'add_handler'):
yield self.obj._connect()
get.assert_called_once_with(self.obj.pid, self.obj)
@testing.gen_test
def test_connect_pooled_connection_invokes_add_handler(self):
conn = yield self.obj._connect()
self.obj._pool_manager.add(self.obj.pid, conn)
with mock.patch.object(self.obj._pool_manager, 'get') as get:
get.return_value = self.conn
with mock.patch.object(self.io_loop, 'add_handler') as add_handler:
yield self.obj._connect()
add_handler.assert_called_once_with(self.conn.fileno(),
self.obj._on_io_events,
ioloop.IOLoop.WRITE)
def test_psycopg2_connect_invokes_psycopg2_connect(self):
with mock.patch('psycopg2.connect') as connect:
self.obj._psycopg2_connect({})
connect.assert_called_once_with(**{'async': True})
def test_on_io_events_returns_if_fd_not_present(self):
with mock.patch.object(self.obj, '_poll_connection') as poll:
self.obj._on_io_events(1337, ioloop.IOLoop.WRITE)
poll.assert_not_called()
def test_on_io_events_calls_poll_connection(self):
with mock.patch.object(self.obj, '_poll_connection') as poll:
self.obj._connections[1337] = True
self.obj._on_io_events(1337, ioloop.IOLoop.WRITE)
poll.assert_called_once_with(1337)
def test_exec_cleanup_closes_cursor(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = mock.Mock()
cursor = mock.Mock()
cursor.close = mock.Mock()
self.obj._exec_cleanup(cursor, 14)
cursor.close.assert_called_once_with()
def test_exec_cleanup_frees_connection(self):
with mock.patch.object(self.obj._pool_manager, 'free') as pm_free:
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = conn = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
pm_free.assert_called_once_with(self.obj.pid, conn)
def test_exec_cleanup_remove_handler_invoked(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler') as rh:
self.obj._connections[14] = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
rh.assert_called_once_with(14)
def test_exec_removes_connection(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
self.assertNotIn(14, self.obj._connections)
def test_exec_removes_future(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = mock.Mock()
self.obj._futures[14] = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
self.assertNotIn(14, self.obj._futures)
def test_pool_manager_add_failures_are_propagated(self):
futures = []
def add_future(future, callback):
futures.append((future, callback))
obj = tornado_session.TornadoSession()
obj._ioloop = mock.Mock()
obj._ioloop.add_future = add_future
future = concurrent.Future()
with mock.patch.object(obj._pool_manager, 'add') as add_method:
add_method.side_effect = pool.PoolFullError(mock.Mock())
obj._create_connection(future)
self.assertEqual(len(futures), 1)
connected_future, callback = futures.pop()
connected_future.set_result(True)
callback(connected_future)
self.assertIs(future.exception(), add_method.side_effect)
class SessionPublicMethodTests(testing.AsyncTestCase):
@testing.gen_test
def test_callproc_invokes_execute(self):
with mock.patch('queries.tornado_session.TornadoSession._execute') as \
_execute:
future = concurrent.Future()
future.set_result(True)
_execute.return_value = future
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
yield obj.callproc('foo', ['bar'])
_execute.assert_called_once_with('callproc', 'foo', ['bar'])
@testing.gen_test
def test_query_invokes_execute(self):
with mock.patch('queries.tornado_session.TornadoSession._execute') as \
_execute:
future = concurrent.Future()
future.set_result(True)
_execute.return_value = future
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
yield obj.query('SELECT 1')
_execute.assert_called_once_with('execute', 'SELECT 1', None)
"""
@testing.gen_test
def test_query_error_key_error(self):
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
with self.assertRaises(Exception):
yield obj.query('SELECT * FROM foo WHERE bar=%(baz)s', {})
@testing.gen_test
def test_query_error_index_error(self):
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
with self.assertRaises(Exception):
r = yield obj.query('SELECT * FROM foo WHERE bar=%s', [])
"""
<MSG> Initial TornadoSession tests
Still have coverage to add
<DFF> @@ -8,5 +8,65 @@ try:
except ImportError:
import unittest
+from psycopg2 import extras
+from tornado import gen
+from tornado import ioloop
+
+from queries import pool
from queries import tornado_session
+
+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._callbacks, {})
+
+ def test_creates_empty_connections_dict(self):
+ self.assertDictEqual(self.obj._connections, {})
+
+ def test_creates_empty_exceptions_dict(self):
+ self.assertDictEqual(self.obj._exceptions, {})
+
+ def test_creates_empty_listeners_dict(self):
+ self.assertDictEqual(self.obj._listeners, {})
+
+ 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.DEFAULT_URI)
+
+ def test_creates_pool_in_manager(self):
+ self.assertIn(self.obj.pid, self.obj._pool_manager._pools)
| 60 | Initial TornadoSession tests | 0 | .py | py | bsd-3-clause | gmr/queries |
1353 | <NME> session_tests.py
<BEF> """
Tests for the session.Session class
"""
import mock
try:
import unittest2 as unittest
except ImportError:
import unittest
import psycopg2
from psycopg2 import extensions
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._reg_type = register_type
self._reg_uuid = register_uuid
self.uri = 'pgsql://postgres@127.0.0.1:5432/queries'
if self.uri in pool.CONNECTIONS:
del pool.CONNECTIONS[self.uri]
self.client = session.Session(self.uri)
def test_psycopg2_connection_invoked(self):
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()
def test_connection_added_to_cache(self):
"""Ensure the connection is in the connection cache"""
self.assertIn(self.uri, pool.CONNECTIONS)
def test_connection_handle_in_cache(self):
"""Ensure that the connection handle in cache is valid"""
self.assertEqual(pool.CONNECTIONS[self.uri]['handle'],
self.client._conn)
def test_cleanup_removes_client_from_cache(self):
"""Ensure that Session._cleanup frees the client in the cache"""
value = pool.CONNECTIONS[self.uri]['clients']
self.client._cleanup()
self.assertEqual(pool.CONNECTIONS[self.uri]['clients'], value - 1)
@unittest.skipIf(not PYPY, 'PyPy only test')
def test_conn_reset_if_pypy(self):
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):
del self.client
cleanup.assert_called_once_with()
@mock.patch('psycopg2.extensions.register_type')
@mock.patch('psycopg2.extras.register_json')
@mock.patch('psycopg2.extras.register_uuid')
def test_context_manager_creation(self, _uuid, _json, _type,):
"""Ensure context manager returns self"""
with session.Session(self.uri) as conn:
self.assertIsInstance(conn, session.Session)
@mock.patch('psycopg2.extensions.register_type')
@mock.patch('psycopg2.extras.register_json')
@mock.patch('psycopg2.extras.register_uuid')
def test_context_manager_cleanup(self, _uuid, _json, _type,):
"""Ensure context manager cleans up after self"""
with mock.patch('queries.session.Session._cleanup') as cleanup:
with session.Session(self.uri):
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)
@mock.patch('psycopg2.extras.register_uuid')
def test_close_removes_from_cache(self, _uuid, _json, _type, _connect):
"""Ensure connection removed from cache on close"""
uri = 'pgsql://foo@bar:9999/baz'
pgsql = session.Session(uri)
self.assertIn(uri, pool.CONNECTIONS)
pgsql.close()
self.assertNotIn(uri, pool.CONNECTIONS)
@mock.patch('psycopg2.connect')
@mock.patch('psycopg2.extensions.register_type')
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> Update session pool usage and tests
<DFF> @@ -2,11 +2,14 @@
Tests for the session.Session class
"""
+import hashlib
import mock
+import uuid
try:
import unittest2 as unittest
except ImportError:
import unittest
+import weakref
import psycopg2
from psycopg2 import extensions
@@ -29,8 +32,9 @@ class SessionTests(unittest.TestCase):
self._reg_type = register_type
self._reg_uuid = register_uuid
self.uri = 'pgsql://postgres@127.0.0.1:5432/queries'
- if self.uri in pool.CONNECTIONS:
- del pool.CONNECTIONS[self.uri]
+ self.pid = hashlib.md5(self.uri).digest()
+ if self.pid in pool.Pools:
+ del pool.Pools[self.pid]
self.client = session.Session(self.uri)
def test_psycopg2_connection_invoked(self):
@@ -74,18 +78,12 @@ class SessionTests(unittest.TestCase):
def test_connection_added_to_cache(self):
"""Ensure the connection is in the connection cache"""
- self.assertIn(self.uri, pool.CONNECTIONS)
-
- def test_connection_handle_in_cache(self):
- """Ensure that the connection handle in cache is valid"""
- self.assertEqual(pool.CONNECTIONS[self.uri]['handle'],
- self.client._conn)
+ self.assertIn(self.pid, pool.Pools)
def test_cleanup_removes_client_from_cache(self):
"""Ensure that Session._cleanup frees the client in the cache"""
- value = pool.CONNECTIONS[self.uri]['clients']
self.client._cleanup()
- self.assertEqual(pool.CONNECTIONS[self.uri]['clients'], value - 1)
+ self.assertNotIn(weakref.ref(self), pool.Pools[self.pid].sessions)
@unittest.skipIf(not PYPY, 'PyPy only test')
def test_conn_reset_if_pypy(self):
@@ -99,18 +97,20 @@ class SessionTests(unittest.TestCase):
del self.client
cleanup.assert_called_once_with()
- @mock.patch('psycopg2.extensions.register_type')
+ @mock.patch('psycopg2.connect')
@mock.patch('psycopg2.extras.register_json')
@mock.patch('psycopg2.extras.register_uuid')
- def test_context_manager_creation(self, _uuid, _json, _type,):
+ @mock.patch('psycopg2.extensions.register_type')
+ def test_context_manager_creation(self, _uuid, _json, _type, _connect):
"""Ensure context manager returns self"""
with session.Session(self.uri) as conn:
self.assertIsInstance(conn, session.Session)
+ @mock.patch('psycopg2.connect')
@mock.patch('psycopg2.extensions.register_type')
@mock.patch('psycopg2.extras.register_json')
@mock.patch('psycopg2.extras.register_uuid')
- def test_context_manager_cleanup(self, _uuid, _json, _type,):
+ def test_context_manager_cleanup(self, _uuid, _json, _type, _connect):
"""Ensure context manager cleans up after self"""
with mock.patch('queries.session.Session._cleanup') as cleanup:
with session.Session(self.uri):
@@ -123,11 +123,9 @@ class SessionTests(unittest.TestCase):
@mock.patch('psycopg2.extras.register_uuid')
def test_close_removes_from_cache(self, _uuid, _json, _type, _connect):
"""Ensure connection removed from cache on close"""
- uri = 'pgsql://foo@bar:9999/baz'
- pgsql = session.Session(uri)
- self.assertIn(uri, pool.CONNECTIONS)
- pgsql.close()
- self.assertNotIn(uri, pool.CONNECTIONS)
+ conn = self.client._conn
+ self.client.close()
+ self.assertNotIn(conn, pool.Pools[self.pid].connections)
@mock.patch('psycopg2.connect')
@mock.patch('psycopg2.extensions.register_type')
| 16 | Update session pool usage and tests | 18 | .py | py | bsd-3-clause | gmr/queries |
1354 | <NME> session_tests.py
<BEF> """
Tests for the session.Session class
"""
import mock
try:
import unittest2 as unittest
except ImportError:
import unittest
import psycopg2
from psycopg2 import extensions
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._reg_type = register_type
self._reg_uuid = register_uuid
self.uri = 'pgsql://postgres@127.0.0.1:5432/queries'
if self.uri in pool.CONNECTIONS:
del pool.CONNECTIONS[self.uri]
self.client = session.Session(self.uri)
def test_psycopg2_connection_invoked(self):
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()
def test_connection_added_to_cache(self):
"""Ensure the connection is in the connection cache"""
self.assertIn(self.uri, pool.CONNECTIONS)
def test_connection_handle_in_cache(self):
"""Ensure that the connection handle in cache is valid"""
self.assertEqual(pool.CONNECTIONS[self.uri]['handle'],
self.client._conn)
def test_cleanup_removes_client_from_cache(self):
"""Ensure that Session._cleanup frees the client in the cache"""
value = pool.CONNECTIONS[self.uri]['clients']
self.client._cleanup()
self.assertEqual(pool.CONNECTIONS[self.uri]['clients'], value - 1)
@unittest.skipIf(not PYPY, 'PyPy only test')
def test_conn_reset_if_pypy(self):
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):
del self.client
cleanup.assert_called_once_with()
@mock.patch('psycopg2.extensions.register_type')
@mock.patch('psycopg2.extras.register_json')
@mock.patch('psycopg2.extras.register_uuid')
def test_context_manager_creation(self, _uuid, _json, _type,):
"""Ensure context manager returns self"""
with session.Session(self.uri) as conn:
self.assertIsInstance(conn, session.Session)
@mock.patch('psycopg2.extensions.register_type')
@mock.patch('psycopg2.extras.register_json')
@mock.patch('psycopg2.extras.register_uuid')
def test_context_manager_cleanup(self, _uuid, _json, _type,):
"""Ensure context manager cleans up after self"""
with mock.patch('queries.session.Session._cleanup') as cleanup:
with session.Session(self.uri):
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)
@mock.patch('psycopg2.extras.register_uuid')
def test_close_removes_from_cache(self, _uuid, _json, _type, _connect):
"""Ensure connection removed from cache on close"""
uri = 'pgsql://foo@bar:9999/baz'
pgsql = session.Session(uri)
self.assertIn(uri, pool.CONNECTIONS)
pgsql.close()
self.assertNotIn(uri, pool.CONNECTIONS)
@mock.patch('psycopg2.connect')
@mock.patch('psycopg2.extensions.register_type')
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> Update session pool usage and tests
<DFF> @@ -2,11 +2,14 @@
Tests for the session.Session class
"""
+import hashlib
import mock
+import uuid
try:
import unittest2 as unittest
except ImportError:
import unittest
+import weakref
import psycopg2
from psycopg2 import extensions
@@ -29,8 +32,9 @@ class SessionTests(unittest.TestCase):
self._reg_type = register_type
self._reg_uuid = register_uuid
self.uri = 'pgsql://postgres@127.0.0.1:5432/queries'
- if self.uri in pool.CONNECTIONS:
- del pool.CONNECTIONS[self.uri]
+ self.pid = hashlib.md5(self.uri).digest()
+ if self.pid in pool.Pools:
+ del pool.Pools[self.pid]
self.client = session.Session(self.uri)
def test_psycopg2_connection_invoked(self):
@@ -74,18 +78,12 @@ class SessionTests(unittest.TestCase):
def test_connection_added_to_cache(self):
"""Ensure the connection is in the connection cache"""
- self.assertIn(self.uri, pool.CONNECTIONS)
-
- def test_connection_handle_in_cache(self):
- """Ensure that the connection handle in cache is valid"""
- self.assertEqual(pool.CONNECTIONS[self.uri]['handle'],
- self.client._conn)
+ self.assertIn(self.pid, pool.Pools)
def test_cleanup_removes_client_from_cache(self):
"""Ensure that Session._cleanup frees the client in the cache"""
- value = pool.CONNECTIONS[self.uri]['clients']
self.client._cleanup()
- self.assertEqual(pool.CONNECTIONS[self.uri]['clients'], value - 1)
+ self.assertNotIn(weakref.ref(self), pool.Pools[self.pid].sessions)
@unittest.skipIf(not PYPY, 'PyPy only test')
def test_conn_reset_if_pypy(self):
@@ -99,18 +97,20 @@ class SessionTests(unittest.TestCase):
del self.client
cleanup.assert_called_once_with()
- @mock.patch('psycopg2.extensions.register_type')
+ @mock.patch('psycopg2.connect')
@mock.patch('psycopg2.extras.register_json')
@mock.patch('psycopg2.extras.register_uuid')
- def test_context_manager_creation(self, _uuid, _json, _type,):
+ @mock.patch('psycopg2.extensions.register_type')
+ def test_context_manager_creation(self, _uuid, _json, _type, _connect):
"""Ensure context manager returns self"""
with session.Session(self.uri) as conn:
self.assertIsInstance(conn, session.Session)
+ @mock.patch('psycopg2.connect')
@mock.patch('psycopg2.extensions.register_type')
@mock.patch('psycopg2.extras.register_json')
@mock.patch('psycopg2.extras.register_uuid')
- def test_context_manager_cleanup(self, _uuid, _json, _type,):
+ def test_context_manager_cleanup(self, _uuid, _json, _type, _connect):
"""Ensure context manager cleans up after self"""
with mock.patch('queries.session.Session._cleanup') as cleanup:
with session.Session(self.uri):
@@ -123,11 +123,9 @@ class SessionTests(unittest.TestCase):
@mock.patch('psycopg2.extras.register_uuid')
def test_close_removes_from_cache(self, _uuid, _json, _type, _connect):
"""Ensure connection removed from cache on close"""
- uri = 'pgsql://foo@bar:9999/baz'
- pgsql = session.Session(uri)
- self.assertIn(uri, pool.CONNECTIONS)
- pgsql.close()
- self.assertNotIn(uri, pool.CONNECTIONS)
+ conn = self.client._conn
+ self.client.close()
+ self.assertNotIn(conn, pool.Pools[self.pid].connections)
@mock.patch('psycopg2.connect')
@mock.patch('psycopg2.extensions.register_type')
| 16 | Update session pool usage and tests | 18 | .py | py | bsd-3-clause | gmr/queries |
1355 | <NME> README.rst
<BEF> Queries: PostgreSQL Simplified
==============================
*Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for
interacting with PostgreSQL.
The popular psycopg2_ package is a full-featured python client. Unfortunately
as a developer, you're often repeating the same steps to get started with your
applications that use it. Queries aims to reduce the complexity of psycopg2
while adding additional features to make writing PostgreSQL client applications
both fast and easy. Check out the `Usage`_ section below to see how easy it can be.
Key features include:
- Simplified API
- Support of Python 2.7+ and 3.4+
- PyPy support via psycopg2cffi_
- Asynchronous support for Tornado_
- Connection information provided by URI
- Query results delivered as a generator based iterators
- Automatically registered data-type support for UUIDs, Unicode and Unicode Arrays
- Ability to directly access psycopg2 ``connection`` and ``cursor`` objects
- Internal connection pooling
|Version| |Status| |Coverage| |License|
Documentation
-------------
Documentation is available at https://queries.readthedocs.org
Installation
------------
Queries is available via pypi_ and can be installed with easy_install or pip:
.. code:: bash
pip install queries
Usage
-----
Queries provides a session based API for interacting with PostgreSQL.
Simply pass in the URI_ of the PostgreSQL server to connect to when creating
a session:
.. code:: python
session = queries.Session("postgresql://postgres@localhost:5432/postgres")
Queries built-in connection pooling will re-use connections when possible,
lowering the overhead of connecting and reconnecting.
When specifying a URI, if you omit the username and database name to connect
with, Queries will use the current OS username for both. You can also omit the
URI when connecting to connect to localhost on port 5432 as the current OS user,
connecting to a database named for the current user. For example, if your
username is ``fred`` and you omit the URI when issuing ``queries.query`` the URI
that is constructed would be ``postgresql://fred@localhost:5432/fred``.
If you'd rather use individual values for the connection, the queries.uri()
method provides a quick and easy way to create a URI to pass into the various
methods.
.. code:: python
>>> queries.uri("server-name", 5432, "dbname", "user", "pass")
'postgresql://user:pass@server-name:5432/dbname'
Environment Variables
^^^^^^^^^^^^^^^^^^^^^
Currently Queries uses the following environment variables for tweaking various
configuration values. The supported ones are:
* ``QUERIES_MAX_POOL_SIZE`` - Modify the maximum size of the connection pool (default: 1)
Using the queries.Session class
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
To execute queries or call stored procedures, you start by creating an instance of the
``queries.Session`` class. It can act as a context manager, meaning you can
use it with the ``with`` keyword and it will take care of cleaning up after itself. For
more information on the ``with`` keyword and context managers, see PEP343_.
In addition to both the ``queries.Session.query`` and ``queries.Session.callproc``
methods that are similar to the simple API methods, the ``queries.Session`` class
provides access to the psycopg2 connection and cursor objects.
**Using queries.Session.query**
The following example shows how a ``queries.Session`` object can be used
as a context manager to query the database table:
.. code:: python
>>> import pprint
>>> import queries
>>>
>>> with queries.Session() as session:
... for row in session.query('SELECT * FROM names'):
... pprint.pprint(row)
...
{'id': 1, 'name': u'Jacob'}
{'id': 2, 'name': u'Mason'}
{'id': 3, 'name': u'Ethan'}
**Using queries.Session.callproc**
This example uses ``queries.Session.callproc`` to execute a stored
procedure and then pretty-prints the single row results as a dictionary:
.. code:: python
>>> import pprint
>>> import queries
{'id': 3, 'name': u'Ethan'}
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
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.listen(8888)
ioloop.IOLoop.instance().start()
.. [*] Simple API methods are not asynchronous and should not be used in an asynchronous Tornado application.
Inspiration
-----------
ioloop.IOLoop.instance().start()
Inspiration
-----------
Queries is inspired by `Kenneth Reitz's <https://github.com/kennethreitz/>`_ awesome
work on `requests <http://docs.python-requests.org/en/latest/>`_.
History
-------
Queries is a fork and enhancement of pgsql_wrapper_, which can be found in the
main GitHub repository of Queries as tags prior to version 1.2.0.
.. _pypi: https://pypi.python.org/pypi/queries
.. _psycopg2: https://pypi.python.org/pypi/psycopg2
.. _documentation: https://queries.readthedocs.org
.. _URI: http://www.postgresql.org/docs/9.3/static/libpq-connect.html#LIBPQ-CONNSTRING
.. _pgsql_wrapper: https://pypi.python.org/pypi/pgsql_wrapper
.. _Tornado: http://tornadoweb.org
.. _PEP343: http://legacy.python.org/dev/peps/pep-0343/
.. _psycopg2cffi: https://pypi.python.org/pypi/psycopg2cffi
.. |Version| image:: https://img.shields.io/pypi/v/queries.svg?
:target: https://pypi.python.org/pypi/queries
.. |Status| image:: https://img.shields.io/travis/gmr/queries.svg?
:target: https://travis-ci.org/gmr/queries
.. |Coverage| image:: https://img.shields.io/codecov/c/github/gmr/queries.svg?
:target: https://codecov.io/github/gmr/queries?branch=master
.. |License| image:: https://img.shields.io/github/license/gmr/queries.svg?
:target: https://github.com/gmr/queries
<MSG> Update the reference
[ci skip]
<DFF> @@ -114,7 +114,7 @@ be used as a context manager.
{'id': 3, 'name': u'Ethan'}
In addition to providing a Pythonic, synchronous client API for PostgreSQL,
-Queries provides a very similar asynchronous API for use with Tornado_ [*]_.
+Queries provides a very similar asynchronous API for use with Tornado [1]_.
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
@@ -145,7 +145,7 @@ Tornado_ web application to send a JSON payload with the query result set.
application.listen(8888)
ioloop.IOLoop.instance().start()
-.. [*] Simple API methods are not asynchronous and should not be used in an asynchronous Tornado application.
+.. [1] Simple API methods are not asynchronous and should not be used in an asynchronous Tornado application.
Inspiration
-----------
| 2 | Update the reference | 2 | .rst | rst | bsd-3-clause | gmr/queries |
1356 | <NME> README.rst
<BEF> Queries: PostgreSQL Simplified
==============================
*Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for
interacting with PostgreSQL.
The popular psycopg2_ package is a full-featured python client. Unfortunately
as a developer, you're often repeating the same steps to get started with your
applications that use it. Queries aims to reduce the complexity of psycopg2
while adding additional features to make writing PostgreSQL client applications
both fast and easy. Check out the `Usage`_ section below to see how easy it can be.
Key features include:
- Simplified API
- Support of Python 2.7+ and 3.4+
- PyPy support via psycopg2cffi_
- Asynchronous support for Tornado_
- Connection information provided by URI
- Query results delivered as a generator based iterators
- Automatically registered data-type support for UUIDs, Unicode and Unicode Arrays
- Ability to directly access psycopg2 ``connection`` and ``cursor`` objects
- Internal connection pooling
|Version| |Status| |Coverage| |License|
Documentation
-------------
Documentation is available at https://queries.readthedocs.org
Installation
------------
Queries is available via pypi_ and can be installed with easy_install or pip:
.. code:: bash
pip install queries
Usage
-----
Queries provides a session based API for interacting with PostgreSQL.
Simply pass in the URI_ of the PostgreSQL server to connect to when creating
a session:
.. code:: python
session = queries.Session("postgresql://postgres@localhost:5432/postgres")
Queries built-in connection pooling will re-use connections when possible,
lowering the overhead of connecting and reconnecting.
When specifying a URI, if you omit the username and database name to connect
with, Queries will use the current OS username for both. You can also omit the
URI when connecting to connect to localhost on port 5432 as the current OS user,
connecting to a database named for the current user. For example, if your
username is ``fred`` and you omit the URI when issuing ``queries.query`` the URI
that is constructed would be ``postgresql://fred@localhost:5432/fred``.
If you'd rather use individual values for the connection, the queries.uri()
method provides a quick and easy way to create a URI to pass into the various
methods.
.. code:: python
>>> queries.uri("server-name", 5432, "dbname", "user", "pass")
'postgresql://user:pass@server-name:5432/dbname'
Environment Variables
^^^^^^^^^^^^^^^^^^^^^
Currently Queries uses the following environment variables for tweaking various
configuration values. The supported ones are:
* ``QUERIES_MAX_POOL_SIZE`` - Modify the maximum size of the connection pool (default: 1)
Using the queries.Session class
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
To execute queries or call stored procedures, you start by creating an instance of the
``queries.Session`` class. It can act as a context manager, meaning you can
use it with the ``with`` keyword and it will take care of cleaning up after itself. For
more information on the ``with`` keyword and context managers, see PEP343_.
In addition to both the ``queries.Session.query`` and ``queries.Session.callproc``
methods that are similar to the simple API methods, the ``queries.Session`` class
provides access to the psycopg2 connection and cursor objects.
**Using queries.Session.query**
The following example shows how a ``queries.Session`` object can be used
as a context manager to query the database table:
.. code:: python
>>> import pprint
>>> import queries
>>>
>>> with queries.Session() as session:
... for row in session.query('SELECT * FROM names'):
... pprint.pprint(row)
...
{'id': 1, 'name': u'Jacob'}
{'id': 2, 'name': u'Mason'}
{'id': 3, 'name': u'Ethan'}
**Using queries.Session.callproc**
This example uses ``queries.Session.callproc`` to execute a stored
procedure and then pretty-prints the single row results as a dictionary:
.. code:: python
>>> import pprint
>>> import queries
{'id': 3, 'name': u'Ethan'}
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
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.listen(8888)
ioloop.IOLoop.instance().start()
.. [*] Simple API methods are not asynchronous and should not be used in an asynchronous Tornado application.
Inspiration
-----------
ioloop.IOLoop.instance().start()
Inspiration
-----------
Queries is inspired by `Kenneth Reitz's <https://github.com/kennethreitz/>`_ awesome
work on `requests <http://docs.python-requests.org/en/latest/>`_.
History
-------
Queries is a fork and enhancement of pgsql_wrapper_, which can be found in the
main GitHub repository of Queries as tags prior to version 1.2.0.
.. _pypi: https://pypi.python.org/pypi/queries
.. _psycopg2: https://pypi.python.org/pypi/psycopg2
.. _documentation: https://queries.readthedocs.org
.. _URI: http://www.postgresql.org/docs/9.3/static/libpq-connect.html#LIBPQ-CONNSTRING
.. _pgsql_wrapper: https://pypi.python.org/pypi/pgsql_wrapper
.. _Tornado: http://tornadoweb.org
.. _PEP343: http://legacy.python.org/dev/peps/pep-0343/
.. _psycopg2cffi: https://pypi.python.org/pypi/psycopg2cffi
.. |Version| image:: https://img.shields.io/pypi/v/queries.svg?
:target: https://pypi.python.org/pypi/queries
.. |Status| image:: https://img.shields.io/travis/gmr/queries.svg?
:target: https://travis-ci.org/gmr/queries
.. |Coverage| image:: https://img.shields.io/codecov/c/github/gmr/queries.svg?
:target: https://codecov.io/github/gmr/queries?branch=master
.. |License| image:: https://img.shields.io/github/license/gmr/queries.svg?
:target: https://github.com/gmr/queries
<MSG> Update the reference
[ci skip]
<DFF> @@ -114,7 +114,7 @@ be used as a context manager.
{'id': 3, 'name': u'Ethan'}
In addition to providing a Pythonic, synchronous client API for PostgreSQL,
-Queries provides a very similar asynchronous API for use with Tornado_ [*]_.
+Queries provides a very similar asynchronous API for use with Tornado [1]_.
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
@@ -145,7 +145,7 @@ Tornado_ web application to send a JSON payload with the query result set.
application.listen(8888)
ioloop.IOLoop.instance().start()
-.. [*] Simple API methods are not asynchronous and should not be used in an asynchronous Tornado application.
+.. [1] Simple API methods are not asynchronous and should not be used in an asynchronous Tornado application.
Inspiration
-----------
| 2 | Update the reference | 2 | .rst | rst | bsd-3-clause | gmr/queries |
1357 | <NME> pool_tests.py
<BEF> """
Tests for functionality in the pool module
"""
import mock
try:
import unittest2 as unittest
except ImportError:
import unittest
import weakref
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_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.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.handle.close.assertCalledOnce()
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))
class PoolTests(unittest.TestCase):
def setup(self):
self.handle = mock.Mock(spec=pool.Connection)
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> Add coverage of queries.pool.Pool
<DFF> @@ -3,84 +3,271 @@ Tests for functionality in the pool module
"""
import mock
+import time
try:
import unittest2 as unittest
except ImportError:
import unittest
+import uuid
import weakref
from queries import pool
-class ConnectionTests(unittest.TestCase):
+class PoolTests(unittest.TestCase):
+
+ def test_id_is_set(self):
+ pool_id = str(uuid.uuid4())
+ obj = pool.Pool(pool_id)
+ self.assertEqual(obj._id, pool_id)
+
+ def test_id_property(self):
+ pool_id = str(uuid.uuid4())
+ obj = pool.Pool(pool_id)
+ self.assertEqual(obj.id, pool_id)
+
+ def test_idle_ttl_is_default(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ self.assertEqual(obj.idle_ttl, pool.DEFAULT_IDLE_TTL)
+
+ def test_max_size_is_default(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ self.assertEqual(obj.max_size, pool.DEFAULT_MAX_SIZE)
+
+ def test_idle_ttl_constructor_assignment(self):
+ obj = pool.Pool(str(uuid.uuid4()), 10)
+ self.assertEqual(obj.idle_ttl, 10)
+
+ def test_max_size_constructor_assignment(self):
+ obj = pool.Pool(str(uuid.uuid4()), max_size=10)
+ self.assertEqual(obj.max_size, 10)
+
+ def test_idle_ttl_assignment(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ obj.set_idle_ttl(10)
+ self.assertEqual(obj.idle_ttl, 10)
+
+ def test_max_size_assignment(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ obj.set_max_size(10)
+ self.assertEqual(obj.max_size, 10)
+
+ def test_pool_doesnt_contain_connection(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ self.assertNotIn('foo', obj)
+
+ def test_default_connection_count(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ self.assertEqual(len(obj), 0)
+
+ def test_add_new_connection(self):
+ psycopg2_conn = mock.Mock()
+ obj = pool.Pool(str(uuid.uuid4()))
+ obj.add(psycopg2_conn)
+ self.assertIn(psycopg2_conn, obj)
- def 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_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_handle_should_match(self):
- self.assertEqual(self.handle, self.connection.handle)
+ 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_busy_isexecuting_is_false(self):
- self.assertFalse(self.connection.busy)
+ 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_busy_isexecuting_is_true(self):
- self.handle.isexecuting.return_value = True
- self.assertTrue(self.connection.busy)
+ 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_busy_is_used(self):
- self.handle.isexecuting.return_value = False
- self.connection.used_by = mock.Mock()
- self.assertTrue(self.connection.busy)
+ 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_closed_is_true(self):
- self.handle.closed = True
- self.assertTrue(self.connection.closed)
+ def test_close_close_removes_all(self):
- def test_closed_is_false(self):
- self.handle.closed = False
- self.assertFalse(self.connection.closed)
+ obj = pool.Pool(str(uuid.uuid4()))
+ obj.remove = mock.Mock()
+ psycopg2_conns = [mock.Mock(), mock.Mock()]
+ [obj.add(conn) for conn in psycopg2_conns]
+ obj.close()
+ obj.remove.assert_hass_calls(psycopg2_conns)
- def test_close_raises_when_busy(self):
- self.handle.isexecuting.return_value = True
- self.assertRaises(pool.ConnectionBusyError, self.connection.close)
+ def test_free_invokes_connection_free(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ psycopg2_conn = mock.Mock()
+ obj.add(psycopg2_conn)
+ conn = obj._connection(psycopg2_conn)
+ conn.free = mock.Mock()
+ obj.free(psycopg2_conn)
+ conn.free.assert_called_once_with()
- def test_close_invokes_handle_close(self):
- self.handle.isexecuting.return_value = False
- self.connection.used_by = None
- self.connection.close()
- self.handle.close.assertCalledOnce()
+ 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(psycopg2_conn)
+ conn.free = mock.Mock()
+ obj.free(psycopg2_conn)
+ conn.free.assert_called_once_with()
- def test_free_raises_when_busy(self):
- self.handle.isexecuting.return_value = True
- self.assertRaises(pool.ConnectionBusyError, self.connection.free)
+ def test_free_resets_idle_start(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ 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(psycopg2_conn)
+ conn.free = mock.Mock()
+ obj.free(psycopg2_conns[1])
+ self.assertAlmostEqual(int(obj.idle_start), int(time.time()))
- 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_free_raises_on_not_found(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ self.assertRaises(pool.ConnectionNotFoundError, obj.free, mock.Mock())
- def test_id_value_matches(self):
- self.assertEqual(id(self.handle), self.connection.id)
+ def test_get_returns_first_psycopg2_conn(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ 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_lock_raises_when_busy(self):
- self.connection.used_by = mock.Mock()
- self.assertRaises(pool.ConnectionBusyError,
- self.connection.lock, mock.Mock())
+ def test_get_locks_first_psycopg2_conn(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ 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_lock_session_used_by(self):
+ def test_get_resets_idle_start_to_none(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ 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.get(session)
+ self.assertIsNone(obj.idle_start)
+
+ def test_get_raises_when_no_idle_connections(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ psycopg2_conns = [mock.Mock(), mock.Mock()]
+ [obj.add(conn) for conn in psycopg2_conns]
session = mock.Mock()
- self.connection.lock(session)
- self.assertIn(self.connection.used_by,
- weakref.getweakrefs(session))
+ self.assertRaises(pool.NoIdleConnectionsError, obj.get, session)
+ def test_idle_connections(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ 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)
-class PoolTests(unittest.TestCase):
+ 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()
+ obj.add(psycopg2_conn)
+ self.assertRaises(pool.ConnectionBusyError, obj.remove,
+ psycopg2_conn)
- def setup(self):
- self.handle = mock.Mock(spec=pool.Connection)
+ def test__connection_returns_handle(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ psycopg2_conn = mock.Mock()
+ obj.add(psycopg2_conn)
+ self.assertEqual(obj._connection(psycopg2_conn).handle, psycopg2_conn)
| 241 | Add coverage of queries.pool.Pool | 54 | .py | py | bsd-3-clause | gmr/queries |
1358 | <NME> pool_tests.py
<BEF> """
Tests for functionality in the pool module
"""
import mock
try:
import unittest2 as unittest
except ImportError:
import unittest
import weakref
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_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.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.handle.close.assertCalledOnce()
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))
class PoolTests(unittest.TestCase):
def setup(self):
self.handle = mock.Mock(spec=pool.Connection)
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> Add coverage of queries.pool.Pool
<DFF> @@ -3,84 +3,271 @@ Tests for functionality in the pool module
"""
import mock
+import time
try:
import unittest2 as unittest
except ImportError:
import unittest
+import uuid
import weakref
from queries import pool
-class ConnectionTests(unittest.TestCase):
+class PoolTests(unittest.TestCase):
+
+ def test_id_is_set(self):
+ pool_id = str(uuid.uuid4())
+ obj = pool.Pool(pool_id)
+ self.assertEqual(obj._id, pool_id)
+
+ def test_id_property(self):
+ pool_id = str(uuid.uuid4())
+ obj = pool.Pool(pool_id)
+ self.assertEqual(obj.id, pool_id)
+
+ def test_idle_ttl_is_default(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ self.assertEqual(obj.idle_ttl, pool.DEFAULT_IDLE_TTL)
+
+ def test_max_size_is_default(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ self.assertEqual(obj.max_size, pool.DEFAULT_MAX_SIZE)
+
+ def test_idle_ttl_constructor_assignment(self):
+ obj = pool.Pool(str(uuid.uuid4()), 10)
+ self.assertEqual(obj.idle_ttl, 10)
+
+ def test_max_size_constructor_assignment(self):
+ obj = pool.Pool(str(uuid.uuid4()), max_size=10)
+ self.assertEqual(obj.max_size, 10)
+
+ def test_idle_ttl_assignment(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ obj.set_idle_ttl(10)
+ self.assertEqual(obj.idle_ttl, 10)
+
+ def test_max_size_assignment(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ obj.set_max_size(10)
+ self.assertEqual(obj.max_size, 10)
+
+ def test_pool_doesnt_contain_connection(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ self.assertNotIn('foo', obj)
+
+ def test_default_connection_count(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ self.assertEqual(len(obj), 0)
+
+ def test_add_new_connection(self):
+ psycopg2_conn = mock.Mock()
+ obj = pool.Pool(str(uuid.uuid4()))
+ obj.add(psycopg2_conn)
+ self.assertIn(psycopg2_conn, obj)
- def 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_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_handle_should_match(self):
- self.assertEqual(self.handle, self.connection.handle)
+ 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_busy_isexecuting_is_false(self):
- self.assertFalse(self.connection.busy)
+ 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_busy_isexecuting_is_true(self):
- self.handle.isexecuting.return_value = True
- self.assertTrue(self.connection.busy)
+ 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_busy_is_used(self):
- self.handle.isexecuting.return_value = False
- self.connection.used_by = mock.Mock()
- self.assertTrue(self.connection.busy)
+ 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_closed_is_true(self):
- self.handle.closed = True
- self.assertTrue(self.connection.closed)
+ def test_close_close_removes_all(self):
- def test_closed_is_false(self):
- self.handle.closed = False
- self.assertFalse(self.connection.closed)
+ obj = pool.Pool(str(uuid.uuid4()))
+ obj.remove = mock.Mock()
+ psycopg2_conns = [mock.Mock(), mock.Mock()]
+ [obj.add(conn) for conn in psycopg2_conns]
+ obj.close()
+ obj.remove.assert_hass_calls(psycopg2_conns)
- def test_close_raises_when_busy(self):
- self.handle.isexecuting.return_value = True
- self.assertRaises(pool.ConnectionBusyError, self.connection.close)
+ def test_free_invokes_connection_free(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ psycopg2_conn = mock.Mock()
+ obj.add(psycopg2_conn)
+ conn = obj._connection(psycopg2_conn)
+ conn.free = mock.Mock()
+ obj.free(psycopg2_conn)
+ conn.free.assert_called_once_with()
- def test_close_invokes_handle_close(self):
- self.handle.isexecuting.return_value = False
- self.connection.used_by = None
- self.connection.close()
- self.handle.close.assertCalledOnce()
+ 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(psycopg2_conn)
+ conn.free = mock.Mock()
+ obj.free(psycopg2_conn)
+ conn.free.assert_called_once_with()
- def test_free_raises_when_busy(self):
- self.handle.isexecuting.return_value = True
- self.assertRaises(pool.ConnectionBusyError, self.connection.free)
+ def test_free_resets_idle_start(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ 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(psycopg2_conn)
+ conn.free = mock.Mock()
+ obj.free(psycopg2_conns[1])
+ self.assertAlmostEqual(int(obj.idle_start), int(time.time()))
- 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_free_raises_on_not_found(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ self.assertRaises(pool.ConnectionNotFoundError, obj.free, mock.Mock())
- def test_id_value_matches(self):
- self.assertEqual(id(self.handle), self.connection.id)
+ def test_get_returns_first_psycopg2_conn(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ 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_lock_raises_when_busy(self):
- self.connection.used_by = mock.Mock()
- self.assertRaises(pool.ConnectionBusyError,
- self.connection.lock, mock.Mock())
+ def test_get_locks_first_psycopg2_conn(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ 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_lock_session_used_by(self):
+ def test_get_resets_idle_start_to_none(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ 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.get(session)
+ self.assertIsNone(obj.idle_start)
+
+ def test_get_raises_when_no_idle_connections(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ psycopg2_conns = [mock.Mock(), mock.Mock()]
+ [obj.add(conn) for conn in psycopg2_conns]
session = mock.Mock()
- self.connection.lock(session)
- self.assertIn(self.connection.used_by,
- weakref.getweakrefs(session))
+ self.assertRaises(pool.NoIdleConnectionsError, obj.get, session)
+ def test_idle_connections(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ 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)
-class PoolTests(unittest.TestCase):
+ 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()
+ obj.add(psycopg2_conn)
+ self.assertRaises(pool.ConnectionBusyError, obj.remove,
+ psycopg2_conn)
- def setup(self):
- self.handle = mock.Mock(spec=pool.Connection)
+ def test__connection_returns_handle(self):
+ obj = pool.Pool(str(uuid.uuid4()))
+ psycopg2_conn = mock.Mock()
+ obj.add(psycopg2_conn)
+ self.assertEqual(obj._connection(psycopg2_conn).handle, psycopg2_conn)
| 241 | Add coverage of queries.pool.Pool | 54 | .py | py | bsd-3-clause | gmr/queries |
1359 | <NME> utils.py
<BEF> ADDFILE
<MSG> Utilities for URI parsing
<DFF> @@ -0,0 +1,58 @@
+"""
+Utility functions for access to OS level info and URI parsing
+
+"""
+import collections
+import os
+import pwd
+try:
+ from urllib import parse as _urlparse
+except ImportError:
+ import urlparse as _urlparse
+
+Parsed = collections.namedtuple('Parsed',
+ 'scheme,netloc,path,params,query,fragment,'
+ 'username,password,hostname,port')
+
+DEFAULT_HOSTNAME = 'localhost'
+DEFAULT_PORT = 5432
+DEFAULT_DBNAME = 'postgres'
+DEFAULT_USERNAME = 'postgres'
+
+def get_current_user():
+ """Return the current username for the logged in user
+
+ :rtype: str
+
+ """
+ return pwd.getpwuid(os.getuid())[0]
+
+
+def parse_qs(query_string):
+ return _urlparse.parse_qs(query_string)
+
+
+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()
+ return {'host': parsed.hostname or DEFAULT_HOSTNAME,
+ 'port': parsed.port or DEFAULT_PORT,
+ 'dbname': parsed.path[1:] or default_user,
+ 'user': parsed.username or default_user,
+ 'password': parsed.password}
+
+
+def urlparse(url):
+ value = 'http%s' % url[5:] if url[:5] == 'pgsql' else url
+ parsed = _urlparse.urlparse(value)
+ return Parsed(parsed.scheme.replace('http', 'pgsql'), parsed.netloc,
+ parsed.path, parsed.params, parsed.query, parsed.fragment,
+ parsed.username, parsed.password, parsed.hostname,
+ parsed.port)
\ No newline at end of file
| 58 | Utilities for URI parsing | 0 | .py | py | bsd-3-clause | gmr/queries |
1360 | <NME> utils.py
<BEF> ADDFILE
<MSG> Utilities for URI parsing
<DFF> @@ -0,0 +1,58 @@
+"""
+Utility functions for access to OS level info and URI parsing
+
+"""
+import collections
+import os
+import pwd
+try:
+ from urllib import parse as _urlparse
+except ImportError:
+ import urlparse as _urlparse
+
+Parsed = collections.namedtuple('Parsed',
+ 'scheme,netloc,path,params,query,fragment,'
+ 'username,password,hostname,port')
+
+DEFAULT_HOSTNAME = 'localhost'
+DEFAULT_PORT = 5432
+DEFAULT_DBNAME = 'postgres'
+DEFAULT_USERNAME = 'postgres'
+
+def get_current_user():
+ """Return the current username for the logged in user
+
+ :rtype: str
+
+ """
+ return pwd.getpwuid(os.getuid())[0]
+
+
+def parse_qs(query_string):
+ return _urlparse.parse_qs(query_string)
+
+
+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()
+ return {'host': parsed.hostname or DEFAULT_HOSTNAME,
+ 'port': parsed.port or DEFAULT_PORT,
+ 'dbname': parsed.path[1:] or default_user,
+ 'user': parsed.username or default_user,
+ 'password': parsed.password}
+
+
+def urlparse(url):
+ value = 'http%s' % url[5:] if url[:5] == 'pgsql' else url
+ parsed = _urlparse.urlparse(value)
+ return Parsed(parsed.scheme.replace('http', 'pgsql'), parsed.netloc,
+ parsed.path, parsed.params, parsed.query, parsed.fragment,
+ parsed.username, parsed.password, parsed.hostname,
+ parsed.port)
\ No newline at end of file
| 58 | Utilities for URI parsing | 0 | .py | py | bsd-3-clause | gmr/queries |
1361 | <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
from psycopg2 import extras
from queries import pool
from queries import results
from queries import utils
LOGGER = logging.getLogger(__name__)
from queries import DEFAULT_URI
from queries import PYPY
DEFAULT_ENCODING = 'UTF8'
class Session(object):
"""The Session class allows for a unified (and simplified) view of
interfacing with a PostgreSQL database server. The Session object can
act as a context manager, providing automated cleanup and simple, Pythonic
way of interacting with the object.
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
"""
_conn = None
_cursor = None
_tpc_id = None
_uri = None
# Connection status constants
INTRANS = extensions.STATUS_IN_TRANSACTION
PREPARED = extensions.STATUS_PREPARED
READY = extensions.STATUS_READY
SETUP = extensions.STATUS_SETUP
# Transaction status constants
TX_ACTIVE = extensions.TRANSACTION_STATUS_ACTIVE
TX_IDLE = extensions.TRANSACTION_STATUS_IDLE
TX_INERROR = extensions.TRANSACTION_STATUS_INERROR
TX_INTRANS = extensions.TRANSACTION_STATUS_INTRANS
TX_UNKNOWN = extensions.TRANSACTION_STATUS_UNKNOWN
def __init__(self, uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
pool_max_size=pool.DEFAULT_MAX_SIZE,
autocommit=True):
"""Connect to a PostgreSQL server using the module wide connection and
set the isolation level.
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
"""
self._pool_manager = pool.PoolManager.instance()
self._uri = uri
# Ensure the pool exists in the pool manager
if self.pid not in self._pool_manager:
self._pool_manager.create(self.pid, pool_idle_ttl, pool_max_size)
self._conn = self._connect()
self._cursor_factory = cursor_factory
self._cursor = self._get_cursor(self._conn)
self._autocommit(autocommit)
@property
def backend_pid(self):
"""Return the backend process ID of the PostgreSQL server that this
session is connected to.
:rtype: int
"""
return self._conn.get_backend_pid()
def callproc(self, name, args=None):
"""Call a stored procedure on the server, returning the results in a
:py:class:`queries.Results` instance.
:param str name: The procedure name
:param list args: The list of arguments to pass in
:rtype: queries.Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
try:
self._cursor.callproc(name, args)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def close(self):
"""Explicitly close the connection and remove it from the connection
pool if pooling is enabled. If the connection is already closed
:raises: psycopg2.InterfaceError
"""
if not self._conn:
raise psycopg2.InterfaceError('Connection not open')
LOGGER.info('Closing connection %r in %s', self._conn, self.pid)
self._pool_manager.free(self.pid, self._conn)
self._pool_manager.remove_connection(self.pid, self._conn)
# Un-assign the connection and cursor
self._conn, self._cursor = None, None
@property
def connection(self):
"""Return the current open connection to PostgreSQL.
:rtype: psycopg2.extensions.connection
"""
return self._conn
@property
def cursor(self):
"""Return the current, active cursor for the open connection.
:rtype: psycopg2.extensions.cursor
"""
return self._cursor
@property
def encoding(self):
"""Return the current client encoding value.
:rtype: str
"""
return self._conn.encoding
@property
def notices(self):
"""Return a list of up to the last 50 server notices sent to the client.
:rtype: list
"""
return self._conn.notices
@property
def pid(self):
"""Return the pool ID used for connection pooling.
:rtype: str
"""
return hashlib.md5(':'.join([self.__class__.__name__,
self._uri]).encode('utf-8')).hexdigest()
def query(self, sql, parameters=None):
"""A generator to issue a query on the server, mogrifying the
parameters against the sql statement. Results are returned as a
:py:class:`queries.Results` object which can act as an iterator and
has multiple ways to access the result data.
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: queries.Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
try:
self._cursor.execute(sql, parameters)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def set_encoding(self, value=DEFAULT_ENCODING):
"""Set the client encoding for the session if the value specified
is different than the current client encoding.
:param str value: The encoding value to use
"""
if self._conn.encoding != value:
self._conn.set_client_encoding(value)
def __del__(self):
"""When deleting the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def __enter__(self):
"""For use as a context manager, return a handle to this object
instance.
:rtype: Session
"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""When leaving the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def _autocommit(self, autocommit):
"""Set the isolation level automatically to commit or not after every query
:param autocommit: Boolean (Default - True)
"""
self._conn.autocommit = autocommit
def _cleanup(self):
"""Remove the connection from the stack, closing out the cursor"""
if self._cursor:
LOGGER.debug('Closing the cursor on %s', self.pid)
self._cursor.close()
self._cursor = None
if self._conn:
LOGGER.debug('Freeing %s in the pool', self.pid)
try:
pool.PoolManager.instance().free(self.pid, self._conn)
except pool.ConnectionNotFoundError:
pass
self._conn = None
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
if possible, or by creating the new connection.
:rtype: psycopg2.extensions.connection
:raises: pool.NoIdleConnectionsError
"""
# Attempt to get a cached connection from the connection pool
try:
connection = self._pool_manager.get(self.pid, self)
LOGGER.debug("Re-using connection for %s", self.pid)
except pool.NoIdleConnectionsError:
if self._pool_manager.is_full(self.pid):
raise
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
LOGGER.debug("Creating a new connection for %s", self.pid)
connection = self._psycopg2_connect(kwargs)
self._pool_manager.add(self.pid, connection)
self._pool_manager.lock(self.pid, connection, self)
# Added in because psycopg2ct connects and leaves the connection in
# a weird state: consts.STATUS_DATESTYLE, returning from
# Connection._setup without setting the state as const.STATUS_OK
if utils.PYPY:
connection.reset()
# Register the custom data types
self._register_unicode(connection)
self._register_uuid(connection)
return connection
def _get_cursor(self, connection, name=None):
"""Return a cursor for the given cursor_factory. Specify a name to
use server-side cursors.
:param connection: The connection to create a cursor on
:type connection: psycopg2.extensions.connection
:param str name: A cursor name for a server side cursor
:rtype: psycopg2.extensions.cursor
"""
cursor = connection.cursor(name=name,
cursor_factory=self._cursor_factory)
if name is not None:
cursor.scrollable = True
cursor.withhold = True
return cursor
def _incr_exceptions(self):
"""Increment the number of exceptions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).exceptions += 1
def _incr_executions(self):
"""Increment the number of executions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).executions += 1
def _psycopg2_connect(self, kwargs):
"""Return a psycopg2 connection for the specified kwargs. Extend for
use in async session adapters.
:param dict kwargs: Keyword connection args
:rtype: psycopg2.extensions.connection
"""
return psycopg2.connect(**kwargs)
@staticmethod
def _register_unicode(connection):
"""Register the cursor to be able to receive Unicode string.
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE,
connection)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY,
connection)
@staticmethod
def _register_uuid(connection):
"""Register the UUID extension from the psycopg2.extra module
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extras.register_uuid(conn_or_curs=connection)
@property
def _status(self):
"""Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queries.Session.READY: Connected, no active transaction
:rtype: int
"""
if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
return self.READY
return self._conn.status
<MSG> Cleanup imports
<DFF> @@ -30,15 +30,10 @@ import psycopg2
from psycopg2 import extensions
from psycopg2 import extras
-from queries import pool
-from queries import results
-from queries import utils
+from queries import pool, results, utils, DEFAULT_URI, PYPY
LOGGER = logging.getLogger(__name__)
-from queries import DEFAULT_URI
-from queries import PYPY
-
DEFAULT_ENCODING = 'UTF8'
| 1 | Cleanup imports | 6 | .py | py | bsd-3-clause | gmr/queries |
1362 | <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
from psycopg2 import extras
from queries import pool
from queries import results
from queries import utils
LOGGER = logging.getLogger(__name__)
from queries import DEFAULT_URI
from queries import PYPY
DEFAULT_ENCODING = 'UTF8'
class Session(object):
"""The Session class allows for a unified (and simplified) view of
interfacing with a PostgreSQL database server. The Session object can
act as a context manager, providing automated cleanup and simple, Pythonic
way of interacting with the object.
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
"""
_conn = None
_cursor = None
_tpc_id = None
_uri = None
# Connection status constants
INTRANS = extensions.STATUS_IN_TRANSACTION
PREPARED = extensions.STATUS_PREPARED
READY = extensions.STATUS_READY
SETUP = extensions.STATUS_SETUP
# Transaction status constants
TX_ACTIVE = extensions.TRANSACTION_STATUS_ACTIVE
TX_IDLE = extensions.TRANSACTION_STATUS_IDLE
TX_INERROR = extensions.TRANSACTION_STATUS_INERROR
TX_INTRANS = extensions.TRANSACTION_STATUS_INTRANS
TX_UNKNOWN = extensions.TRANSACTION_STATUS_UNKNOWN
def __init__(self, uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
pool_max_size=pool.DEFAULT_MAX_SIZE,
autocommit=True):
"""Connect to a PostgreSQL server using the module wide connection and
set the isolation level.
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
"""
self._pool_manager = pool.PoolManager.instance()
self._uri = uri
# Ensure the pool exists in the pool manager
if self.pid not in self._pool_manager:
self._pool_manager.create(self.pid, pool_idle_ttl, pool_max_size)
self._conn = self._connect()
self._cursor_factory = cursor_factory
self._cursor = self._get_cursor(self._conn)
self._autocommit(autocommit)
@property
def backend_pid(self):
"""Return the backend process ID of the PostgreSQL server that this
session is connected to.
:rtype: int
"""
return self._conn.get_backend_pid()
def callproc(self, name, args=None):
"""Call a stored procedure on the server, returning the results in a
:py:class:`queries.Results` instance.
:param str name: The procedure name
:param list args: The list of arguments to pass in
:rtype: queries.Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
try:
self._cursor.callproc(name, args)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def close(self):
"""Explicitly close the connection and remove it from the connection
pool if pooling is enabled. If the connection is already closed
:raises: psycopg2.InterfaceError
"""
if not self._conn:
raise psycopg2.InterfaceError('Connection not open')
LOGGER.info('Closing connection %r in %s', self._conn, self.pid)
self._pool_manager.free(self.pid, self._conn)
self._pool_manager.remove_connection(self.pid, self._conn)
# Un-assign the connection and cursor
self._conn, self._cursor = None, None
@property
def connection(self):
"""Return the current open connection to PostgreSQL.
:rtype: psycopg2.extensions.connection
"""
return self._conn
@property
def cursor(self):
"""Return the current, active cursor for the open connection.
:rtype: psycopg2.extensions.cursor
"""
return self._cursor
@property
def encoding(self):
"""Return the current client encoding value.
:rtype: str
"""
return self._conn.encoding
@property
def notices(self):
"""Return a list of up to the last 50 server notices sent to the client.
:rtype: list
"""
return self._conn.notices
@property
def pid(self):
"""Return the pool ID used for connection pooling.
:rtype: str
"""
return hashlib.md5(':'.join([self.__class__.__name__,
self._uri]).encode('utf-8')).hexdigest()
def query(self, sql, parameters=None):
"""A generator to issue a query on the server, mogrifying the
parameters against the sql statement. Results are returned as a
:py:class:`queries.Results` object which can act as an iterator and
has multiple ways to access the result data.
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: queries.Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
try:
self._cursor.execute(sql, parameters)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def set_encoding(self, value=DEFAULT_ENCODING):
"""Set the client encoding for the session if the value specified
is different than the current client encoding.
:param str value: The encoding value to use
"""
if self._conn.encoding != value:
self._conn.set_client_encoding(value)
def __del__(self):
"""When deleting the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def __enter__(self):
"""For use as a context manager, return a handle to this object
instance.
:rtype: Session
"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""When leaving the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def _autocommit(self, autocommit):
"""Set the isolation level automatically to commit or not after every query
:param autocommit: Boolean (Default - True)
"""
self._conn.autocommit = autocommit
def _cleanup(self):
"""Remove the connection from the stack, closing out the cursor"""
if self._cursor:
LOGGER.debug('Closing the cursor on %s', self.pid)
self._cursor.close()
self._cursor = None
if self._conn:
LOGGER.debug('Freeing %s in the pool', self.pid)
try:
pool.PoolManager.instance().free(self.pid, self._conn)
except pool.ConnectionNotFoundError:
pass
self._conn = None
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
if possible, or by creating the new connection.
:rtype: psycopg2.extensions.connection
:raises: pool.NoIdleConnectionsError
"""
# Attempt to get a cached connection from the connection pool
try:
connection = self._pool_manager.get(self.pid, self)
LOGGER.debug("Re-using connection for %s", self.pid)
except pool.NoIdleConnectionsError:
if self._pool_manager.is_full(self.pid):
raise
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
LOGGER.debug("Creating a new connection for %s", self.pid)
connection = self._psycopg2_connect(kwargs)
self._pool_manager.add(self.pid, connection)
self._pool_manager.lock(self.pid, connection, self)
# Added in because psycopg2ct connects and leaves the connection in
# a weird state: consts.STATUS_DATESTYLE, returning from
# Connection._setup without setting the state as const.STATUS_OK
if utils.PYPY:
connection.reset()
# Register the custom data types
self._register_unicode(connection)
self._register_uuid(connection)
return connection
def _get_cursor(self, connection, name=None):
"""Return a cursor for the given cursor_factory. Specify a name to
use server-side cursors.
:param connection: The connection to create a cursor on
:type connection: psycopg2.extensions.connection
:param str name: A cursor name for a server side cursor
:rtype: psycopg2.extensions.cursor
"""
cursor = connection.cursor(name=name,
cursor_factory=self._cursor_factory)
if name is not None:
cursor.scrollable = True
cursor.withhold = True
return cursor
def _incr_exceptions(self):
"""Increment the number of exceptions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).exceptions += 1
def _incr_executions(self):
"""Increment the number of executions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).executions += 1
def _psycopg2_connect(self, kwargs):
"""Return a psycopg2 connection for the specified kwargs. Extend for
use in async session adapters.
:param dict kwargs: Keyword connection args
:rtype: psycopg2.extensions.connection
"""
return psycopg2.connect(**kwargs)
@staticmethod
def _register_unicode(connection):
"""Register the cursor to be able to receive Unicode string.
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE,
connection)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY,
connection)
@staticmethod
def _register_uuid(connection):
"""Register the UUID extension from the psycopg2.extra module
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extras.register_uuid(conn_or_curs=connection)
@property
def _status(self):
"""Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queries.Session.READY: Connected, no active transaction
:rtype: int
"""
if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
return self.READY
return self._conn.status
<MSG> Cleanup imports
<DFF> @@ -30,15 +30,10 @@ import psycopg2
from psycopg2 import extensions
from psycopg2 import extras
-from queries import pool
-from queries import results
-from queries import utils
+from queries import pool, results, utils, DEFAULT_URI, PYPY
LOGGER = logging.getLogger(__name__)
-from queries import DEFAULT_URI
-from queries import PYPY
-
DEFAULT_ENCODING = 'UTF8'
| 1 | Cleanup imports | 6 | .py | py | bsd-3-clause | gmr/queries |
1363 | <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.1',
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> Dont remove the pool on clean
<DFF> @@ -28,7 +28,7 @@ classifiers = ['Development Status :: 5 - Production/Stable',
'Topic :: Software Development :: Libraries']
setup(name='queries',
- version='1.10.1',
+ version='1.10.2',
description="Simplified PostgreSQL client built upon Psycopg2",
maintainer="Gavin M. Roy",
maintainer_email="gavinmroy@gmail.com",
| 1 | Dont remove the pool on clean | 1 | .py | py | bsd-3-clause | gmr/queries |
1364 | <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.1',
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> Dont remove the pool on clean
<DFF> @@ -28,7 +28,7 @@ classifiers = ['Development Status :: 5 - Production/Stable',
'Topic :: Software Development :: Libraries']
setup(name='queries',
- version='1.10.1',
+ version='1.10.2',
description="Simplified PostgreSQL client built upon Psycopg2",
maintainer="Gavin M. Roy",
maintainer_email="gavinmroy@gmail.com",
| 1 | Dont remove the pool on clean | 1 | .py | py | bsd-3-clause | gmr/queries |
1365 | <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_creates_empty_connections_dict(self):
self.assertDictEqual(self.obj._connections, {})
def test_creates_empty_listeners_dict(self):
self.assertDictEqual(self.obj._listeners, {})
def test_sets_default_cursor_factory(self):
self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor)
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):
self.obj._on_io_events,
ioloop.IOLoop.WRITE)
class SessionPublicMethodTests(testing.AsyncTestCase):
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = mock.Mock()
cursor = mock.Mock()
cursor.close = mock.Mock()
self.obj._exec_cleanup(cursor, 14)
cursor.close.assert_called_once_with()
def test_exec_cleanup_frees_connection(self):
with mock.patch.object(self.obj._pool_manager, 'free') as pm_free:
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = conn = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
pm_free.assert_called_once_with(self.obj.pid, conn)
def test_exec_cleanup_remove_handler_invoked(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler') as rh:
self.obj._connections[14] = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
rh.assert_called_once_with(14)
def test_exec_removes_connection(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
self.assertNotIn(14, self.obj._connections)
def test_exec_removes_future(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = mock.Mock()
self.obj._futures[14] = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
self.assertNotIn(14, self.obj._futures)
def test_pool_manager_add_failures_are_propagated(self):
futures = []
def add_future(future, callback):
futures.append((future, callback))
obj = tornado_session.TornadoSession()
obj._ioloop = mock.Mock()
obj._ioloop.add_future = add_future
future = concurrent.Future()
with mock.patch.object(obj._pool_manager, 'add') as add_method:
add_method.side_effect = pool.PoolFullError(mock.Mock())
obj._create_connection(future)
self.assertEqual(len(futures), 1)
connected_future, callback = futures.pop()
connected_future.set_result(True)
callback(connected_future)
self.assertIs(future.exception(), add_method.side_effect)
class SessionPublicMethodTests(testing.AsyncTestCase):
@testing.gen_test
def test_callproc_invokes_execute(self):
with mock.patch('queries.tornado_session.TornadoSession._execute') as \
_execute:
future = concurrent.Future()
future.set_result(True)
_execute.return_value = future
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
yield obj.callproc('foo', ['bar'])
_execute.assert_called_once_with('callproc', 'foo', ['bar'])
@testing.gen_test
def test_query_invokes_execute(self):
with mock.patch('queries.tornado_session.TornadoSession._execute') as \
_execute:
future = concurrent.Future()
future.set_result(True)
_execute.return_value = future
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
yield obj.query('SELECT 1')
_execute.assert_called_once_with('execute', 'SELECT 1', None)
"""
@testing.gen_test
def test_query_error_key_error(self):
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
with self.assertRaises(Exception):
yield obj.query('SELECT * FROM foo WHERE bar=%(baz)s', {})
@testing.gen_test
def test_query_error_index_error(self):
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
with self.assertRaises(Exception):
r = yield obj.query('SELECT * FROM foo WHERE bar=%s', [])
"""
<MSG> Remove test for removed listener dict, add more coverage
<DFF> @@ -56,9 +56,6 @@ class SessionInitTests(unittest.TestCase):
def test_creates_empty_connections_dict(self):
self.assertDictEqual(self.obj._connections, {})
- def test_creates_empty_listeners_dict(self):
- self.assertDictEqual(self.obj._listeners, {})
-
def test_sets_default_cursor_factory(self):
self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor)
@@ -127,6 +124,12 @@ class SessionConnectTests(testing.AsyncTestCase):
self.obj._on_io_events,
ioloop.IOLoop.WRITE)
+ @testing.gen_test
+ 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)
+
class SessionPublicMethodTests(testing.AsyncTestCase):
| 6 | Remove test for removed listener dict, add more coverage | 3 | .py | py | bsd-3-clause | gmr/queries |
1366 | <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_creates_empty_connections_dict(self):
self.assertDictEqual(self.obj._connections, {})
def test_creates_empty_listeners_dict(self):
self.assertDictEqual(self.obj._listeners, {})
def test_sets_default_cursor_factory(self):
self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor)
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):
self.obj._on_io_events,
ioloop.IOLoop.WRITE)
class SessionPublicMethodTests(testing.AsyncTestCase):
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = mock.Mock()
cursor = mock.Mock()
cursor.close = mock.Mock()
self.obj._exec_cleanup(cursor, 14)
cursor.close.assert_called_once_with()
def test_exec_cleanup_frees_connection(self):
with mock.patch.object(self.obj._pool_manager, 'free') as pm_free:
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = conn = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
pm_free.assert_called_once_with(self.obj.pid, conn)
def test_exec_cleanup_remove_handler_invoked(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler') as rh:
self.obj._connections[14] = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
rh.assert_called_once_with(14)
def test_exec_removes_connection(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
self.assertNotIn(14, self.obj._connections)
def test_exec_removes_future(self):
with mock.patch.object(self.obj._pool_manager, 'free'):
with mock.patch.object(self.obj._ioloop, 'remove_handler'):
self.obj._connections[14] = mock.Mock()
self.obj._futures[14] = mock.Mock()
self.obj._exec_cleanup(mock.Mock(), 14)
self.assertNotIn(14, self.obj._futures)
def test_pool_manager_add_failures_are_propagated(self):
futures = []
def add_future(future, callback):
futures.append((future, callback))
obj = tornado_session.TornadoSession()
obj._ioloop = mock.Mock()
obj._ioloop.add_future = add_future
future = concurrent.Future()
with mock.patch.object(obj._pool_manager, 'add') as add_method:
add_method.side_effect = pool.PoolFullError(mock.Mock())
obj._create_connection(future)
self.assertEqual(len(futures), 1)
connected_future, callback = futures.pop()
connected_future.set_result(True)
callback(connected_future)
self.assertIs(future.exception(), add_method.side_effect)
class SessionPublicMethodTests(testing.AsyncTestCase):
@testing.gen_test
def test_callproc_invokes_execute(self):
with mock.patch('queries.tornado_session.TornadoSession._execute') as \
_execute:
future = concurrent.Future()
future.set_result(True)
_execute.return_value = future
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
yield obj.callproc('foo', ['bar'])
_execute.assert_called_once_with('callproc', 'foo', ['bar'])
@testing.gen_test
def test_query_invokes_execute(self):
with mock.patch('queries.tornado_session.TornadoSession._execute') as \
_execute:
future = concurrent.Future()
future.set_result(True)
_execute.return_value = future
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
yield obj.query('SELECT 1')
_execute.assert_called_once_with('execute', 'SELECT 1', None)
"""
@testing.gen_test
def test_query_error_key_error(self):
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
with self.assertRaises(Exception):
yield obj.query('SELECT * FROM foo WHERE bar=%(baz)s', {})
@testing.gen_test
def test_query_error_index_error(self):
obj = tornado_session.TornadoSession(io_loop=self.io_loop)
with self.assertRaises(Exception):
r = yield obj.query('SELECT * FROM foo WHERE bar=%s', [])
"""
<MSG> Remove test for removed listener dict, add more coverage
<DFF> @@ -56,9 +56,6 @@ class SessionInitTests(unittest.TestCase):
def test_creates_empty_connections_dict(self):
self.assertDictEqual(self.obj._connections, {})
- def test_creates_empty_listeners_dict(self):
- self.assertDictEqual(self.obj._listeners, {})
-
def test_sets_default_cursor_factory(self):
self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor)
@@ -127,6 +124,12 @@ class SessionConnectTests(testing.AsyncTestCase):
self.obj._on_io_events,
ioloop.IOLoop.WRITE)
+ @testing.gen_test
+ 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)
+
class SessionPublicMethodTests(testing.AsyncTestCase):
| 6 | Remove test for removed listener dict, add more coverage | 3 | .py | py | bsd-3-clause | gmr/queries |
1367 | <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._reg_type = register_type
self._reg_uuid = register_uuid
self.uri = 'pgsql://postgres@127.0.0.1:5432/queries'
self.pid = hashlib.md5(self.uri).digest()
if self.pid in pool.Pools:
del pool.Pools[self.pid]
self.client = session.Session(self.uri)
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 hashlib/unicode issues in Python 3
<DFF> @@ -32,7 +32,7 @@ class SessionTests(unittest.TestCase):
self._reg_type = register_type
self._reg_uuid = register_uuid
self.uri = 'pgsql://postgres@127.0.0.1:5432/queries'
- self.pid = hashlib.md5(self.uri).digest()
+ self.pid = hashlib.md5(self.uri.encode('utf-8')).digest()
if self.pid in pool.Pools:
del pool.Pools[self.pid]
self.client = session.Session(self.uri)
| 1 | Fix hashlib/unicode issues in Python 3 | 1 | .py | py | bsd-3-clause | gmr/queries |
1368 | <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._reg_type = register_type
self._reg_uuid = register_uuid
self.uri = 'pgsql://postgres@127.0.0.1:5432/queries'
self.pid = hashlib.md5(self.uri).digest()
if self.pid in pool.Pools:
del pool.Pools[self.pid]
self.client = session.Session(self.uri)
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 hashlib/unicode issues in Python 3
<DFF> @@ -32,7 +32,7 @@ class SessionTests(unittest.TestCase):
self._reg_type = register_type
self._reg_uuid = register_uuid
self.uri = 'pgsql://postgres@127.0.0.1:5432/queries'
- self.pid = hashlib.md5(self.uri).digest()
+ self.pid = hashlib.md5(self.uri.encode('utf-8')).digest()
if self.pid in pool.Pools:
del pool.Pools[self.pid]
self.client = session.Session(self.uri)
| 1 | Fix hashlib/unicode issues in Python 3 | 1 | .py | py | bsd-3-clause | gmr/queries |
1369 | <NME> tornado_session.py
<BEF> """
Tornado Session Adapter
Use Queries asynchronously within the Tornado framework.
Example Use:
.. code:: python
class NameListHandler(web.RequestHandler):
def initialize(self):
self.session = queries.TornadoSession(pool_max_size=60)
@gen.coroutine
def get(self):
data = yield self.session.query('SELECT * FROM names')
if data:
self.finish({'names': data.items()})
data.free()
else:
self.set_status(500, 'Error querying the data')
"""
import logging
import socket
import warnings
from tornado import concurrent, ioloop
from psycopg2 import extras, extensions
import psycopg2
from queries import pool, results, session, utils
LOGGER = logging.getLogger(__name__)
DEFAULT_MAX_POOL_SIZE = 25
class Results(results.Results):
"""A TornadoSession specific :py:class:`queries.Results` class that adds
the :py:meth:`Results.free <queries.tornado_session.Results.free>` method.
The :py:meth:`Results.free <queries.tornado_session.Results.free>` method
**must** be called to free the connection that the results were generated
on. `Results` objects that are not freed will cause the connections to
remain locked and your application will eventually run out of connections
in the pool.
The following examples illustrate the various behaviors that the
::py:class:`queries.Results <queries.tornado_session.Requests>` class
implements:
**Using Results as an Iterator**
.. code:: python
results = yield session.query('SELECT * FROM foo')
for row in results
print row
results.free()
**Accessing an individual row by index**
.. code:: python
results = yield session.query('SELECT * FROM foo')
print results[1] # Access the second row of the results
results.free()
**Casting single row results as a dict**
.. code:: python
results = yield session.query('SELECT * FROM foo LIMIT 1')
print results.as_dict()
results.free()
**Checking to see if a query was successful**
.. code:: python
sql = "UPDATE foo SET bar='baz' WHERE qux='corgie'"
results = yield session.query(sql)
if results:
print 'Success'
results.free()
**Checking the number of rows by using len(Results)**
.. code:: python
results = yield session.query('SELECT * FROM foo')
print '%i rows' % len(results)
results.free()
"""
def __init__(self, cursor, cleanup, fd):
self.cursor = cursor
self._cleanup = cleanup
self._fd = fd
self._freed = False
def free(self):
"""Release the results and connection lock from the TornadoSession
object. This **must** be called after you finish processing the results
from :py:meth:`TornadoSession.query <queries.TornadoSession.query>` or
:py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>`
or the connection will not be able to be reused by other asynchronous
requests.
"""
self._freed = True
self._cleanup(self.cursor, self._fd)
def __del__(self):
if not self._freed:
LOGGER.warning('Auto-freeing result on deletion')
self.free()
class TornadoSession(session.Session):
"""Session class for Tornado asynchronous applications. Uses
:py:func:`tornado.gen.coroutine` to wrap API methods for use in Tornado.
Utilizes connection pooling to ensure that multiple concurrent asynchronous
queries do not block each other. Heavily trafficked services will require
a higher ``max_pool_size`` to allow for greater connection concurrency.
:py:meth:`TornadoSession.query <queries.TornadoSession.query>` and
:py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` must
call :py:meth:`Results.free <queries.tornado_session.Results.free>`
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
"""
def __init__(self, uri=session.DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
pool_max_size=DEFAULT_MAX_POOL_SIZE,
io_loop=None):
"""Connect to a PostgreSQL server using the module wide connection and
set the isolation level.
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
:param tornado.ioloop.IOLoop io_loop: IOLoop instance to use
"""
self._connections = dict()
self._cleanup_callback = None
self._cursor_factory = cursor_factory
self._futures = dict()
self._ioloop = io_loop or ioloop.IOLoop.current()
self._pool_manager = pool.PoolManager.instance()
self._pool_max_size = pool_max_size
self._pool_idle_ttl = pool_idle_ttl
self._uri = uri
self._ensure_pool_exists()
def _ensure_pool_exists(self):
"""Create the pool in the pool manager if it does not exist."""
if self.pid not in self._pool_manager:
self._pool_manager.create(self.pid, self._pool_idle_ttl,
self._pool_max_size, self._ioloop.time)
@property
def connection(self):
"""Do not use this directly with Tornado applications
:return:
"""
return None
@property
def cursor(self):
return None
def callproc(self, name, args=None):
"""Call a stored procedure asynchronously on the server, passing in the
arguments to be passed to the stored procedure, yielding the results
as a :py:class:`Results <queries.tornado_session.Results>` object.
You **must** free the results that are returned by this method to
unlock the connection used to perform the query. Failure to do so
will cause your Tornado application to run out of connections.
:param str name: The stored procedure name
:param list args: An optional list of procedure arguments
:rtype: Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
return self._execute('callproc', name, args)
def query(self, sql, parameters=None):
"""Issue a query asynchronously on the server, mogrifying the
parameters against the sql statement and yielding the results
as a :py:class:`Results <queries.tornado_session.Results>` object.
You **must** free the results that are returned by this method to
unlock the connection used to perform the query. Failure to do so
will cause your Tornado application to run out of connections.
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
return self._execute('execute', sql, parameters)
def validate(self):
"""Validate the session can connect or has open connections to
PostgreSQL. As of ``1.10.3``
.. deprecated:: 1.10.3
As of 1.10.3, this method only warns about Deprecation
:rtype: bool
"""
warnings.warn(
'All functionality removed from this method', DeprecationWarning)
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
if possible, or by creating the new connection.
:rtype: psycopg2.extensions.connection
:raises: pool.NoIdleConnectionsError
"""
future = concurrent.Future()
# Attempt to get a cached connection from the connection pool
try:
connection = self._pool_manager.get(self.pid, self)
self._connections[connection.fileno()] = connection
future.set_result(connection)
# Add the connection to the IOLoop
self._ioloop.add_handler(connection.fileno(),
self._on_io_events,
ioloop.IOLoop.WRITE)
except pool.NoIdleConnectionsError:
self._create_connection(future)
return future
def _create_connection(self, future):
"""Create a new PostgreSQL connection
:param tornado.concurrent.Future future: future for new conn result
"""
LOGGER.debug('Creating a new connection for %s', self.pid)
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
try:
connection = self._psycopg2_connect(kwargs)
except (psycopg2.Error, OSError, socket.error) as error:
future.set_exception(error)
return
# Add the connection for use in _poll_connection
fd = connection.fileno()
self._connections[fd] = connection
def on_connected(cf):
"""Invoked by the IOLoop when the future is complete for the
connection
:param Future cf: The future for the initial connection
"""
if cf.exception():
self._cleanup_fd(fd, True)
future.set_exception(cf.exception())
else:
try:
# Add the connection to the pool
LOGGER.debug('Connection established for %s', self.pid)
self._pool_manager.add(self.pid, connection)
except (ValueError, pool.PoolException) as err:
LOGGER.exception('Failed to add %r to the pool', self.pid)
self._cleanup_fd(fd)
future.set_exception(err)
return
self._pool_manager.lock(self.pid, connection, self)
# Added in because psycopg2cffi connects and leaves the
# connection in a weird state: consts.STATUS_DATESTYLE,
# returning from Connection._setup without setting the state
# as const.STATUS_OK
if utils.PYPY:
connection.status = extensions.STATUS_READY
# Register the custom data types
self._register_unicode(connection)
self._register_uuid(connection)
# Set the future result
future.set_result(connection)
# Add a future that fires once connected
self._futures[fd] = concurrent.Future()
self._ioloop.add_future(self._futures[fd], on_connected)
# Add the connection to the IOLoop
self._ioloop.add_handler(connection.fileno(),
self._on_io_events,
ioloop.IOLoop.WRITE)
def completed(qf):
"""Invoked by the IOLoop when the future has completed"""
if qf.exception():
self._exec_cleanup(cursor, conn.fileno())
future.set_exception(qf.exception())
future.set_result(Results(cursor,
self._exec_cleanup,
conn.fileno()))
: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
:param int fd: The connection file descriptor
"""
cursor.close()
self._pool_manager.free(self.pid, self._connections[fd])
err = qf.exception()
LOGGER.debug('Cleaning cursor due to exception: %r', err)
self._exec_cleanup(cursor, conn.fileno())
future.set_exception(err)
self._ioloop.remove_handler(fd)
@gen.coroutine
def _on_io_events(self, fd=None, events=None):
"""Invoked by Tornado's IOLoop when there are events for the fd
self._futures[conn.fileno()] = concurrent.Future()
# Add the future to the IOLoop
self._ioloop.add_future(self._futures[conn.fileno()],
completed)
return
self._poll_connection(fd)
@gen.coroutine
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.
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> Add some logging and remove coroutine decorators
Non-async functions do not need the decorators
<DFF> @@ -337,8 +337,10 @@ class TornadoSession(session.Session):
def completed(qf):
"""Invoked by the IOLoop when the future has completed"""
if qf.exception():
+ LOGGER.debug('Cleaning cursor due to exception: %r',
+ qf.exception())
self._exec_cleanup(cursor, conn.fileno())
- future.set_exception(qf.exception())
+ raise qf.exception()
future.set_result(Results(cursor,
self._exec_cleanup,
conn.fileno()))
@@ -367,6 +369,7 @@ class TornadoSession(session.Session):
:param int fd: The connection file descriptor
"""
+ LOGGER.debug('Closing cursor and cleaning %s', fd)
cursor.close()
self._pool_manager.free(self.pid, self._connections[fd])
@@ -377,7 +380,6 @@ class TornadoSession(session.Session):
self._ioloop.remove_handler(fd)
- @gen.coroutine
def _on_io_events(self, fd=None, events=None):
"""Invoked by Tornado's IOLoop when there are events for the fd
@@ -389,7 +391,6 @@ class TornadoSession(session.Session):
return
self._poll_connection(fd)
- @gen.coroutine
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.
| 4 | Add some logging and remove coroutine decorators | 3 | .py | py | bsd-3-clause | gmr/queries |
1370 | <NME> tornado_session.py
<BEF> """
Tornado Session Adapter
Use Queries asynchronously within the Tornado framework.
Example Use:
.. code:: python
class NameListHandler(web.RequestHandler):
def initialize(self):
self.session = queries.TornadoSession(pool_max_size=60)
@gen.coroutine
def get(self):
data = yield self.session.query('SELECT * FROM names')
if data:
self.finish({'names': data.items()})
data.free()
else:
self.set_status(500, 'Error querying the data')
"""
import logging
import socket
import warnings
from tornado import concurrent, ioloop
from psycopg2 import extras, extensions
import psycopg2
from queries import pool, results, session, utils
LOGGER = logging.getLogger(__name__)
DEFAULT_MAX_POOL_SIZE = 25
class Results(results.Results):
"""A TornadoSession specific :py:class:`queries.Results` class that adds
the :py:meth:`Results.free <queries.tornado_session.Results.free>` method.
The :py:meth:`Results.free <queries.tornado_session.Results.free>` method
**must** be called to free the connection that the results were generated
on. `Results` objects that are not freed will cause the connections to
remain locked and your application will eventually run out of connections
in the pool.
The following examples illustrate the various behaviors that the
::py:class:`queries.Results <queries.tornado_session.Requests>` class
implements:
**Using Results as an Iterator**
.. code:: python
results = yield session.query('SELECT * FROM foo')
for row in results
print row
results.free()
**Accessing an individual row by index**
.. code:: python
results = yield session.query('SELECT * FROM foo')
print results[1] # Access the second row of the results
results.free()
**Casting single row results as a dict**
.. code:: python
results = yield session.query('SELECT * FROM foo LIMIT 1')
print results.as_dict()
results.free()
**Checking to see if a query was successful**
.. code:: python
sql = "UPDATE foo SET bar='baz' WHERE qux='corgie'"
results = yield session.query(sql)
if results:
print 'Success'
results.free()
**Checking the number of rows by using len(Results)**
.. code:: python
results = yield session.query('SELECT * FROM foo')
print '%i rows' % len(results)
results.free()
"""
def __init__(self, cursor, cleanup, fd):
self.cursor = cursor
self._cleanup = cleanup
self._fd = fd
self._freed = False
def free(self):
"""Release the results and connection lock from the TornadoSession
object. This **must** be called after you finish processing the results
from :py:meth:`TornadoSession.query <queries.TornadoSession.query>` or
:py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>`
or the connection will not be able to be reused by other asynchronous
requests.
"""
self._freed = True
self._cleanup(self.cursor, self._fd)
def __del__(self):
if not self._freed:
LOGGER.warning('Auto-freeing result on deletion')
self.free()
class TornadoSession(session.Session):
"""Session class for Tornado asynchronous applications. Uses
:py:func:`tornado.gen.coroutine` to wrap API methods for use in Tornado.
Utilizes connection pooling to ensure that multiple concurrent asynchronous
queries do not block each other. Heavily trafficked services will require
a higher ``max_pool_size`` to allow for greater connection concurrency.
:py:meth:`TornadoSession.query <queries.TornadoSession.query>` and
:py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` must
call :py:meth:`Results.free <queries.tornado_session.Results.free>`
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
"""
def __init__(self, uri=session.DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
pool_max_size=DEFAULT_MAX_POOL_SIZE,
io_loop=None):
"""Connect to a PostgreSQL server using the module wide connection and
set the isolation level.
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
:param tornado.ioloop.IOLoop io_loop: IOLoop instance to use
"""
self._connections = dict()
self._cleanup_callback = None
self._cursor_factory = cursor_factory
self._futures = dict()
self._ioloop = io_loop or ioloop.IOLoop.current()
self._pool_manager = pool.PoolManager.instance()
self._pool_max_size = pool_max_size
self._pool_idle_ttl = pool_idle_ttl
self._uri = uri
self._ensure_pool_exists()
def _ensure_pool_exists(self):
"""Create the pool in the pool manager if it does not exist."""
if self.pid not in self._pool_manager:
self._pool_manager.create(self.pid, self._pool_idle_ttl,
self._pool_max_size, self._ioloop.time)
@property
def connection(self):
"""Do not use this directly with Tornado applications
:return:
"""
return None
@property
def cursor(self):
return None
def callproc(self, name, args=None):
"""Call a stored procedure asynchronously on the server, passing in the
arguments to be passed to the stored procedure, yielding the results
as a :py:class:`Results <queries.tornado_session.Results>` object.
You **must** free the results that are returned by this method to
unlock the connection used to perform the query. Failure to do so
will cause your Tornado application to run out of connections.
:param str name: The stored procedure name
:param list args: An optional list of procedure arguments
:rtype: Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
return self._execute('callproc', name, args)
def query(self, sql, parameters=None):
"""Issue a query asynchronously on the server, mogrifying the
parameters against the sql statement and yielding the results
as a :py:class:`Results <queries.tornado_session.Results>` object.
You **must** free the results that are returned by this method to
unlock the connection used to perform the query. Failure to do so
will cause your Tornado application to run out of connections.
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
return self._execute('execute', sql, parameters)
def validate(self):
"""Validate the session can connect or has open connections to
PostgreSQL. As of ``1.10.3``
.. deprecated:: 1.10.3
As of 1.10.3, this method only warns about Deprecation
:rtype: bool
"""
warnings.warn(
'All functionality removed from this method', DeprecationWarning)
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
if possible, or by creating the new connection.
:rtype: psycopg2.extensions.connection
:raises: pool.NoIdleConnectionsError
"""
future = concurrent.Future()
# Attempt to get a cached connection from the connection pool
try:
connection = self._pool_manager.get(self.pid, self)
self._connections[connection.fileno()] = connection
future.set_result(connection)
# Add the connection to the IOLoop
self._ioloop.add_handler(connection.fileno(),
self._on_io_events,
ioloop.IOLoop.WRITE)
except pool.NoIdleConnectionsError:
self._create_connection(future)
return future
def _create_connection(self, future):
"""Create a new PostgreSQL connection
:param tornado.concurrent.Future future: future for new conn result
"""
LOGGER.debug('Creating a new connection for %s', self.pid)
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
try:
connection = self._psycopg2_connect(kwargs)
except (psycopg2.Error, OSError, socket.error) as error:
future.set_exception(error)
return
# Add the connection for use in _poll_connection
fd = connection.fileno()
self._connections[fd] = connection
def on_connected(cf):
"""Invoked by the IOLoop when the future is complete for the
connection
:param Future cf: The future for the initial connection
"""
if cf.exception():
self._cleanup_fd(fd, True)
future.set_exception(cf.exception())
else:
try:
# Add the connection to the pool
LOGGER.debug('Connection established for %s', self.pid)
self._pool_manager.add(self.pid, connection)
except (ValueError, pool.PoolException) as err:
LOGGER.exception('Failed to add %r to the pool', self.pid)
self._cleanup_fd(fd)
future.set_exception(err)
return
self._pool_manager.lock(self.pid, connection, self)
# Added in because psycopg2cffi connects and leaves the
# connection in a weird state: consts.STATUS_DATESTYLE,
# returning from Connection._setup without setting the state
# as const.STATUS_OK
if utils.PYPY:
connection.status = extensions.STATUS_READY
# Register the custom data types
self._register_unicode(connection)
self._register_uuid(connection)
# Set the future result
future.set_result(connection)
# Add a future that fires once connected
self._futures[fd] = concurrent.Future()
self._ioloop.add_future(self._futures[fd], on_connected)
# Add the connection to the IOLoop
self._ioloop.add_handler(connection.fileno(),
self._on_io_events,
ioloop.IOLoop.WRITE)
def completed(qf):
"""Invoked by the IOLoop when the future has completed"""
if qf.exception():
self._exec_cleanup(cursor, conn.fileno())
future.set_exception(qf.exception())
future.set_result(Results(cursor,
self._exec_cleanup,
conn.fileno()))
: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
:param int fd: The connection file descriptor
"""
cursor.close()
self._pool_manager.free(self.pid, self._connections[fd])
err = qf.exception()
LOGGER.debug('Cleaning cursor due to exception: %r', err)
self._exec_cleanup(cursor, conn.fileno())
future.set_exception(err)
self._ioloop.remove_handler(fd)
@gen.coroutine
def _on_io_events(self, fd=None, events=None):
"""Invoked by Tornado's IOLoop when there are events for the fd
self._futures[conn.fileno()] = concurrent.Future()
# Add the future to the IOLoop
self._ioloop.add_future(self._futures[conn.fileno()],
completed)
return
self._poll_connection(fd)
@gen.coroutine
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.
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> Add some logging and remove coroutine decorators
Non-async functions do not need the decorators
<DFF> @@ -337,8 +337,10 @@ class TornadoSession(session.Session):
def completed(qf):
"""Invoked by the IOLoop when the future has completed"""
if qf.exception():
+ LOGGER.debug('Cleaning cursor due to exception: %r',
+ qf.exception())
self._exec_cleanup(cursor, conn.fileno())
- future.set_exception(qf.exception())
+ raise qf.exception()
future.set_result(Results(cursor,
self._exec_cleanup,
conn.fileno()))
@@ -367,6 +369,7 @@ class TornadoSession(session.Session):
:param int fd: The connection file descriptor
"""
+ LOGGER.debug('Closing cursor and cleaning %s', fd)
cursor.close()
self._pool_manager.free(self.pid, self._connections[fd])
@@ -377,7 +380,6 @@ class TornadoSession(session.Session):
self._ioloop.remove_handler(fd)
- @gen.coroutine
def _on_io_events(self, fd=None, events=None):
"""Invoked by Tornado's IOLoop when there are events for the fd
@@ -389,7 +391,6 @@ class TornadoSession(session.Session):
return
self._poll_connection(fd)
- @gen.coroutine
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.
| 4 | Add some logging and remove coroutine decorators | 3 | .py | py | bsd-3-clause | gmr/queries |
1371 | <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
-----
for row in queries.execute(uri, 'SELECT 1 as value'):
print(data['value'])
Creating a Session object for transactional behavior:
.. code:: python
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
pgsql.commit()
.. |Version| image:: https://badge.fury.io/py/queries.svg?
:target: http://badge.fury.io/py/queries
* ``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> Additional examples
<DFF> @@ -40,6 +40,16 @@ Executing a query and fetching data:
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
@@ -53,6 +63,10 @@ Creating a Session object for transactional behavior:
pgsql.commit()
+
+
+
+
.. |Version| image:: https://badge.fury.io/py/queries.svg?
:target: http://badge.fury.io/py/queries
| 14 | Additional examples | 0 | .rst | rst | bsd-3-clause | gmr/queries |
1372 | <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
-----
for row in queries.execute(uri, 'SELECT 1 as value'):
print(data['value'])
Creating a Session object for transactional behavior:
.. code:: python
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
pgsql.commit()
.. |Version| image:: https://badge.fury.io/py/queries.svg?
:target: http://badge.fury.io/py/queries
* ``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> Additional examples
<DFF> @@ -40,6 +40,16 @@ Executing a query and fetching data:
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
@@ -53,6 +63,10 @@ Creating a Session object for transactional behavior:
pgsql.commit()
+
+
+
+
.. |Version| image:: https://badge.fury.io/py/queries.svg?
:target: http://badge.fury.io/py/queries
| 14 | Additional examples | 0 | .rst | rst | bsd-3-clause | gmr/queries |
1373 | <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_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()
obj.add(psycopg2_conn)
self.assertRaises(pool.ConnectionBusyError, obj.remove,
psycopg2_conn)
def test__connection_returns_handle(self):
obj = pool.Pool(str(uuid.uuid4()))
psycopg2_conn = mock.Mock()
obj.add(psycopg2_conn)
self.assertEqual(
obj.connection_handle(psycopg2_conn).handle, psycopg2_conn)
def test_shutdown_raises_when_executing(self):
psycopg2_conn = mock_connection()
psycopg2_conn.isexecuting.return_value = True
obj = pool.Pool(str(uuid.uuid4()))
obj.add(psycopg2_conn)
self.assertRaises(pool.ConnectionBusyError, obj.shutdown)
<MSG> Fix tests
<DFF> @@ -271,6 +271,7 @@ class PoolTests(unittest.TestCase):
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)
| 1 | Fix tests | 0 | .py | py | bsd-3-clause | gmr/queries |
1374 | <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_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()
obj.add(psycopg2_conn)
self.assertRaises(pool.ConnectionBusyError, obj.remove,
psycopg2_conn)
def test__connection_returns_handle(self):
obj = pool.Pool(str(uuid.uuid4()))
psycopg2_conn = mock.Mock()
obj.add(psycopg2_conn)
self.assertEqual(
obj.connection_handle(psycopg2_conn).handle, psycopg2_conn)
def test_shutdown_raises_when_executing(self):
psycopg2_conn = mock_connection()
psycopg2_conn.isexecuting.return_value = True
obj = pool.Pool(str(uuid.uuid4()))
obj.add(psycopg2_conn)
self.assertRaises(pool.ConnectionBusyError, obj.shutdown)
<MSG> Fix tests
<DFF> @@ -271,6 +271,7 @@ class PoolTests(unittest.TestCase):
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)
| 1 | Fix tests | 0 | .py | py | bsd-3-clause | gmr/queries |
1375 | <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._reg_type = register_type
self._reg_uuid = register_uuid
self.uri = 'pgsql://postgres@127.0.0.1:5432/queries'
self.pid = hashlib.md5(self.uri.encode('utf-8')).digest()
if self.pid in pool.Pools:
del pool.Pools[self.pid]
self.client = session.Session(self.uri)
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> Return the hex digest string for the pid, fix tests
<DFF> @@ -30,7 +30,7 @@ class SessionTests(unittest.TestCase):
self._reg_type = register_type
self._reg_uuid = register_uuid
self.uri = 'pgsql://postgres@127.0.0.1:5432/queries'
- self.pid = hashlib.md5(self.uri.encode('utf-8')).digest()
+ self.pid = (hashlib.md5(self.uri.encode('utf-8')).hexdigest())
if self.pid in pool.Pools:
del pool.Pools[self.pid]
self.client = session.Session(self.uri)
| 1 | Return the hex digest string for the pid, fix tests | 1 | .py | py | bsd-3-clause | gmr/queries |
1376 | <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._reg_type = register_type
self._reg_uuid = register_uuid
self.uri = 'pgsql://postgres@127.0.0.1:5432/queries'
self.pid = hashlib.md5(self.uri.encode('utf-8')).digest()
if self.pid in pool.Pools:
del pool.Pools[self.pid]
self.client = session.Session(self.uri)
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> Return the hex digest string for the pid, fix tests
<DFF> @@ -30,7 +30,7 @@ class SessionTests(unittest.TestCase):
self._reg_type = register_type
self._reg_uuid = register_uuid
self.uri = 'pgsql://postgres@127.0.0.1:5432/queries'
- self.pid = hashlib.md5(self.uri.encode('utf-8')).digest()
+ self.pid = (hashlib.md5(self.uri.encode('utf-8')).hexdigest())
if self.pid in pool.Pools:
del pool.Pools[self.pid]
self.client = session.Session(self.uri)
| 1 | Return the hex digest string for the pid, fix tests | 1 | .py | py | bsd-3-clause | gmr/queries |
1377 | <NME> bootstrap
<BEF> #!/bin/sh
# vim: set ts=2 sts=2 sw=2 et:
test -n "$SHELLDEBUG" && set -x
if test -e /var/run/docker.sock
then
DOCKER_IP=127.0.0.1
else
echo "Docker environment not detected."
exit 1
fi
set -e
if test -z "$COMPOSE_PROJECT_NAME"
then
CWD=${PWD##*/}
export COMPOSE_PROJECT_NAME=${CWD/_/}
fi
test -d build || mkdir build
get_exposed_port() {
docker-compose port $1 $2 | cut -d: -f2
}
docker-compose down -t 0 --volumes --remove-orphans
docker-compose pull
docker-compose up -d --no-recreate
PORT=$(get_exposed_port postgres 5432)
printf "Waiting for postgres "
export PG
until docker-compose exec postgres pg_isready -q; do
printf "."
sleep 1
done
echo " done"
cat > build/test-environment<<EOF
export PGHOST=${DOCKER_IP}
export PGPORT=${PORT}
EOF
<MSG> Simplify build dir creation
<DFF> @@ -16,7 +16,7 @@ then
export COMPOSE_PROJECT_NAME=${CWD/_/}
fi
-test -d build || mkdir build
+mkdir -p build
get_exposed_port() {
docker-compose port $1 $2 | cut -d: -f2
| 1 | Simplify build dir creation | 1 | bootstrap | bsd-3-clause | gmr/queries |
|
1378 | <NME> bootstrap
<BEF> #!/bin/sh
# vim: set ts=2 sts=2 sw=2 et:
test -n "$SHELLDEBUG" && set -x
if test -e /var/run/docker.sock
then
DOCKER_IP=127.0.0.1
else
echo "Docker environment not detected."
exit 1
fi
set -e
if test -z "$COMPOSE_PROJECT_NAME"
then
CWD=${PWD##*/}
export COMPOSE_PROJECT_NAME=${CWD/_/}
fi
test -d build || mkdir build
get_exposed_port() {
docker-compose port $1 $2 | cut -d: -f2
}
docker-compose down -t 0 --volumes --remove-orphans
docker-compose pull
docker-compose up -d --no-recreate
PORT=$(get_exposed_port postgres 5432)
printf "Waiting for postgres "
export PG
until docker-compose exec postgres pg_isready -q; do
printf "."
sleep 1
done
echo " done"
cat > build/test-environment<<EOF
export PGHOST=${DOCKER_IP}
export PGPORT=${PORT}
EOF
<MSG> Simplify build dir creation
<DFF> @@ -16,7 +16,7 @@ then
export COMPOSE_PROJECT_NAME=${CWD/_/}
fi
-test -d build || mkdir build
+mkdir -p build
get_exposed_port() {
docker-compose port $1 $2 | cut -d: -f2
| 1 | Simplify build dir creation | 1 | bootstrap | bsd-3-clause | gmr/queries |
|
1379 | <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.
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, pythoic
way of interacting with the object.
:param str uri: PostgreSQL connection URI
_conn = None
_cursor = None
_tpc_id = None
_uri = None
# Connection status constants
INTRANS = extensions.STATUS_IN_TRANSACTION
PREPARED = extensions.STATUS_PREPARED
READY = extensions.STATUS_READY
SETUP = extensions.STATUS_SETUP
# Transaction status constants
TX_ACTIVE = extensions.TRANSACTION_STATUS_ACTIVE
TX_IDLE = extensions.TRANSACTION_STATUS_IDLE
TX_INERROR = extensions.TRANSACTION_STATUS_INERROR
TX_INTRANS = extensions.TRANSACTION_STATUS_INTRANS
TX_UNKNOWN = extensions.TRANSACTION_STATUS_UNKNOWN
def __init__(self, uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
pool_max_size=pool.DEFAULT_MAX_SIZE,
autocommit=True):
"""Connect to a PostgreSQL server using the module wide connection and
set the isolation level.
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
"""
self._pool_manager = pool.PoolManager.instance()
self._uri = uri
# Ensure the pool exists in the pool manager
if self.pid not in self._pool_manager:
self._pool_manager.create(self.pid, pool_idle_ttl, pool_max_size)
self._conn = self._connect()
self._cursor_factory = cursor_factory
self._cursor = self._get_cursor(self._conn)
self._autocommit(autocommit)
@property
def backend_pid(self):
"""Return the backend process ID of the PostgreSQL server that this
session is connected to.
:rtype: int
"""
return self._conn.get_backend_pid()
def callproc(self, name, args=None):
"""Call a stored procedure on the server, returning the results in a
:py:class:`queries.Results` instance.
:param str name: The procedure name
:param list args: The list of arguments to pass in
:rtype: queries.Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
try:
self._cursor.callproc(name, args)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def close(self):
"""Explicitly close the connection and remove it from the connection
pool if pooling is enabled. If the connection is already closed
:raises: psycopg2.InterfaceError
"""
if not self._conn:
raise psycopg2.InterfaceError('Connection not open')
LOGGER.info('Closing connection %r in %s', self._conn, self.pid)
self._pool_manager.free(self.pid, self._conn)
self._pool_manager.remove_connection(self.pid, self._conn)
@property
def connection(self):
"""The current open connection to PostgreSQL.
:rtype: psycopg2.extensions.connection
:rtype: psycopg2.extensions.connection
@property
def cursor(self):
"""The current, active cursor for the open connection.
:rtype: psycopg2.extensions.cursor
:rtype: psycopg2.extensions.cursor
@property
def encoding(self):
"""The current client encoding value.
:rtype: str
:rtype: str
@property
def notices(self):
"""A list of up to the last 50 server notices sent to the client.
:rtype: list
:rtype: list
@property
def pid(self):
"""Return the pool ID used for connection pooling
:rtype: str
:rtype: str
"""
return hashlib.md5(':'.join([self.__class__.__name__,
self._uri]).encode('utf-8')).hexdigest()
def query(self, sql, parameters=None):
"""A generator to issue a query on the server, mogrifying the
parameters against the sql statement. Results are returned as a
:py:class:`queries.Results` object which can act as an iterator and
has multiple ways to access the result data.
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: queries.Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
try:
self._cursor.execute(sql, parameters)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def set_encoding(self, value=DEFAULT_ENCODING):
"""Set the client encoding for the session if the value specified
is different than the current client encoding.
:param str value: The encoding value to use
"""
if self._conn.encoding != value:
self._conn.set_client_encoding(value)
def __del__(self):
"""When deleting the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def __enter__(self):
"""For use as a context manager, return a handle to this object
instance.
:rtype: Session
"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""When leaving the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def _autocommit(self, autocommit):
"""Set the isolation level automatically to commit or not after every query
:param autocommit: Boolean (Default - True)
"""
self._conn.autocommit = autocommit
def _cleanup(self):
"""Remove the connection from the stack, closing out the cursor"""
if self._cursor:
LOGGER.debug('Closing the cursor on %s', self.pid)
self._cursor.close()
self._cursor = None
if self._conn:
LOGGER.debug('Freeing %s in the pool', self.pid)
try:
pool.PoolManager.instance().free(self.pid, self._conn)
except pool.ConnectionNotFoundError:
pass
self._conn = None
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
if possible, or by creating the new connection.
:rtype: psycopg2.extensions.connection
:raises: pool.NoIdleConnectionsError
"""
# Attempt to get a cached connection from the connection pool
try:
connection = self._pool_manager.get(self.pid, self)
LOGGER.debug("Re-using connection for %s", self.pid)
except pool.NoIdleConnectionsError:
if self._pool_manager.is_full(self.pid):
raise
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
LOGGER.debug("Creating a new connection for %s", self.pid)
connection = self._psycopg2_connect(kwargs)
self._pool_manager.add(self.pid, connection)
self._pool_manager.lock(self.pid, connection, self)
# Added in because psycopg2ct connects and leaves the connection in
# a weird state: consts.STATUS_DATESTYLE, returning from
# Connection._setup without setting the state as const.STATUS_OK
if utils.PYPY:
connection.reset()
# Register the custom data types
self._register_unicode(connection)
self._register_uuid(connection)
return connection
def _get_cursor(self, connection, name=None):
"""Return a cursor for the given cursor_factory. Specify a name to
use server-side cursors.
:param connection: The connection to create a cursor on
:type connection: psycopg2.extensions.connection
:param str name: A cursor name for a server side cursor
:rtype: psycopg2.extensions.cursor
"""
cursor = connection.cursor(name=name,
cursor_factory=self._cursor_factory)
if name is not None:
cursor.scrollable = True
cursor.withhold = True
return cursor
def _incr_exceptions(self):
"""Increment the number of exceptions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).exceptions += 1
def _incr_executions(self):
"""Increment the number of executions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).executions += 1
def _psycopg2_connect(self, kwargs):
"""Return a psycopg2 connection for the specified kwargs. Extend for
use in async session adapters.
:param dict kwargs: Keyword connection args
:rtype: psycopg2.extensions.connection
"""
return psycopg2.connect(**kwargs)
@staticmethod
def _register_unicode(connection):
"""Register the cursor to be able to receive Unicode string.
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE,
connection)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY,
connection)
@staticmethod
def _register_uuid(connection):
"""Register the UUID extension from the psycopg2.extra module
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extras.register_uuid(conn_or_curs=connection)
@property
def _status(self):
"""Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queries.Session.READY: Connected, no active transaction
:rtype: int
"""
if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
return self.READY
return self._conn.status
<MSG> Merge pull request #21 from nvllsvm/master
Typos and consistency
<DFF> @@ -45,7 +45,7 @@ DEFAULT_ENCODING = 'UTF8'
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, pythoic
+ act as a context manager, providing automated cleanup and simple, Pythonic
way of interacting with the object.
:param str uri: PostgreSQL connection URI
@@ -145,7 +145,7 @@ class Session(object):
@property
def connection(self):
- """The current open connection to PostgreSQL.
+ """Return the current open connection to PostgreSQL.
:rtype: psycopg2.extensions.connection
@@ -154,7 +154,7 @@ class Session(object):
@property
def cursor(self):
- """The current, active cursor for the open connection.
+ """Return the current, active cursor for the open connection.
:rtype: psycopg2.extensions.cursor
@@ -163,7 +163,7 @@ class Session(object):
@property
def encoding(self):
- """The current client encoding value.
+ """Return the current client encoding value.
:rtype: str
@@ -172,7 +172,7 @@ class Session(object):
@property
def notices(self):
- """A list of up to the last 50 server notices sent to the client.
+ """Return a list of up to the last 50 server notices sent to the client.
:rtype: list
@@ -181,7 +181,7 @@ class Session(object):
@property
def pid(self):
- """Return the pool ID used for connection pooling
+ """Return the pool ID used for connection pooling.
:rtype: str
| 6 | Merge pull request #21 from nvllsvm/master | 6 | .py | py | bsd-3-clause | gmr/queries |
1380 | <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.
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, pythoic
way of interacting with the object.
:param str uri: PostgreSQL connection URI
_conn = None
_cursor = None
_tpc_id = None
_uri = None
# Connection status constants
INTRANS = extensions.STATUS_IN_TRANSACTION
PREPARED = extensions.STATUS_PREPARED
READY = extensions.STATUS_READY
SETUP = extensions.STATUS_SETUP
# Transaction status constants
TX_ACTIVE = extensions.TRANSACTION_STATUS_ACTIVE
TX_IDLE = extensions.TRANSACTION_STATUS_IDLE
TX_INERROR = extensions.TRANSACTION_STATUS_INERROR
TX_INTRANS = extensions.TRANSACTION_STATUS_INTRANS
TX_UNKNOWN = extensions.TRANSACTION_STATUS_UNKNOWN
def __init__(self, uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
pool_max_size=pool.DEFAULT_MAX_SIZE,
autocommit=True):
"""Connect to a PostgreSQL server using the module wide connection and
set the isolation level.
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
"""
self._pool_manager = pool.PoolManager.instance()
self._uri = uri
# Ensure the pool exists in the pool manager
if self.pid not in self._pool_manager:
self._pool_manager.create(self.pid, pool_idle_ttl, pool_max_size)
self._conn = self._connect()
self._cursor_factory = cursor_factory
self._cursor = self._get_cursor(self._conn)
self._autocommit(autocommit)
@property
def backend_pid(self):
"""Return the backend process ID of the PostgreSQL server that this
session is connected to.
:rtype: int
"""
return self._conn.get_backend_pid()
def callproc(self, name, args=None):
"""Call a stored procedure on the server, returning the results in a
:py:class:`queries.Results` instance.
:param str name: The procedure name
:param list args: The list of arguments to pass in
:rtype: queries.Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
try:
self._cursor.callproc(name, args)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def close(self):
"""Explicitly close the connection and remove it from the connection
pool if pooling is enabled. If the connection is already closed
:raises: psycopg2.InterfaceError
"""
if not self._conn:
raise psycopg2.InterfaceError('Connection not open')
LOGGER.info('Closing connection %r in %s', self._conn, self.pid)
self._pool_manager.free(self.pid, self._conn)
self._pool_manager.remove_connection(self.pid, self._conn)
@property
def connection(self):
"""The current open connection to PostgreSQL.
:rtype: psycopg2.extensions.connection
:rtype: psycopg2.extensions.connection
@property
def cursor(self):
"""The current, active cursor for the open connection.
:rtype: psycopg2.extensions.cursor
:rtype: psycopg2.extensions.cursor
@property
def encoding(self):
"""The current client encoding value.
:rtype: str
:rtype: str
@property
def notices(self):
"""A list of up to the last 50 server notices sent to the client.
:rtype: list
:rtype: list
@property
def pid(self):
"""Return the pool ID used for connection pooling
:rtype: str
:rtype: str
"""
return hashlib.md5(':'.join([self.__class__.__name__,
self._uri]).encode('utf-8')).hexdigest()
def query(self, sql, parameters=None):
"""A generator to issue a query on the server, mogrifying the
parameters against the sql statement. Results are returned as a
:py:class:`queries.Results` object which can act as an iterator and
has multiple ways to access the result data.
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: queries.Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
try:
self._cursor.execute(sql, parameters)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def set_encoding(self, value=DEFAULT_ENCODING):
"""Set the client encoding for the session if the value specified
is different than the current client encoding.
:param str value: The encoding value to use
"""
if self._conn.encoding != value:
self._conn.set_client_encoding(value)
def __del__(self):
"""When deleting the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def __enter__(self):
"""For use as a context manager, return a handle to this object
instance.
:rtype: Session
"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""When leaving the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def _autocommit(self, autocommit):
"""Set the isolation level automatically to commit or not after every query
:param autocommit: Boolean (Default - True)
"""
self._conn.autocommit = autocommit
def _cleanup(self):
"""Remove the connection from the stack, closing out the cursor"""
if self._cursor:
LOGGER.debug('Closing the cursor on %s', self.pid)
self._cursor.close()
self._cursor = None
if self._conn:
LOGGER.debug('Freeing %s in the pool', self.pid)
try:
pool.PoolManager.instance().free(self.pid, self._conn)
except pool.ConnectionNotFoundError:
pass
self._conn = None
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
if possible, or by creating the new connection.
:rtype: psycopg2.extensions.connection
:raises: pool.NoIdleConnectionsError
"""
# Attempt to get a cached connection from the connection pool
try:
connection = self._pool_manager.get(self.pid, self)
LOGGER.debug("Re-using connection for %s", self.pid)
except pool.NoIdleConnectionsError:
if self._pool_manager.is_full(self.pid):
raise
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
LOGGER.debug("Creating a new connection for %s", self.pid)
connection = self._psycopg2_connect(kwargs)
self._pool_manager.add(self.pid, connection)
self._pool_manager.lock(self.pid, connection, self)
# Added in because psycopg2ct connects and leaves the connection in
# a weird state: consts.STATUS_DATESTYLE, returning from
# Connection._setup without setting the state as const.STATUS_OK
if utils.PYPY:
connection.reset()
# Register the custom data types
self._register_unicode(connection)
self._register_uuid(connection)
return connection
def _get_cursor(self, connection, name=None):
"""Return a cursor for the given cursor_factory. Specify a name to
use server-side cursors.
:param connection: The connection to create a cursor on
:type connection: psycopg2.extensions.connection
:param str name: A cursor name for a server side cursor
:rtype: psycopg2.extensions.cursor
"""
cursor = connection.cursor(name=name,
cursor_factory=self._cursor_factory)
if name is not None:
cursor.scrollable = True
cursor.withhold = True
return cursor
def _incr_exceptions(self):
"""Increment the number of exceptions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).exceptions += 1
def _incr_executions(self):
"""Increment the number of executions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).executions += 1
def _psycopg2_connect(self, kwargs):
"""Return a psycopg2 connection for the specified kwargs. Extend for
use in async session adapters.
:param dict kwargs: Keyword connection args
:rtype: psycopg2.extensions.connection
"""
return psycopg2.connect(**kwargs)
@staticmethod
def _register_unicode(connection):
"""Register the cursor to be able to receive Unicode string.
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE,
connection)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY,
connection)
@staticmethod
def _register_uuid(connection):
"""Register the UUID extension from the psycopg2.extra module
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extras.register_uuid(conn_or_curs=connection)
@property
def _status(self):
"""Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queries.Session.READY: Connected, no active transaction
:rtype: int
"""
if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
return self.READY
return self._conn.status
<MSG> Merge pull request #21 from nvllsvm/master
Typos and consistency
<DFF> @@ -45,7 +45,7 @@ DEFAULT_ENCODING = 'UTF8'
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, pythoic
+ act as a context manager, providing automated cleanup and simple, Pythonic
way of interacting with the object.
:param str uri: PostgreSQL connection URI
@@ -145,7 +145,7 @@ class Session(object):
@property
def connection(self):
- """The current open connection to PostgreSQL.
+ """Return the current open connection to PostgreSQL.
:rtype: psycopg2.extensions.connection
@@ -154,7 +154,7 @@ class Session(object):
@property
def cursor(self):
- """The current, active cursor for the open connection.
+ """Return the current, active cursor for the open connection.
:rtype: psycopg2.extensions.cursor
@@ -163,7 +163,7 @@ class Session(object):
@property
def encoding(self):
- """The current client encoding value.
+ """Return the current client encoding value.
:rtype: str
@@ -172,7 +172,7 @@ class Session(object):
@property
def notices(self):
- """A list of up to the last 50 server notices sent to the client.
+ """Return a list of up to the last 50 server notices sent to the client.
:rtype: list
@@ -181,7 +181,7 @@ class Session(object):
@property
def pid(self):
- """Return the pool ID used for connection pooling
+ """Return the pool ID used for connection pooling.
:rtype: str
| 6 | Merge pull request #21 from nvllsvm/master | 6 | .py | py | bsd-3-clause | gmr/queries |
1381 | <NME> .checkignore
<BEF> ADDFILE
<MSG> Add for quantified code
<DFF> @@ -0,0 +1,2 @@
+setup.py
+tests
| 2 | Add for quantified code | 0 | checkignore | bsd-3-clause | gmr/queries |
|
1382 | <NME> .checkignore
<BEF> ADDFILE
<MSG> Add for quantified code
<DFF> @@ -0,0 +1,2 @@
+setup.py
+tests
| 2 | Add for quantified code | 0 | checkignore | bsd-3-clause | gmr/queries |
|
1383 | <NME> history.rst
<BEF> Version History
===============
-----------------
- Narrow the pin to psycopg2 < 2.8 due to a breaking change
- Fix Results iterator for Python 3.7 (#31 - `nvllsvm <https://github.com/nvllsvm>`_)
2.0.0 2018-01-29
-----------------
- REMOVED support for Python 2.6
- FIXED CPU Pegging bug: Cleanup IOLoop and internal stack in ``TornadoSession`` on connection error. In the case of a connection error, the failure to do this caused CPU to peg @ 100% utilization looping on a non-existent file descriptor. Thanks to `cknave <https://github.com/cknave>`_ for his work on identifying the issue, proposing a fix, and writing a working test case.
- Move the integration tests to use a local docker development environment
- Added new methods ``queries.pool.Pool.report`` and ``queries.pool.PoolManager.Report`` for reporting pool status.
- Added new methods to ``queries.pool.Pool`` for returning a list of busy, closed, executing, and locked connections.
1.10.4 2018-01-10
-----------------
- Implement ``Results.__bool__`` to be explicit about Python 3 support.
- Catch any exception raised when using TornadoSession and invoking the execute function in psycopg2 for exceptions raised prior to sending the query to Postgres.
This could be psycopg2.Error, IndexError, KeyError, or who knows, it's not documented in psycopg2.
1.10.3 2017-11-01
-----------------
- Remove the functionality from ``TornadoSession.validate`` and make it raise a ``DeprecationWarning``
- Catch the ``KeyError`` raised when ``PoolManager.clean()`` is invoked for a pool that doesn't exist
1.10.2 2017-10-26
-----------------
- Ensure the pool exists when executing a query in TornadoSession, the new timeout behavior prevented that from happening.
1.10.1 2017-10-24
-----------------
- Use an absolute time in the call to ``add_timeout``
1.10.0 2017-09-27
-----------------
- Free when tornado_session.Result is ``__del__``'d without ``free`` being called.
- Auto-clean the pool after Results.free TTL+1 in tornado_session.TornadoSession
- Don't raise NotImplementedError in Results.free for synchronous use, just treat as a noop
1.9.1 2016-10-25
----------------
- Add better exception handling around connections and getting the logged in user
1.9.0 2016-07-01
----------------
- Handle a potential race condition in TornadoSession when too many simultaneous new connections are made and a pool fills up
- Increase logging in various places to be more informative
- Restructure queries specific exceptions to all extend off of a base QueriesException
- Trivial code cleanup
1.8.10 2016-06-14
-----------------
- Propagate PoolManager exceptions from TornadoSession (#20) - Fix by Dave Shawley
1.8.9 2015-11-11
----------------
- Move to psycopg2cffi for PyPy support
1.7.5 2015-09-03
----------------
- Don't let Session and TornadoSession share connections
1.7.1 2015-03-25
----------------
- Fix TornadoSession's use of cleanup (#8) - Fix by Oren Itamar
1.7.0 2015-01-13
----------------
- Implement :py:meth:`Pool.shutdown <queries.pool.Pool.shutdown>` and :py:meth:`PoolManager.shutdown <queries.pool.PoolManager.shutdown>` to
cleanly shutdown all open, non-executing connections across a Pool or all pools. Update locks in Pool operations to ensure atomicity.
1.6.1 2015-01-09
----------------
- Fixes an iteration error when closing a pool (#7) - Fix by Chris McGuire
1.6.0 2014-11-20
-----------------
- Handle URI encoded password values properly
1.5.0 2014-10-07
----------------
- Handle empty query results in the iterator (#4) - Fix by Den Teresh
1.4.0 2014-09-04
----------------
- Address exception handling in tornado_session
<MSG> Add to version history [ci-skip]
<DFF> @@ -1,2 +1,4 @@
Version History
-===============
\ No newline at end of file
+===============
+- 1.4.0 2014-09-04
+ - Address exception handling in tornado_session
| 3 | Add to version history [ci-skip] | 1 | .rst | rst | bsd-3-clause | gmr/queries |
1384 | <NME> history.rst
<BEF> Version History
===============
-----------------
- Narrow the pin to psycopg2 < 2.8 due to a breaking change
- Fix Results iterator for Python 3.7 (#31 - `nvllsvm <https://github.com/nvllsvm>`_)
2.0.0 2018-01-29
-----------------
- REMOVED support for Python 2.6
- FIXED CPU Pegging bug: Cleanup IOLoop and internal stack in ``TornadoSession`` on connection error. In the case of a connection error, the failure to do this caused CPU to peg @ 100% utilization looping on a non-existent file descriptor. Thanks to `cknave <https://github.com/cknave>`_ for his work on identifying the issue, proposing a fix, and writing a working test case.
- Move the integration tests to use a local docker development environment
- Added new methods ``queries.pool.Pool.report`` and ``queries.pool.PoolManager.Report`` for reporting pool status.
- Added new methods to ``queries.pool.Pool`` for returning a list of busy, closed, executing, and locked connections.
1.10.4 2018-01-10
-----------------
- Implement ``Results.__bool__`` to be explicit about Python 3 support.
- Catch any exception raised when using TornadoSession and invoking the execute function in psycopg2 for exceptions raised prior to sending the query to Postgres.
This could be psycopg2.Error, IndexError, KeyError, or who knows, it's not documented in psycopg2.
1.10.3 2017-11-01
-----------------
- Remove the functionality from ``TornadoSession.validate`` and make it raise a ``DeprecationWarning``
- Catch the ``KeyError`` raised when ``PoolManager.clean()`` is invoked for a pool that doesn't exist
1.10.2 2017-10-26
-----------------
- Ensure the pool exists when executing a query in TornadoSession, the new timeout behavior prevented that from happening.
1.10.1 2017-10-24
-----------------
- Use an absolute time in the call to ``add_timeout``
1.10.0 2017-09-27
-----------------
- Free when tornado_session.Result is ``__del__``'d without ``free`` being called.
- Auto-clean the pool after Results.free TTL+1 in tornado_session.TornadoSession
- Don't raise NotImplementedError in Results.free for synchronous use, just treat as a noop
1.9.1 2016-10-25
----------------
- Add better exception handling around connections and getting the logged in user
1.9.0 2016-07-01
----------------
- Handle a potential race condition in TornadoSession when too many simultaneous new connections are made and a pool fills up
- Increase logging in various places to be more informative
- Restructure queries specific exceptions to all extend off of a base QueriesException
- Trivial code cleanup
1.8.10 2016-06-14
-----------------
- Propagate PoolManager exceptions from TornadoSession (#20) - Fix by Dave Shawley
1.8.9 2015-11-11
----------------
- Move to psycopg2cffi for PyPy support
1.7.5 2015-09-03
----------------
- Don't let Session and TornadoSession share connections
1.7.1 2015-03-25
----------------
- Fix TornadoSession's use of cleanup (#8) - Fix by Oren Itamar
1.7.0 2015-01-13
----------------
- Implement :py:meth:`Pool.shutdown <queries.pool.Pool.shutdown>` and :py:meth:`PoolManager.shutdown <queries.pool.PoolManager.shutdown>` to
cleanly shutdown all open, non-executing connections across a Pool or all pools. Update locks in Pool operations to ensure atomicity.
1.6.1 2015-01-09
----------------
- Fixes an iteration error when closing a pool (#7) - Fix by Chris McGuire
1.6.0 2014-11-20
-----------------
- Handle URI encoded password values properly
1.5.0 2014-10-07
----------------
- Handle empty query results in the iterator (#4) - Fix by Den Teresh
1.4.0 2014-09-04
----------------
- Address exception handling in tornado_session
<MSG> Add to version history [ci-skip]
<DFF> @@ -1,2 +1,4 @@
Version History
-===============
\ No newline at end of file
+===============
+- 1.4.0 2014-09-04
+ - Address exception handling in tornado_session
| 3 | Add to version history [ci-skip] | 1 | .rst | rst | bsd-3-clause | gmr/queries |
1385 | <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> Add 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 | Add python 3.4 | 1 | .yml | travis | bsd-3-clause | gmr/queries |
1386 | <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> Add 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 | Add python 3.4 | 1 | .yml | travis | bsd-3-clause | gmr/queries |
1387 | <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._connections = dict()
self._futures = dict()
self._listeners = dict()
self._cursor_factory = cursor_factory
self._ioloop = io_loop or ioloop.IOLoop.instance()
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
"""
return self._execute('callproc', name, args)
@gen.coroutine
def listen(self, channel, callback):
"""Listen for notifications from PostgreSQL on the specified channel,
passing in a callback to receive the notifications.
:param str channel: The channel to stop listening on
:param method callback: The method to call on each notification
"""
conn = yield self._connect()
# Get the cursor
cursor = self._get_cursor(conn)
# Add the channel and callback to the class level listeners
self._listeners[channel] = (conn.fileno(), 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, conn.fileno()))
# Iterate through all of the notifications
while conn.notifies:
notify = conn.notifies.pop()
callback(channel, notify.pid, notify.payload)
# Set a new callback for the fd if we're not exiting
if channel in self._listeners:
self._futures[conn.fileno()] = \
yield gen.Callback((self, conn.fileno()))
def query(self, sql, parameters=None):
"""Issue a query asynchronously on the server, mogrifying the
parameters against the sql statement and yielding the results
"""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
"""
return self._execute('execute', sql, parameters)
def unlisten(self, channel):
"""Cancel a listening to notifications on a PostgreSQL notification
channel.
: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._futures[fd] = concurrent.Future()
# Create a callback, unlisten and wait for the result
self._futures[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, either by reusing a connection from the pool
if possible, or by creating the new connection.
"""Validate the session can connect or has open connections to
PostgreSQL. As of ``1.10.3``
.. deprecated:: 1.10.3
As of 1.10.3, this method only warns about Deprecation
:rtype: bool
"""
warnings.warn(
'All functionality removed from this method', DeprecationWarning)
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
if possible, or by creating the new connection.
:rtype: psycopg2.extensions.connection
:raises: pool.NoIdleConnectionsError
"""
future = concurrent.Future()
# Attempt to get a cached connection from the connection pool
try:
connection = self._pool_manager.get(self.pid, self)
self._connections[connection.fileno()] = connection
future.set_result(connection)
# Add the connection to the IOLoop
self._ioloop.add_handler(connection.fileno(),
self._on_io_events,
ioloop.IOLoop.WRITE)
except pool.NoIdleConnectionsError:
self._create_connection(future)
return future
def _create_connection(self, future):
"""Create a new PostgreSQL connection
:param tornado.concurrent.Future future: future for new conn result
"""
LOGGER.debug('Creating a new connection for %s', self.pid)
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
try:
connection = self._psycopg2_connect(kwargs)
except (psycopg2.Error, OSError, socket.error) as error:
future.set_exception(error)
return
# Add the connection for use in _poll_connection
fd = connection.fileno()
self._connections[fd] = connection
def on_connected(cf):
"""Invoked by the IOLoop when the future is complete for the
connection
:param Future cf: The future for the initial connection
"""
if cf.exception():
self._cleanup_fd(fd, True)
future.set_exception(cf.exception())
else:
try:
# Add the connection to the pool
LOGGER.debug('Connection established for %s', self.pid)
self._pool_manager.add(self.pid, connection)
except (ValueError, pool.PoolException) as err:
LOGGER.exception('Failed to add %r to the pool', self.pid)
self._cleanup_fd(fd)
future.set_exception(err)
return
self._pool_manager.lock(self.pid, connection, self)
# Added in because psycopg2cffi connects and leaves the
# connection in a weird state: consts.STATUS_DATESTYLE,
# returning from Connection._setup without setting the state
# as const.STATUS_OK
if utils.PYPY:
connection.status = extensions.STATUS_READY
# Register the custom data types
self._register_unicode(connection)
self._register_uuid(connection)
# Set the future result
future.set_result(connection)
# Add a future that fires once connected
self._futures[fd] = concurrent.Future()
self._ioloop.add_future(self._futures[fd], on_connected)
# Add the connection to the IOLoop
self._ioloop.add_handler(connection.fileno(),
self._on_io_events,
ioloop.IOLoop.WRITE)
def _execute(self, method, query, parameters=None):
"""Issue a query asynchronously on the server, mogrifying the
parameters against the sql statement and yielding the results
as a :py:class:`Results <queries.tornado_session.Results>` object.
This function reduces duplicate code for callproc and query by getting
the class attribute for the method passed in as the function to call.
:param str method: The method attribute to use
:param str query: The SQL statement or Stored Procedure name
:param list|dict parameters: A dictionary of query parameters
:rtype: Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
future = concurrent.Future()
def on_connected(cf):
"""Invoked by the future returned by self._connect"""
if cf.exception():
future.set_exception(cf.exception())
return
# Get the psycopg2 connection object and cursor
conn = cf.result()
cursor = self._get_cursor(conn)
def completed(qf):
"""Invoked by the IOLoop when the future has completed"""
if qf.exception():
self._incr_exceptions(conn)
err = qf.exception()
LOGGER.debug('Cleaning cursor due to exception: %r', err)
self._exec_cleanup(cursor, conn.fileno())
future.set_exception(err)
else:
self._incr_executions(conn)
value = Results(cursor, self._exec_cleanup, conn.fileno())
future.set_result(value)
# Setup a callback to wait on the query result
self._futures[conn.fileno()] = concurrent.Future()
# Add the future to the IOLoop
self._ioloop.add_future(self._futures[conn.fileno()],
completed)
# Get the cursor, execute the query
func = getattr(cursor, method)
try:
func(query, parameters)
except Exception as error:
future.set_exception(error)
# Ensure the pool exists for the connection
self._ensure_pool_exists()
# Grab a connection to PostgreSQL
self._ioloop.add_future(self._connect(), on_connected)
# Return the future for the query result
return future
def _exec_cleanup(self, cursor, fd):
"""Close the cursor, remove any references to the fd in internal state
and remove the fd from the ioloop.
:param psycopg2.extensions.cursor cursor: The cursor to close
:param int fd: The connection file descriptor
"""
LOGGER.debug('Closing cursor and cleaning %s', fd)
try:
cursor.close()
except (psycopg2.Error, psycopg2.Warning) as error:
LOGGER.debug('Error closing the cursor: %s', error)
self._cleanup_fd(fd)
# If the cleanup callback exists, remove it
if self._cleanup_callback:
self._ioloop.remove_timeout(self._cleanup_callback)
# Create a new cleanup callback to clean the pool of idle connections
self._cleanup_callback = self._ioloop.add_timeout(
self._ioloop.time() + self._pool_idle_ttl + 1,
self._pool_manager.clean, self.pid)
def _cleanup_fd(self, fd, close=False):
"""Ensure the socket socket is removed from the IOLoop, the
connection stack, and futures stack.
:param int fd: The fd # to cleanup
"""
self._ioloop.remove_handler(fd)
if fd in self._connections:
try:
self._pool_manager.free(self.pid, self._connections[fd])
except pool.ConnectionNotFoundError:
pass
if close:
self._connections[fd].close()
del self._connections[fd]
if fd in self._futures:
del self._futures[fd]
def _incr_exceptions(self, conn):
"""Increment the number of exceptions for the current connection.
:param psycopg2.extensions.connection conn: the psycopg2 connection
"""
self._pool_manager.get_connection(self.pid, conn).exceptions += 1
def _incr_executions(self, conn):
"""Increment the number of executions for the current connection.
:param psycopg2.extensions.connection conn: the psycopg2 connection
"""
self._pool_manager.get_connection(self.pid, conn).executions += 1
def _on_io_events(self, fd=None, _events=None):
"""Invoked by Tornado's IOLoop when there are events for the fd
:param int fd: The file descriptor for the event
:param int _events: The events raised
"""
if fd not in self._connections:
LOGGER.warning('Received IO event for non-existing connection')
return
self._poll_connection(fd)
def _poll_connection(self, fd):
"""Check with psycopg2 to see what action to take. If the state is
POLL_OK, we should have a pending callback for that fd.
:param int fd: The socket fd for the postgresql connection
"""
try:
state = self._connections[fd].poll()
except (OSError, socket.error) as error:
self._ioloop.remove_handler(fd)
if fd in self._futures and not self._futures[fd].done():
self._futures[fd].set_exception(
psycopg2.OperationalError('Connection error (%s)' % error)
)
except (psycopg2.Error, psycopg2.Warning) as error:
if fd in self._futures and not self._futures[fd].done():
self._futures[fd].set_exception(error)
else:
if state == extensions.POLL_OK:
if fd in self._futures and not self._futures[fd].done():
self._futures[fd].set_result(True)
elif state == extensions.POLL_WRITE:
self._ioloop.update_handler(fd, ioloop.IOLoop.WRITE)
elif state == extensions.POLL_READ:
self._ioloop.update_handler(fd, ioloop.IOLoop.READ)
elif state == extensions.POLL_ERROR:
self._ioloop.remove_handler(fd)
if fd in self._futures and not self._futures[fd].done():
self._futures[fd].set_exception(
psycopg2.Error('Poll Error'))
def _psycopg2_connect(self, kwargs):
"""Return a psycopg2 connection for the specified kwargs. Extend for
use in async session adapters.
:param dict kwargs: Keyword connection args
:rtype: psycopg2.extensions.connection
"""
kwargs['async'] = True
return psycopg2.connect(**kwargs)
<MSG> Remove LISTEN/NOTIFY support in tornado_session
<DFF> @@ -155,7 +155,6 @@ class TornadoSession(session.Session):
"""
self._connections = dict()
self._futures = dict()
- self._listeners = dict()
self._cursor_factory = cursor_factory
self._ioloop = io_loop or ioloop.IOLoop.instance()
@@ -203,42 +202,6 @@ class TornadoSession(session.Session):
"""
return self._execute('callproc', name, args)
- @gen.coroutine
- def listen(self, channel, callback):
- """Listen for notifications from PostgreSQL on the specified channel,
- passing in a callback to receive the notifications.
-
- :param str channel: The channel to stop listening on
- :param method callback: The method to call on each notification
-
- """
- conn = yield self._connect()
-
- # Get the cursor
- cursor = self._get_cursor(conn)
-
- # Add the channel and callback to the class level listeners
- self._listeners[channel] = (conn.fileno(), 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, conn.fileno()))
-
- # Iterate through all of the notifications
- while conn.notifies:
- notify = conn.notifies.pop()
- callback(channel, notify.pid, notify.payload)
-
- # Set a new callback for the fd if we're not exiting
- if channel in self._listeners:
- self._futures[conn.fileno()] = \
- yield gen.Callback((self, conn.fileno()))
-
def query(self, sql, parameters=None):
"""Issue a query asynchronously on the server, mogrifying the
parameters against the sql statement and yielding the results
@@ -263,31 +226,6 @@ class TornadoSession(session.Session):
"""
return self._execute('execute', sql, parameters)
- def unlisten(self, channel):
- """Cancel a listening to notifications on a PostgreSQL notification
- channel.
-
- :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._futures[fd] = concurrent.Future()
-
- # Create a callback, unlisten and wait for the result
- self._futures[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, either by reusing a connection from the pool
if possible, or by creating the new connection.
| 0 | Remove LISTEN/NOTIFY support in tornado_session | 62 | .py | py | bsd-3-clause | gmr/queries |
1388 | <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._connections = dict()
self._futures = dict()
self._listeners = dict()
self._cursor_factory = cursor_factory
self._ioloop = io_loop or ioloop.IOLoop.instance()
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
"""
return self._execute('callproc', name, args)
@gen.coroutine
def listen(self, channel, callback):
"""Listen for notifications from PostgreSQL on the specified channel,
passing in a callback to receive the notifications.
:param str channel: The channel to stop listening on
:param method callback: The method to call on each notification
"""
conn = yield self._connect()
# Get the cursor
cursor = self._get_cursor(conn)
# Add the channel and callback to the class level listeners
self._listeners[channel] = (conn.fileno(), 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, conn.fileno()))
# Iterate through all of the notifications
while conn.notifies:
notify = conn.notifies.pop()
callback(channel, notify.pid, notify.payload)
# Set a new callback for the fd if we're not exiting
if channel in self._listeners:
self._futures[conn.fileno()] = \
yield gen.Callback((self, conn.fileno()))
def query(self, sql, parameters=None):
"""Issue a query asynchronously on the server, mogrifying the
parameters against the sql statement and yielding the results
"""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
"""
return self._execute('execute', sql, parameters)
def unlisten(self, channel):
"""Cancel a listening to notifications on a PostgreSQL notification
channel.
: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._futures[fd] = concurrent.Future()
# Create a callback, unlisten and wait for the result
self._futures[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, either by reusing a connection from the pool
if possible, or by creating the new connection.
"""Validate the session can connect or has open connections to
PostgreSQL. As of ``1.10.3``
.. deprecated:: 1.10.3
As of 1.10.3, this method only warns about Deprecation
:rtype: bool
"""
warnings.warn(
'All functionality removed from this method', DeprecationWarning)
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
if possible, or by creating the new connection.
:rtype: psycopg2.extensions.connection
:raises: pool.NoIdleConnectionsError
"""
future = concurrent.Future()
# Attempt to get a cached connection from the connection pool
try:
connection = self._pool_manager.get(self.pid, self)
self._connections[connection.fileno()] = connection
future.set_result(connection)
# Add the connection to the IOLoop
self._ioloop.add_handler(connection.fileno(),
self._on_io_events,
ioloop.IOLoop.WRITE)
except pool.NoIdleConnectionsError:
self._create_connection(future)
return future
def _create_connection(self, future):
"""Create a new PostgreSQL connection
:param tornado.concurrent.Future future: future for new conn result
"""
LOGGER.debug('Creating a new connection for %s', self.pid)
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
try:
connection = self._psycopg2_connect(kwargs)
except (psycopg2.Error, OSError, socket.error) as error:
future.set_exception(error)
return
# Add the connection for use in _poll_connection
fd = connection.fileno()
self._connections[fd] = connection
def on_connected(cf):
"""Invoked by the IOLoop when the future is complete for the
connection
:param Future cf: The future for the initial connection
"""
if cf.exception():
self._cleanup_fd(fd, True)
future.set_exception(cf.exception())
else:
try:
# Add the connection to the pool
LOGGER.debug('Connection established for %s', self.pid)
self._pool_manager.add(self.pid, connection)
except (ValueError, pool.PoolException) as err:
LOGGER.exception('Failed to add %r to the pool', self.pid)
self._cleanup_fd(fd)
future.set_exception(err)
return
self._pool_manager.lock(self.pid, connection, self)
# Added in because psycopg2cffi connects and leaves the
# connection in a weird state: consts.STATUS_DATESTYLE,
# returning from Connection._setup without setting the state
# as const.STATUS_OK
if utils.PYPY:
connection.status = extensions.STATUS_READY
# Register the custom data types
self._register_unicode(connection)
self._register_uuid(connection)
# Set the future result
future.set_result(connection)
# Add a future that fires once connected
self._futures[fd] = concurrent.Future()
self._ioloop.add_future(self._futures[fd], on_connected)
# Add the connection to the IOLoop
self._ioloop.add_handler(connection.fileno(),
self._on_io_events,
ioloop.IOLoop.WRITE)
def _execute(self, method, query, parameters=None):
"""Issue a query asynchronously on the server, mogrifying the
parameters against the sql statement and yielding the results
as a :py:class:`Results <queries.tornado_session.Results>` object.
This function reduces duplicate code for callproc and query by getting
the class attribute for the method passed in as the function to call.
:param str method: The method attribute to use
:param str query: The SQL statement or Stored Procedure name
:param list|dict parameters: A dictionary of query parameters
:rtype: Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
future = concurrent.Future()
def on_connected(cf):
"""Invoked by the future returned by self._connect"""
if cf.exception():
future.set_exception(cf.exception())
return
# Get the psycopg2 connection object and cursor
conn = cf.result()
cursor = self._get_cursor(conn)
def completed(qf):
"""Invoked by the IOLoop when the future has completed"""
if qf.exception():
self._incr_exceptions(conn)
err = qf.exception()
LOGGER.debug('Cleaning cursor due to exception: %r', err)
self._exec_cleanup(cursor, conn.fileno())
future.set_exception(err)
else:
self._incr_executions(conn)
value = Results(cursor, self._exec_cleanup, conn.fileno())
future.set_result(value)
# Setup a callback to wait on the query result
self._futures[conn.fileno()] = concurrent.Future()
# Add the future to the IOLoop
self._ioloop.add_future(self._futures[conn.fileno()],
completed)
# Get the cursor, execute the query
func = getattr(cursor, method)
try:
func(query, parameters)
except Exception as error:
future.set_exception(error)
# Ensure the pool exists for the connection
self._ensure_pool_exists()
# Grab a connection to PostgreSQL
self._ioloop.add_future(self._connect(), on_connected)
# Return the future for the query result
return future
def _exec_cleanup(self, cursor, fd):
"""Close the cursor, remove any references to the fd in internal state
and remove the fd from the ioloop.
:param psycopg2.extensions.cursor cursor: The cursor to close
:param int fd: The connection file descriptor
"""
LOGGER.debug('Closing cursor and cleaning %s', fd)
try:
cursor.close()
except (psycopg2.Error, psycopg2.Warning) as error:
LOGGER.debug('Error closing the cursor: %s', error)
self._cleanup_fd(fd)
# If the cleanup callback exists, remove it
if self._cleanup_callback:
self._ioloop.remove_timeout(self._cleanup_callback)
# Create a new cleanup callback to clean the pool of idle connections
self._cleanup_callback = self._ioloop.add_timeout(
self._ioloop.time() + self._pool_idle_ttl + 1,
self._pool_manager.clean, self.pid)
def _cleanup_fd(self, fd, close=False):
"""Ensure the socket socket is removed from the IOLoop, the
connection stack, and futures stack.
:param int fd: The fd # to cleanup
"""
self._ioloop.remove_handler(fd)
if fd in self._connections:
try:
self._pool_manager.free(self.pid, self._connections[fd])
except pool.ConnectionNotFoundError:
pass
if close:
self._connections[fd].close()
del self._connections[fd]
if fd in self._futures:
del self._futures[fd]
def _incr_exceptions(self, conn):
"""Increment the number of exceptions for the current connection.
:param psycopg2.extensions.connection conn: the psycopg2 connection
"""
self._pool_manager.get_connection(self.pid, conn).exceptions += 1
def _incr_executions(self, conn):
"""Increment the number of executions for the current connection.
:param psycopg2.extensions.connection conn: the psycopg2 connection
"""
self._pool_manager.get_connection(self.pid, conn).executions += 1
def _on_io_events(self, fd=None, _events=None):
"""Invoked by Tornado's IOLoop when there are events for the fd
:param int fd: The file descriptor for the event
:param int _events: The events raised
"""
if fd not in self._connections:
LOGGER.warning('Received IO event for non-existing connection')
return
self._poll_connection(fd)
def _poll_connection(self, fd):
"""Check with psycopg2 to see what action to take. If the state is
POLL_OK, we should have a pending callback for that fd.
:param int fd: The socket fd for the postgresql connection
"""
try:
state = self._connections[fd].poll()
except (OSError, socket.error) as error:
self._ioloop.remove_handler(fd)
if fd in self._futures and not self._futures[fd].done():
self._futures[fd].set_exception(
psycopg2.OperationalError('Connection error (%s)' % error)
)
except (psycopg2.Error, psycopg2.Warning) as error:
if fd in self._futures and not self._futures[fd].done():
self._futures[fd].set_exception(error)
else:
if state == extensions.POLL_OK:
if fd in self._futures and not self._futures[fd].done():
self._futures[fd].set_result(True)
elif state == extensions.POLL_WRITE:
self._ioloop.update_handler(fd, ioloop.IOLoop.WRITE)
elif state == extensions.POLL_READ:
self._ioloop.update_handler(fd, ioloop.IOLoop.READ)
elif state == extensions.POLL_ERROR:
self._ioloop.remove_handler(fd)
if fd in self._futures and not self._futures[fd].done():
self._futures[fd].set_exception(
psycopg2.Error('Poll Error'))
def _psycopg2_connect(self, kwargs):
"""Return a psycopg2 connection for the specified kwargs. Extend for
use in async session adapters.
:param dict kwargs: Keyword connection args
:rtype: psycopg2.extensions.connection
"""
kwargs['async'] = True
return psycopg2.connect(**kwargs)
<MSG> Remove LISTEN/NOTIFY support in tornado_session
<DFF> @@ -155,7 +155,6 @@ class TornadoSession(session.Session):
"""
self._connections = dict()
self._futures = dict()
- self._listeners = dict()
self._cursor_factory = cursor_factory
self._ioloop = io_loop or ioloop.IOLoop.instance()
@@ -203,42 +202,6 @@ class TornadoSession(session.Session):
"""
return self._execute('callproc', name, args)
- @gen.coroutine
- def listen(self, channel, callback):
- """Listen for notifications from PostgreSQL on the specified channel,
- passing in a callback to receive the notifications.
-
- :param str channel: The channel to stop listening on
- :param method callback: The method to call on each notification
-
- """
- conn = yield self._connect()
-
- # Get the cursor
- cursor = self._get_cursor(conn)
-
- # Add the channel and callback to the class level listeners
- self._listeners[channel] = (conn.fileno(), 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, conn.fileno()))
-
- # Iterate through all of the notifications
- while conn.notifies:
- notify = conn.notifies.pop()
- callback(channel, notify.pid, notify.payload)
-
- # Set a new callback for the fd if we're not exiting
- if channel in self._listeners:
- self._futures[conn.fileno()] = \
- yield gen.Callback((self, conn.fileno()))
-
def query(self, sql, parameters=None):
"""Issue a query asynchronously on the server, mogrifying the
parameters against the sql statement and yielding the results
@@ -263,31 +226,6 @@ class TornadoSession(session.Session):
"""
return self._execute('execute', sql, parameters)
- def unlisten(self, channel):
- """Cancel a listening to notifications on a PostgreSQL notification
- channel.
-
- :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._futures[fd] = concurrent.Future()
-
- # Create a callback, unlisten and wait for the result
- self._futures[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, either by reusing a connection from the pool
if possible, or by creating the new connection.
| 0 | Remove LISTEN/NOTIFY support in tornado_session | 62 | .py | py | bsd-3-clause | gmr/queries |
1389 | <NME> pool.py
<BEF> """
Connection Pooling
"""
import logging
import threading
import time
import weakref
import weakref
LOGGER = logging.getLogger(__name__)
DEFAULT_IDLE_TTL = 60
DEFAULT_MAX_SIZE = 1
class Connection(object):
class Connection(object):
"""Contains the handle to the connection, the current state of the
connection and methods for manipulating the state of the connection.
"""
_lock = threading.Lock()
def __init__(self, handle):
self.handle = handle
self.used_by = None
self.executions = 0
self.exceptions = 0
def close(self):
"""Close the connection
:raises: ConnectionBusyError
"""
LOGGER.debug('Connection %s closing', self.id)
if self.busy and not self.closed:
raise ConnectionBusyError(self)
with self._lock:
if not self.handle.closed:
try:
self.handle.close()
except psycopg2.InterfaceError as error:
LOGGER.error('Error closing socket: %s', error)
@property
def closed(self):
"""Return if the psycopg2 connection is closed.
:rtype: bool
"""
return self.handle.closed != 0
@property
def busy(self):
"""Return if the connection is currently executing a query or is locked
by a session that still exists.
:rtype: bool
"""
if self.handle.isexecuting():
return True
elif self.used_by is None:
return False
return not self.used_by() is None
@property
def executing(self):
"""Return if the connection is currently executing a query
:rtype: bool
"""
return self.handle.isexecuting()
def free(self):
"""Remove the lock on the connection if the connection is not active
:raises: ConnectionBusyError
"""
LOGGER.debug('Connection %s freeing', self.id)
if self.handle.isexecuting():
raise ConnectionBusyError(self)
with self._lock:
self.used_by = None
LOGGER.debug('Connection %s freed', self.id)
@property
def id(self):
"""Return id of the psycopg2 connection object
:rtype: int
"""
return id(self.handle)
def lock(self, session):
"""Lock the connection, ensuring that it is not busy and storing
a weakref for the session.
:param queries.Session session: The session to lock the connection with
:raises: ConnectionBusyError
"""
if self.busy:
raise ConnectionBusyError(self)
with self._lock:
self.used_by = weakref.ref(session)
LOGGER.debug('Connection %s locked', self.id)
@property
def locked(self):
"""Return if the connection is currently exclusively locked
:rtype: bool
"""
return self.used_by is not None
class Pool(object):
"""A connection pool for gaining access to and managing connections"""
_lock = threading.Lock()
idle_start = None
idle_ttl = DEFAULT_IDLE_TTL
max_size = DEFAULT_MAX_SIZE
def __init__(self,
pool_id,
idle_ttl=DEFAULT_IDLE_TTL,
max_size=DEFAULT_MAX_SIZE,
time_method=None):
self.connections = {}
self._id = pool_id
self.idle_ttl = idle_ttl
self.max_size = max_size
self.time_method = time_method or time.time
def __contains__(self, connection):
"""Return True if the pool contains the connection"""
return id(connection) in self.connections
def __len__(self):
"""Return the number of connections in the pool"""
return len(self.connections)
def add(self, connection):
"""Add a new connection to the pool
:param connection: The connection to add to the pool
:type connection: psycopg2.extensions.connection
:raises: PoolFullError
"""
if id(connection) in self.connections:
raise ValueError('Connection already exists in pool')
if len(self.connections) == self.max_size:
LOGGER.warning('Race condition found when adding new connection')
try:
connection.close()
except (psycopg2.Error, psycopg2.Warning) as error:
LOGGER.error('Error closing the conn that cant be used: %s',
error)
raise PoolFullError(self)
with self._lock:
self.connections[id(connection)] = Connection(connection)
LOGGER.debug('Pool %s added connection %s', self.id, id(connection))
@property
def busy_connections(self):
"""Return a list of active/busy connections
:rtype: list
"""
return [c for c in self.connections.values()
if c.busy and not c.closed]
def clean(self):
"""Clean the pool by removing any closed connections and if the pool's
idle has exceeded its idle TTL, remove all connections.
"""
LOGGER.debug('Cleaning the pool')
for connection in [self.connections[k] for k in self.connections if
self.connections[k].closed]:
LOGGER.debug('Removing %s', connection.id)
self.remove(connection.handle)
if self.idle_duration > self.idle_ttl:
self.close()
LOGGER.debug('Pool %s cleaned', self.id)
def close(self):
"""Close the pool by closing and removing all of the connections"""
for cid in list(self.connections.keys()):
self.remove(self.connections[cid].handle)
LOGGER.debug('Pool %s closed', self.id)
@property
def closed_connections(self):
"""Return a list of closed connections
:rtype: list
"""
return [c for c in self.connections.values() if c.closed]
def connection_handle(self, connection):
"""Return a connection object for the given psycopg2 connection
:param connection: The connection to return a parent for
:type connection: psycopg2.extensions.connection
:rtype: Connection
"""
return self.connections[id(connection)]
@property
def executing_connections(self):
"""Return a list of connections actively executing queries
:rtype: list
"""
return [c for c in self.connections.values() if c.executing]
def free(self, connection):
"""Free the connection from use by the session that was using it.
:param connection: The connection to free
:type connection: psycopg2.extensions.connection
:raises: ConnectionNotFoundError
"""
LOGGER.debug('Pool %s freeing connection %s', self.id, id(connection))
try:
self.connection_handle(connection).free()
except KeyError:
raise ConnectionNotFoundError(self.id, id(connection))
if self.idle_connections == list(self.connections.values()):
with self._lock:
self.idle_start = self.time_method()
LOGGER.debug('Pool %s freed connection %s', self.id, id(connection))
def get(self, session):
"""Return an idle connection and assign the session to the connection
:param queries.Session session: The session to assign
:rtype: psycopg2.extensions.connection
:raises: NoIdleConnectionsError
"""
idle = self.idle_connections
if idle:
connection = idle.pop(0)
connection.lock(session)
if self.idle_start:
with self._lock:
self.idle_start = None
return connection.handle
raise NoIdleConnectionsError(self.id)
@property
def id(self):
"""Return the ID for this pool
:rtype: str
"""
return self._id
@property
def idle_connections(self):
"""Return a list of idle connections
:rtype: list
"""
return [c for c in self.connections.values()
if not c.busy and not c.closed]
@property
def idle_duration(self):
"""Return the number of seconds that the pool has had no active
connections.
:rtype: float
"""
if self.idle_start is None:
return 0
return self.time_method() - self.idle_start
@property
def is_full(self):
"""Return True if there are no more open slots for connections.
:rtype: bool
"""
return len(self.connections) >= self.max_size
def lock(self, connection, session):
"""Explicitly lock the specified connection
:type connection: psycopg2.extensions.connection
:param connection: The connection to lock
:param queries.Session session: The session to hold the lock
"""
cid = id(connection)
try:
self.connection_handle(connection).lock(session)
except KeyError:
raise ConnectionNotFoundError(self.id, cid)
else:
if self.idle_start:
with self._lock:
self.idle_start = None
LOGGER.debug('Pool %s locked connection %s', self.id, cid)
@property
def locked_connections(self):
"""Return a list of all locked connections
:rtype: list
"""
return [c for c in self.connections.values() if c.locked]
def remove(self, connection):
"""Remove the connection from the pool
:param connection: The connection to remove
:type connection: psycopg2.extensions.connection
:raises: ConnectionNotFoundError
:raises: ConnectionBusyError
"""
cid = id(connection)
if cid not in self.connections:
raise ConnectionNotFoundError(self.id, cid)
self.connection_handle(connection).close()
with self._lock:
del self.connections[cid]
LOGGER.debug('Pool %s removed connection %s', self.id, cid)
def report(self):
"""Return a report about the pool state and configuration.
:rtype: dict
"""
return {
'connections': {
'busy': len(self.busy_connections),
'closed': len(self.closed_connections),
'executing': len(self.executing_connections),
'idle': len(self.idle_connections),
'locked': len(self.busy_connections)
},
'exceptions': sum([c.exceptions
for c in self.connections.values()]),
'executions': sum([c.executions
for c in self.connections.values()]),
'full': self.is_full,
'idle': {
'duration': self.idle_duration,
'ttl': self.idle_ttl
},
'max_size': self.max_size
}
def shutdown(self):
"""Forcefully shutdown the entire pool, closing all non-executing
connections.
:raises: ConnectionBusyError
"""
with self._lock:
for cid in list(self.connections.keys()):
if self.connections[cid].executing:
raise ConnectionBusyError(cid)
if self.connections[cid].locked:
self.connections[cid].free()
self.connections[cid].close()
del self.connections[cid]
def set_idle_ttl(self, ttl):
"""Set the idle ttl
:param int ttl: The TTL when idle
"""
with self._lock:
self.idle_ttl = ttl
def set_max_size(self, size):
"""Set the maximum number of connections
:param int size: The maximum number of connections
"""
with self._lock:
self.max_size = size
class PoolManager(object):
"""The connection pool object implements behavior around connections and
their use in queries.Session objects.
We carry a pool id instead of the connection URI so that we will not be
carrying the URI in memory, creating a possible security issue.
"""
_lock = threading.Lock()
_pools = {}
def __contains__(self, pid):
"""Returns True if the pool exists
:param str pid: The pool id to check for
:rtype: bool
"""
return pid in self.__class__._pools
@classmethod
def instance(cls):
"""Only allow a single PoolManager instance to exist, returning the
handle for it.
:rtype: PoolManager
"""
if not hasattr(cls, '_instance'):
with cls._lock:
cls._instance = cls()
return cls._instance
@classmethod
def add(cls, pid, connection):
"""Add a new connection and session to a pool.
:param str pid: The pool id
:type connection: psycopg2.extensions.connection
:param connection: The connection to add to the pool
"""
with cls._lock:
cls._ensure_pool_exists(pid)
cls._pools[pid].add(connection)
@classmethod
def clean(cls, pid):
"""Clean the specified pool, removing any closed connections or
stale locks.
:param str pid: The pool id to clean
"""
with cls._lock:
try:
cls._ensure_pool_exists(pid)
except KeyError:
LOGGER.debug('Pool clean invoked against missing pool %s', pid)
return
cls._pools[pid].clean()
cls._maybe_remove_pool(pid)
@classmethod
def create(cls, pid, idle_ttl=DEFAULT_IDLE_TTL, max_size=DEFAULT_MAX_SIZE,
time_method=None):
"""Create a new pool, with the ability to pass in values to override
the default idle TTL and the default maximum size.
A pool's idle TTL defines the amount of time that a pool can be open
without any sessions before it is removed.
A pool's max size defines the maximum number of connections that can
be added to the pool to prevent unbounded open connections.
:param str pid: The pool ID
:param int idle_ttl: Time in seconds for the idle TTL
:param int max_size: The maximum pool size
:param callable time_method: Override the use of :py:meth:`time.time`
method for time values.
:raises: KeyError
"""
if pid in cls._pools:
raise KeyError('Pool %s already exists' % pid)
with cls._lock:
LOGGER.debug("Creating Pool: %s (%i/%i)", pid, idle_ttl, max_size)
cls._pools[pid] = Pool(pid, idle_ttl, max_size, time_method)
@classmethod
def free(cls, pid, connection):
"""Free a connection that was locked by a session
:param str pid: The pool ID
:param connection: The connection to remove
:type connection: psycopg2.extensions.connection
"""
with cls._lock:
LOGGER.debug('Freeing %s from pool %s', id(connection), pid)
cls._ensure_pool_exists(pid)
cls._pools[pid].free(connection)
@classmethod
def get(cls, pid, session):
"""Get an idle, unused connection from the pool. Once a connection has
been retrieved, it will be marked as in-use until it is freed.
:param str pid: The pool ID
:param queries.Session session: The session to assign to the connection
:rtype: psycopg2.extensions.connection
"""
with cls._lock:
cls._ensure_pool_exists(pid)
return cls._pools[pid].get(session)
@classmethod
def get_connection(cls, pid, connection):
"""Return the specified :class:`~queries.pool.Connection` from the
pool.
:param str pid: The pool ID
:param connection: The connection to return for
:type connection: psycopg2.extensions.connection
:rtype: queries.pool.Connection
"""
with cls._lock:
return cls._pools[pid].connection_handle(connection)
@classmethod
def has_connection(cls, pid, connection):
"""Check to see if a pool has the specified connection
:param str pid: The pool ID
:param connection: The connection to check for
:type connection: psycopg2.extensions.connection
:rtype: bool
"""
with cls._lock:
cls._ensure_pool_exists(pid)
return connection in cls._pools[pid]
@classmethod
def has_idle_connection(cls, pid):
"""Check to see if a pool has an idle connection
:param str pid: The pool ID
:rtype: bool
"""
with cls._lock:
cls._ensure_pool_exists(pid)
return bool(cls._pools[pid].idle_connections)
@classmethod
def is_full(cls, pid):
"""Return a bool indicating if the specified pool is full
:param str pid: The pool id
:rtype: bool
"""
with cls._lock:
cls._ensure_pool_exists(pid)
return cls._pools[pid].is_full
@classmethod
def lock(cls, pid, connection, session):
"""Explicitly lock the specified connection in the pool
:param str pid: The pool id
:type connection: psycopg2.extensions.connection
:param connection: The connection to add to the pool
: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> Merge pull request #9 from djt5019/add-max-pool-size-environ-variable
Add support for the QUERIES_MAX_POOL_SIZE env var
<DFF> @@ -3,6 +3,7 @@ Connection Pooling
"""
import logging
+import os
import threading
import time
import weakref
@@ -10,7 +11,7 @@ import weakref
LOGGER = logging.getLogger(__name__)
DEFAULT_IDLE_TTL = 60
-DEFAULT_MAX_SIZE = 1
+DEFAULT_MAX_SIZE = os.environ.get('QUERIES_MAX_POOL_SIZE', 1)
class Connection(object):
| 2 | Merge pull request #9 from djt5019/add-max-pool-size-environ-variable | 1 | .py | py | bsd-3-clause | gmr/queries |
1390 | <NME> pool.py
<BEF> """
Connection Pooling
"""
import logging
import threading
import time
import weakref
import weakref
LOGGER = logging.getLogger(__name__)
DEFAULT_IDLE_TTL = 60
DEFAULT_MAX_SIZE = 1
class Connection(object):
class Connection(object):
"""Contains the handle to the connection, the current state of the
connection and methods for manipulating the state of the connection.
"""
_lock = threading.Lock()
def __init__(self, handle):
self.handle = handle
self.used_by = None
self.executions = 0
self.exceptions = 0
def close(self):
"""Close the connection
:raises: ConnectionBusyError
"""
LOGGER.debug('Connection %s closing', self.id)
if self.busy and not self.closed:
raise ConnectionBusyError(self)
with self._lock:
if not self.handle.closed:
try:
self.handle.close()
except psycopg2.InterfaceError as error:
LOGGER.error('Error closing socket: %s', error)
@property
def closed(self):
"""Return if the psycopg2 connection is closed.
:rtype: bool
"""
return self.handle.closed != 0
@property
def busy(self):
"""Return if the connection is currently executing a query or is locked
by a session that still exists.
:rtype: bool
"""
if self.handle.isexecuting():
return True
elif self.used_by is None:
return False
return not self.used_by() is None
@property
def executing(self):
"""Return if the connection is currently executing a query
:rtype: bool
"""
return self.handle.isexecuting()
def free(self):
"""Remove the lock on the connection if the connection is not active
:raises: ConnectionBusyError
"""
LOGGER.debug('Connection %s freeing', self.id)
if self.handle.isexecuting():
raise ConnectionBusyError(self)
with self._lock:
self.used_by = None
LOGGER.debug('Connection %s freed', self.id)
@property
def id(self):
"""Return id of the psycopg2 connection object
:rtype: int
"""
return id(self.handle)
def lock(self, session):
"""Lock the connection, ensuring that it is not busy and storing
a weakref for the session.
:param queries.Session session: The session to lock the connection with
:raises: ConnectionBusyError
"""
if self.busy:
raise ConnectionBusyError(self)
with self._lock:
self.used_by = weakref.ref(session)
LOGGER.debug('Connection %s locked', self.id)
@property
def locked(self):
"""Return if the connection is currently exclusively locked
:rtype: bool
"""
return self.used_by is not None
class Pool(object):
"""A connection pool for gaining access to and managing connections"""
_lock = threading.Lock()
idle_start = None
idle_ttl = DEFAULT_IDLE_TTL
max_size = DEFAULT_MAX_SIZE
def __init__(self,
pool_id,
idle_ttl=DEFAULT_IDLE_TTL,
max_size=DEFAULT_MAX_SIZE,
time_method=None):
self.connections = {}
self._id = pool_id
self.idle_ttl = idle_ttl
self.max_size = max_size
self.time_method = time_method or time.time
def __contains__(self, connection):
"""Return True if the pool contains the connection"""
return id(connection) in self.connections
def __len__(self):
"""Return the number of connections in the pool"""
return len(self.connections)
def add(self, connection):
"""Add a new connection to the pool
:param connection: The connection to add to the pool
:type connection: psycopg2.extensions.connection
:raises: PoolFullError
"""
if id(connection) in self.connections:
raise ValueError('Connection already exists in pool')
if len(self.connections) == self.max_size:
LOGGER.warning('Race condition found when adding new connection')
try:
connection.close()
except (psycopg2.Error, psycopg2.Warning) as error:
LOGGER.error('Error closing the conn that cant be used: %s',
error)
raise PoolFullError(self)
with self._lock:
self.connections[id(connection)] = Connection(connection)
LOGGER.debug('Pool %s added connection %s', self.id, id(connection))
@property
def busy_connections(self):
"""Return a list of active/busy connections
:rtype: list
"""
return [c for c in self.connections.values()
if c.busy and not c.closed]
def clean(self):
"""Clean the pool by removing any closed connections and if the pool's
idle has exceeded its idle TTL, remove all connections.
"""
LOGGER.debug('Cleaning the pool')
for connection in [self.connections[k] for k in self.connections if
self.connections[k].closed]:
LOGGER.debug('Removing %s', connection.id)
self.remove(connection.handle)
if self.idle_duration > self.idle_ttl:
self.close()
LOGGER.debug('Pool %s cleaned', self.id)
def close(self):
"""Close the pool by closing and removing all of the connections"""
for cid in list(self.connections.keys()):
self.remove(self.connections[cid].handle)
LOGGER.debug('Pool %s closed', self.id)
@property
def closed_connections(self):
"""Return a list of closed connections
:rtype: list
"""
return [c for c in self.connections.values() if c.closed]
def connection_handle(self, connection):
"""Return a connection object for the given psycopg2 connection
:param connection: The connection to return a parent for
:type connection: psycopg2.extensions.connection
:rtype: Connection
"""
return self.connections[id(connection)]
@property
def executing_connections(self):
"""Return a list of connections actively executing queries
:rtype: list
"""
return [c for c in self.connections.values() if c.executing]
def free(self, connection):
"""Free the connection from use by the session that was using it.
:param connection: The connection to free
:type connection: psycopg2.extensions.connection
:raises: ConnectionNotFoundError
"""
LOGGER.debug('Pool %s freeing connection %s', self.id, id(connection))
try:
self.connection_handle(connection).free()
except KeyError:
raise ConnectionNotFoundError(self.id, id(connection))
if self.idle_connections == list(self.connections.values()):
with self._lock:
self.idle_start = self.time_method()
LOGGER.debug('Pool %s freed connection %s', self.id, id(connection))
def get(self, session):
"""Return an idle connection and assign the session to the connection
:param queries.Session session: The session to assign
:rtype: psycopg2.extensions.connection
:raises: NoIdleConnectionsError
"""
idle = self.idle_connections
if idle:
connection = idle.pop(0)
connection.lock(session)
if self.idle_start:
with self._lock:
self.idle_start = None
return connection.handle
raise NoIdleConnectionsError(self.id)
@property
def id(self):
"""Return the ID for this pool
:rtype: str
"""
return self._id
@property
def idle_connections(self):
"""Return a list of idle connections
:rtype: list
"""
return [c for c in self.connections.values()
if not c.busy and not c.closed]
@property
def idle_duration(self):
"""Return the number of seconds that the pool has had no active
connections.
:rtype: float
"""
if self.idle_start is None:
return 0
return self.time_method() - self.idle_start
@property
def is_full(self):
"""Return True if there are no more open slots for connections.
:rtype: bool
"""
return len(self.connections) >= self.max_size
def lock(self, connection, session):
"""Explicitly lock the specified connection
:type connection: psycopg2.extensions.connection
:param connection: The connection to lock
:param queries.Session session: The session to hold the lock
"""
cid = id(connection)
try:
self.connection_handle(connection).lock(session)
except KeyError:
raise ConnectionNotFoundError(self.id, cid)
else:
if self.idle_start:
with self._lock:
self.idle_start = None
LOGGER.debug('Pool %s locked connection %s', self.id, cid)
@property
def locked_connections(self):
"""Return a list of all locked connections
:rtype: list
"""
return [c for c in self.connections.values() if c.locked]
def remove(self, connection):
"""Remove the connection from the pool
:param connection: The connection to remove
:type connection: psycopg2.extensions.connection
:raises: ConnectionNotFoundError
:raises: ConnectionBusyError
"""
cid = id(connection)
if cid not in self.connections:
raise ConnectionNotFoundError(self.id, cid)
self.connection_handle(connection).close()
with self._lock:
del self.connections[cid]
LOGGER.debug('Pool %s removed connection %s', self.id, cid)
def report(self):
"""Return a report about the pool state and configuration.
:rtype: dict
"""
return {
'connections': {
'busy': len(self.busy_connections),
'closed': len(self.closed_connections),
'executing': len(self.executing_connections),
'idle': len(self.idle_connections),
'locked': len(self.busy_connections)
},
'exceptions': sum([c.exceptions
for c in self.connections.values()]),
'executions': sum([c.executions
for c in self.connections.values()]),
'full': self.is_full,
'idle': {
'duration': self.idle_duration,
'ttl': self.idle_ttl
},
'max_size': self.max_size
}
def shutdown(self):
"""Forcefully shutdown the entire pool, closing all non-executing
connections.
:raises: ConnectionBusyError
"""
with self._lock:
for cid in list(self.connections.keys()):
if self.connections[cid].executing:
raise ConnectionBusyError(cid)
if self.connections[cid].locked:
self.connections[cid].free()
self.connections[cid].close()
del self.connections[cid]
def set_idle_ttl(self, ttl):
"""Set the idle ttl
:param int ttl: The TTL when idle
"""
with self._lock:
self.idle_ttl = ttl
def set_max_size(self, size):
"""Set the maximum number of connections
:param int size: The maximum number of connections
"""
with self._lock:
self.max_size = size
class PoolManager(object):
"""The connection pool object implements behavior around connections and
their use in queries.Session objects.
We carry a pool id instead of the connection URI so that we will not be
carrying the URI in memory, creating a possible security issue.
"""
_lock = threading.Lock()
_pools = {}
def __contains__(self, pid):
"""Returns True if the pool exists
:param str pid: The pool id to check for
:rtype: bool
"""
return pid in self.__class__._pools
@classmethod
def instance(cls):
"""Only allow a single PoolManager instance to exist, returning the
handle for it.
:rtype: PoolManager
"""
if not hasattr(cls, '_instance'):
with cls._lock:
cls._instance = cls()
return cls._instance
@classmethod
def add(cls, pid, connection):
"""Add a new connection and session to a pool.
:param str pid: The pool id
:type connection: psycopg2.extensions.connection
:param connection: The connection to add to the pool
"""
with cls._lock:
cls._ensure_pool_exists(pid)
cls._pools[pid].add(connection)
@classmethod
def clean(cls, pid):
"""Clean the specified pool, removing any closed connections or
stale locks.
:param str pid: The pool id to clean
"""
with cls._lock:
try:
cls._ensure_pool_exists(pid)
except KeyError:
LOGGER.debug('Pool clean invoked against missing pool %s', pid)
return
cls._pools[pid].clean()
cls._maybe_remove_pool(pid)
@classmethod
def create(cls, pid, idle_ttl=DEFAULT_IDLE_TTL, max_size=DEFAULT_MAX_SIZE,
time_method=None):
"""Create a new pool, with the ability to pass in values to override
the default idle TTL and the default maximum size.
A pool's idle TTL defines the amount of time that a pool can be open
without any sessions before it is removed.
A pool's max size defines the maximum number of connections that can
be added to the pool to prevent unbounded open connections.
:param str pid: The pool ID
:param int idle_ttl: Time in seconds for the idle TTL
:param int max_size: The maximum pool size
:param callable time_method: Override the use of :py:meth:`time.time`
method for time values.
:raises: KeyError
"""
if pid in cls._pools:
raise KeyError('Pool %s already exists' % pid)
with cls._lock:
LOGGER.debug("Creating Pool: %s (%i/%i)", pid, idle_ttl, max_size)
cls._pools[pid] = Pool(pid, idle_ttl, max_size, time_method)
@classmethod
def free(cls, pid, connection):
"""Free a connection that was locked by a session
:param str pid: The pool ID
:param connection: The connection to remove
:type connection: psycopg2.extensions.connection
"""
with cls._lock:
LOGGER.debug('Freeing %s from pool %s', id(connection), pid)
cls._ensure_pool_exists(pid)
cls._pools[pid].free(connection)
@classmethod
def get(cls, pid, session):
"""Get an idle, unused connection from the pool. Once a connection has
been retrieved, it will be marked as in-use until it is freed.
:param str pid: The pool ID
:param queries.Session session: The session to assign to the connection
:rtype: psycopg2.extensions.connection
"""
with cls._lock:
cls._ensure_pool_exists(pid)
return cls._pools[pid].get(session)
@classmethod
def get_connection(cls, pid, connection):
"""Return the specified :class:`~queries.pool.Connection` from the
pool.
:param str pid: The pool ID
:param connection: The connection to return for
:type connection: psycopg2.extensions.connection
:rtype: queries.pool.Connection
"""
with cls._lock:
return cls._pools[pid].connection_handle(connection)
@classmethod
def has_connection(cls, pid, connection):
"""Check to see if a pool has the specified connection
:param str pid: The pool ID
:param connection: The connection to check for
:type connection: psycopg2.extensions.connection
:rtype: bool
"""
with cls._lock:
cls._ensure_pool_exists(pid)
return connection in cls._pools[pid]
@classmethod
def has_idle_connection(cls, pid):
"""Check to see if a pool has an idle connection
:param str pid: The pool ID
:rtype: bool
"""
with cls._lock:
cls._ensure_pool_exists(pid)
return bool(cls._pools[pid].idle_connections)
@classmethod
def is_full(cls, pid):
"""Return a bool indicating if the specified pool is full
:param str pid: The pool id
:rtype: bool
"""
with cls._lock:
cls._ensure_pool_exists(pid)
return cls._pools[pid].is_full
@classmethod
def lock(cls, pid, connection, session):
"""Explicitly lock the specified connection in the pool
:param str pid: The pool id
:type connection: psycopg2.extensions.connection
:param connection: The connection to add to the pool
: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> Merge pull request #9 from djt5019/add-max-pool-size-environ-variable
Add support for the QUERIES_MAX_POOL_SIZE env var
<DFF> @@ -3,6 +3,7 @@ Connection Pooling
"""
import logging
+import os
import threading
import time
import weakref
@@ -10,7 +11,7 @@ import weakref
LOGGER = logging.getLogger(__name__)
DEFAULT_IDLE_TTL = 60
-DEFAULT_MAX_SIZE = 1
+DEFAULT_MAX_SIZE = os.environ.get('QUERIES_MAX_POOL_SIZE', 1)
class Connection(object):
| 2 | Merge pull request #9 from djt5019/add-max-pool-size-environ-variable | 1 | .py | py | bsd-3-clause | gmr/queries |
1391 | <NME> results_tests.py
<BEF> """
Tests for functionality in the results module
"""
import logging
import unittest
import mock
import psycopg2
from queries import results
LOGGER = logging.getLogger(__name__)
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]
LOGGER.debug('Row: %r', row)
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):
_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:
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'):
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()
LOGGER.debug('Result: %r', result)
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'):
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'):
self.assertRaises(ValueError, self.obj.as_dict)
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()
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')
<MSG> Allow iterating over empty query results
<DFF> @@ -41,6 +41,12 @@ class ResultsTestCase(unittest.TestCase):
_row = self.obj[1]
self.cursor.fetchone.assert_called_once_with()
+ def test_iter_on_empty(self):
+ self.cursor.rowcount = 0
+ with mock.patch.object(self.obj, '_rewind') as rewind:
+ [x for x in self.obj]
+ assert not rewind.called, '_rewind should not be called on empty result'
+
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:
@@ -99,6 +105,13 @@ class ResultsTestCase(unittest.TestCase):
def test_free_raises_exception(self):
self.assertRaises(NotImplementedError, self.obj.free)
+ def test_items_returns_on_empty(self):
+ self.cursor.rowcount = 0
+ self.cursor.scroll = mock.Mock()
+ self.cursor.fetchall = mock.Mock()
+ self.obj.items()
+ assert not self.cursor.scroll.called, 'Cursor.scroll should not be called on empty result'
+
def test_items_invokes_scroll(self):
self.cursor.scroll = mock.Mock()
self.cursor.fetchall = mock.Mock()
| 13 | Allow iterating over empty query results | 0 | .py | py | bsd-3-clause | gmr/queries |
1392 | <NME> results_tests.py
<BEF> """
Tests for functionality in the results module
"""
import logging
import unittest
import mock
import psycopg2
from queries import results
LOGGER = logging.getLogger(__name__)
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]
LOGGER.debug('Row: %r', row)
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):
_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:
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'):
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()
LOGGER.debug('Result: %r', result)
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'):
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'):
self.assertRaises(ValueError, self.obj.as_dict)
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()
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')
<MSG> Allow iterating over empty query results
<DFF> @@ -41,6 +41,12 @@ class ResultsTestCase(unittest.TestCase):
_row = self.obj[1]
self.cursor.fetchone.assert_called_once_with()
+ def test_iter_on_empty(self):
+ self.cursor.rowcount = 0
+ with mock.patch.object(self.obj, '_rewind') as rewind:
+ [x for x in self.obj]
+ assert not rewind.called, '_rewind should not be called on empty result'
+
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:
@@ -99,6 +105,13 @@ class ResultsTestCase(unittest.TestCase):
def test_free_raises_exception(self):
self.assertRaises(NotImplementedError, self.obj.free)
+ def test_items_returns_on_empty(self):
+ self.cursor.rowcount = 0
+ self.cursor.scroll = mock.Mock()
+ self.cursor.fetchall = mock.Mock()
+ self.obj.items()
+ assert not self.cursor.scroll.called, 'Cursor.scroll should not be called on empty result'
+
def test_items_invokes_scroll(self):
self.cursor.scroll = mock.Mock()
self.cursor.fetchall = mock.Mock()
| 13 | Allow iterating over empty query results | 0 | .py | py | bsd-3-clause | gmr/queries |
1393 | <NME> bootstrap
<BEF> #!/bin/sh
# vim: set ts=2 sts=2 sw=2 et:
test -n "$SHELLDEBUG" && set -x
if test -e /var/run/docker.sock
then
DOCKER_IP=127.0.0.1
else
echo "Docker environment not detected."
exit 1
fi
set -e
if test -z "$COMPOSE_PROJECT_NAME"
then
CWD=${PWD##*/}
export COMPOSE_PROJECT_NAME=${CWD/_/}
fi
mkdir -p build
get_exposed_port() {
docker-compose port $1 $2 | cut -d: -f2
}
docker-compose down -t 0 --volumes --remove-orphans
docker-compose pull
docker-compose up -d --no-recreate
PORT=$(get_exposed_port postgres 5432)
echo "Waiting for postgres \c"
export PG
until docker-compose exec postgres psql -U postgres -c 'SELECT 1' > /dev/null 2> /dev/null; do
echo ".\c"
sleep 1
done
echo " done"
cat > build/test-environment<<EOF
export PGHOST=${DOCKER_IP}
export PGPORT=${PORT}
EOF
<MSG> Replace echo with printf
<DFF> @@ -28,10 +28,10 @@ docker-compose up -d --no-recreate
PORT=$(get_exposed_port postgres 5432)
-echo "Waiting for postgres \c"
+printf "Waiting for postgres "
export PG
until docker-compose exec postgres psql -U postgres -c 'SELECT 1' > /dev/null 2> /dev/null; do
- echo ".\c"
+ printf "."
sleep 1
done
echo " done"
| 2 | Replace echo with printf | 2 | bootstrap | bsd-3-clause | gmr/queries |
|
1394 | <NME> bootstrap
<BEF> #!/bin/sh
# vim: set ts=2 sts=2 sw=2 et:
test -n "$SHELLDEBUG" && set -x
if test -e /var/run/docker.sock
then
DOCKER_IP=127.0.0.1
else
echo "Docker environment not detected."
exit 1
fi
set -e
if test -z "$COMPOSE_PROJECT_NAME"
then
CWD=${PWD##*/}
export COMPOSE_PROJECT_NAME=${CWD/_/}
fi
mkdir -p build
get_exposed_port() {
docker-compose port $1 $2 | cut -d: -f2
}
docker-compose down -t 0 --volumes --remove-orphans
docker-compose pull
docker-compose up -d --no-recreate
PORT=$(get_exposed_port postgres 5432)
echo "Waiting for postgres \c"
export PG
until docker-compose exec postgres psql -U postgres -c 'SELECT 1' > /dev/null 2> /dev/null; do
echo ".\c"
sleep 1
done
echo " done"
cat > build/test-environment<<EOF
export PGHOST=${DOCKER_IP}
export PGPORT=${PORT}
EOF
<MSG> Replace echo with printf
<DFF> @@ -28,10 +28,10 @@ docker-compose up -d --no-recreate
PORT=$(get_exposed_port postgres 5432)
-echo "Waiting for postgres \c"
+printf "Waiting for postgres "
export PG
until docker-compose exec postgres psql -U postgres -c 'SELECT 1' > /dev/null 2> /dev/null; do
- echo ".\c"
+ printf "."
sleep 1
done
echo " done"
| 2 | Replace echo with printf | 2 | bootstrap | bsd-3-clause | gmr/queries |
|
1395 | <NME> setup.py
<BEF> from setuptools import setup
import platform
# Make the install_requires
# 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',
extras_require={'tornado': 'tornado'},
license=open('LICENSE').read(),
package_data={'': ['LICENSE', 'README.md']},
py_modules=['pgsql_wrapper'],
classifiers=['Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'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> Fix setup.py to install the right thing
<DFF> @@ -1,4 +1,5 @@
from setuptools import setup
+import os
import platform
# Make the install_requires
@@ -22,7 +23,7 @@ setup(name='queries',
extras_require={'tornado': 'tornado'},
license=open('LICENSE').read(),
package_data={'': ['LICENSE', 'README.md']},
- py_modules=['pgsql_wrapper'],
+ packages=['queries'],
classifiers=['Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
| 2 | Fix setup.py to install the right thing | 1 | .py | py | bsd-3-clause | gmr/queries |
1396 | <NME> setup.py
<BEF> from setuptools import setup
import platform
# Make the install_requires
# 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',
extras_require={'tornado': 'tornado'},
license=open('LICENSE').read(),
package_data={'': ['LICENSE', 'README.md']},
py_modules=['pgsql_wrapper'],
classifiers=['Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'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> Fix setup.py to install the right thing
<DFF> @@ -1,4 +1,5 @@
from setuptools import setup
+import os
import platform
# Make the install_requires
@@ -22,7 +23,7 @@ setup(name='queries',
extras_require={'tornado': 'tornado'},
license=open('LICENSE').read(),
package_data={'': ['LICENSE', 'README.md']},
- py_modules=['pgsql_wrapper'],
+ packages=['queries'],
classifiers=['Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
| 2 | Fix setup.py to install the right thing | 1 | .py | py | bsd-3-clause | gmr/queries |
1397 | <NME> session.py
<BEF> """The Session class allows for a unified (and simplified) view of
interfacing with a PostgreSQL database server.
Connection details are passed in as a PostgreSQL URI and connections are pooled
by default, allowing for reuse of connections across modules in the Python
runtime without having to pass around the object handle.
While you can still access the raw `psycopg2` connection and cursor objects to
provide ultimate flexibility in how you use the queries.Session object, there
are convenience methods designed to simplify the interaction with PostgreSQL.
For `psycopg2` functionality outside of what is exposed in Session, simply
use the Session.connection or Session.cursor properties to gain access to
either object just as you would in a program using psycopg2 directly.
Example usage:
.. code:: python
import queries
with queries.Session('pgsql://postgres@localhost/postgres') as session:
for row in session.Query('SELECT * FROM table'):
print row
"""
import hashlib
import logging
import psycopg2
from psycopg2 import extensions, extras
from queries import pool, results, utils
LOGGER = logging.getLogger(__name__)
DEFAULT_ENCODING = 'UTF8'
DEFAULT_URI = 'postgresql://localhost:5432'
class Session(object):
"""The Session class allows for a unified (and simplified) view of
interfacing with a PostgreSQL database server. The Session object can
act as a context manager, providing automated cleanup and simple, Pythonic
way of interacting with the object.
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
"""
_conn = None
_cursor = None
_tpc_id = None
_uri = None
# Connection status constants
INTRANS = extensions.STATUS_IN_TRANSACTION
PREPARED = extensions.STATUS_PREPARED
READY = extensions.STATUS_READY
SETUP = extensions.STATUS_SETUP
# Transaction status constants
TX_ACTIVE = extensions.TRANSACTION_STATUS_ACTIVE
TX_IDLE = extensions.TRANSACTION_STATUS_IDLE
TX_INERROR = extensions.TRANSACTION_STATUS_INERROR
TX_INTRANS = extensions.TRANSACTION_STATUS_INTRANS
TX_UNKNOWN = extensions.TRANSACTION_STATUS_UNKNOWN
def __init__(self, uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
pool_max_size=pool.DEFAULT_MAX_SIZE,
autocommit=True):
"""Connect to a PostgreSQL server using the module wide connection and
set the isolation level.
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
"""
self._pool_manager = pool.PoolManager.instance()
self._uri = uri
# Ensure the pool exists in the pool manager
if self.pid not in self._pool_manager:
self._pool_manager.create(self.pid, pool_idle_ttl, pool_max_size)
self._conn = self._connect()
self._cursor_factory = cursor_factory
self._pool_manager.create(self.pid, pool_idle_ttl, pool_max_size)
self._conn = self._connect()
self._cursor_factory = cursor_factory
self._cursor = self._get_cursor(self._conn)
self._autocommit()
session is connected to.
:rtype: int
"""
return self._conn.get_backend_pid()
def callproc(self, name, args=None):
"""Call a stored procedure on the server, returning the results in a
:py:class:`queries.Results` instance.
:param str name: The procedure name
:param list args: The list of arguments to pass in
:rtype: queries.Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
try:
self._cursor.callproc(name, args)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def close(self):
"""Explicitly close the connection and remove it from the connection
pool if pooling is enabled. If the connection is already closed
:raises: psycopg2.InterfaceError
"""
self._pool_manager.remove_connection(self.pid, self._conn)
# Close the connection
self._conn, self._cursor = None, None
@property
self._conn, self._cursor = None, None
@property
def connection(self):
"""Return the current open connection to PostgreSQL.
:rtype: psycopg2.extensions.connection
"""
return self._conn
@property
def cursor(self):
"""Return the current, active cursor for the open connection.
:rtype: psycopg2.extensions.cursor
"""
return self._cursor
@property
def encoding(self):
"""Return the current client encoding value.
:rtype: str
"""
return self._conn.encoding
@property
def notices(self):
"""Return a list of up to the last 50 server notices sent to the client.
:rtype: list
"""
return self._conn.notices
@property
def pid(self):
"""Return the pool ID used for connection pooling.
:rtype: str
"""
return hashlib.md5(':'.join([self.__class__.__name__,
self._uri]).encode('utf-8')).hexdigest()
def query(self, sql, parameters=None):
"""A generator to issue a query on the server, mogrifying the
parameters against the sql statement. Results are returned as a
:py:class:`queries.Results` object which can act as an iterator and
has multiple ways to access the result data.
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: queries.Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
try:
self._cursor.execute(sql, parameters)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def set_encoding(self, value=DEFAULT_ENCODING):
"""Set the client encoding for the session if the value specified
is different than the current client encoding.
:param str value: The encoding value to use
"""
if self._conn.encoding != value:
self._conn.set_client_encoding(value)
def __del__(self):
"""When deleting the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def __enter__(self):
"""For use as a context manager, return a handle to this object
instance.
:rtype: Session
"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""When leaving the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def _autocommit(self, autocommit):
"""Set the isolation level automatically to commit or not after every query
:param autocommit: Boolean (Default - True)
"""
self._conn.autocommit = autocommit
def _cleanup(self):
"""Remove the connection from the stack, closing out the cursor"""
if self._cursor:
LOGGER.debug('Closing the cursor on %s', self.pid)
self._cursor.close()
self._cursor = None
if self._conn:
LOGGER.debug('Freeing %s in the pool', self.pid)
try:
pool.PoolManager.instance().free(self.pid, self._conn)
except pool.ConnectionNotFoundError:
pass
self._conn = None
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
if possible, or by creating the new connection.
:rtype: psycopg2.extensions.connection
:raises: pool.NoIdleConnectionsError
"""
# Attempt to get a cached connection from the connection pool
try:
connection = self._pool_manager.get(self.pid, self)
LOGGER.debug("Re-using connection for %s", self.pid)
except pool.NoIdleConnectionsError:
if self._pool_manager.is_full(self.pid):
raise
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
LOGGER.debug("Creating a new connection for %s", self.pid)
connection = self._psycopg2_connect(kwargs)
self._pool_manager.add(self.pid, connection)
self._pool_manager.lock(self.pid, connection, self)
# Added in because psycopg2ct connects and leaves the connection in
# a weird state: consts.STATUS_DATESTYLE, returning from
# Connection._setup without setting the state as const.STATUS_OK
if utils.PYPY:
connection.reset()
# Register the custom data types
self._register_unicode(connection)
self._register_uuid(connection)
return connection
def _get_cursor(self, connection, name=None):
"""Return a cursor for the given cursor_factory. Specify a name to
use server-side cursors.
:param connection: The connection to create a cursor on
:type connection: psycopg2.extensions.connection
:param str name: A cursor name for a server side cursor
:rtype: psycopg2.extensions.cursor
"""
cursor = connection.cursor(name=name,
cursor_factory=self._cursor_factory)
if name is not None:
cursor.scrollable = True
cursor.withhold = True
return cursor
def _incr_exceptions(self):
"""Increment the number of exceptions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).exceptions += 1
def _incr_executions(self):
"""Increment the number of executions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).executions += 1
def _psycopg2_connect(self, kwargs):
"""Return a psycopg2 connection for the specified kwargs. Extend for
use in async session adapters.
:param dict kwargs: Keyword connection args
:rtype: psycopg2.extensions.connection
"""
return psycopg2.connect(**kwargs)
@staticmethod
def _register_unicode(connection):
"""Register the cursor to be able to receive Unicode string.
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE,
connection)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY,
connection)
@staticmethod
def _register_uuid(connection):
"""Register the UUID extension from the psycopg2.extra module
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extras.register_uuid(conn_or_curs=connection)
@property
def _status(self):
"""Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queries.Session.READY: Connected, no active transaction
:rtype: int
"""
if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
return self.READY
return self._conn.status
<MSG> Comment update [ci skip]
<DFF> @@ -93,7 +93,6 @@ class Session(object):
self._pool_manager.create(self.pid, pool_idle_ttl, pool_max_size)
self._conn = self._connect()
-
self._cursor_factory = cursor_factory
self._cursor = self._get_cursor(self._conn)
self._autocommit()
@@ -140,7 +139,7 @@ class Session(object):
self._pool_manager.remove_connection(self.pid, self._conn)
- # Close the connection
+ # Un-assign the connection and cursor
self._conn, self._cursor = None, None
@property
| 1 | Comment update [ci skip] | 2 | .py | py | bsd-3-clause | gmr/queries |
1398 | <NME> session.py
<BEF> """The Session class allows for a unified (and simplified) view of
interfacing with a PostgreSQL database server.
Connection details are passed in as a PostgreSQL URI and connections are pooled
by default, allowing for reuse of connections across modules in the Python
runtime without having to pass around the object handle.
While you can still access the raw `psycopg2` connection and cursor objects to
provide ultimate flexibility in how you use the queries.Session object, there
are convenience methods designed to simplify the interaction with PostgreSQL.
For `psycopg2` functionality outside of what is exposed in Session, simply
use the Session.connection or Session.cursor properties to gain access to
either object just as you would in a program using psycopg2 directly.
Example usage:
.. code:: python
import queries
with queries.Session('pgsql://postgres@localhost/postgres') as session:
for row in session.Query('SELECT * FROM table'):
print row
"""
import hashlib
import logging
import psycopg2
from psycopg2 import extensions, extras
from queries import pool, results, utils
LOGGER = logging.getLogger(__name__)
DEFAULT_ENCODING = 'UTF8'
DEFAULT_URI = 'postgresql://localhost:5432'
class Session(object):
"""The Session class allows for a unified (and simplified) view of
interfacing with a PostgreSQL database server. The Session object can
act as a context manager, providing automated cleanup and simple, Pythonic
way of interacting with the object.
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
"""
_conn = None
_cursor = None
_tpc_id = None
_uri = None
# Connection status constants
INTRANS = extensions.STATUS_IN_TRANSACTION
PREPARED = extensions.STATUS_PREPARED
READY = extensions.STATUS_READY
SETUP = extensions.STATUS_SETUP
# Transaction status constants
TX_ACTIVE = extensions.TRANSACTION_STATUS_ACTIVE
TX_IDLE = extensions.TRANSACTION_STATUS_IDLE
TX_INERROR = extensions.TRANSACTION_STATUS_INERROR
TX_INTRANS = extensions.TRANSACTION_STATUS_INTRANS
TX_UNKNOWN = extensions.TRANSACTION_STATUS_UNKNOWN
def __init__(self, uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
pool_max_size=pool.DEFAULT_MAX_SIZE,
autocommit=True):
"""Connect to a PostgreSQL server using the module wide connection and
set the isolation level.
:param str uri: PostgreSQL connection URI
:param psycopg2.extensions.cursor: The cursor type to use
:param int pool_idle_ttl: How long idle pools keep connections open
:param int pool_max_size: The maximum size of the pool to use
"""
self._pool_manager = pool.PoolManager.instance()
self._uri = uri
# Ensure the pool exists in the pool manager
if self.pid not in self._pool_manager:
self._pool_manager.create(self.pid, pool_idle_ttl, pool_max_size)
self._conn = self._connect()
self._cursor_factory = cursor_factory
self._pool_manager.create(self.pid, pool_idle_ttl, pool_max_size)
self._conn = self._connect()
self._cursor_factory = cursor_factory
self._cursor = self._get_cursor(self._conn)
self._autocommit()
session is connected to.
:rtype: int
"""
return self._conn.get_backend_pid()
def callproc(self, name, args=None):
"""Call a stored procedure on the server, returning the results in a
:py:class:`queries.Results` instance.
:param str name: The procedure name
:param list args: The list of arguments to pass in
:rtype: queries.Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
try:
self._cursor.callproc(name, args)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def close(self):
"""Explicitly close the connection and remove it from the connection
pool if pooling is enabled. If the connection is already closed
:raises: psycopg2.InterfaceError
"""
self._pool_manager.remove_connection(self.pid, self._conn)
# Close the connection
self._conn, self._cursor = None, None
@property
self._conn, self._cursor = None, None
@property
def connection(self):
"""Return the current open connection to PostgreSQL.
:rtype: psycopg2.extensions.connection
"""
return self._conn
@property
def cursor(self):
"""Return the current, active cursor for the open connection.
:rtype: psycopg2.extensions.cursor
"""
return self._cursor
@property
def encoding(self):
"""Return the current client encoding value.
:rtype: str
"""
return self._conn.encoding
@property
def notices(self):
"""Return a list of up to the last 50 server notices sent to the client.
:rtype: list
"""
return self._conn.notices
@property
def pid(self):
"""Return the pool ID used for connection pooling.
:rtype: str
"""
return hashlib.md5(':'.join([self.__class__.__name__,
self._uri]).encode('utf-8')).hexdigest()
def query(self, sql, parameters=None):
"""A generator to issue a query on the server, mogrifying the
parameters against the sql statement. Results are returned as a
:py:class:`queries.Results` object which can act as an iterator and
has multiple ways to access the result data.
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: queries.Results
:raises: queries.DataError
:raises: queries.DatabaseError
:raises: queries.IntegrityError
:raises: queries.InternalError
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
:raises: queries.OperationalError
:raises: queries.ProgrammingError
"""
try:
self._cursor.execute(sql, parameters)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def set_encoding(self, value=DEFAULT_ENCODING):
"""Set the client encoding for the session if the value specified
is different than the current client encoding.
:param str value: The encoding value to use
"""
if self._conn.encoding != value:
self._conn.set_client_encoding(value)
def __del__(self):
"""When deleting the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def __enter__(self):
"""For use as a context manager, return a handle to this object
instance.
:rtype: Session
"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""When leaving the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def _autocommit(self, autocommit):
"""Set the isolation level automatically to commit or not after every query
:param autocommit: Boolean (Default - True)
"""
self._conn.autocommit = autocommit
def _cleanup(self):
"""Remove the connection from the stack, closing out the cursor"""
if self._cursor:
LOGGER.debug('Closing the cursor on %s', self.pid)
self._cursor.close()
self._cursor = None
if self._conn:
LOGGER.debug('Freeing %s in the pool', self.pid)
try:
pool.PoolManager.instance().free(self.pid, self._conn)
except pool.ConnectionNotFoundError:
pass
self._conn = None
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
if possible, or by creating the new connection.
:rtype: psycopg2.extensions.connection
:raises: pool.NoIdleConnectionsError
"""
# Attempt to get a cached connection from the connection pool
try:
connection = self._pool_manager.get(self.pid, self)
LOGGER.debug("Re-using connection for %s", self.pid)
except pool.NoIdleConnectionsError:
if self._pool_manager.is_full(self.pid):
raise
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
LOGGER.debug("Creating a new connection for %s", self.pid)
connection = self._psycopg2_connect(kwargs)
self._pool_manager.add(self.pid, connection)
self._pool_manager.lock(self.pid, connection, self)
# Added in because psycopg2ct connects and leaves the connection in
# a weird state: consts.STATUS_DATESTYLE, returning from
# Connection._setup without setting the state as const.STATUS_OK
if utils.PYPY:
connection.reset()
# Register the custom data types
self._register_unicode(connection)
self._register_uuid(connection)
return connection
def _get_cursor(self, connection, name=None):
"""Return a cursor for the given cursor_factory. Specify a name to
use server-side cursors.
:param connection: The connection to create a cursor on
:type connection: psycopg2.extensions.connection
:param str name: A cursor name for a server side cursor
:rtype: psycopg2.extensions.cursor
"""
cursor = connection.cursor(name=name,
cursor_factory=self._cursor_factory)
if name is not None:
cursor.scrollable = True
cursor.withhold = True
return cursor
def _incr_exceptions(self):
"""Increment the number of exceptions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).exceptions += 1
def _incr_executions(self):
"""Increment the number of executions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).executions += 1
def _psycopg2_connect(self, kwargs):
"""Return a psycopg2 connection for the specified kwargs. Extend for
use in async session adapters.
:param dict kwargs: Keyword connection args
:rtype: psycopg2.extensions.connection
"""
return psycopg2.connect(**kwargs)
@staticmethod
def _register_unicode(connection):
"""Register the cursor to be able to receive Unicode string.
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE,
connection)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY,
connection)
@staticmethod
def _register_uuid(connection):
"""Register the UUID extension from the psycopg2.extra module
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extras.register_uuid(conn_or_curs=connection)
@property
def _status(self):
"""Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queries.Session.READY: Connected, no active transaction
:rtype: int
"""
if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
return self.READY
return self._conn.status
<MSG> Comment update [ci skip]
<DFF> @@ -93,7 +93,6 @@ class Session(object):
self._pool_manager.create(self.pid, pool_idle_ttl, pool_max_size)
self._conn = self._connect()
-
self._cursor_factory = cursor_factory
self._cursor = self._get_cursor(self._conn)
self._autocommit()
@@ -140,7 +139,7 @@ class Session(object):
self._pool_manager.remove_connection(self.pid, self._conn)
- # Close the connection
+ # Un-assign the connection and cursor
self._conn, self._cursor = None, None
@property
| 1 | Comment update [ci skip] | 2 | .py | py | bsd-3-clause | gmr/queries |
1399 | <NME> utils_tests.py
<BEF> """
Tests for functionality in the utils module
"""
import platform
import unittest
import mock
import queries
from queries import utils
class GetCurrentUserTests(unittest.TestCase):
@mock.patch('pwd.getpwuid')
def test_get_current_user(self, getpwuid):
"""get_current_user returns value from pwd.getpwuid"""
getpwuid.return_value = ['mocky']
self.assertEqual(utils.get_current_user(), 'mocky')
class URLParseTestCase(unittest.TestCase):
URI = 'pgsql://foo:bar@baz:5444/qux'
def test_urlparse_hostname(self):
"""hostname should match expectation"""
class URICreationTests(unittest.TestCase):
def test_uri_with_password(self):
expectation = 'postgresql://foo:bar@baz:5433/qux'
self.assertEqual(queries.uri('baz', 5433, 'qux', 'foo', 'bar'),
expectation)
def test_uri_without_password(self):
expectation = 'postgresql://foo@baz:5433/qux'
self.assertEqual(queries.uri('baz', 5433, 'qux', 'foo'),
expectation)
def test_default_uri(self):
expectation = 'postgresql://postgres@localhost:5432/postgres'
self.assertEqual(queries.uri(), expectation)
class URIToKWargsTestCase(unittest.TestCase):
URI = ('pgsql://foo:bar@baz:5444/qux?options=foo&options=bar&keepalives=1&'
'invalid=true')
def test_uri_to_kwargs_host(self):
"""hostname should match expectation"""
def test_urlparse_port(self):
"""port should match expectation"""
self.assertEqual(utils.urlparse(self.URI).port, 5444)
def test_urlparse_path(self):
"""path should match expectation"""
self.assertEqual(utils.urlparse(self.URI).path, '/qux')
def test_urlparse_username(self):
"""username should match expectation"""
self.assertEqual(utils.urlparse(self.URI).username, 'foo')
def test_urlparse_password(self):
"""password should match expectation"""
self.assertEqual(utils.urlparse(self.URI).password, 'bar')
class URIToKWargsTestCase(unittest.TestCase):
URI = ('postgresql://foo:c%23%5E%25%23%27%24%40%3A@baz:5444/qux?'
'options=foo&options=bar&keepalives=1&invalid=true')
def test_uri_to_kwargs_host(self):
"""hostname should match expectation"""
self.assertEqual(utils.uri_to_kwargs(self.URI)['host'], 'baz')
def test_uri_to_kwargs_port(self):
"""port should match expectation"""
self.assertEqual(utils.uri_to_kwargs(self.URI)['port'], 5444)
def test_uri_to_kwargs_dbname(self):
"""dbname should match expectation"""
self.assertEqual(utils.uri_to_kwargs(self.URI)['dbname'], 'qux')
def test_uri_to_kwargs_username(self):
"""user should match expectation"""
self.assertEqual(utils.uri_to_kwargs(self.URI)['user'], 'foo')
def test_uri_to_kwargs_password(self):
"""password should match expectation"""
self.assertEqual(utils.uri_to_kwargs(self.URI)['password'],
'c#^%#\'$@:')
def test_uri_to_kwargs_options(self):
"""options should match expectation"""
self.assertEqual(utils.uri_to_kwargs(self.URI)['options'],
['foo', 'bar'])
def test_uri_to_kwargs_keepalive(self):
"""keepalive should match expectation"""
self.assertEqual(utils.uri_to_kwargs(self.URI)['keepalives'], 1)
def test_uri_to_kwargs_invalid(self):
"""invalid query argument should not be in kwargs"""
self.assertNotIn('invaid', utils.uri_to_kwargs(self.URI))
def test_unix_socket_path_format_one(self):
socket_path = 'postgresql://%2Fvar%2Flib%2Fpostgresql/dbname'
result = utils.uri_to_kwargs(socket_path)
self.assertEqual(result['host'], '/var/lib/postgresql')
def test_unix_socket_path_format2(self):
socket_path = 'postgresql:///postgres?host=/tmp/'
result = utils.uri_to_kwargs(socket_path)
self.assertEqual(result['host'], '/tmp/')
<MSG> Change the pgsql scheme to postgresql
Match the standard for the URI scheme in PostgreSQL.
<DFF> @@ -22,7 +22,7 @@ class GetCurrentUserTests(unittest.TestCase):
class URLParseTestCase(unittest.TestCase):
- URI = 'pgsql://foo:bar@baz:5444/qux'
+ URI = 'postgresql://foo:bar@baz:5444/qux'
def test_urlparse_hostname(self):
"""hostname should match expectation"""
@@ -47,8 +47,8 @@ class URLParseTestCase(unittest.TestCase):
class URIToKWargsTestCase(unittest.TestCase):
- URI = ('pgsql://foo:bar@baz:5444/qux?options=foo&options=bar&keepalives=1&'
- 'invalid=true')
+ URI = ('postgresql://foo:bar@baz:5444/qux?options=foo&options=bar'
+ '&keepalives=1&invalid=true')
def test_uri_to_kwargs_host(self):
"""hostname should match expectation"""
| 3 | Change the pgsql scheme to postgresql | 3 | .py | py | bsd-3-clause | gmr/queries |