Skip to content

API Reference parrot.bots.database.toolkits.sql

github-actions[bot] edited this page Nov 5, 2026 · 4 revisions

parrot.bots.database.toolkits.sql

View source

SQLToolkit — common SQL operations with overridable dialect hooks.

Inherits DatabaseToolkit and implements schema search, query generation, execution, explain, and validation for SQL databases. Dialect differences (PostgreSQL vs BigQuery vs MySQL) are handled via overridable _get_* hook methods.

All execution goes through asyncdb — the asyncpg-native path is the only supported backend. Query builders emit $1, $2, … positional placeholders.

Alias CachePartition

Re-exported from parrot.bots.database.cache.CachePartition.

Alias Completeness

Re-exported from parrot.bots.database.models.Completeness.

Alias DatabaseToolkit

Re-exported from parrot.bots.database.toolkits.base.DatabaseToolkit.

Alias QueryExecutionResponse

Re-exported from parrot.bots.database.models.QueryExecutionResponse.

Alias QueryRetryConfig

Re-exported from parrot.bots.database.retries.QueryRetryConfig.

Alias RetryContext

Re-exported from parrot.bots.database.retries.RetryContext.

Alias SQLRetryHandler

Re-exported from parrot.bots.database.retries.SQLRetryHandler.

Class SQLToolkit

Common SQL operations with overridable dialect hooks.

Subclass and override the _get_* methods to customize behaviour for specific SQL dialects (PostgreSQL, BigQuery, etc.).

Parameter Type Default Description
dsn str
allowed_schemas Optional[List[str]] None
primary_schema Optional[str] None
tables Optional[List[str]] None
read_only bool True
cache_partition Optional[CachePartition] None
retry_config Optional[QueryRetryConfig] None
database_type str 'postgresql'
**kwargs Any {}

Attributes:

Attribute Type Description
exclude_tools tuple[str, ...]

Method SQLToolkit.search_schema

Search schema identifiers (table/column/comment names) matching search_term.

Searches identifiers (table/column/comment names), not data values. Merges cache and live DB results, deduplicates by (schema, tablename) preferring the higher-completeness entry on collision, and returns results sorted by relevance score descending.

search_schema(search_term: str, schema_name: Optional[str] = None, limit: int = 10) -> List[TableMetadata]

Parameter Type Default Description
search_term str Keyword or pattern to match.
schema_name Optional[str] None Restrict to a specific schema.
limit int 10 Maximum results.

Returns: List[TableMetadata] — Matching TableMetadata list, sorted by relevance descending.

Method SQLToolkit.describe_table

Return full-completeness metadata for schema.table.

Checks the cache first. If the cached entry does not satisfy Completeness.FULL, introspects the table via the DB and stores the result in the cache.

describe_table(schema: str, table: str) -> Optional[TableMetadata]

Parameter Type Default Description
schema str Schema name.
table str Table name.

Returns: Optional[TableMetadata] — TableMetadata with completeness == FULL, or None if the table does not exist.

Method SQLToolkit.generate_query

Prepare a SQL skeleton and schema context for SQL generation.

Ensures every referenced table has FULL completeness metadata before building the context so the LLM never sees columns: [] stubs. Accepts entries as "schema.table" or bare "table" names; bare names are resolved across allowed_schemas.

generate_query(natural_language: str, target_tables: Optional[List[str]] = None, query_type: str = 'SELECT') -> str

Parameter Type Default Description
natural_language str User's question in plain English.
target_tables Optional[List[str]] None Optional list of "schema.table" or bare "table" names. When empty, search_schema is used to discover candidates (top 3).
query_type str 'SELECT' Hint for query type (SELECT, INSERT, etc.).

Returns: str — Skeleton SQL string plus per-table YAML metadata context.

Method SQLToolkit.execute_query

Execute a SQL query and return results or a retry context.

Applies the configured safety policy first. When retry_config is set and the query fails with a retryable error, returns a RetryContext instead of QueryExecutionResponse so that DatabaseAgent.ask() can re-ask the LLM with error context.

Non-retryable exceptions are re-raised when retry_config is set, and wrapped in QueryExecutionResponse(success=False) otherwise (legacy behaviour for callers that don't check the return type).

execute_query(query: str, limit: int = 1000, timeout: int = 30) -> Union[QueryExecutionResponse, RetryContext]

Parameter Type Default Description
query str SQL query string.
limit int 1000 Maximum rows to return.
timeout int 30 Query timeout in seconds.

Returns: Union[QueryExecutionResponse, RetryContext] — QueryExecutionResponse on success or when retrying is not configured; RetryContext when a retryable error occurs and retry_config is set.

Raises:

  • Exception — For non-retryable errors when retry_config is set.

Method SQLToolkit.explain_query

Run EXPLAIN ANALYZE on the given query and return the execution plan.

Always safe to call: for read-only queries (SELECT, WITH, …) the tool runs EXPLAIN ANALYZE and returns the full execution plan including actual rows and timing. For non-read-only statements the tool automatically downgrades to EXPLAIN (planner-only, no execution) so data is never mutated. Callers do not need to check read-only status before invoking this tool.

explain_query(query: str) -> str

Parameter Type Default Description
query str SQL query to explain.

Returns: str — Execution plan text.

Method SQLToolkit.validate_query

Validate SQL syntax and referenced objects.

validate_query(sql: str) -> Dict[str, Any]

Parameter Type Default Description
sql str SQL query to validate.

Returns: Dict[str, Any] — Dict with valid, errors, and referenced_tables keys.

Alias TableMetadata

Re-exported from parrot.bots.database.models.TableMetadata.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally