🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Fixed database migration system issues
sassanix6d869d953d7f
diff --git a/backend/init.sql b/backend/init.sqlindex 8566a06..18d8352 100644--- a/backend/init.sql+++ b/backend/init.sql@@ -3,6 +3,19 @@-- Grant superuser privileges to warranty_userALTER ROLE warranty_user WITH SUPERUSER;+-- Create migrations tracking table+CREATE TABLE IF NOT EXISTS migrations (+ id SERIAL PRIMARY KEY,+ filename VARCHAR(255) NOT NULL UNIQUE,+ applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP+);++-- Insert records for migrations applied in this script+INSERT INTO migrations (filename) VALUES ('001_add_serial_numbers.sql')+ON CONFLICT (filename) DO NOTHING;+INSERT INTO migrations (filename) VALUES ('002_add_purchase_price.sql')+ON CONFLICT (filename) DO NOTHING;+CREATE TABLE warranties (id SERIAL PRIMARY KEY,product_name VARCHAR(255) NOT NULL,diff --git a/backend/migrations/001_add_serial_numbers.sql b/backend/migrations/001_add_serial_numbers.sqlindex b982c72..346c926 100644--- a/backend/migrations/001_add_serial_numbers.sql+++ b/backend/migrations/001_add_serial_numbers.sql@@ -1,11 +1,20 @@-- Add serial numbers table-CREATE TABLE serial_numbers (- id SERIAL PRIMARY KEY,- warranty_id INTEGER NOT NULL,- serial_number VARCHAR(255) NOT NULL,- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,- FOREIGN KEY (warranty_id) REFERENCES warranties(id) ON DELETE CASCADE-);+DO $$+BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM information_schema.tables+ WHERE table_name = 'serial_numbers'+ ) THEN+ CREATE TABLE serial_numbers (+ id SERIAL PRIMARY KEY,+ warranty_id INTEGER NOT NULL,+ serial_number VARCHAR(255) NOT NULL,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ FOREIGN KEY (warranty_id) REFERENCES warranties(id) ON DELETE CASCADE+ );-CREATE INDEX idx_warranty_id ON serial_numbers(warranty_id);-CREATE INDEX idx_serial_number ON serial_numbers(serial_number);\ No newline at end of file+ -- Create indexes only if we created the table+ CREATE INDEX idx_warranty_id ON serial_numbers(warranty_id);+ CREATE INDEX idx_serial_number ON serial_numbers(serial_number);+ END IF;+END $$;\ No newline at end of filediff --git a/backend/migrations/002_add_purchase_price.sql b/backend/migrations/002_add_purchase_price.sqlindex 44697c9..ffd76b8 100644--- a/backend/migrations/002_add_purchase_price.sql+++ b/backend/migrations/002_add_purchase_price.sql@@ -1,2 +1,10 @@--- Add purchase_price column to warranties table-ALTER TABLE warranties ADD COLUMN purchase_price DECIMAL(10, 2);\ No newline at end of file+-- Add purchase_price column to warranties table if it doesn't exist+DO $$+BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM information_schema.columns+ WHERE table_name = 'warranties' AND column_name = 'purchase_price'+ ) THEN+ ALTER TABLE warranties ADD COLUMN purchase_price DECIMAL(10, 2);+ END IF;+END $$;\ No newline at end of filediff --git a/backend/migrations/002_create_user_preferences_table.sql b/backend/migrations/002_create_user_preferences_table.sqlnew file mode 100644index 0000000..da175f3--- /dev/null+++ b/backend/migrations/002_create_user_preferences_table.sql@@ -0,0 +1,37 @@+-- Create user_preferences table if it doesn't exist+DO $$+BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM information_schema.tables WHERE table_name = 'user_preferences'+ ) THEN+ CREATE TABLE user_preferences (+ id SERIAL PRIMARY KEY,+ user_id INTEGER UNIQUE NOT NULL,+ email_notifications BOOLEAN NOT NULL DEFAULT TRUE,+ default_view VARCHAR(10) NOT NULL DEFAULT 'grid',+ theme VARCHAR(10) NOT NULL DEFAULT 'light',+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()+ );++ -- Add user_id constraint if users table exists+ IF EXISTS (+ SELECT 1 FROM information_schema.tables WHERE table_name = 'users'+ ) THEN+ -- First drop the constraint if it already exists (to avoid errors)+ BEGIN+ ALTER TABLE user_preferences DROP CONSTRAINT IF EXISTS user_preferences_user_id_fkey;+ EXCEPTION WHEN OTHERS THEN+ -- Ignore errors+ END;++ -- Add the foreign key constraint+ ALTER TABLE user_preferences+ ADD CONSTRAINT user_preferences_user_id_fkey+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE;+ END IF;++ -- Add index for faster user lookups+ CREATE INDEX IF NOT EXISTS idx_user_preferences_user_id ON user_preferences(user_id);+ END IF;+END $$;\ No newline at end of filediff --git a/backend/migrations/008_add_timezone_column.sql b/backend/migrations/008_add_timezone_column.sqlnew file mode 100644index 0000000..8a835d3--- /dev/null+++ b/backend/migrations/008_add_timezone_column.sql@@ -0,0 +1,17 @@+-- Add timezone column to user_preferences table if it doesn't exist+DO $$+BEGIN+ IF NOT EXISTS (+ SELECT 1+ FROM information_schema.columns+ WHERE table_name = 'user_preferences'+ AND column_name = 'timezone'+ ) THEN+ ALTER TABLE user_preferences+ ADD COLUMN timezone VARCHAR(50) NOT NULL DEFAULT 'UTC';++ RAISE NOTICE 'Added timezone column to user_preferences table';+ ELSE+ RAISE NOTICE 'timezone column already exists in user_preferences table';+ END IF;+END $$;\ No newline at end of filediff --git a/backend/migrations/__pycache__/004_add_user_preferences.cpython-39.pyc b/backend/migrations/__pycache__/004_add_user_preferences.cpython-39.pycnew file mode 100644index 0000000..46e206fBinary files /dev/null and b/backend/migrations/__pycache__/004_add_user_preferences.cpython-39.pyc differdiff --git a/backend/migrations/__pycache__/007_add_expiring_soon_days.cpython-39.pyc b/backend/migrations/__pycache__/007_add_expiring_soon_days.cpython-39.pycnew file mode 100644index 0000000..fe52eacBinary files /dev/null and b/backend/migrations/__pycache__/007_add_expiring_soon_days.cpython-39.pyc differdiff --git a/backend/migrations/apply_migrations.py b/backend/migrations/apply_migrations.pynew file mode 100644index 0000000..578f24d--- /dev/null+++ b/backend/migrations/apply_migrations.py@@ -0,0 +1,156 @@+#!/usr/bin/env python3+import os+import glob+import psycopg2+import logging+import time+import sys+import importlib.util++# Set up logging+logging.basicConfig(+ level=logging.INFO,+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',+ handlers=[logging.StreamHandler()]+)+logger = logging.getLogger(__name__)++def get_db_connection(max_attempts=5, attempt_delay=5):+ """Get a connection to the PostgreSQL database with retry logic"""+ for attempt in range(1, max_attempts + 1):+ try:+ logger.info(f"Attempting to connect to database (attempt {attempt}/{max_attempts})")++ # Get connection details from environment variables or use defaults+ db_host = os.environ.get('DB_HOST', 'localhost')+ db_port = os.environ.get('DB_PORT', '5432')+ db_name = os.environ.get('DB_NAME', 'warranty_db')+ db_user = os.environ.get('DB_USER', 'warranty_user')+ db_password = os.environ.get('DB_PASSWORD', 'warranty_password')++ conn = psycopg2.connect(+ host=db_host,+ port=db_port,+ dbname=db_name,+ user=db_user,+ password=db_password+ )++ # Set autocommit to False for transaction control+ conn.autocommit = False++ logger.info("Database connection successful")+ return conn++ except Exception as e:+ logger.error(f"Database connection error (attempt {attempt}/{max_attempts}): {e}")++ if attempt < max_attempts:+ logger.info(f"Retrying in {attempt_delay} seconds...")+ time.sleep(attempt_delay)+ else:+ logger.error("Maximum connection attempts reached. Could not connect to database.")+ raise++def load_python_migration(file_path):+ """Load a Python migration module dynamically"""+ module_name = os.path.basename(file_path).replace('.py', '')+ spec = importlib.util.spec_from_file_location(module_name, file_path)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module++def apply_migrations():+ """Apply all SQL and Python migration files in the migrations directory"""+ conn = None+ try:+ conn = get_db_connection()+ cur = conn.cursor()++ # Create migrations table if it doesn't exist+ cur.execute("""+ CREATE TABLE IF NOT EXISTS migrations (+ id SERIAL PRIMARY KEY,+ filename VARCHAR(255) NOT NULL UNIQUE,+ applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP+ )+ """)+ conn.commit()++ # Get list of migration files (both SQL and Python)+ migration_dir = os.path.dirname(os.path.abspath(__file__))+ sql_files = sorted(glob.glob(os.path.join(migration_dir, '*.sql')))+ py_files = sorted(glob.glob(os.path.join(migration_dir, '*.py')))+ # Filter out this script itself+ py_files = [f for f in py_files if os.path.basename(f) != 'apply_migrations.py']++ # Combine and sort all migration files by name+ all_migration_files = sorted(sql_files + py_files)++ if not all_migration_files:+ logger.info("No migration files found.")+ return++ # Get list of already applied migrations+ cur.execute("SELECT filename FROM migrations")+ applied_migrations = set([row[0] for row in cur.fetchall()])++ # Apply each migration file if not already applied+ for migration_file in all_migration_files:+ filename = os.path.basename(migration_file)++ if filename in applied_migrations:+ logger.info(f"Migration {filename} already applied, skipping.")+ continue++ logger.info(f"Applying migration: {filename}")++ try:+ if migration_file.endswith('.sql'):+ # Apply SQL migration+ with open(migration_file, 'r') as f:+ sql = f.read()++ cur.execute(sql)+ elif migration_file.endswith('.py'):+ # Apply Python migration+ migration_module = load_python_migration(migration_file)+ if hasattr(migration_module, 'upgrade'):+ migration_module.upgrade(cur)+ else:+ logger.warning(f"Python migration {filename} does not have an upgrade function, skipping.")+ continue++ # Record the migration as applied+ cur.execute(+ "INSERT INTO migrations (filename) VALUES (%s)",+ (filename,)+ )++ conn.commit()+ logger.info(f"Migration {filename} applied successfully")++ except Exception as e:+ conn.rollback()+ logger.error(f"Error applying migration {filename}: {e}")+ if migration_file.endswith('.sql'):+ logger.error(f"\nQUERY: {sql}\n")+ raise++ except Exception as e:+ logger.error(f"Migration error: {e}")+ if conn:+ conn.rollback()+ raise++ finally:+ if conn:+ conn.close()++if __name__ == "__main__":+ try:+ apply_migrations()+ logger.info("Migrations completed successfully")+ except Exception as e:+ logger.error(f"Migration process failed: {e}")+ sys.exit(1)\ No newline at end of filediff --git a/docker-compose.yml b/docker-compose.ymlindex aaa6093..8ae0f07 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -9,6 +9,7 @@ services:- ./data:/data- ./uploads:/data/uploads- ./migrations:/app/migrations+ - ./backend/migrations:/app/backend_migrationsenvironment:- DB_HOST=warrackerdb- DB_NAME=warranty_db@@ -20,6 +21,7 @@ services:- SMTP_PORT=${SMTP_PORT:-1025}- SMTP_USERNAME=${SMTP_USERNAME:[email protected]}- SMTP_PASSWORD=${SMTP_PASSWORD:-}+ - PYTHONUNBUFFERED=1depends_on:warrackerdb:condition: service_healthy@@ -27,7 +29,8 @@ services:command: >bash -c "chmod -R 777 /data/uploads &&- cd /app/migrations && python apply_migrations.py &&+ cd /app && ls -la /app/backend_migrations &&+ python /app/backend_migrations/apply_migrations.py &&python /app/fix_permissions.py &&exec /usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf"diff --git a/migrations/apply_migrations.py b/migrations/apply_migrations.pyindex 8840b5a..578f24d 100644--- a/migrations/apply_migrations.py+++ b/migrations/apply_migrations.py@@ -5,6 +5,7 @@ import psycopg2import loggingimport timeimport sys+import importlib.util# Set up logginglogging.basicConfig(@@ -51,8 +52,16 @@ def get_db_connection(max_attempts=5, attempt_delay=5):logger.error("Maximum connection attempts reached. Could not connect to database.")raise+def load_python_migration(file_path):+ """Load a Python migration module dynamically"""+ module_name = os.path.basename(file_path).replace('.py', '')+ spec = importlib.util.spec_from_file_location(module_name, file_path)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+def apply_migrations():- """Apply all SQL migration files in the migrations directory"""+ """Apply all SQL and Python migration files in the migrations directory"""conn = Nonetry:conn = get_db_connection()@@ -68,11 +77,17 @@ def apply_migrations():""")conn.commit()- # Get list of migration files+ # Get list of migration files (both SQL and Python)migration_dir = os.path.dirname(os.path.abspath(__file__))- migration_files = sorted(glob.glob(os.path.join(migration_dir, '*.sql')))+ sql_files = sorted(glob.glob(os.path.join(migration_dir, '*.sql')))+ py_files = sorted(glob.glob(os.path.join(migration_dir, '*.py')))+ # Filter out this script itself+ py_files = [f for f in py_files if os.path.basename(f) != 'apply_migrations.py']++ # Combine and sort all migration files by name+ all_migration_files = sorted(sql_files + py_files)- if not migration_files:+ if not all_migration_files:logger.info("No migration files found.")return@@ -81,7 +96,7 @@ def apply_migrations():applied_migrations = set([row[0] for row in cur.fetchall()])# Apply each migration file if not already applied- for migration_file in migration_files:+ for migration_file in all_migration_files:filename = os.path.basename(migration_file)if filename in applied_migrations:@@ -91,11 +106,20 @@ def apply_migrations():logger.info(f"Applying migration: {filename}")try:- # Read and execute the SQL file- with open(migration_file, 'r') as f:- sql = f.read()-- cur.execute(sql)+ if migration_file.endswith('.sql'):+ # Apply SQL migration+ with open(migration_file, 'r') as f:+ sql = f.read()++ cur.execute(sql)+ elif migration_file.endswith('.py'):+ # Apply Python migration+ migration_module = load_python_migration(migration_file)+ if hasattr(migration_module, 'upgrade'):+ migration_module.upgrade(cur)+ else:+ logger.warning(f"Python migration {filename} does not have an upgrade function, skipping.")+ continue# Record the migration as appliedcur.execute(@@ -109,7 +133,8 @@ def apply_migrations():except Exception as e:conn.rollback()logger.error(f"Error applying migration {filename}: {e}")- logger.error(f"\nQUERY: {sql}\n")+ if migration_file.endswith('.sql'):+ logger.error(f"\nQUERY: {sql}\n")raiseexcept Exception as e: