Загрузка данных


import sqlite3

DB_NAME = "clinic.db"

def get_connection():
    conn = sqlite3.connect(DB_NAME)
    conn.execute("PRAGMA foreign_keys = ON;")
    return conn

def init_db():
    conn = get_connection()
    cursor = conn.cursor()
    cursor.executescript("""
    CREATE TABLE IF NOT EXISTS Service (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        description TEXT,
        price REAL NOT NULL
    );

    CREATE TABLE IF NOT EXISTS Patient (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        first_name TEXT NOT NULL,
        last_name TEXT NOT NULL,
        birthday TEXT NOT NULL,
        phone TEXT NOT NULL
    );

    CREATE TABLE IF NOT EXISTS Doctor (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        first_name TEXT NOT NULL,
        last_name TEXT NOT NULL,
        specialization TEXT NOT NULL
    );

    CREATE TABLE IF NOT EXISTS Cabinet (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        room_number TEXT NOT NULL,
        floor INTEGER NOT NULL,
        room_type TEXT NOT NULL
    );

    CREATE TABLE IF NOT EXISTS Appointment (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        patient_id INTEGER NOT NULL,
        doctor_id INTEGER NOT NULL,
        service_id INTEGER NOT NULL,
        cabinet_id INTEGER NOT NULL,
        datetime TEXT NOT NULL,
        status TEXT NOT NULL,
        complaints TEXT,
        diagnosis TEXT,
        FOREIGN KEY (patient_id) REFERENCES Patient(id) ON DELETE CASCADE,
        FOREIGN KEY (doctor_id) REFERENCES Doctor(id) ON DELETE RESTRICT,
        FOREIGN KEY (service_id) REFERENCES Service(id) ON DELETE RESTRICT,
        FOREIGN KEY (cabinet_id) REFERENCES Cabinet(id) ON DELETE RESTRICT
    );

    CREATE TABLE IF NOT EXISTS Prescription (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        appointment_id INTEGER NOT NULL,
        medication_name TEXT NOT NULL,
        instructions TEXT,
        FOREIGN KEY (appointment_id) REFERENCES Appointment(id) ON DELETE CASCADE
    );

    CREATE TABLE IF NOT EXISTS Payment (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        appointment_id INTEGER NOT NULL,
        sum REAL NOT NULL,
        payment_method TEXT NOT NULL,
        datetime TEXT NOT NULL,
        status TEXT NOT NULL,
        FOREIGN KEY (appointment_id) REFERENCES Appointment(id) ON DELETE CASCADE
    );
    """)
    conn.commit()
    conn.close()

TABLES = {
    "1": "Patient",
    "2": "Doctor",
    "3": "Service",
    "4": "Cabinet",
    "5": "Appointment",
    "6": "Prescription",
    "7": "Payment"
}

def choose_table():
    print("\nДоступные таблицы:")
    for key, name in TABLES.items():
        print(f"{key}. {name}")
    choice = input("Выберите номер таблицы: ").strip()
    return TABLES.get(choice)

# ==========================================
# 1. CREATE (Универсальное добавление)
# ==========================================
def create_record():
    table = choose_table()
    if not table:
        print("Ошибка: неверный номер таблицы.\n")
        return

    conn = get_connection()
    cursor = conn.cursor()

    try:
        if table == "Patient":
            fn = input("Имя: ").strip()
            ln = input("Фамилия: ").strip()
            bd = input("Дата рождения (ГГГГ-ММ-ДД): ").strip()
            ph = input("Телефон: ").strip()
            cursor.execute(
                "INSERT INTO Patient (first_name, last_name, birthday, phone) VALUES (?, ?, ?, ?)",
                (fn, ln, bd, ph)
            )

        elif table == "Doctor":
            fn = input("Имя врача: ").strip()
            ln = input("Фамилия врача: ").strip()
            sp = input("Специализация: ").strip()
            cursor.execute(
                "INSERT INTO Doctor (first_name, last_name, specialization) VALUES (?, ?, ?)",
                (fn, ln, sp)
            )

        elif table == "Service":
            name = input("Название услуги: ").strip()
            desc = input("Описание услуги: ").strip()
            price = float(input("Цена: ").strip())
            cursor.execute(
                "INSERT INTO Service (name, description, price) VALUES (?, ?, ?)",
                (name, desc, price)
            )

        elif table == "Cabinet":
            num = input("Номер кабинета: ").strip()
            floor = int(input("Этаж: ").strip())
            rtype = input("Тип кабинета (терапия, узи и т.д.): ").strip()
            cursor.execute(
                "INSERT INTO Cabinet (room_number, floor, room_type) VALUES (?, ?, ?)",
                (num, floor, rtype)
            )

        elif table == "Appointment":
            pid = int(input("ID пациента: ").strip())
            did = int(input("ID врача: ").strip())
            sid = int(input("ID услуги: ").strip())
            cid = int(input("ID кабинета: ").strip())
            dt = input("Дата и время (ГГГГ-ММ-ДД ЧЧ:ММ): ").strip()
            st = input("Статус (Запланирован/Завершен): ").strip()
            comp = input("Жалобы: ").strip()
            diag = input("Диагноз: ").strip()
            cursor.execute("""
                INSERT INTO Appointment (patient_id, doctor_id, service_id, cabinet_id, datetime, status, complaints, diagnosis)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            """, (pid, did, sid, cid, dt, st, comp, diag))

        elif table == "Prescription":
            aid = int(input("ID приема: ").strip())
            med = input("Название препарата: ").strip()
            ins = input("Инструкция по приему: ").strip()
            cursor.execute(
                "INSERT INTO Prescription (appointment_id, medication_name, instructions) VALUES (?, ?, ?)",
                (aid, med, ins)
            )

        elif table == "Payment":
            aid = int(input("ID приема: ").strip())
            sm = float(input("Сумма: ").strip())
            pm = input("Способ оплаты (карта/наличные): ").strip()
            dt = input("Дата и время платежа (ГГГГ-ММ-ДД ЧЧ:ММ): ").strip()
            st = input("Статус платежа (Оплачено/Ожидание): ").strip()
            cursor.execute("""
                INSERT INTO Payment (appointment_id, sum, payment_method, datetime, status)
                VALUES (?, ?, ?, ?, ?)
            """, (aid, sm, pm, dt, st))

        conn.commit()
        print(f"-> Запись успешно добавлена в {table} (ID: {cursor.lastrowid})!\n")

    except sqlite3.IntegrityError as e:
        print(f"-> Ошибка внешнего ключа или обязательного поля: {e}\n")
    except ValueError as e:
        print(f"-> Ошибка формата введенных данных: {e}\n")
    finally:
        conn.close()

# ==========================================
# 2. READ (Вывод любой таблицы)
# ==========================================
def read_records():
    table = choose_table()
    if not table:
        print("Ошибка: неверный номер таблицы.\n")
        return

    conn = get_connection()
    cursor = conn.cursor()
    cursor.execute(f"SELECT * FROM {table}")
    rows = cursor.fetchall()
    columns = [desc[0] for desc in cursor.description]

    print(f"\n--- Таблица: {table} ---")
    if not rows:
        print("Таблица пока пуста.")
    else:
        print(" | ".join(columns))
        print("-" * 50)
        for row in rows:
            print(" | ".join(str(item) for item in row))
    print()
    conn.close()

# ==========================================
# 3. UPDATE (Выбор таблицы, ID и конкретного поля)
# ==========================================
def update_record():
    table = choose_table()
    if not table:
        print("Ошибка: неверный номер таблицы.\n")
        return

    conn = get_connection()
    cursor = conn.cursor()

    # Получаем названия всех колонок таблицы
    cursor.execute(f"PRAGMA table_info({table})")
    cols_info = cursor.fetchall()
    editable_columns = [col[1] for col in cols_info if col[1] != "id"]

    row_id = input(f"Введи ID записи в таблице {table}, которую нужно изменить: ").strip()

    print("\nКакое поле обновить?")
    for idx, col in enumerate(editable_columns, 1):
        print(f"{idx}. {col}")

    col_choice = input("Номер поля: ").strip()
    try:
        field_idx = int(col_choice) - 1
        if 0 <= field_idx < len(editable_columns):
            field_name = editable_columns[field_idx]
        else:
            print("Неверный номер поля.\n")
            conn.close()
            return
    except ValueError:
        print("Номер должен быть числом.\n")
        conn.close()
        return

    new_val = input(f"Введи новое значение для {field_name}: ").strip()

    try:
        cursor.execute(f"UPDATE {table} SET {field_name} = ? WHERE id = ?", (new_val, row_id))
        conn.commit()
        if cursor.rowcount > 0:
            print(f"-> Запись #{row_id} в {table} успешно обновлена!\n")
        else:
            print(f"-> Запись с ID {row_id} не найдена.\n")
    except sqlite3.Error as e:
        print(f"-> Ошибка при обновлении: {e}\n")
    finally:
        conn.close()

# ==========================================
# 4. DELETE (Удаление по ID из любой таблицы)
# ==========================================
def delete_record():
    table = choose_table()
    if not table:
        print("Ошибка: неверный номер таблицы.\n")
        return

    row_id = input(f"Введи ID записи для удаления из {table}: ").strip()
    conn = get_connection()
    cursor = conn.cursor()

    try:
        cursor.execute(f"DELETE FROM {table} WHERE id = ?", (row_id,))
        conn.commit()
        if cursor.rowcount > 0:
            print(f"-> Запись #{row_id} из {table} удалена!\n")
        else:
            print(f"-> Запись с ID {row_id} не найдена.\n")
    except sqlite3.IntegrityError as e:
        print(f"-> Невозможно удалить запись: на неё ссылаются другие таблицы ({e})\n")
    finally:
        conn.close()

def main():
    init_db()
    while True:
        print("=== СИСТЕМА УПРАВЛЕНИЯ КЛИНИКОЙ ===")
        print("1. Добавить запись (CREATE)")
        print("2. Просмотреть таблицу (READ)")
        print("3. Изменить поле записи (UPDATE)")
        print("4. Удалить запись (DELETE)")
        print("0. Выход")

        action = input("Выберите действие: ").strip()
        if action == "1":
            create_record()
        elif action == "2":
            read_records()
        elif action == "3":
            update_record()
        elif action == "4":
            delete_record()
        elif action == "0":
            print("Работа завершена.")
            break
        else:
            print("Неизвестный пункт меню.\n")

if __name__ == "__main__":
    main()