1
|
import os
|
2
|
import sqlite3
|
3
|
from sqlite3 import Connection
|
4
|
from pathlib import Path
|
5
|
from injector import Module, provider, singleton
|
6
|
|
7
|
from src.config.configuration import Configuration
|
8
|
from src.constants import TEST_DATABASE_FILE, SCHEMA_SQL_FILE, VALUES_SQL_FILE
|
9
|
from src.utils.file_anchor import FileAnchor
|
10
|
from src.utils.logger import Logger
|
11
|
|
12
|
|
13
|
class ConnectionProvider(Module):
|
14
|
"""
|
15
|
Dependency injection module that provides database connection singleton
|
16
|
"""
|
17
|
|
18
|
@singleton
|
19
|
@provider
|
20
|
def connect(self, configuration: Configuration) -> Connection:
|
21
|
"""
|
22
|
Create an SQLite connection based on the given configuration
|
23
|
:param configuration: Configuration class with application config data
|
24
|
:return: connection singleton
|
25
|
"""
|
26
|
|
27
|
Logger.debug(f"Creating a database connection [{configuration.connection_string}].")
|
28
|
|
29
|
try:
|
30
|
db_file = FileAnchor(configuration.root_dir, configuration.connection_string)
|
31
|
db_path = Path(db_file.shortest_relative_path())
|
32
|
if not os.path.exists(db_path.parent.absolute()) and \
|
33
|
configuration.connection_string != TEST_DATABASE_FILE:
|
34
|
os.makedirs(db_path.parent.absolute())
|
35
|
|
36
|
co = sqlite3.connect(database=configuration.connection_string, check_same_thread=False)
|
37
|
cu = co.cursor()
|
38
|
|
39
|
schema_sql_file = open(FileAnchor(configuration.root_dir, SCHEMA_SQL_FILE).shortest_relative_path())
|
40
|
schema_sql = schema_sql_file.read()
|
41
|
|
42
|
values_sql_file = open(FileAnchor(configuration.root_dir, VALUES_SQL_FILE).shortest_relative_path())
|
43
|
values_sql = values_sql_file.read()
|
44
|
|
45
|
cu.executescript(schema_sql)
|
46
|
cu.executescript(values_sql)
|
47
|
except sqlite3.Error as e:
|
48
|
Logger.error(f"Unknown error during database setting.")
|
49
|
raise e
|
50
|
|
51
|
return co
|