1 |
07a6c869
|
David Friesecký
|
import os
|
2 |
77f06c5e
|
Jan Pašek
|
import sqlite3
|
3 |
|
|
from sqlite3 import Connection
|
4 |
|
|
|
5 |
|
|
from injector import Module, provider, singleton
|
6 |
|
|
|
7 |
|
|
from src.config.configuration import Configuration
|
8 |
7ad820d0
|
David Friesecký
|
from src.constants import DB_DIR, TEST_DATABASE_FILE, SCHEMA_SQL_FILE, VALUES_SQL_FILE
|
9 |
5678036c
|
David Friesecký
|
from src.utils.file_anchor import FileAnchor
|
10 |
5e31b492
|
David Friesecký
|
from src.utils.logger import Logger
|
11 |
77f06c5e
|
Jan Pašek
|
|
12 |
|
|
|
13 |
|
|
class ConnectionProvider(Module):
|
14 |
b593b83c
|
Jan Pašek
|
"""
|
15 |
|
|
Dependency injection module that provides database connection singleton
|
16 |
|
|
"""
|
17 |
77f06c5e
|
Jan Pašek
|
|
18 |
|
|
@singleton
|
19 |
|
|
@provider
|
20 |
|
|
def connect(self, configuration: Configuration) -> Connection:
|
21 |
b593b83c
|
Jan Pašek
|
"""
|
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 |
5e31b492
|
David Friesecký
|
|
27 |
|
|
Logger.debug(f"Creating a database connection [{configuration.connection_string}].")
|
28 |
|
|
|
29 |
|
|
try:
|
30 |
5678036c
|
David Friesecký
|
if not os.path.exists(FileAnchor(configuration.root_dir, DB_DIR).shortest_relative_path()) and \
|
31 |
|
|
configuration.connection_string != TEST_DATABASE_FILE:
|
32 |
|
|
os.makedirs(FileAnchor(configuration.root_dir, DB_DIR).shortest_relative_path())
|
33 |
07a6c869
|
David Friesecký
|
|
34 |
5e31b492
|
David Friesecký
|
co = sqlite3.connect(database=configuration.connection_string, check_same_thread=False)
|
35 |
|
|
cu = co.cursor()
|
36 |
7ad820d0
|
David Friesecký
|
|
37 |
|
|
schema_sql_file = open(FileAnchor(configuration.root_dir, SCHEMA_SQL_FILE).shortest_relative_path())
|
38 |
|
|
schema_sql = schema_sql_file.read()
|
39 |
|
|
|
40 |
|
|
values_sql_file = open(FileAnchor(configuration.root_dir, VALUES_SQL_FILE).shortest_relative_path())
|
41 |
|
|
values_sql = values_sql_file.read()
|
42 |
|
|
|
43 |
|
|
cu.executescript(schema_sql)
|
44 |
|
|
cu.executescript(values_sql)
|
45 |
5e31b492
|
David Friesecký
|
except sqlite3.Error as e:
|
46 |
|
|
Logger.error(f"Unknown error during database setting.")
|
47 |
|
|
raise e
|
48 |
|
|
|
49 |
77f06c5e
|
Jan Pašek
|
return co
|