Commit f2a00fa1 authored by Simon Oliver Tveit's avatar Simon Oliver Tveit
Browse files

sqlite in memory session

Adds option to run the sqla_session against a sqlite in memory session.
This is instead of the normal session connecting to the postgresql database
The advantage of doing it this way is tha all the code using sessions
will automatically use the test session if running testssqlite in memory session
parent bfdc9f2c
......@@ -5,6 +5,7 @@ from contextlib import contextmanager
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import NullPool
from sqlalchemy.pool import StaticPool
from redis import StrictRedis
......@@ -31,15 +32,29 @@ def get_sqlalchemy_conn_str(**kwargs) -> str:
f"{db_data['hostname']}:{db_data['port']}/{db_data['database']}"
)
Session = None
def create_test_session():
from cnaas_nms.db.base import Base
global Session
engine = create_engine('sqlite://',
connect_args={'check_same_thread':False},
poolclass=StaticPool)
Base.metadata.create_all(engine)
engine.connect()
Session = sessionmaker(bind=engine)
conn_str = get_sqlalchemy_conn_str()
engine = create_engine(conn_str, pool_size=50, max_overflow=50)
connection = engine.connect()
Session = sessionmaker(bind=engine)
def create_session():
global Session
conn_str = get_sqlalchemy_conn_str()
engine = create_engine(conn_str, pool_size=50, max_overflow=50)
connection = engine.connect()
Session = sessionmaker(bind=engine)
@contextmanager
def sqla_session(**kwargs):
def sqla_session():
if Session is None:
create_session()
session = Session()
try:
yield session
......@@ -50,6 +65,20 @@ def sqla_session(**kwargs):
finally:
session.close()
@contextmanager
def sqla_test_session():
if Session is None:
create_test_session()
session = Session()
try:
yield session
session.flush()
except:
session.rollback()
raise
finally:
session.close()
@contextmanager
def sqla_execute(**kwargs):
conn_str = get_sqlalchemy_conn_str(**kwargs)
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment