1
|
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
|
from src.utils.logger import Logger
|
10
|
|
11
|
|
12
|
class ConnectionProvider(Module):
|
13
|
"""
|
14
|
Dependency injection module that provides database connection singleton
|
15
|
"""
|
16
|
|
17
|
@singleton
|
18
|
@provider
|
19
|
def connect(self, configuration: Configuration) -> Connection:
|
20
|
"""
|
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
|
|
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
|
return co
|