From eaf416316a6342b7b322c1c800b3115535864bb7 Mon Sep 17 00:00:00 2001 From: Nathan Woodburn Date: Wed, 22 Oct 2025 12:20:14 +1100 Subject: [PATCH] feat: Try to migrate db --- website/__init__.py | 16 +++++++++++++ website/migrations.py | 54 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 website/__init__.py create mode 100644 website/migrations.py diff --git a/website/__init__.py b/website/__init__.py new file mode 100644 index 0000000..d3dcc42 --- /dev/null +++ b/website/__init__.py @@ -0,0 +1,16 @@ +import os +from flask import Flask + +def create_app(): + app = Flask(__name__) + app.config.from_object(os.environ['APP_SETTINGS']) + + # Import models after app creation but before init_db + from .models import db, User + db.init_app(app) + + # Run migrations to fix schema issues + from .migrations import add_missing_columns_to_oauth2_code + add_missing_columns_to_oauth2_code(app) + + return app \ No newline at end of file diff --git a/website/migrations.py b/website/migrations.py new file mode 100644 index 0000000..4d5e5ee --- /dev/null +++ b/website/migrations.py @@ -0,0 +1,54 @@ +import sqlite3 +from sqlalchemy import inspect +from flask import current_app + +def add_missing_columns_to_oauth2_code(app): + """ + Check and add missing columns to oauth2_code table + """ + with app.app_context(): + from website.models import db + + # Get the engine and inspector + engine = db.engine + inspector = inspect(engine) + + # Check if oauth2_code table exists + if 'oauth2_code' not in inspector.get_table_names(): + return # Table doesn't exist yet + + # Get existing columns + columns = [column['name'] for column in inspector.get_columns('oauth2_code')] + + # Define columns that should be added if missing + missing_columns = { + 'acr': 'TEXT', + 'amr': 'TEXT', + 'code_challenge': 'TEXT', + 'code_challenge_method': 'TEXT' + } + + # Check which columns need to be added + columns_to_add = {col: dtype for col, dtype in missing_columns.items() if col not in columns} + + if not columns_to_add: + return # No columns need to be added + + # Connect directly to SQLite to add columns + try: + db_path = current_app.config.get('SQLALCHEMY_DATABASE_URI').replace('sqlite:///', '') + conn = sqlite3.connect(db_path) + cursor = conn.cursor() + + for column, dtype in columns_to_add.items(): + try: + cursor.execute(f'ALTER TABLE oauth2_code ADD COLUMN {column} {dtype};') + print(f"Added missing column '{column}' to oauth2_code table") + except sqlite3.OperationalError as e: + # Column might have been added in a concurrent process + print(f"Note: {str(e)}") + + conn.commit() + conn.close() + except Exception as e: + print(f"Error during migration: {str(e)}")