Skip to content

🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!

Fixed migrations and docker-compose

sassanix7cb9950be814
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 24bed13..1197a77 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,20 @@
# Changelog
+## [0.9.8.7] - 2025-04-03
+
+### Fixed
+- **Migration System Overhaul:** Refactored the database migration system for improved reliability and consistency.
+ - Standardized on `backend/migrations/apply_migrations.py` for applying migrations.
+ - Removed obsolete top-level `migrations/` directory and `backend/run_migrations.py` script.
+ - Simplified `backend/init.sql` to only handle initial role alterations, removing table creation logic.
+ - Corrected `docker-compose.yml` volume mounts and command to use the new migration path (`backend/migrations`).
+ - Cleaned up `Dockerfile` by removing redundant migration script calls and ensuring correct migration directory copying.
+ - Resolved conflicting `user_preferences` table creation by removing the SQL version and relying on the Python migration.
+ - Renamed and renumbered all migration files sequentially (000 to 010) in `backend/migrations/` for clear execution order.
+ - Added `000_create_warranties_table.sql` migration to ensure the base table exists before other migrations reference it.
+ - Verified and ensured idempotency (`CREATE/ALTER ... IF NOT EXISTS`) for all migration scripts, preventing errors on re-runs.
+ - Corrected `fix_permissions.py` execution by ensuring `fix_permissions.sql` is copied into the Docker image.
+
## [0.9.8.6] - 2025-04-01
### Added
diff --git a/Docker/docker-compose.yml b/Docker/docker-compose.yml
index 74fa545..ed7fb06 100644
--- a/Docker/docker-compose.yml
+++ b/Docker/docker-compose.yml
@@ -15,10 +15,10 @@ services:
- SMTP_PASSWORD=password
depends_on:
- - warrackerdb
+ warrackerdb:
+ condition: service_healthy
restart: unless-stopped
-
- # Using a standard PostgreSQL image with initialization
+
warrackerdb:
image: postgres:15-alpine
volumes:
@@ -27,39 +27,13 @@ services:
- POSTGRES_DB=warranty_db
- POSTGRES_USER=warranty_user
- POSTGRES_PASSWORD=${DB_PASSWORD:-warranty_password}
- # This will create the init script directly
- - POSTGRES_MULTIPLE_DATABASES=warranty_db
- - PGUSER=warranty_user
restart: unless-stopped
- # Simple initialization approach
- command: >
- sh -c '
- # Create initialization script
- mkdir -p /docker-entrypoint-initdb.d
- echo "CREATE TABLE IF NOT EXISTS warranties (
- id SERIAL PRIMARY KEY,
- product_name VARCHAR(255) NOT NULL,
- product_url TEXT,
- purchase_date DATE NOT NULL,
- warranty_years INTEGER NOT NULL,
- expiration_date DATE NOT NULL,
- invoice_path TEXT,
- manual_path TEXT,
- purchase_price DECIMAL(10, 2)
- );" > /docker-entrypoint-initdb.d/01-tables.sql
-
- echo "CREATE TABLE IF NOT EXISTS serial_numbers (
- id SERIAL PRIMARY KEY,
- warranty_id INTEGER REFERENCES warranties(id) ON DELETE CASCADE,
- serial_number VARCHAR(255) NOT NULL
- );" > /docker-entrypoint-initdb.d/02-serial-numbers.sql
-
- echo "CREATE INDEX IF NOT EXISTS idx_warranty_id ON serial_numbers(warranty_id);
- CREATE INDEX IF NOT EXISTS idx_expiration_date ON warranties(expiration_date);" > /docker-entrypoint-initdb.d/03-indexes.sql
-
- # Run the standard PostgreSQL entrypoint script
- docker-entrypoint.sh postgres
- '
+
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
+ interval: 5s
+ timeout: 5s
+ retries: 5
volumes:
postgres_data:
diff --git a/Dockerfile b/Dockerfile
index 19d0729..d27fef6 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -24,10 +24,9 @@ RUN pip install --no-cache-dir -r requirements.txt
# Copy backend code
COPY backend/app.py .
COPY backend/gunicorn_config.py .
-COPY backend/run_migrations.py .
COPY backend/fix_permissions.py .
COPY backend/fix_permissions.sql .
-COPY backend/migrations/ ./migrations/
+COPY backend/migrations/ /app/migrations/
# Copy frontend files
COPY frontend/*.html /var/www/html/
@@ -42,7 +41,7 @@ COPY nginx.conf /etc/nginx/conf.d/default.conf
RUN echo '#!/bin/bash\n\
set -e # Exit immediately if a command exits with a non-zero status.\n\
echo "Running database migrations..."\n\
-python /app/run_migrations.py\n\
+python /app/migrations/apply_migrations.py\n\
echo "Ensuring admin role has proper permissions..."\n\
# Retry logic for granting superuser privileges\n\
max_attempts=5\n\
@@ -177,4 +176,4 @@ stopasgroup=true ; Ensure all gunicorn processes receive the stop s
EOF
# Start supervisor which will manage the setup, nginx, and gunicorn processes
-CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]
\ No newline at end of file
+CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]
diff --git a/backend/app.py b/backend/app.py
index 4a17097..187429a 100644
--- a/backend/app.py
+++ b/backend/app.py
@@ -124,101 +124,102 @@ def init_db():
conn = get_db_connection()
cur = conn.cursor()
- # Create users table if it doesn't exist
- cur.execute("""
- CREATE TABLE IF NOT EXISTS users (
- id SERIAL PRIMARY KEY,
- username VARCHAR(50) UNIQUE NOT NULL,
- email VARCHAR(100) UNIQUE NOT NULL,
- password_hash VARCHAR(255) NOT NULL,
- first_name VARCHAR(50),
- last_name VARCHAR(50),
- is_active BOOLEAN DEFAULT TRUE,
- is_admin BOOLEAN DEFAULT FALSE,
- created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
- )
- """)
-
- # Create user_preferences table if it doesn't exist
- cur.execute("""
- CREATE TABLE IF NOT EXISTS user_preferences (
- id SERIAL PRIMARY KEY,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- email_notifications BOOLEAN NOT NULL DEFAULT TRUE,
- default_view VARCHAR(10) NOT NULL DEFAULT 'grid',
- theme VARCHAR(10) NOT NULL DEFAULT 'light',
- expiring_soon_days INTEGER NOT NULL DEFAULT 30,
- notification_frequency VARCHAR(10) NOT NULL DEFAULT 'daily',
- notification_time VARCHAR(5) NOT NULL DEFAULT '09:00',
- created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- UNIQUE(user_id)
- )
- """)
-
- # Check if timezone column exists and add if it doesn't
- cur.execute("""
- DO $$
- BEGIN
- IF NOT EXISTS (
- SELECT column_name
- 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';
- END IF;
- END $$;
- """)
-
- # Create warranties table if it doesn't exist
- cur.execute("""
- CREATE TABLE IF NOT EXISTS warranties (
- id SERIAL PRIMARY KEY,
- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
- item_name VARCHAR(100) NOT NULL,
- purchase_date DATE NOT NULL,
- expiration_date DATE NOT NULL,
- purchase_price DECIMAL(10,2),
- serial_number VARCHAR(100),
- category VARCHAR(50),
- notes TEXT,
- created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
- updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
- )
- """)
-
- # Create warranty_documents table if it doesn't exist
- cur.execute("""
- CREATE TABLE IF NOT EXISTS warranty_documents (
- id INTEGER PRIMARY KEY,
- warranty_id INTEGER NOT NULL REFERENCES warranties(id) ON DELETE CASCADE,
- file_name VARCHAR(255) NOT NULL,
- file_path VARCHAR(255) NOT NULL,
- file_type VARCHAR(50),
- file_size INTEGER,
- created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
- )
- """)
-
- # Create sequence if it doesn't exist
- cur.execute("""
- DO $$
- BEGIN
- IF NOT EXISTS (SELECT 1 FROM pg_sequences WHERE sequencename = 'warranty_documents_id_seq') THEN
- CREATE SEQUENCE warranty_documents_id_seq;
- END IF;
- END $$;
- """)
-
- # Alter table to use the sequence
- cur.execute("""
- ALTER TABLE warranty_documents
- ALTER COLUMN id SET DEFAULT nextval('warranty_documents_id_seq');
- """)
-
+ # Create users table if it doesn't exist - Handled by migrations
+ # cur.execute("""
+ # CREATE TABLE IF NOT EXISTS users (
+ # id SERIAL PRIMARY KEY,
+ # username VARCHAR(50) UNIQUE NOT NULL,
+ # email VARCHAR(100) UNIQUE NOT NULL,
+ # password_hash VARCHAR(255) NOT NULL,
+ # first_name VARCHAR(50),
+ # last_name VARCHAR(50),
+ # is_active BOOLEAN DEFAULT TRUE,
+ # is_admin BOOLEAN DEFAULT FALSE,
+ # created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
+ # updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
+ # )
+ # """)
+
+ # Create user_preferences table if it doesn't exist - Handled by migrations
+ # cur.execute("""
+ # CREATE TABLE IF NOT EXISTS user_preferences (
+ # id SERIAL PRIMARY KEY,
+ # user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ # email_notifications BOOLEAN NOT NULL DEFAULT TRUE,
+ # default_view VARCHAR(10) NOT NULL DEFAULT 'grid',
+ # theme VARCHAR(10) NOT NULL DEFAULT 'light',
+ # expiring_soon_days INTEGER NOT NULL DEFAULT 30,
+ # notification_frequency VARCHAR(10) NOT NULL DEFAULT 'daily',
+ # notification_time VARCHAR(5) NOT NULL DEFAULT '09:00',
+ # created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
+ # updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
+ # UNIQUE(user_id)
+ # )
+ # """)
+
+ # Check if timezone column exists and add if it doesn't - Handled by migrations (e.g., 008_add_timezone_column.sql)
+ # cur.execute("""
+ # DO $$
+ # BEGIN
+ # IF NOT EXISTS (
+ # SELECT column_name
+ # 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';
+ # END IF;
+ # END $$;
+ # """)
+
+ # Create warranties table if it doesn't exist - Handled by migrations
+ # cur.execute("""
+ # CREATE TABLE IF NOT EXISTS warranties (
+ # id SERIAL PRIMARY KEY,
+ # user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ # item_name VARCHAR(100) NOT NULL,
+ # purchase_date DATE NOT NULL,
+ # expiration_date DATE NOT NULL,
+ # purchase_price DECIMAL(10,2),
+ # serial_number VARCHAR(100),
+ # category VARCHAR(50),
+ # notes TEXT,
+ # created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
+ # updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
+ # )
+ # """)
+
+ # Create warranty_documents table if it doesn't exist - Handled by migrations
+ # cur.execute("""
+ # CREATE TABLE IF NOT EXISTS warranty_documents (
+ # id INTEGER PRIMARY KEY,
+ # warranty_id INTEGER NOT NULL REFERENCES warranties(id) ON DELETE CASCADE,
+ # file_name VARCHAR(255) NOT NULL,
+ # file_path VARCHAR(255) NOT NULL,
+ # file_type VARCHAR(50),
+ # file_size INTEGER,
+ # created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
+ # )
+ # """)
+
+ # Create sequence if it doesn't exist - Handled by migrations
+ # cur.execute("""
+ # DO $$
+ # BEGIN
+ # IF NOT EXISTS (SELECT 1 FROM pg_sequences WHERE sequencename = 'warranty_documents_id_seq') THEN
+ # CREATE SEQUENCE warranty_documents_id_seq;
+ # END IF;
+ # END $$;
+ # """)
+
+ # Alter table to use the sequence - Handled by migrations
+ # cur.execute("""
+ # ALTER TABLE warranty_documents
+ # ALTER COLUMN id SET DEFAULT nextval('warranty_documents_id_seq');
+ # """)
+
+ # We might still need to commit if other operations were performed before the commented blocks
conn.commit()
cur.close()
conn.close()
@@ -3034,4 +3035,4 @@ def add_tags_to_warranty(warranty_id):
return jsonify({"error": "Failed to update tags"}), 500
finally:
if conn:
- release_db_connection(conn)
\ No newline at end of file
+ release_db_connection(conn)
diff --git a/backend/init.sql b/backend/init.sql
index 18d8352..1afc0cc 100644
--- a/backend/init.sql
+++ b/backend/init.sql
@@ -3,43 +3,5 @@
-- Grant superuser privileges to warranty_user
ALTER 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,
- purchase_date DATE NOT NULL,
- warranty_years INTEGER NOT NULL,
- expiration_date DATE,
- invoice_path TEXT,
- manual_path TEXT,
- product_url TEXT,
- purchase_price DECIMAL(10, 2),
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-);
-
-CREATE INDEX idx_expiration_date ON warranties(expiration_date);
-CREATE INDEX idx_product_name ON warranties(product_name);
-
--- 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
-);
-
-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
+-- The rest of the file content (CREATE TABLE, INSERT INTO) should be removed.
+-- The migration system (apply_migrations.py) will handle table creation.
\ No newline at end of file
diff --git a/backend/migrations/000_create_warranties_table.sql b/backend/migrations/000_create_warranties_table.sql
new file mode 100644
index 0000000..4122853
--- /dev/null
+++ b/backend/migrations/000_create_warranties_table.sql
@@ -0,0 +1,20 @@
+-- backend/migrations/000_create_warranties_table.sql
+
+-- Create warranties table if it doesn't exist
+CREATE TABLE IF NOT EXISTS warranties (
+ id SERIAL PRIMARY KEY,
+ product_name VARCHAR(255) NOT NULL,
+ purchase_date DATE NOT NULL,
+ warranty_years INTEGER NOT NULL,
+ expiration_date DATE,
+ invoice_path TEXT,
+ manual_path TEXT,
+ product_url TEXT,
+ -- purchase_price is added by migration 002
+ -- user_id is added by migration 003
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+);
+
+-- Create indexes if they don't exist
+CREATE INDEX IF NOT EXISTS idx_expiration_date ON warranties(expiration_date);
+CREATE INDEX IF NOT EXISTS idx_product_name ON warranties(product_name);
\ No newline at end of file
diff --git a/backend/migrations/002_add_users_table.sql b/backend/migrations/002_add_users_table.sql
deleted file mode 100644
index b7b02e0..0000000
--- a/backend/migrations/002_add_users_table.sql
+++ /dev/null
@@ -1,51 +0,0 @@
--- Migration: Add users table and related tables
-
--- Users table
-CREATE TABLE users (
- id SERIAL PRIMARY KEY,
- username VARCHAR(255) NOT NULL UNIQUE,
- email VARCHAR(255) NOT NULL UNIQUE,
- password_hash VARCHAR(255) NOT NULL,
- first_name VARCHAR(255),
- last_name VARCHAR(255),
- is_active BOOLEAN DEFAULT TRUE,
- is_admin BOOLEAN DEFAULT FALSE,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- last_login TIMESTAMP
-);
-
-CREATE INDEX idx_username ON users(username);
-CREATE INDEX idx_email ON users(email);
-
--- Add user_id to warranties table to associate warranties with users
-ALTER TABLE warranties ADD COLUMN user_id INTEGER;
-ALTER TABLE warranties ADD CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL;
-CREATE INDEX idx_user_id ON warranties(user_id);
-
--- Create password reset tokens table
-CREATE TABLE password_reset_tokens (
- id SERIAL PRIMARY KEY,
- user_id INTEGER NOT NULL,
- token VARCHAR(255) NOT NULL,
- expires_at TIMESTAMP NOT NULL,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-);
-
-CREATE INDEX idx_token ON password_reset_tokens(token);
-CREATE INDEX idx_user_id_token ON password_reset_tokens(user_id);
-
--- Create user sessions table
-CREATE TABLE user_sessions (
- id SERIAL PRIMARY KEY,
- user_id INTEGER NOT NULL,
- session_token VARCHAR(255) NOT NULL,
- expires_at TIMESTAMP NOT NULL,
- ip_address VARCHAR(45),
- user_agent TEXT,
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
- FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
-);
-
-CREATE INDEX idx_session_token ON user_sessions(session_token);
-CREATE INDEX idx_user_id_session ON user_sessions(user_id);
diff --git a/backend/migrations/002_create_user_preferences_table.sql b/backend/migrations/002_create_user_preferences_table.sql
deleted file mode 100644
index da175f3..0000000
--- a/backend/migrations/002_create_user_preferences_table.sql
+++ /dev/null
@@ -1,37 +0,0 @@
--- 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 file
diff --git a/backend/migrations/003_add_users_table.sql b/backend/migrations/003_add_users_table.sql
new file mode 100644
index 0000000..82f5304
--- /dev/null
+++ b/backend/migrations/003_add_users_table.sql
@@ -0,0 +1,63 @@
+-- Migration: Add users table and related tables
+
+-- Users table
+CREATE TABLE IF NOT EXISTS users (
+ id SERIAL PRIMARY KEY,
+ username VARCHAR(255) NOT NULL UNIQUE,
+ email VARCHAR(255) NOT NULL UNIQUE,
+ password_hash VARCHAR(255) NOT NULL,
+ first_name VARCHAR(255),
+ last_name VARCHAR(255),
+ is_active BOOLEAN DEFAULT TRUE,
+ is_admin BOOLEAN DEFAULT FALSE,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ last_login TIMESTAMP
+);
+
+CREATE INDEX IF NOT EXISTS idx_username ON users(username);
+CREATE INDEX IF NOT EXISTS idx_email ON users(email);
+
+-- Add user_id to warranties table if it doesn't exist
+ALTER TABLE warranties ADD COLUMN IF NOT EXISTS user_id INTEGER;
+
+-- Add foreign key constraint if it doesn't exist
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint
+ WHERE conname = 'fk_user' AND conrelid = 'warranties'::regclass
+ ) THEN
+ ALTER TABLE warranties ADD CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL;
+ END IF;
+END
+$$;
+
+CREATE INDEX IF NOT EXISTS idx_user_id ON warranties(user_id);
+
+-- Create password reset tokens table
+CREATE TABLE IF NOT EXISTS password_reset_tokens (
+ id SERIAL PRIMARY KEY,
+ user_id INTEGER NOT NULL,
+ token VARCHAR(255) NOT NULL,
+ expires_at TIMESTAMP NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+);
+
+CREATE INDEX IF NOT EXISTS idx_token ON password_reset_tokens(token);
+CREATE INDEX IF NOT EXISTS idx_user_id_token ON password_reset_tokens(user_id);
+
+-- Create user sessions table
+CREATE TABLE IF NOT EXISTS user_sessions (
+ id SERIAL PRIMARY KEY,
+ user_id INTEGER NOT NULL,
+ session_token VARCHAR(255) NOT NULL,
+ expires_at TIMESTAMP NOT NULL,
+ ip_address VARCHAR(45),
+ user_agent TEXT,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+);
+
+CREATE INDEX IF NOT EXISTS idx_session_token ON user_sessions(session_token);
+CREATE INDEX IF NOT EXISTS idx_user_id_session ON user_sessions(user_id);
diff --git a/backend/migrations/004_add_user_preferences.py b/backend/migrations/004_create_user_preferences_table.py
similarity index 100%
rename from backend/migrations/004_add_user_preferences.py
rename to backend/migrations/004_create_user_preferences_table.py
diff --git a/backend/migrations/007_add_expiring_soon_days.py b/backend/migrations/005_add_expiring_soon_days_column.py
similarity index 100%
rename from backend/migrations/007_add_expiring_soon_days.py
rename to backend/migrations/005_add_expiring_soon_days_column.py
diff --git a/backend/migrations/003_add_notification_preferences.sql b/backend/migrations/006_add_notification_preferences.sql
similarity index 100%
rename from backend/migrations/003_add_notification_preferences.sql
rename to backend/migrations/006_add_notification_preferences.sql
diff --git a/backend/migrations/003_add_tags.sql b/backend/migrations/007_add_tags.sql
similarity index 100%
rename from backend/migrations/003_add_tags.sql
rename to backend/migrations/007_add_tags.sql
diff --git a/backend/migrations/005_configure_admin_roles.sql b/backend/migrations/008_configure_admin_roles.sql
similarity index 100%
rename from backend/migrations/005_configure_admin_roles.sql
rename to backend/migrations/008_configure_admin_roles.sql
diff --git a/backend/migrations/006_ensure_admin_permissions.sql b/backend/migrations/009_ensure_admin_permissions.sql
similarity index 100%
rename from backend/migrations/006_ensure_admin_permissions.sql
rename to backend/migrations/009_ensure_admin_permissions.sql
diff --git a/backend/migrations/008_add_timezone_column.sql b/backend/migrations/010_add_timezone_column.sql
similarity index 100%
rename from backend/migrations/008_add_timezone_column.sql
rename to backend/migrations/010_add_timezone_column.sql
diff --git a/backend/migrations/__pycache__/004_create_user_preferences_table.cpython-39.pyc b/backend/migrations/__pycache__/004_create_user_preferences_table.cpython-39.pyc
new file mode 100644
index 0000000..fcac455
Binary files /dev/null and b/backend/migrations/__pycache__/004_create_user_preferences_table.cpython-39.pyc differ
diff --git a/backend/migrations/__pycache__/005_add_expiring_soon_days_column.cpython-39.pyc b/backend/migrations/__pycache__/005_add_expiring_soon_days_column.cpython-39.pyc
new file mode 100644
index 0000000..efbb225
Binary files /dev/null and b/backend/migrations/__pycache__/005_add_expiring_soon_days_column.cpython-39.pyc differ
diff --git a/backend/run_migrations.py b/backend/run_migrations.py
deleted file mode 100644
index ad1b131..0000000
--- a/backend/run_migrations.py
+++ /dev/null
@@ -1,105 +0,0 @@
-#!/usr/bin/env python3
-import os
-import sys
-import psycopg2
-import logging
-from psycopg2 import pool
-import time
-
-# Configure logging
-logging.basicConfig(level=logging.INFO)
-logger = logging.getLogger(__name__)
-
-# PostgreSQL connection details
-DB_HOST = os.environ.get('DB_HOST', 'warrackerdb')
-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')
-
-def create_db_connection(max_retries=5, retry_delay=5):
- """Create a database connection with retry logic"""
- attempt = 0
- last_exception = None
-
- while attempt < max_retries:
- try:
- logger.info(f"Attempting to connect to database (attempt {attempt+1}/{max_retries})")
- conn = psycopg2.connect(
- host=DB_HOST,
- database=DB_NAME,
- user=DB_USER,
- password=DB_PASSWORD
- )
- logger.info("Database connection successful")
- return conn
- except Exception as e:
- last_exception = e
- logger.error(f"Database connection error: {e}")
- logger.info(f"Retrying in {retry_delay} seconds...")
- time.sleep(retry_delay)
- attempt += 1
-
- # If we got here, all connection attempts failed
- logger.error(f"Failed to connect to database after {max_retries} attempts")
- raise last_exception
-
-def run_migrations():
- """Run all migration scripts in order"""
- conn = None
- try:
- conn = create_db_connection()
- conn.autocommit = False
- cursor = conn.cursor()
-
- # Get list of migration files
- migration_dir = os.path.join(os.path.dirname(__file__), 'migrations')
- migration_files = sorted([f for f in os.listdir(migration_dir) if f.endswith('.sql')])
-
- # Create migrations table if it doesn't exist
- cursor.execute('''
- CREATE TABLE IF NOT EXISTS migrations (
- id SERIAL PRIMARY KEY,
- filename VARCHAR(255) NOT NULL UNIQUE,
- applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
- )
- ''')
-
- # Get already applied migrations
- cursor.execute('SELECT filename FROM migrations')
- applied_migrations = {row[0] for row in cursor.fetchall()}
-
- # Apply new migrations
- for migration_file in migration_files:
- if migration_file in applied_migrations:
- logger.info(f"Migration {migration_file} already applied, skipping")
- continue
-
- logger.info(f"Applying migration: {migration_file}")
- migration_path = os.path.join(migration_dir, migration_file)
-
- with open(migration_path, 'r') as f:
- migration_sql = f.read()
-
- try:
- cursor.execute(migration_sql)
- cursor.execute('INSERT INTO migrations (filename) VALUES (%s)', (migration_file,))
- logger.info(f"Migration {migration_file} applied successfully")
- except Exception as e:
- conn.rollback()
- logger.error(f"Error applying migration {migration_file}: {e}")
- raise
-
- conn.commit()
- logger.info("All migrations applied successfully")
-
- except Exception as e:
- logger.error(f"Migration error: {e}")
- if conn:
- conn.rollback()
- sys.exit(1)
- finally:
- if conn:
- conn.close()
-
-if __name__ == "__main__":
- run_migrations()
\ No newline at end of file
diff --git a/docker-compose.yml b/docker-compose.yml
index 939cf2e..c313f40 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -7,8 +7,7 @@ services:
- "8005:80"
volumes:
- ./uploads:/data/uploads
- - ./migrations:/app/migrations
- - ./backend/migrations:/app/backend_migrations
+ - ./backend/migrations:/app/migrations
environment:
- DB_HOST=warrackerdb
- DB_NAME=warranty_db
@@ -27,8 +26,8 @@ services:
restart: unless-stopped
command: >
bash -c "
- cd /app && ls -la /app/backend_migrations &&
- python /app/backend_migrations/apply_migrations.py &&
+ cd /app && ls -la /app/migrations &&
+ python /app/migrations/apply_migrations.py &&
python /app/fix_permissions.py &&
exec /usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf
"