Spaces:
Sleeping

File size: 2,415 Bytes
c1c5e35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ba84e9
c1c5e35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/env python3
"""Add missing columns to the `diploma` table in the SQLite DB.

This script is idempotent and will only run ALTER TABLE for columns
that don't already exist. It expects the DB at the project root as
configured in `config.py` (default `data.db`).

Usage:
    python scripts/add_diploma_columns.py

Backup your DB first if it contains important data.
"""
import sqlite3
import os

# Try multiple likely DB locations (project root and instance folder)
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DB_CANDIDATES = [
    os.path.join(BASE_DIR, "data.db"),
    os.path.join(BASE_DIR, "instance", "data.db"),
]

def find_db_path():
    for p in DB_CANDIDATES:
        if os.path.exists(p):
            return p
    # fallback to first candidate (where seed/reset create it normally)
    return DB_CANDIDATES[0]

DB_PATH = find_db_path()

# Columns to add to the `diploma` table if they don't already exist
columns_to_add = {
    "student_name": "TEXT",
    "student_id": "TEXT",
    "center_name": "TEXT",
    "certification_title": "TEXT",
    "graduation_year": "INTEGER",
    "registration_number": "TEXT",
    "director": "TEXT",
    "provincial_director": "TEXT",
    "professor": "TEXT",
    # store uploaded PDF filename/path (files are saved to `static/pdfs`)
    "pdf": "TEXT",
}


def get_existing_columns(conn):
    cur = conn.execute("PRAGMA table_info('diploma')")
    return [row[1] for row in cur.fetchall()]


def main():
    if not os.path.exists(DB_PATH):
        print("Database not found. Tried these locations:")
        for p in DB_CANDIDATES:
            print(" -", p)
        print("You can create the DB by running: python .\seed.py (or python .\reset_db.py to recreate)")
        return

    conn = sqlite3.connect(DB_PATH)
    try:
        existing = get_existing_columns(conn)
        print("Existing columns:", existing)

        for col, coltype in columns_to_add.items():
            if col in existing:
                print(f"Column '{col}' already exists — skipping")
                continue
            stmt = f"ALTER TABLE diploma ADD COLUMN {col} {coltype}"
            print("Executing:", stmt)
            conn.execute(stmt)
        conn.commit()
        print("Done — added missing columns.")
    except sqlite3.OperationalError as e:
        print("SQLite error:", e)
    finally:
        conn.close()


if __name__ == "__main__":
    main()