1 |
77f06c5e
|
Jan Pašek
|
import sqlite3
|
2 |
|
|
from sqlite3 import Connection
|
3 |
|
|
|
4 |
|
|
from injector import Module, provider, singleton
|
5 |
|
|
|
6 |
|
|
from src.config.configuration import Configuration
|
7 |
|
|
from src.db.init_queries import DEFAULT_VALUES_SQL
|
8 |
|
|
from src.db.setup_database import SCHEMA_SQL
|
9 |
5e31b492
|
David Friesecký
|
from src.utils.logger import Logger
|
10 |
77f06c5e
|
Jan Pašek
|
|
11 |
|
|
|
12 |
|
|
class ConnectionProvider(Module):
|
13 |
b593b83c
|
Jan Pašek
|
"""
|
14 |
|
|
Dependency injection module that provides database connection singleton
|
15 |
|
|
"""
|
16 |
77f06c5e
|
Jan Pašek
|
|
17 |
|
|
@singleton
|
18 |
|
|
@provider
|
19 |
|
|
def connect(self, configuration: Configuration) -> Connection:
|
20 |
b593b83c
|
Jan Pašek
|
"""
|
21 |
|
|
Create an SQLite connection based on the given configuration
|
22 |
|
|
:param configuration: Configuration class with application config data
|
23 |
|
|
:return: connection singleton
|
24 |
|
|
"""
|
25 |
5e31b492
|
David Friesecký
|
|
26 |
|
|
Logger.debug(f"Creating a database connection [{configuration.connection_string}].")
|
27 |
|
|
|
28 |
|
|
try:
|
29 |
|
|
co = sqlite3.connect(database=configuration.connection_string, check_same_thread=False)
|
30 |
|
|
cu = co.cursor()
|
31 |
|
|
cu.executescript(SCHEMA_SQL) # TODO change setup_database not to drop tables if they exist
|
32 |
|
|
cu.executescript(DEFAULT_VALUES_SQL)
|
33 |
|
|
except sqlite3.Error as e:
|
34 |
|
|
Logger.error(f"Unknown error during database setting.")
|
35 |
|
|
raise e
|
36 |
|
|
|
37 |
77f06c5e
|
Jan Pašek
|
return co
|