run-llama/llama_index · error · ValueError

sql_database must be provided.

Error message

sql_database must be provided.

What it means

SQLStructStoreIndexContext (the base context object for SQL table extraction) requires a SQLDatabase instance; it validates that sql_database is not None at construction. The parameter is typed as SQLDatabase (not Optional) but the None check exists because older call signatures and duck-typed callers could pass None.

Source

Thrown at llama-index-core/llama_index/core/indices/common/struct_store/base.py:59

        table_context_task (Optional[str]): The query to perform
            on the table context. A default query string is used
            if none is provided by the user.

    """

    def __init__(
        self,
        sql_database: SQLDatabase,
        llm: Optional[LLM] = None,
        text_splitter: Optional[TextSplitter] = None,
        table_context_prompt: Optional[BasePromptTemplate] = None,
        refine_table_context_prompt: Optional[BasePromptTemplate] = None,
        table_context_task: Optional[str] = None,
    ) -> None:
        """Initialize params."""
        # TODO: take in an entire index instead of forming a response builder
        if sql_database is None:
            raise ValueError("sql_database must be provided.")
        self._sql_database = sql_database
        self._text_splitter = text_splitter
        self._llm = llm or Settings.llm
        self._prompt_helper = Settings._prompt_helper or PromptHelper.from_llm_metadata(
            self._llm.metadata,
        )
        self._callback_manager = Settings.callback_manager
        self._table_context_prompt = (
            table_context_prompt or DEFAULT_TABLE_CONTEXT_PROMPT
        )
        self._refine_table_context_prompt = (
            refine_table_context_prompt or DEFAULT_REFINE_TABLE_CONTEXT_PROMPT_SEL
        )
        self._table_context_task = table_context_task or DEFAULT_TABLE_CONTEXT_QUERY

    def build_all_context_from_documents(
        self,
        documents_dict: Dict[str, List[BaseNode]],

View on GitHub (pinned to afd0fef371)

Solutions

  1. Create the database wrapper and pass it: from llama_index.core.sql_database import SQLDatabase; sql_db = SQLDatabase(engine, include_tables=['my_table']).
  2. If building SQLStructIndex.from_documents, make sure the sql_database kwarg is actually forwarded in your call.
  3. Audit custom context subclasses to ensure sql_database is threaded through to super().__init__.

Example fix

# before
index = SQLStructIndex.from_documents(docs, sql_database=None)  # ValueError

# after
from llama_index.core import SQLDatabase
from sqlalchemy import create_engine
engine = create_engine("sqlite:///data.db")
sql_db = SQLDatabase(engine, include_tables=["items"])
index = SQLStructIndex.from_documents(docs, sql_database=sql_db)
Defensive patterns

Strategy: validation

Validate before calling

if sql_database is None:
    raise ValueError("Create SQLDatabase(engine) and pass sql_database=<instance>")

Type guard

def has_sql_database(db) -> bool:
    from llama_index.core.sql_database import SQLDatabase
    return isinstance(db, SQLDatabase)

Prevention

When it happens

Trigger: Constructing BaseSQLStructStoreIndexContext (or a subclass like SQLStructStoreIndexContext) with sql_database=None; omitting the sql_database keyword when subclass constructors don't enforce defaults.

Common situations: Building a SQLStructIndex/PGVectorSQLStructStoreIndex without wiring up the SQLDatabase(engine) first; custom subclasses that forward **kwargs and accidentally swallow sql_database; test stubs passing None placeholders.

Related errors


AI-assisted analysis of run-llama/llama_index@afd0fef371 (2026-08-15). Data as JSON: /api/errors/10fa260e4bb203e3. Report an issue: GitHub.