Skip to content

Commit

Permalink
DB - Add method to use a database session with a context block.
Browse files Browse the repository at this point in the history
Co-authored-by: aaarendt <[email protected]>
  • Loading branch information
jomey and aaarendt committed Jan 29, 2025
1 parent 63f7a50 commit ef81473
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
12 changes: 12 additions & 0 deletions snowexsql/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,18 @@ def get_db(credentials_path=None, return_metadata=False):
return engine, session


@contextmanager
def db_session_with_credentials(credentials_path=None):
"""
Helper method to allow database session with a context block.
Args:
credentials_path (string): Full path to credentials file (Optional)
"""
yield get_db(credentials_path)


def get_table_attributes(DataCls):
"""
Returns a list of all the table columns to be used for each entry
Expand Down
16 changes: 13 additions & 3 deletions tests/test_db.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import pytest
import snowexsql
from snowexsql.db import (
DB_CONNECTION_PROTOCOL, db_connection_string, get_db, load_credentials
)
from snowexsql.db import (DB_CONNECTION_PROTOCOL, db_connection_string,
db_session_with_credentials, get_db,
load_credentials)
from sqlalchemy import Engine, MetaData
from sqlalchemy.orm import Session

Expand Down Expand Up @@ -52,6 +52,16 @@ def test_returns_metadata(self):
MetaData
)

@pytest.mark.usefixtures('db_connection_string_patch')
def test_db_session_with_credentials(self, monkeypatch, test_db_info):
engine, session = None, None
with db_session_with_credentials() as (test_engine, test_session):
engine = test_engine
session = test_session

assert isinstance(engine, Engine)
assert isinstance(session, Session)

@pytest.mark.usefixtures('db_connection_string_patch')
@pytest.mark.parametrize("return_metadata, expected_objs", [
(False, 2),
Expand Down

0 comments on commit ef81473

Please sign in to comment.