kennethreitz/django-postgrespool — pull request #4 by nigma (2012-10-24 21:56:29+00:00)
Title: Invalidate broken connections

So the thing is that when a database error occurs the broken connection is not removed from the pool and is used to serve incoming requests.

In particular this happens when a network connection error occurs, which causes ``psycopg2.OperationalError`` (further wrapped as ``django.db.utils.DatabaseError``) being thrown in the DB API driver:

```
DatabaseError at /
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
```

My understanding is that the SQLAlchemy engine can intercept such events during query execution and then [detect](https://bitbucket.org/sqlalchemy/sqlalchemy/src/8c4bdf39b4db/lib/sqlalchemy/dialects/postgresql/psycopg2.py#cl-364), [handle](https://bitbucket.org/sqlalchemy/sqlalchemy/src/8b4c41c2982239908f453b245c42a4f64b18f991/lib/sqlalchemy/engine/base.py?at=default#cl-963) and [invalidate](https://bitbucket.org/sqlalchemy/sqlalchemy/src/8b4c41c2982239908f453b245c42a4f64b18f991/lib/sqlalchemy/engine/base.py?at=default#cl-292) broken connections.

I have added corresponding checks to the Django DB wrappers to detect such errors after a failed query execution. Not sure if there are any other edge cases though. Take a look.