from sqlalchemy import Column, Integer, String, Boolean, Date, DateTime, Text, ForeignKey
from sqlalchemy.orm import declarative_base, Session
from sqlalchemy import create_engine, select
from sqlalchemy.dialects.postgresql import TIMESTAMP
from typing import Optional, Dict, Any
from datetime import datetime, date
Base = declarative_base()
class ProductMaker(Base):
__tablename__ = 'product_maker'
product_maker_id = Column(Integer, primary_key=True, autoincrement=True)
business_name = Column(Text, nullable=False)
business_registration_path = Column(Text, nullable=False)
year_incorporated = Column(Text, nullable=False)
founder_ceo = Column(Text, nullable=False)
website = Column(Text, nullable=False)
category = Column(Text, nullable=False)
# Composite Types (simplified for dict conversion)
office_address = Column(Text)
warehouse_address = Column(Text)
telephone = Column(Text)
validation_status = Column(Boolean, nullable=False)
last_validation_date = Column(Date, nullable=False)
created_at = Column(TIMESTAMP, default=datetime.utcnow)
created_by = Column(Text, nullable=False)
updated_at = Column(TIMESTAMP, default=datetime.utcnow, onupdate=datetime.utcnow)
tsi_user_info_id = Column(Text, ForeignKey('tsi_user_info.tsi_user_info_id'))
def convert_product_maker_to_dict(product_maker: Optional[ProductMaker]) -> Optional[Dict[str, Any]]:
"""
Convert a ProductMaker instance to a dictionary
Args:
product_maker (ProductMaker): The ProductMaker instance to convert
Returns:
Dict[str, Any]: A dictionary representation of the ProductMaker
"""
if product_maker is None:
return None
return {
"product_maker_id": product_maker.product_maker_id,
"business_name": product_maker.business_name,
"business_registration_path": product_maker.business_registration_path,
"year_incorporated": product_maker.year_incorporated,
"founder_ceo": product_maker.founder_ceo,
"website": product_maker.website,
"category": product_maker.category,
"office_address": product_maker.office_address,
"warehouse_address": product_maker.warehouse_address,
"telephone": product_maker.telephone,
"validation_status": product_maker.validation_status,
"last_validation_date": (
product_maker.last_validation_date.isoformat()
if isinstance(product_maker.last_validation_date, date)
else product_maker.last_validation_date
),
"created_at": (
product_maker.created_at.isoformat()
if isinstance(product_maker.created_at, datetime)
else product_maker.created_at
),
"created_by": product_maker.created_by,
"updated_at": (
product_maker.updated_at.isoformat()
if isinstance(product_maker.updated_at, datetime)
else product_maker.updated_at
),
"tsi_user_info_id": product_maker.tsi_user_info_id
}
def query_product_maker_by_id(session: Session, product_maker_id: int) -> Optional[Dict[str, Any]]:
"""
Query a Product Maker by its ID and return as a dictionary
Args:
session (Session): SQLAlchemy database session
product_maker_id (int): ID of the Product Maker to retrieve
Returns:
Optional[Dict[str, Any]]: Dictionary representation of the Product Maker or None
"""
query = select(ProductMaker).where(ProductMaker.product_maker_id == product_maker_id)
result = session.execute(query).scalar_one_or_none()
return convert_product_maker_to_dict(result)
def query_multiple_product_makers(session: Session, **kwargs) -> List[Dict[str, Any]]:
"""
Query multiple Product Makers with optional filtering
Args:
session (Session): SQLAlchemy database session
**kwargs: Keyword arguments for filtering
Returns:
List[Dict[str, Any]]: List of Product Maker dictionaries
"""
# Start with base query
query = select(ProductMaker)
# Add filters based on kwargs
for key, value in kwargs.items():
if hasattr(ProductMaker, key):
query = query.where(getattr(ProductMaker, key) == value)
# Execute query and convert results
results = session.execute(query).scalars().all()
return [convert_product_maker_to_dict(maker) for maker in results]
# Example usage
def main():
# Create engine (replace with your actual database connection string)
engine = create_engine('postgresql://username:password@localhost/your_database')
# Create tables (if they don't exist)
Base.metadata.create_all(engine)
# Create a session
with Session(engine) as session:
# Example 1: Query a single Product Maker by ID
product_maker_dict = query_product_maker_by_id(session, 1)
if product_maker_dict:
print("Single Product Maker:")
print(product_maker_dict)
# Example 2: Query multiple Product Makers with filters
validated_makers = query_multiple_product_makers(
session,
validation_status=True,
created_by='admin_user'
)
print("\nValidated Product Makers:")
for maker in validated_makers:
print(maker)
# Advanced querying with more complex filtering
def advanced_querying_examples(session: Session):
"""
Demonstrate advanced querying techniques
Args:
session (Session): SQLAlchemy database session
"""
# 1. Complex filtering
complex_query = (
select(ProductMaker)
.where(ProductMaker.validation_status == True)
.where(ProductMaker.year_incorporated >= '2020')
.order_by(ProductMaker.created_at.desc())
.limit(10)
)
complex_results = session.execute(complex_query).scalars().all()
complex_results_dicts = [convert_product_maker_to_dict(maker) for maker in complex_results]
# 2. Pagination example
def paginate_product_makers(session: Session, page: int = 1, per_page: int = 10):
"""
Paginate Product Makers
Args:
session (Session): SQLAlchemy database session
page (int): Page number
per_page (int): Number of items per page
Returns:
List[Dict[str, Any]]: Paginated Product Makers
"""
offset = (page - 1) * per_page
query = (
select(ProductMaker)
.order_by(ProductMaker.created_at.desc())
.offset(offset)
.limit(per_page)
)
results = session.execute(query).scalars().all()
return [convert_product_maker_to_dict(maker) for maker in results]
# Example pagination
first_page = paginate_product_makers(session, page=1, per_page=10)
second_page = paginate_product_makers(session, page=2, per_page=10)
if __name__ == "__main__":
main()