SQLAlchemyTableRetriever

SQLAlchemyTableRetriever

SQLAlchemyTableRetriever 는 SQLAlchemy가 지원하는 어떤 데이터베이스에든 연결해 SQL 쿼리를 실행하는 테이블 리트리버예요. PostgreSQL, MySQL, SQLite, MSSQL 등 SQLAlchemy가 말할 수 있는 모든 백엔드를 다뤄요.

출처: 문서

본문

개요 (Overview)

SQLAlchemyTableRetriever 는 백엔드에 구애받지 않는 테이블 리트리버예요. SQLAlchemy가 다루는 모든 것과 통신해요 — PostgreSQL, MySQL, SQLite, MSSQL, 그리고 서드파티 드라이버가 커버하는 그 밖의 여러 방언까지요. SQL 쿼리를 주면 결과를 Pandas DataFrame(dataframe)과 렌더링 준비가 된 Markdown 표(table)로 돌려줘요. 후자는 프롬프트에 바로 넣기 편리하죠. 결과는 최대 10,000행으로 제한돼요.

쿼리가 실패하면 컴포넌트는 예외를 던지지 않고, 빈 DataFrame을 반환하며 SQLAlchemy 오류 문자열을 error 출력에 넣어요. 그래서 전체를 try/except로 감싸지 않고도 파이프라인에 안전하게 넣을 수 있어요.

연결 파라미터 (Connection parameters)

init 인자는 SQLAlchemy URL의 각 부분에 직접 대응해요:

  • drivername — 유일하게 필수인 인자예요. 백엔드에 맞는 드라이버를 고르세요. 예: postgresql+psycopg2, mysql+pymysql, sqlite, mssql+pyodbc.
  • host, port, database, username — 표준 연결 요소예요. 백엔드가 요구하는 값을 전달하세요.
  • password — Haystack Secret이에요. Secret.from_env_var("MY_DB_PASSWORD") 로 환경 변수에서 해석하거나, Secret.from_token("…") 으로 인라인으로 넣을 수 있어요(로컬 실험 외에는 권장하지 않아요).

SQLite의 경우 drivername="sqlite" 에 database=":memory:" 만 있으면 충분해요 — host/user/password가 필요 없어요.

init_script

init_script 를 전달하면 컴포넌트가 처음 웜업될 때 한 번, 단일 트랜잭션으로 하나 이상의 SQL 문을 실행해요. 대표적인 용도는:

  • 데모나 테스트를 위한 인메모리 SQLite 데이터베이스 시딩
  • 쿼리 실행 전 임시 뷰나 세션 레벨 설정 만들기

리스트의 각 항목은 단일 문(statement)이에요.

사용법 (Usage)

sqlalchemy-haystack 패키지와 데이터베이스용 드라이버를 설치하세요:

pip install sqlalchemy-haystack
# For PostgreSQL, also install a driver:
pip install psycopg2-binary

단독으로 쓰기

init_script 로 시딩한 인메모리 SQLite 데이터베이스를 사용하는 자족(self-contained) 예시예요:

from haystack_integrations.components.retrievers.sqlalchemy import (
    SQLAlchemyTableRetriever,
)

retriever = SQLAlchemyTableRetriever(
    drivername="sqlite",
    database=":memory:",
    init_script=[
        "CREATE TABLE employees (name TEXT, salary INTEGER)",
        "INSERT INTO employees VALUES ('Ada', 90000), ('Linus', 85000), ('Grace', 95000)",
    ],
)
result = retriever.run(query="SELECT name, salary FROM employees ORDER BY salary DESC")
print(result["dataframe"])
print(result["table"])

실제 백엔드에 연결하는 것도 똑같아요 — 드라이버만 바꾸고 연결 정보를 전달하면 돼요:

from haystack.utils import Secret
from haystack_integrations.components.retrievers.sqlalchemy import (
    SQLAlchemyTableRetriever,
)

retriever = SQLAlchemyTableRetriever(
    drivername="postgresql+psycopg2",
    host="db.example.com",
    port=5432,
    database="analytics",
    username="readonly",
    password=Secret.from_env_var("ANALYTICS_DB_PASSWORD"),
)

파이프라인에서 쓰기

리트리버의 Markdown table 출력을 LLM의 컨텍스트로 사용해요 — 예를 들어 LLM에게 쿼리 결과를 요약하라고 시킬 수 있어요:

from haystack import Pipeline
from haystack.utils import Secret
from haystack.components.builders import ChatPromptBuilder
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.retrievers.sqlalchemy import (
    SQLAlchemyTableRetriever,
)

retriever = SQLAlchemyTableRetriever(
    drivername="postgresql+psycopg2",
    host="db.example.com",
    port=5432,
    database="analytics",
    username="readonly",
    password=Secret.from_env_var("ANALYTICS_DB_PASSWORD"),
)

pipeline = Pipeline()
pipeline.add_component(
    "builder",
    ChatPromptBuilder(
        template=[ChatMessage.from_user("Describe this table: {{ table }}")],
        required_variables="*",
    ),
)
pipeline.add_component("db", retriever)
pipeline.add_component("llm", OpenAIChatGenerator(model="gpt-4o"))
pipeline.connect("db.table", "builder.table")
pipeline.connect("builder.prompt", "llm.messages")
pipeline.run(data={"query": "SELECT employee, salary FROM employees LIMIT 10"})

더 알아보기 (Learn more)