Spaces:
Sleeping

xertify / scripts /migrate_diploma_pk.py
Fedgo29
Adding changes by FedgoX
d7f2456
Raw History Blame Contribute Delete
3.28 kB
#!/usr/bin/env python3
"""Migrate `diploma` table to use `registration_number` as primary key.
This script will:
- find the project's SQLite DB (project root or instance/)
- create a new table `diploma_new` with registration_number TEXT PRIMARY KEY
- copy rows from `diploma` to `diploma_new` (requires non-null registration_number)
- drop the old `diploma` table and rename `diploma_new` -> `diploma`
BACKUP your DB before running.
Usage:
python scripts/migrate_diploma_pk.py
"""
import os
import sqlite3
import sys
BASE = os.path.dirname(os.path.dirname(__file__))
DB_CANDIDATES = [
os.path.join(BASE, "data.db"),
os.path.join(BASE, "instance", "data.db"),
]
def find_db():
for p in DB_CANDIDATES:
if os.path.exists(p):
return p
return DB_CANDIDATES[0]
DB = find_db()
if not os.path.exists(DB):
print("Database not found at:")
for p in DB_CANDIDATES:
print(" -", p)
sys.exit(1)
print("Using DB:", DB)
backup = DB + ".backup"
print("Creating backup:", backup)
import shutil
shutil.copy2(DB, backup)
conn = sqlite3.connect(DB)
cur = conn.cursor()
def column_exists(table, col):
cur.execute(f"PRAGMA table_info('{table}')")
return any(r[1] == col for r in cur.fetchall())
if not column_exists('diploma', 'registration_number'):
print("Table 'diploma' has no 'registration_number' column — aborting.")
conn.close()
sys.exit(1)
# Inspect columns in old table
cur.execute("PRAGMA table_info('diploma')")
cols = [r[1] for r in cur.fetchall()]
print("Existing diploma columns:", cols)
# Define new table schema — include all existing fields but make registration_number TEXT PRIMARY KEY
# We'll try to preserve column types where possible
create_sql = '''
CREATE TABLE diploma_new (
registration_number TEXT PRIMARY KEY,
user_id INTEGER,
certification_title TEXT,
director TEXT,
professor TEXT,
issue_date DATE,
student_name TEXT,
student_id TEXT,
center_name TEXT,
provincial_director TEXT,
graduation_year INTEGER,
entity_id INTEGER,
hash_code TEXT UNIQUE
);
'''
print("Creating new table 'diploma_new'...")
cur.execute(create_sql)
# Copy rows — require registration_number not null
cols_to_copy = [c for c in cols if c != 'id']
cols_list = ",".join(cols_to_copy)
print("Copying rows (only where registration_number IS NOT NULL)...")
cur.execute(f"SELECT COUNT(*) FROM diploma WHERE registration_number IS NULL")
nulls = cur.fetchone()[0]
if nulls > 0:
print(f"Found {nulls} rows with NULL registration_number — these will NOT be migrated.\n\nAborting. Fix data first or export these rows before proceeding.")
conn.rollback()
conn.close()
sys.exit(1)
placeholders = ",".join(['?'] * len(cols_to_copy))
cur.execute(f"SELECT {cols_list} FROM diploma")
rows = cur.fetchall()
insert_sql = f"INSERT INTO diploma_new ({cols_list}) VALUES ({placeholders})"
cur.executemany(insert_sql, rows)
conn.commit()
print(f"Copied {len(rows)} rows to diploma_new.")
print("Dropping old 'diploma' table and renaming 'diploma_new' to 'diploma'...")
cur.execute("DROP TABLE diploma")
cur.execute("ALTER TABLE diploma_new RENAME TO diploma")
conn.commit()
print("Migration complete. Original DB backed up at:", backup)
conn.close()