39 lines
1.0 KiB
Python
39 lines
1.0 KiB
Python
"""
|
|
PostgreSQL Database Tester Application
|
|
"""
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker, scoped_session
|
|
import os
|
|
|
|
# Get database connection string from environment variable or use default
|
|
DATABASE_URL = os.environ.get(
|
|
"DATABASE_URL",
|
|
"postgresql://postgres:password@localhost:5432/postgres"
|
|
)
|
|
|
|
# Create SQLAlchemy engine
|
|
engine = create_engine(DATABASE_URL)
|
|
|
|
# Create session factory
|
|
session_factory = sessionmaker(bind=engine)
|
|
Session = scoped_session(session_factory)
|
|
|
|
# Create base class for declarative models
|
|
Base = declarative_base()
|
|
Base.query = Session.query_property()
|
|
|
|
def init_db():
|
|
"""Initialize the database by creating all tables"""
|
|
# Import all models to ensure they're registered with Base
|
|
from app.models import user, post
|
|
|
|
# Create all tables
|
|
Base.metadata.create_all(bind=engine)
|
|
|
|
print("Database tables created successfully!")
|
|
|
|
def get_session():
|
|
"""Get a database session"""
|
|
return Session()
|