33
44"""This DatabaseManager module handles the sqlite database connection."""
55import logging
6- from types import TracebackType
7- from typing import Any , Optional
86
97import sqlalchemy .exc
10- from sqlalchemy import Table , create_engine , insert , select
11- from sqlalchemy .orm import DeclarativeBase , Session
8+ from sqlalchemy import create_engine , select
9+ from sqlalchemy .orm import DeclarativeBase
1210
1311from macaron .database .views import create_view
1412
@@ -20,13 +18,7 @@ class ORMBase(DeclarativeBase):
2018
2119
2220class DatabaseManager :
23- """
24- This class handles and manages the connection to sqlite database during the session.
25-
26- Note that since SQLAlchemy lazy-loads the fields of mapped ORM objects, if the database connection is closed any
27- orm-mapped objects will become invalid. As such the lifetime of the database manager must be longer than any of the
28- objects added to the database (using add() or add_and_commit()).
29- """
21+ """This class handles and manages the connection to sqlite database during the session."""
3022
3123 def __init__ (self , db_path : str , base : type [DeclarativeBase ] = ORMBase ):
3224 """Initialize instance.
@@ -36,88 +28,10 @@ def __init__(self, db_path: str, base: type[DeclarativeBase] = ORMBase):
3628 db_path : str
3729 The path to the target database.
3830 """
39- self .engine = create_engine (f"sqlite+pysqlite:///{ db_path } " , echo = False , future = True )
31+ self .engine = create_engine (f"sqlite+pysqlite:///{ db_path } " , echo = False )
4032 self .db_name = db_path
41- self .session = Session (self .engine )
4233 self ._base = base
4334
44- def terminate (self ) -> None :
45- """Terminate the connection to the database, discarding any transaction in progress."""
46- self .session .close ()
47-
48- def __enter__ (self ) -> "DatabaseManager" :
49- return self
50-
51- def __exit__ (
52- self , exc_type : Optional [type [BaseException ]], exc_val : Optional [BaseException ], exc_tb : Optional [TracebackType ]
53- ) -> None :
54- self .terminate ()
55-
56- def add_and_commit (self , item ) -> None : # type: ignore
57- """Add an ORM object to the session and commit it.
58-
59- Following commit any auto-updated primary key values in the object will be populated and readable.
60- The object can still be modified and read after being committed.
61-
62- Parameters
63- ----------
64- item: the orm-mapped object to add to the database.
65- """
66- try :
67- self .session .add (item )
68- self .session .commit ()
69- except sqlalchemy .exc .SQLAlchemyError as error :
70- logger .error ("Database error %s" , error )
71- self .session .rollback ()
72-
73- def add (self , item ) -> None : # type: ignore
74- """Add an item to the database and flush it.
75-
76- Once added the row remains accessible and modifiable, and the primary key field is populated to reflect its
77- record in the database.
78-
79- If terminate is called before commit the object will be lost.
80-
81- Parameters
82- ----------
83- item:
84- the orm-mapped object to add to the database.
85- """
86- try :
87- self .session .add (item )
88- self .session .flush ()
89- except sqlalchemy .exc .SQLAlchemyError as error :
90- logger .error ("Database error %s" , error )
91- self .session .rollback ()
92-
93- def insert (self , table : Table , values : dict ) -> None :
94- """Populate the table with provided values and add it to the database using the core api.
95-
96- Parameters
97- ----------
98- table: Table
99- The Table to insert to
100- values: dict
101- The mapping from column names to values to insert into the Table
102- """
103- try :
104- self .execute (insert (table ).values (** values ))
105- except sqlalchemy .exc .SQLAlchemyError as error :
106- logger .error ("Database error %s" , error )
107-
108- def execute (self , query : Any ) -> None :
109- """
110- Execute a SQLAlchemy core api query using a short-lived engine connection.
111-
112- Parameters
113- ----------
114- query: Any
115- The SQLalchemy query to execute
116- """
117- with self .engine .connect () as conn :
118- conn .execute (query )
119- conn .commit ()
120-
12135 def create_tables (self ) -> None :
12236 """
12337 Automatically create views for all tables known to _base.metadata.
0 commit comments