Files
Uch-Practic/app/__pycache__/database.py

83 lines
2.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import sqlite3
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DB_PATH = os.path.join(BASE_DIR, "database.db")
def get_connection():
"""Открывает соединение с БД."""
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row # доступ к колонкам по имени
conn.execute("PRAGMA foreign_keys = ON")
return conn
def init_db():
"""Создаёт таблицы при первом запуске."""
conn = get_connection()
cur = conn.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
salt TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY,
user_id INTEGER NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
expires_at TEXT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
)
""")
# status — текстовое состояние ("on"/"off"/"error" и т.д.)
# value — произвольный числовой параметр объекта
cur.execute("""
CREATE TABLE IF NOT EXISTS objects (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_id INTEGER NOT NULL,
name TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'off',
value REAL NOT NULL DEFAULT 0,
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY (owner_id) REFERENCES users (id) ON DELETE CASCADE
)
""")
# source: 'user' — команда из кабинета, 'external' — данные от внешней системы
cur.execute("""
CREATE TABLE IF NOT EXISTS command_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
object_id INTEGER NOT NULL,
source TEXT NOT NULL,
status TEXT NOT NULL,
value REAL NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY (object_id) REFERENCES objects (id) ON DELETE CASCADE
)
""")
# миграция: поля профиля пилота (для существующих БД)
cur.execute("PRAGMA table_info(users)")
existing_cols = {row[1] for row in cur.fetchall()}
profile_cols = {
"full_name": "TEXT",
"birth_date": "TEXT",
"phone": "TEXT",
"gender": "TEXT",
}
for col, col_type in profile_cols.items():
if col not in existing_cols:
cur.execute(f"ALTER TABLE users ADD COLUMN {col} {col_type}")
conn.commit()
conn.close()