2026-06-12 11:58:47 +00:00
|
|
|
# database/connection.py
|
|
|
|
|
import sqlite3
|
|
|
|
|
import os
|
|
|
|
|
|
|
|
|
|
DB_NAME = "spanish_trainer.db"
|
|
|
|
|
|
|
|
|
|
def get_connection():
|
|
|
|
|
"""Returns a standard connection object to the SQLite database."""
|
|
|
|
|
return sqlite3.connect(DB_NAME)
|
|
|
|
|
|
|
|
|
|
def init_db():
|
|
|
|
|
"""
|
|
|
|
|
Initializes the SQLite database tables if they do not exist.
|
|
|
|
|
This safely runs on every boot without wiping your existing data.
|
|
|
|
|
"""
|
|
|
|
|
print(f"🗄️ Checking database status for '{DB_NAME}'...")
|
|
|
|
|
|
|
|
|
|
# The SQL schema we designed for your glossary, cross-references, and tracks
|
|
|
|
|
schema = """
|
|
|
|
|
CREATE TABLE IF NOT EXISTS phrases (
|
|
|
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
|
|
|
text TEXT NOT NULL,
|
|
|
|
|
language TEXT NOT NULL,
|
|
|
|
|
textbook TEXT DEFAULT NULL,
|
|
|
|
|
unit INTEGER DEFAULT NULL,
|
|
|
|
|
source_context TEXT DEFAULT NULL,
|
|
|
|
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
CREATE TABLE IF NOT EXISTS translations (
|
|
|
|
|
source_phrase_id INTEGER,
|
|
|
|
|
target_phrase_id INTEGER,
|
|
|
|
|
PRIMARY KEY (source_phrase_id, target_phrase_id),
|
|
|
|
|
FOREIGN KEY (source_phrase_id) REFERENCES phrases(id) ON DELETE CASCADE,
|
|
|
|
|
FOREIGN KEY (target_phrase_id) REFERENCES phrases(id) ON DELETE CASCADE
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
CREATE TABLE IF NOT EXISTS audio_tracks (
|
|
|
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
|
|
|
phrase_id INTEGER NOT NULL,
|
|
|
|
|
voice_gender TEXT NOT NULL,
|
|
|
|
|
voice_name TEXT NOT NULL,
|
|
|
|
|
file_path TEXT NOT NULL,
|
|
|
|
|
is_reference INTEGER DEFAULT 1,
|
|
|
|
|
FOREIGN KEY (phrase_id) REFERENCES phrases(id) ON DELETE CASCADE
|
|
|
|
|
);
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
conn = get_connection()
|
|
|
|
|
try:
|
|
|
|
|
cursor = conn.cursor()
|
|
|
|
|
# executescript allows running multiple CREATE TABLE statements at once
|
|
|
|
|
cursor.executescript(schema)
|
|
|
|
|
conn.commit()
|
|
|
|
|
print("✅ Database tables verified and initialized successfully.")
|
|
|
|
|
except sqlite3.Error as e:
|
|
|
|
|
print(f"❌ Database initialization failed: {e}")
|
|
|
|
|
finally:
|
|
|
|
|
conn.close()
|