Spaces:
Sleeping
Sleeping
File size: 3,221 Bytes
7644eac |
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 |
#!/usr/bin/env python3
"""
Initialize PostgreSQL database on Render.
This script runs database migrations to create all required tables.
"""
import os
import sys
from flask_migrate import upgrade
from web_app import create_app, db
def init_database():
"""Initialize database with migrations"""
print("=" * 60)
print("π§ Initializing PostgreSQL Database on Render")
print("=" * 60)
# Check if DATABASE_URL is set
database_url = os.environ.get('DATABASE_URL')
if not database_url:
print("β ERROR: DATABASE_URL environment variable not set!")
print("Please configure PostgreSQL in Render dashboard.")
sys.exit(1)
print(f"β
Database URL found: {database_url[:30]}...")
# Create Flask app
print("\nπ¦ Creating Flask application...")
app = create_app()
with app.app_context():
print("\nπ Checking database connection...")
try:
# Test database connection
db.engine.connect()
print("β
Database connection successful!")
except Exception as e:
print(f"β Database connection failed: {e}")
sys.exit(1)
print("\nπ Running database migrations...")
try:
# Run all migrations
upgrade()
print("β
Database migrations completed successfully!")
except Exception as e:
print(f"β οΈ Migration warning: {e}")
print("\nAttempting to create missing tables...")
try:
# Create tables if they don't exist (ignores existing ones)
from sqlalchemy import inspect
inspector = inspect(db.engine)
existing_tables = inspector.get_table_names()
print(f"π Existing tables: {', '.join(existing_tables)}")
# Only create tables that don't exist
db.create_all()
print("β
Database schema verified/updated!")
except Exception as e2:
# If it fails due to existing constraints, that's actually OK
if "already exists" in str(e2).lower():
print("β οΈ Some tables/constraints already exist - this is OK!")
print("β
Database schema is ready!")
else:
print(f"β Failed to create tables: {e2}")
sys.exit(1)
print("\nπ Verifying tables...")
try:
# Check if users table exists
from web_app.models import User
user_count = User.query.count()
print(f"β
Users table exists (current count: {user_count})")
except Exception as e:
print(f"β Users table verification failed: {e}")
sys.exit(1)
print("\n" + "=" * 60)
print("β
Database initialization complete!")
print("=" * 60)
print("\nYour database is ready to use. You can now:")
print("1. Register new users")
print("2. Login with Google OAuth")
print("3. Create learning paths")
print("\n")
if __name__ == "__main__":
init_database()
|