Untitled

mail@pastecode.io avatar
unknown
plain_text
15 days ago
3.2 kB
2
Indexable
Never
import strawberry
from strawberry.fastapi import GraphQLRouter
from sqlalchemy import Column, Integer, String, ForeignKey, create_engine, select
from sqlalchemy.orm import relationship, sessionmaker, Session
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.inspection import inspect
from fastapi import FastAPI, Depends, HTTPException
from typing import List, Optional

# Database configuration
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"  # Replace with your database URL

# Create SQLAlchemy engine
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# Base declarative class
Base = declarative_base()

# Database models
class User(Base):
    __tablename__ = 'mdm_users'
    MDM_USER_ID = Column(Integer, primary_key=True)
    MDM_LOGIN = Column(String, unique=True)
    countries = relationship('UserCountry', back_populates='user')
    therapeutics = relationship('UserTherapeutic', back_populates='user')

class UserCountry(Base):
    __tablename__ = 'mdm_users_countries'
    USER_CNTRY_ID = Column(Integer, primary_key=True)
    USER_ID = Column(Integer, ForeignKey('mdm_users.MDM_USER_ID'))
    COUNTRY_ID = Column(Integer)
    user = relationship('User', back_populates='countries')

class UserTherapeutic(Base):
    __tablename__ = 'mdm_users_therapeutics'
    USER_TA_ID = Column(Integer, primary_key=True)
    USER_ID = Column(Integer, ForeignKey('mdm_users.MDM_USER_ID'))
    TA_ID = Column(Integer)
    user = relationship('User', back_populates='therapeutics')

class ProductView(Base):  # Your dynamic model here
    __tablename__ = 'mdm_product_view'
    # Example columns
    ID = Column(Integer, primary_key=True)
    PRODUCT_NAME = Column(String)
    COUNTRY_ID = Column(Integer)
    # Add other columns as necessary

# FastAPI app initialization
app = FastAPI()

# Dependency to get DB session
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# Function to create a dynamic Strawberry type from a SQLAlchemy model
def get_dynamic_type(model):
    fields = {}
    mapper = inspect(model)
    for column in mapper.attrs:
        fields[column.key] = strawberry.field()  # Using default types
    return strawberry.type(model.__name__, **fields)

# Create dynamic GraphQL type for ProductView
ProductViewType = get_dynamic_type(ProductView)

@strawberry.type
class Query:
    @strawberry.field
    async def get_product_data(self, db: Session = Depends(get_db)) -> List[ProductViewType]:
        results = db.query(ProductView).all()  # Replace with your query logic
        # Dynamically create a list of ProductViewType from the results
        return [ProductViewType(**{column.key: getattr(product, column.key) for column in inspect(ProductView).c}) for product in results]

# Create GraphQL schema and router
schema = strawberry.Schema(query=Query)
graphql_app = GraphQLRouter(schema)

# Include the GraphQL router in your FastAPI app
app.include_router(graphql_app, prefix="/graphql")

# Create tables if not exist
@app.on_event("startup")
def startup_event():
    Base.metadata.create_all(bind=engine)
Leave a Comment