gcp-hockey-results/motm_app/add_squad_history.py

92 lines
3.5 KiB
Python
Executable File

#!/usr/bin/env python3
"""
Database migration script to add squad_history table for historical squad tracking.
This script creates the squad_history table to preserve squad data when resetting for a new match.
"""
from db_config import db_config
from sqlalchemy import text
import sys
def add_squad_history_table():
"""Create squad_history table for historical squad records."""
try:
engine = db_config.engine
with engine.connect() as connection:
# Check if table already exists
try:
result = connection.execute(text("SELECT COUNT(*) FROM squad_history LIMIT 1"))
print("✓ Table 'squad_history' already exists")
return True
except Exception:
pass
# Create the squad_history table
try:
# PostgreSQL/SQLite compatible syntax
create_table_sql = text("""
CREATE TABLE squad_history (
id SERIAL PRIMARY KEY,
player_number INTEGER,
player_forenames VARCHAR(50),
player_surname VARCHAR(30),
player_nickname VARCHAR(30),
match_date DATE,
fixture_number VARCHAR(20),
archived_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
connection.execute(create_table_sql)
connection.commit()
print("✓ Successfully created 'squad_history' table (PostgreSQL)")
return True
except Exception as e:
# Try SQLite syntax
try:
connection.rollback()
create_table_sql = text("""
CREATE TABLE squad_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
player_number INTEGER,
player_forenames VARCHAR(50),
player_surname VARCHAR(30),
player_nickname VARCHAR(30),
match_date DATE,
fixture_number VARCHAR(20),
archived_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
connection.execute(create_table_sql)
connection.commit()
print("✓ Successfully created 'squad_history' table (SQLite)")
return True
except Exception as e2:
print(f"✗ Error creating table: {str(e2)}")
return False
except Exception as e:
print(f"✗ Error connecting to database: {str(e)}")
return False
if __name__ == "__main__":
print("=" * 60)
print("Squad History Table - Database Migration")
print("=" * 60)
print("\nThis script will create the 'squad_history' table to preserve")
print("historical squad data when resetting for new matches.\n")
result = add_squad_history_table()
if result:
print("\n✓ Migration completed successfully!")
print("\nSquad data will now be preserved when you reset the squad.")
print("Historical squads are stored with match date and fixture number.")
sys.exit(0)
else:
print("\n✗ Migration failed!")
print("Please check the error messages above.")
sys.exit(1)