from sqlalchemy import Column, String, Text, ForeignKey, Boolean, Index, Computed, Integer from sqlalchemy.dialects.postgresql import UUID, TSVECTOR from sqlalchemy.orm import relationship from pgvector.sqlalchemy import Vector from core.database import Base from core.config import get_settings from models.base import PrimaryKeyMixin, TimestampMixin, SoftDeleteMixin settings = get_settings() class KBArticle(Base, PrimaryKeyMixin, TimestampMixin, SoftDeleteMixin): __tablename__ = "kb_articles" workspace_id = Column(UUID(as_uuid=True), ForeignKey("workspaces.id"), nullable=False, index=True) author_id = Column(UUID(as_uuid=True), ForeignKey("users.id"), nullable=False) project_id = Column(UUID(as_uuid=True), ForeignKey("projects.id"), nullable=True) title = Column(String(500), nullable=False) content = Column(Text, nullable=False) category = Column(String(100), nullable=True) is_published = Column(Boolean, default=True) summary = Column(Text, nullable=True) duplicate_of_id = Column(UUID(as_uuid=True), ForeignKey("kb_articles.id"), nullable=True, index=True) force_original = Column(Boolean, default=False, index=True) content_hash = Column(String(64), nullable=True, index=True) # --- Discovery Telemetry --- view_count = Column(Integer, default=0, nullable=False) citation_count = Column(Integer, default=0, nullable=False) # Semantic vector for RAG embedding = Column(Vector(settings.AI_TEXT_EMBEDDING_DIM), nullable=True) # Version Control version = Column(Integer, default=1, nullable=False) # --- Search Optimization --- # 1. Computed TSVector for GIN search (Keyword Engine) search_vector = Column( TSVECTOR, Computed("to_tsvector('english', coalesce(title, '') || ' ' || coalesce(content, ''))", persisted=True) ) # 2. Indexes for hybrid search __table_args__ = ( Index('idx_kb_search_vector', "search_vector", postgresql_using='gin'), Index( 'idx_kb_embedding_hnsw', "embedding", postgresql_using='hnsw', postgresql_with={'m': 16, 'ef_construction': 64}, postgresql_ops={'embedding': 'vector_cosine_ops'} ), ) # Relationships workspace = relationship("Workspace") author = relationship("User") project = relationship("Project", back_populates="kb_articles") chunks = relationship("KBArticleChunk", back_populates="article", cascade="all, delete-orphan") attachments = relationship("Attachment", back_populates="article", cascade="all, delete-orphan") versions = relationship("KBArticleVersion", back_populates="article", cascade="all, delete-orphan", order_by="desc(KBArticleVersion.version_number)") # Self-referential for duplicates duplicate_of = relationship("KBArticle", remote_side="KBArticle.id", backref="duplicates")