Fix database migration error by adding project root to Python path

This commit is contained in:
Automated Action 2025-06-12 19:12:40 +00:00
parent 3ae0760d76
commit 67786a73f4
2 changed files with 71 additions and 2 deletions

View File

@ -1,12 +1,18 @@
import sys
from logging.config import fileConfig
from pathlib import Path
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
# Import Base for metadata
from app.db.base import Base
# Add the project root directory to the Python path
# This ensures that the 'app' module can be found regardless of where alembic is run from
sys.path.insert(0, str(Path(__file__).parent.parent.absolute()))
# Import Base for metadata after adding the project root to sys.path
from app.db.base import Base # noqa
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.

63
test_migration.py Normal file
View File

@ -0,0 +1,63 @@
"""
Test script to check if alembic can find the app module.
This is a dry-run script that doesn't modify the database.
"""
import importlib.util
import sys
from pathlib import Path
def test_imports():
"""Test if app module can be imported."""
# Add project root to Python path
project_root = Path(__file__).parent.absolute()
sys.path.insert(0, str(project_root))
# Try to import the app module
try:
# We're just testing if the import works, not using the module
importlib.import_module("app")
print("✅ Successfully imported app module")
# Try to import Base from app.db.base
try:
importlib.import_module("app.db.base")
print("✅ Successfully imported Base from app.db.base")
return True
except ImportError as e:
print(f"❌ Failed to import Base from app.db.base: {e}")
return False
except ImportError as e:
print(f"❌ Failed to import app module: {e}")
return False
def check_alembic_env():
"""Check if alembic env.py can be imported."""
env_path = Path(__file__).parent / "migrations" / "env.py"
if not env_path.exists():
print(f"❌ Alembic env.py not found at {env_path}")
return False
try:
# Just check if we can create a spec for the module
spec = importlib.util.spec_from_file_location("env", env_path)
if spec is not None:
print("✅ Alembic env.py can be loaded")
return True
else:
print("❌ Could not create spec for alembic env.py")
return False
except Exception as e:
print(f"❌ Failed to load alembic env.py: {e}")
return False
if __name__ == "__main__":
print("Testing imports for alembic migrations...")
imports_ok = test_imports()
env_ok = check_alembic_env()
if imports_ok and env_ok:
print("\n✅ All tests passed. Alembic should now be able to run migrations.")
sys.exit(0)
else:
print("\n❌ Some tests failed. Check the output above for details.")
sys.exit(1)