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
|
|
10
|
|
11
|
class ConnectionProvider(Module):
|
12
|
"""
|
13
|
Dependency injection module that provides database connection singleton
|
14
|
"""
|
15
|
|
16
|
@singleton
|
17
|
@provider
|
18
|
def connect(self, configuration: Configuration) -> Connection:
|
19
|
"""
|
20
|
Create an SQLite connection based on the given configuration
|
21
|
:param configuration: Configuration class with application config data
|
22
|
:return: connection singleton
|
23
|
"""
|
24
|
co = sqlite3.connect(database=configuration.connection_string, check_same_thread=False)
|
25
|
cu = co.cursor()
|
26
|
cu.executescript(SCHEMA_SQL) # TODO change setup_database not to drop tables if they exist
|
27
|
cu.executescript(DEFAULT_VALUES_SQL)
|
28
|
return co
|