id = Column(Integer, primary_key=True)
        session_id = Column(Text)
        message = Column(Text)
    return Message
[docs]class DefaultMessageConverter(BaseMessageConverter):
    """The default message converter for SQLChatMessageHistory."""
[docs]    def __init__(self, table_name: str):
        self.model_class = create_message_model(table_name, declarative_base())
[docs]    def from_sql_model(self, sql_message: Any) -> BaseMessage:
        return messages_from_dict([json.loads(sql_message.message)])[0]
[docs]    def to_sql_model(self, message: BaseMessage, session_id: str) -> Any:
        return self.model_class(
            session_id=session_id, message=json.dumps(_message_to_dict(message))
        )
[docs]    def get_sql_model_class(self) -> Any:
        return self.model_class
[docs]class SQLChatMessageHistory(BaseChatMessageHistory):
    """Chat message history stored in an SQL database."""
[docs]    def __init__(
        self,
        session_id: str,
        connection_string: str,
        table_name: str = "message_store",
        session_id_field_name: str = "session_id",
        custom_message_converter: Optional[BaseMessageConverter] = None,
    ):
        self.connection_string = connection_string
        self.engine = create_engine(connection_string, echo=False)
        self.session_id_field_name = session_id_field_name
        self.converter = custom_message_converter or DefaultMessageConverter(table_name)
        self.sql_model_class = self.converter.get_sql_model_class()
        if not hasattr(self.sql_model_class, session_id_field_name):
            raise ValueError("SQL model class must have session_id column")
        self._create_table_if_not_exists()
        self.session_id = session_id