Spaces:
Runtime error
Runtime error
| """Base model classes and database setup for the chat agent.""" | |
| from datetime import datetime | |
| from uuid import uuid4 | |
| from sqlalchemy import Column, DateTime, String, TypeDecorator | |
| from sqlalchemy.dialects.postgresql import UUID | |
| from sqlalchemy.ext.declarative import declarative_base | |
| from sqlalchemy.orm import sessionmaker | |
| from flask_sqlalchemy import SQLAlchemy | |
| # Create SQLAlchemy instance | |
| db = SQLAlchemy() | |
| # Custom UUID type that works with both PostgreSQL and SQLite | |
| class GUID(TypeDecorator): | |
| """Platform-independent GUID type. | |
| Uses PostgreSQL's UUID type, otherwise uses String(36). | |
| """ | |
| impl = String | |
| cache_ok = True | |
| def load_dialect_impl(self, dialect): | |
| if dialect.name == 'postgresql': | |
| return dialect.type_descriptor(UUID(as_uuid=True)) | |
| else: | |
| return dialect.type_descriptor(String(36)) | |
| def process_bind_param(self, value, dialect): | |
| if value is None: | |
| return value | |
| elif dialect.name == 'postgresql': | |
| return value | |
| else: | |
| return str(value) | |
| def process_result_value(self, value, dialect): | |
| if value is None: | |
| return value | |
| else: | |
| return value | |
| # Base model class with common fields | |
| class BaseModel(db.Model): | |
| """Base model class with common fields and methods.""" | |
| __abstract__ = True | |
| id = Column(GUID(), primary_key=True, default=lambda: str(uuid4())) | |
| created_at = Column(DateTime, default=datetime.utcnow, nullable=False) | |
| updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) | |
| def to_dict(self): | |
| """Convert model instance to dictionary.""" | |
| return { | |
| column.name: getattr(self, column.name) | |
| for column in self.__table__.columns | |
| } | |
| def __repr__(self): | |
| """String representation of the model.""" | |
| return f"<{self.__class__.__name__}(id={self.id})>" |