Files
website/utils/db_fix.py

78 lines
2.7 KiB
Python
Executable File

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sqlite3
from datetime import datetime
import sys
import importlib.util
# Add the parent directory to path so we can import the app
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parent_dir)
from app import app, db_path
from models import db
def ensure_db_dir():
"""Make sure the database directory exists."""
os.makedirs(os.path.dirname(db_path), exist_ok=True)
def fix_database_schema():
"""Fix the database schema by adding missing columns."""
with app.app_context():
# Ensure directory exists
ensure_db_dir()
# Check if database exists, create tables if needed
if not os.path.exists(db_path):
print("Database doesn't exist. Creating all tables from scratch...")
db.create_all()
print("Database tables created successfully!")
return
# Connect to existing database
print(f"Connecting to database: {db_path}")
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Check if User table exists
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='user'")
if not cursor.fetchone():
print("User table doesn't exist. Creating all tables from scratch...")
conn.close()
db.create_all()
print("Database tables created successfully!")
return
# Check existing columns
cursor.execute("PRAGMA table_info(user)")
columns = cursor.fetchall()
column_names = [col[1] for col in columns]
print("Existing columns in User table:", column_names)
# Add missing columns
if 'created_at' not in column_names:
print("Adding 'created_at' column to User table...")
cursor.execute("ALTER TABLE user ADD COLUMN created_at TIMESTAMP")
if 'last_login' not in column_names:
print("Adding 'last_login' column to User table...")
cursor.execute("ALTER TABLE user ADD COLUMN last_login TIMESTAMP")
if 'avatar' not in column_names:
print("Adding 'avatar' column to User table...")
cursor.execute("ALTER TABLE user ADD COLUMN avatar VARCHAR(200)")
if 'bio' not in column_names:
print("Adding 'bio' column to User table...")
cursor.execute("ALTER TABLE user ADD COLUMN bio TEXT")
# Commit the changes
conn.commit()
conn.close()
print("Database schema updated successfully!")
return True
if __name__ == "__main__":
fix_database_schema()