Projekt

Obecné

Profil

« Předchozí | Další » 

Revize 07a6c869

Přidáno uživatelem David Friesecký před téměř 4 roky(ů)

Re #8696 - Improved DB creation
- secured start application without lost data

Zobrazit rozdíly:

SQLite_database_check.sql
1
/* Drop Tables */
2
DROP TABLE IF EXISTS 'CertificateTypes'
3
;
4

  
5
DROP TABLE IF EXISTS 'CertificateUsages'
6
;
7

  
8
/* Create Tables with Primary and Foreign Keys, Check and Unique Constraints */
9

  
10
CREATE TABLE IF NOT EXISTS 'Certificates'
11
(
12
	'id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
13
	'valid_from' TEXT NOT NULL,
14
	'valid_to' TEXT NOT NULL,
15
	'pem_data' TEXT NOT NULL,
16
	'common_name' TEXT NOT NULL,
17
	'country_code' TEXT NULL,
18
	'locality' TEXT NULL,
19
	'province' TEXT NULL,
20
	'organization' TEXT NULL,
21
	'organizational_unit' TEXT NULL,
22
	'email_address' TEXT NULL,
23
	'revocation_date' TEXT NULL,
24
	'revocation_reason' TEXT NULL,
25
	'deletion_date' TEXT NULL,
26
	'certificate_type_id' INTEGER NOT NULL,
27
	'parent_certificate_id' INTEGER NOT NULL,
28
	'private_key_id' INTEGER NOT NULL,
29
	CONSTRAINT 'FK_Certificates' FOREIGN KEY ('parent_certificate_id') REFERENCES 'Certificates' ('id') ON DELETE No Action ON UPDATE No Action,
30
	CONSTRAINT 'FK_CertificateTypes' FOREIGN KEY ('certificate_type_id') REFERENCES 'CertificateTypes' ('id') ON DELETE No Action ON UPDATE No Action,
31
	CONSTRAINT 'FK_PrivateKeys' FOREIGN KEY ('private_key_id') REFERENCES 'PrivateKeys' ('id') ON DELETE No Action ON UPDATE No Action
32
)
33
;
34

  
35
CREATE TABLE IF NOT EXISTS 'CertificateTypes'
36
(
37
	'id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
38
	'certificate_type' TEXT NOT NULL
39
)
40
;
41

  
42
CREATE TABLE IF NOT EXISTS 'CertificateUsages'
43
(
44
	'id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
45
	'certificate_id' INTEGER NOT NULL,
46
	'usage_type_id' INTEGER NOT NULL,
47
	CONSTRAINT 'FK_Certificates' FOREIGN KEY ('certificate_id') REFERENCES 'Certificates' ('id') ON DELETE Cascade ON UPDATE No Action,
48
	CONSTRAINT 'FK_UsageTypes' FOREIGN KEY ('usage_type_id') REFERENCES 'UsageTypes' ('id') ON DELETE No Action ON UPDATE No Action
49
)
50
;
51

  
52
CREATE TABLE IF NOT EXISTS 'PrivateKeys'
53
(
54
	'id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
55
	'private_key' TEXT NOT NULL,
56
	'password' TEXT NULL
57
)
58
;
59

  
60
CREATE TABLE IF NOT EXISTS 'UsageTypes'
61
(
62
	'id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
63
	'usage_type' TEXT NOT NULL
64
)
65
;
src/config/configuration.py
7 7
from injector import singleton, inject
8 8

  
9 9
from src.constants import DEFAULT_CONNECTION_STRING, TEST_DATABASE_FILE, DEFAULT_SERVER_BASE_URL, LOG_NAME, \
10
    LOG_DIR, DEFAULT_LOG_LEVEL
10
    LOG_DIR, DEFAULT_LOG_LEVEL, LOG_FILENAME
11 11
from src.constants import LOG_FILE_LOCATION, LOG_FORMAT
12 12
from src.utils.logger import Logger
13 13

  
......
88 88
        os.makedirs(LOG_DIR)
89 89

  
90 90
    handler = logging.handlers.TimedRotatingFileHandler(
91
        os.path.join(LOG_DIR, "application.log"),
91
        os.path.join(LOG_DIR, LOG_FILENAME),
92 92
        when='H', interval=1)
93 93
    formatter = logging.Formatter(LOG_FORMAT)
94 94
    handler.setFormatter(formatter)
src/config/connection_provider.py
1
import os
1 2
import sqlite3
2 3
from sqlite3 import Connection
3 4

  
4 5
from injector import Module, provider, singleton
5 6

  
6 7
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
8
from src.constants import DB_DIR
9
from src.db.init_queries import DEFAULT_VALUES_SQL, CHECK_SCHEMA_SQL
10
from src.db.setup_database import setup_database
9 11
from src.utils.logger import Logger
10 12

  
11 13

  
......
26 28
        Logger.debug(f"Creating a database connection [{configuration.connection_string}].")
27 29

  
28 30
        try:
31
            if not os.path.exists(DB_DIR):
32
                os.makedirs(DB_DIR)
33

  
29 34
            co = sqlite3.connect(database=configuration.connection_string, check_same_thread=False)
30 35
            cu = co.cursor()
31
            cu.executescript(SCHEMA_SQL)  # TODO change setup_database not to drop tables if they exist
36
            cu.executescript(CHECK_SCHEMA_SQL)
32 37
            cu.executescript(DEFAULT_VALUES_SQL)
33 38
        except sqlite3.Error as e:
34 39
            Logger.error(f"Unknown error during database setting.")
src/constants.py
2 2

  
3 3
INMEMORY_DATABASE_FILE = ":memory:"
4 4
TEST_DATABASE_FILE = INMEMORY_DATABASE_FILE
5
DATABASE_FILE = "db/database_sqlite.db"
5
DB_DIR = "db"
6
DATABASE_FILE = f"{DB_DIR}/database_sqlite.db"
6 7
DATABASE_FILE_LOCATION = FileAnchor("aswi2021jmsd", DATABASE_FILE)
7 8
DATETIME_FORMAT = "%d.%m.%Y %H:%M:%S"
8 9

  
9 10
LOG_DIR = "logs"
10
LOG_FILE = f"{LOG_DIR}/application.log"
11
LOG_FILENAME = "application.log"
12
LOG_FILE = f"{LOG_DIR}/{LOG_FILENAME}"
11 13
LOG_FILE_LOCATION = FileAnchor("aswi2021jmsd", LOG_FILE)
12 14
LOG_FORMAT = "%(levelname)-8s %(asctime)s - %(message)s"
13 15
LOG_NAME = "app_logger"
src/db/init_queries.py
1 1
SCHEMA_SQL = """
2 2
/* ---------------------------------------------------- */
3 3
/*  Generated by Enterprise Architect Version 13.5 		*/
4
/*  Created On : 29-dub-2021 11:55:46 				*/
4
/*  Created On : 29-dub-2021 11:55:46 				    */
5 5
/*  DBMS       : SQLite 								*/
6 6
/* ---------------------------------------------------- */
7 7

  
......
83 83

  
84 84
"""
85 85

  
86
DEFAULT_VALUES_SQL = """
87
/* ---------------------------------------------------- */
88
/*  Generated by Enterprise Architect Version 13.5 		*/
89
/*  Created On : 26-bře-2021 13:33:05 				*/
90
/*  DBMS       : SQLite 								*/
91
/* ---------------------------------------------------- */
86
CHECK_SCHEMA_SQL = """
87
/* Drop Tables */
88
DROP TABLE IF EXISTS 'CertificateTypes'
89
;
90

  
91
DROP TABLE IF EXISTS 'CertificateUsages'
92
;
93

  
94
/* Create Tables with Primary and Foreign Keys, Check and Unique Constraints */
95

  
96
CREATE TABLE IF NOT EXISTS 'Certificates'
97
(
98
	'id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
99
	'valid_from' TEXT NOT NULL,
100
	'valid_to' TEXT NOT NULL,
101
	'pem_data' TEXT NOT NULL,
102
	'common_name' TEXT NOT NULL,
103
	'country_code' TEXT NULL,
104
	'locality' TEXT NULL,
105
	'province' TEXT NULL,
106
	'organization' TEXT NULL,
107
	'organizational_unit' TEXT NULL,
108
	'email_address' TEXT NULL,
109
	'revocation_date' TEXT NULL,
110
	'revocation_reason' TEXT NULL,
111
	'deletion_date' TEXT NULL,
112
	'certificate_type_id' INTEGER NOT NULL,
113
	'parent_certificate_id' INTEGER NOT NULL,
114
	'private_key_id' INTEGER NOT NULL,
115
	CONSTRAINT 'FK_Certificates' FOREIGN KEY ('parent_certificate_id') REFERENCES 'Certificates' ('id') ON DELETE No Action ON UPDATE No Action,
116
	CONSTRAINT 'FK_CertificateTypes' FOREIGN KEY ('certificate_type_id') REFERENCES 'CertificateTypes' ('id') ON DELETE No Action ON UPDATE No Action,
117
	CONSTRAINT 'FK_PrivateKeys' FOREIGN KEY ('private_key_id') REFERENCES 'PrivateKeys' ('id') ON DELETE No Action ON UPDATE No Action
118
)
119
;
120

  
121
CREATE TABLE IF NOT EXISTS 'CertificateTypes'
122
(
123
	'id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
124
	'certificate_type' TEXT NOT NULL
125
)
126
;
127

  
128
CREATE TABLE IF NOT EXISTS 'CertificateUsages'
129
(
130
	'id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
131
	'certificate_id' INTEGER NOT NULL,
132
	'usage_type_id' INTEGER NOT NULL,
133
	CONSTRAINT 'FK_Certificates' FOREIGN KEY ('certificate_id') REFERENCES 'Certificates' ('id') ON DELETE Cascade ON UPDATE No Action,
134
	CONSTRAINT 'FK_UsageTypes' FOREIGN KEY ('usage_type_id') REFERENCES 'UsageTypes' ('id') ON DELETE No Action ON UPDATE No Action
135
)
136
;
92 137

  
138
CREATE TABLE IF NOT EXISTS 'PrivateKeys'
139
(
140
	'id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
141
	'private_key' TEXT NOT NULL,
142
	'password' TEXT NULL
143
)
144
;
145

  
146
CREATE TABLE IF NOT EXISTS 'UsageTypes'
147
(
148
	'id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
149
	'usage_type' TEXT NOT NULL
150
)
151
;
152

  
153
"""
154

  
155
DEFAULT_VALUES_SQL = """
93 156
/* Insert default values */
94 157

  
95 158
INSERT INTO CertificateTypes(certificate_type) VALUES('ROOT_CA');
src/db/setup_database.py
1
import os
1 2
import sqlite3
3
from pathlib import Path
2 4

  
3
from src.constants import DATABASE_FILE_LOCATION
5
from src.constants import DATABASE_FILE_LOCATION, DB_DIR
4 6
from src.db.init_queries import SCHEMA_SQL, DEFAULT_VALUES_SQL
5 7
from src.utils.logger import Logger
6 8

  
......
9 11
    Logger.debug(f"Database is setting.")
10 12

  
11 13
    try:
14
        # TODO improve creating DB dir
15
        if not os.path.exists(DB_DIR):
16
            os.makedirs("../../" + DB_DIR)
17

  
18
        # TODO improve creating DB file (now via FileAnchor)
12 19
        co = sqlite3.connect(DATABASE_FILE_LOCATION.shortest_relative_path())
13 20
        cu = co.cursor()
14 21
        cu.executescript(SCHEMA_SQL)
......
21 28

  
22 29

  
23 30
if __name__ == '__main__':
24
    setup_database()
31
    setup_database()

Také k dispozici: Unified diff