Spaces:
Sleeping
Sleeping
File size: 5,477 Bytes
5be081e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | """
Database Verification Script for Todo API
Purpose: Verify database connection and schema initialization
Usage: python -m backend.src.db.verify
This script:
1. Tests database connection to Neon PostgreSQL
2. Verifies all tables are created correctly
3. Checks indexes are in place
4. Validates schema matches SQLModel definitions
Run this after setting up your DATABASE_URL in .env file.
"""
import asyncio
import sys
import logging
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger("database.verify")
async def verify_database():
"""
Verify database setup and connectivity.
Returns:
bool: True if all checks pass, False otherwise
"""
try:
# Import after logging is configured
from backend.src.db import (
init_database,
get_session,
check_database_health,
get_engine
)
logger.info("=" * 60)
logger.info("Database Verification Script")
logger.info("=" * 60)
# Step 1: Check database health
logger.info("\n[1/5] Checking database connectivity...")
is_healthy = await check_database_health()
if not is_healthy:
logger.error("β Database connection failed")
return False
logger.info("β Database connection successful")
# Step 2: Initialize database (create tables and indexes)
logger.info("\n[2/5] Initializing database schema...")
await init_database()
logger.info("β Database schema initialized")
# Step 3: Verify todos table exists
logger.info("\n[3/5] Verifying todos table...")
engine = get_engine()
async with engine.begin() as conn:
result = await conn.execute(text("""
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_name = 'todos'
);
"""))
table_exists = result.scalar()
if not table_exists:
logger.error("β Todos table not found")
return False
logger.info("β Todos table exists")
# Step 4: Verify table schema
logger.info("\n[4/5] Verifying table schema...")
async with engine.begin() as conn:
result = await conn.execute(text("""
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = 'todos'
ORDER BY ordinal_position;
"""))
columns = result.fetchall()
required_columns = {
'id': 'uuid',
'user_id': 'character varying',
'title': 'character varying',
'description': 'character varying',
'is_completed': 'boolean',
'created_at': 'timestamp without time zone',
'updated_at': 'timestamp without time zone'
}
found_columns = {col[0]: col[1] for col in columns}
for col_name, col_type in required_columns.items():
if col_name not in found_columns:
logger.error(f"β Missing column: {col_name}")
return False
logger.info(f" β Column '{col_name}' ({found_columns[col_name]})")
# Step 5: Verify indexes
logger.info("\n[5/5] Verifying indexes...")
async with engine.begin() as conn:
result = await conn.execute(text("""
SELECT indexname
FROM pg_indexes
WHERE tablename = 'todos';
"""))
indexes = [row[0] for row in result.fetchall()]
required_indexes = ['todos_pkey', 'ix_todos_user_id', 'idx_todos_user_completed']
for index_name in required_indexes:
if index_name in indexes:
logger.info(f" β Index '{index_name}' exists")
else:
logger.warning(f" β Index '{index_name}' not found (may be created with different name)")
logger.info("\n" + "=" * 60)
logger.info("β All verification checks passed!")
logger.info("=" * 60)
logger.info("\nDatabase is ready for use.")
logger.info("Next steps:")
logger.info(" 1. Start the FastAPI server: uvicorn backend.src.api.main:app --reload")
logger.info(" 2. Test the API endpoints with authentication")
logger.info(" 3. Verify user isolation in multi-tenant scenarios")
return True
except ValueError as e:
logger.error(f"\nβ Configuration error: {e}")
logger.error("\nPlease ensure:")
logger.error(" 1. .env file exists in project root")
logger.error(" 2. DATABASE_URL is set with your Neon connection string")
logger.error(" 3. Format: postgresql://user:password@host.neon.tech/database")
return False
except Exception as e:
logger.error(f"\nβ Verification failed: {e}")
logger.exception("Full error details:")
return False
async def main():
"""Main entry point for verification script."""
success = await verify_database()
sys.exit(0 if success else 1)
if __name__ == "__main__":
asyncio.run(main())
|