2021-09-20 17:27:40 +08:00
|
|
|
from sqlalchemy.future import select
|
|
|
|
from sqlalchemy.orm import Session, scoped_session, Query
|
|
|
|
from .utils import classproperty
|
|
|
|
|
|
|
|
|
|
|
|
class NoSessionError(RuntimeError):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2021-12-17 04:26:13 +08:00
|
|
|
class NoConnectionError(RuntimeError):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2021-09-20 17:27:40 +08:00
|
|
|
class SessionMixin:
|
|
|
|
_session = None
|
2021-12-17 04:26:13 +08:00
|
|
|
_connection = None
|
2021-09-20 17:27:40 +08:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def set_session(cls, session):
|
|
|
|
"""
|
|
|
|
:type session: scoped_session | Session
|
|
|
|
"""
|
|
|
|
cls._session = session
|
|
|
|
|
|
|
|
@classproperty
|
|
|
|
def session(cls):
|
|
|
|
"""
|
|
|
|
:rtype: scoped_session | Session
|
|
|
|
"""
|
|
|
|
if cls._session is not None:
|
|
|
|
return cls._session
|
|
|
|
else:
|
|
|
|
raise NoSessionError('Cant get session.'
|
2021-12-17 04:26:13 +08:00
|
|
|
'Please, call SaActiveRecord.set_session()')
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def set_conn_object(cls, connection):
|
|
|
|
cls._connection = connection
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def session_connector(cls):
|
|
|
|
if cls._connection is not None:
|
|
|
|
return cls._connection
|
|
|
|
else:
|
|
|
|
raise NoConnectionError('Cant get db connection object.'
|
|
|
|
'Please, call SaActiveRecord.set_conn_object()')
|