This commit is contained in:
+47
-3
@@ -46,6 +46,10 @@ def ensure_database_structure():
|
||||
conn = None
|
||||
cursor = None
|
||||
|
||||
# Проверка режима отладки
|
||||
log_debug = os.getenv('LOG_DEBUG_DATA', 'false').lower() == 'true'
|
||||
changes_made = False # Флаг для отслеживания изменений
|
||||
|
||||
try:
|
||||
# Подключение без указания базы данных
|
||||
conn = mysql.connector.connect(
|
||||
@@ -56,9 +60,24 @@ def ensure_database_structure():
|
||||
cursor = conn.cursor(buffered=True) # Используем буферизованный курсор
|
||||
|
||||
# Создание базы данных если не существует
|
||||
cursor.execute(f"CREATE DATABASE IF NOT EXISTS {DB_CONFIG['database']} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
|
||||
# Проверяем существование базы данных
|
||||
cursor.execute("""
|
||||
SELECT COUNT(*)
|
||||
FROM information_schema.schemata
|
||||
WHERE schema_name = %s
|
||||
""", (DB_CONFIG['database'],))
|
||||
|
||||
db_exists = cursor.fetchone()[0] > 0
|
||||
|
||||
if not db_exists:
|
||||
cursor.execute(f"CREATE DATABASE {DB_CONFIG['database']} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
|
||||
changes_made = True
|
||||
log_message(f"Database {DB_CONFIG['database']} created")
|
||||
else:
|
||||
if log_debug:
|
||||
log_message(f"Database {DB_CONFIG['database']} already exists")
|
||||
|
||||
cursor.execute(f"USE {DB_CONFIG['database']}")
|
||||
log_message("Database checked/created successfully")
|
||||
|
||||
# Список таблиц и их структур
|
||||
tables = {
|
||||
@@ -185,8 +204,10 @@ def ensure_database_structure():
|
||||
if cursor.fetchone()[0] == 0:
|
||||
# Таблица не существует, создаем её
|
||||
cursor.execute(table_sql)
|
||||
changes_made = True
|
||||
log_message(f"Table {table_name} created")
|
||||
else:
|
||||
if log_debug:
|
||||
log_message(f"Table {table_name} exists")
|
||||
|
||||
except mysql.connector.Error as err:
|
||||
@@ -206,8 +227,10 @@ def ensure_database_structure():
|
||||
"INSERT INTO users (username, password) VALUES (%s, %s)",
|
||||
(username, hashed_password)
|
||||
)
|
||||
changes_made = True
|
||||
log_message(f"Created default admin user: {username}")
|
||||
else:
|
||||
# Важное предупреждение - всегда логируем
|
||||
log_message("Environment variables DEFNM/DEFPW not set. Admin not created.")
|
||||
except mysql.connector.Error as err:
|
||||
log_message(f"Error creating default admin: {err}")
|
||||
@@ -257,8 +280,10 @@ def ensure_database_structure():
|
||||
if cursor.fetchone()[0] == 0:
|
||||
# Столбец не существует, добавляем его
|
||||
cursor.execute(f"ALTER TABLE {table_name} ADD COLUMN {column} {column_type}")
|
||||
changes_made = True
|
||||
log_message(f"Added column {column} to table {table_name}")
|
||||
else:
|
||||
if log_debug:
|
||||
log_message(f"Column {column} already exists in table {table_name}")
|
||||
|
||||
except mysql.connector.Error as err:
|
||||
@@ -309,13 +334,32 @@ def ensure_database_structure():
|
||||
|
||||
for index_sql in all_indexes:
|
||||
try:
|
||||
cursor.execute(index_sql)
|
||||
# Извлекаем имя индекса и таблицы из SQL
|
||||
index_name = index_sql.split('IF NOT EXISTS')[1].split(' ON ')[0].strip()
|
||||
table_name = index_sql.split(' ON ')[1].split(' (')[0].strip()
|
||||
|
||||
# Проверяем существование индекса
|
||||
cursor.execute("""
|
||||
SELECT COUNT(*)
|
||||
FROM information_schema.statistics
|
||||
WHERE table_schema = %s AND table_name = %s AND index_name = %s
|
||||
""", (DB_CONFIG['database'], table_name, index_name))
|
||||
|
||||
index_exists = cursor.fetchone()[0] > 0
|
||||
|
||||
if not index_exists:
|
||||
# Индекс не существует, создаем его
|
||||
cursor.execute(index_sql)
|
||||
changes_made = True
|
||||
log_message(f"Index created: {index_name}")
|
||||
else:
|
||||
if log_debug:
|
||||
log_message(f"Index {index_name} already exists")
|
||||
except mysql.connector.Error as err:
|
||||
log_message(f"Error creating index: {err}")
|
||||
|
||||
conn.commit()
|
||||
# Финальное сообщение выводится всегда
|
||||
log_message("Database structure ensured successfully")
|
||||
|
||||
except mysql.connector.Error as err:
|
||||
|
||||
Reference in New Issue
Block a user