2018-05-15 22:35:23 +02:00
|
|
|
from typing import Optional, Any
|
|
|
|
|
2016-07-19 08:12:35 +02:00
|
|
|
from django.db import connection
|
2016-09-10 21:08:37 +02:00
|
|
|
from zerver.lib.db import TimeTrackingConnection
|
2016-07-19 08:12:35 +02:00
|
|
|
|
|
|
|
import sqlalchemy
|
|
|
|
|
|
|
|
# This is a Pool that doesn't close connections. Therefore it can be used with
|
|
|
|
# existing Django database connections.
|
|
|
|
class NonClosingPool(sqlalchemy.pool.NullPool):
|
2017-11-05 11:15:10 +01:00
|
|
|
def status(self) -> str:
|
2016-07-19 08:12:35 +02:00
|
|
|
return "NonClosingPool"
|
|
|
|
|
2017-11-05 11:15:10 +01:00
|
|
|
def _do_return_conn(self, conn: sqlalchemy.engine.base.Connection) -> None:
|
2016-07-19 08:12:35 +02:00
|
|
|
pass
|
|
|
|
|
2017-11-05 11:15:10 +01:00
|
|
|
def recreate(self) -> 'NonClosingPool':
|
2016-10-17 08:22:00 +02:00
|
|
|
return self.__class__(creator=self._creator,
|
2016-07-19 08:12:35 +02:00
|
|
|
recycle=self._recycle,
|
|
|
|
use_threadlocal=self._use_threadlocal,
|
|
|
|
reset_on_return=self._reset_on_return,
|
|
|
|
echo=self.echo,
|
|
|
|
logging_name=self._orig_logging_name,
|
|
|
|
_dispatch=self.dispatch)
|
|
|
|
|
2018-05-15 22:35:23 +02:00
|
|
|
sqlalchemy_engine = None # type: Optional[Any]
|
2017-11-05 11:15:10 +01:00
|
|
|
def get_sqlalchemy_connection() -> sqlalchemy.engine.base.Connection:
|
2016-07-19 08:12:35 +02:00
|
|
|
global sqlalchemy_engine
|
|
|
|
if sqlalchemy_engine is None:
|
2017-11-05 11:15:10 +01:00
|
|
|
def get_dj_conn() -> TimeTrackingConnection:
|
2016-07-19 08:12:35 +02:00
|
|
|
connection.ensure_connection()
|
|
|
|
return connection.connection
|
|
|
|
sqlalchemy_engine = sqlalchemy.create_engine('postgresql://',
|
|
|
|
creator=get_dj_conn,
|
|
|
|
poolclass=NonClosingPool,
|
|
|
|
pool_reset_on_return=False)
|
|
|
|
sa_connection = sqlalchemy_engine.connect()
|
|
|
|
sa_connection.execution_options(autocommit=False)
|
|
|
|
return sa_connection
|