Skip to content

API Reference parrot.tools.databasequery.toolkit

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

parrot.tools.databasequery.toolkit

View source

DatabaseQueryToolkit — Multi-database tools as an AbstractToolkit.

Exposes LLM-callable tools via public async methods:

  • get_database_metadata
  • validate_query
  • execute_database_query
  • fetch_database_row
  • get_table_metadata
  • test_connection
  • save_result

Every query method routes through parrot.security.QueryValidator to block DDL/DML before reaching the underlying source.

Part of FEAT-105 — databasetoolkit-clash. Part of FEAT-136 — database-toolkit-parity.

Alias AbstractDatabaseSource

Re-exported from parrot.tools.databasequery.base.AbstractDatabaseSource.

Alias AbstractToolkit

Re-exported from parrot.tools.toolkit.AbstractToolkit.

Class DatabaseQueryToolkit

Multi-database toolkit — discover schema, validate queries, execute.

Inherits from AbstractToolkit so public async methods are automatically discovered and wrapped as AbstractTool instances. Use get_tools() to retrieve them and attach them to an Agent or AgentCrew.

Tool names (with tool_prefix="dq"):

  • dq_get_database_metadata
  • dq_validate_query
  • dq_execute_database_query
  • dq_fetch_database_row
  • dq_get_table_metadata
  • dq_test_connection
  • dq_save_result (only when output_dir is configured)

DDL/DML guard: Every query-executing method calls parrot.security.QueryValidator.validate_query BEFORE contacting the underlying source, ensuring that dangerous statements (DROP, INSERT, UPDATE, …) are rejected even if the caller skips validate_query.

Supported drivers (canonical names): pg, mysql, bigquery, sqlite, oracle, mssql, clickhouse, duckdb, influx, mongo, atlas, documentdb, elastic — plus all aliases resolved by normalize_driver().

Parameter Type Default Description
**kwargs Any {} Supported keyword arguments: - output_dir (str | Path | None): Directory for save_result output files. When not set, save_result is excluded from the tool list and returns an error dict if called directly. - static_dir (str | Path | None): Optional public URL root for generating file_url values in save_result responses. - All other kwargs are forwarded to AbstractToolkit.__init__.

Attributes:

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

Method DatabaseQueryToolkit.get_source

Return a (cached) source instance for driver.

Not a tool — listed in exclude_tools.

get_source(driver: str) -> AbstractDatabaseSource

Parameter Type Default Description
driver str Raw driver name (alias or canonical).

Returns: AbstractDatabaseSource — A concrete AbstractDatabaseSource instance.

Method DatabaseQueryToolkit.cleanup

Close all cached source pools.

Not a tool — listed in exclude_tools. Called automatically by AbstractToolkit.stop() lifecycle if hooked.

cleanup() -> None

Method DatabaseQueryToolkit.get_database_metadata

Discover database schema. Call this FIRST before writing queries.

Returns table names, column names, and data types for the target database. Use this to understand what data is available before attempting to run a query.

get_database_metadata(driver: str, credentials: Optional[dict[str, Any]] = None, tables: Optional[list[str]] = None) -> MetadataResult

Parameter Type Default Description
driver str Canonical driver name (e.g. 'pg', 'mysql', 'mongo', 'elastic') or a supported alias (e.g. 'postgres', 'postgresql').
credentials Optional[dict[str, Any]] None Optional connection credentials dictionary. When omitted, the source falls back to environment-variable defaults.
tables Optional[list[str]] None Optional list of table or collection names to inspect. When omitted, the source returns metadata for all objects.

Returns: MetadataResult — MetadataResult containing tables (list of TableMeta) and optionally an error field on failure. Serialized to dict via _post_execute.

Method DatabaseQueryToolkit.validate_query

Validate a query for safety and syntax. Call BEFORE executing.

Applies a two-layer guard:

  1. DDL/DML safety check (parrot.security.QueryValidator) — rejects CREATE, DROP, INSERT, UPDATE, DELETE, TRUNCATE, GRANT, EXEC, etc. Returns immediately if the query is unsafe, without contacting the underlying database.
  2. Syntactic check (source.validate_query via sqlglot) — only reached for safe queries; returns dialect-aware parse errors.

validate_query(driver: str, query: str) -> ValidationResult

Parameter Type Default Description
driver str Canonical driver name or alias (see get_database_metadata).
query str Query string to validate.

Returns: ValidationResult — ValidationResult with valid (bool), optional error (str), and dialect (str). valid=False means the query MUST NOT be executed. Serialized to dict via _post_execute.

Method DatabaseQueryToolkit.get_table_metadata

Get detailed metadata for a specific table or collection.

Fetches schema information (column names, types, constraints) for a single named table, view, or collection. Useful when you already know which table to query and want to inspect its structure.

get_table_metadata(driver: str, table: str, credentials: Optional[dict[str, Any]] = None) -> MetadataResult

Parameter Type Default Description
driver str Canonical driver name or alias (see get_database_metadata).
table str The exact table, view, or collection name to inspect.
credentials Optional[dict[str, Any]] None Optional connection credentials dictionary. When omitted, the source falls back to environment-variable defaults.

Returns: MetadataResult — MetadataResult scoped to the single requested table. Serialized to dict via _post_execute.

Method DatabaseQueryToolkit.test_connection

Test connectivity to the target database.

Attempts a lightweight connection check appropriate for the driver (e.g. SELECT 1 for SQL, ping for MongoDB, info() for Elasticsearch, buckets() for InfluxDB).

test_connection(driver: str, credentials: Optional[dict[str, Any]] = None) -> dict[str, Any]

Parameter Type Default Description
driver str Canonical driver name or alias.
credentials Optional[dict[str, Any]] None Optional explicit connection credentials. When omitted, the source falls back to environment-variable defaults.

Returns: dict[str, Any] — {"status": "success"} on success, or {"status": "error", "message": "<description>"} on failure.

Method DatabaseQueryToolkit.execute_database_query

Execute a validated query and return all matching rows or documents.

Re-applies the QueryValidator DDL/DML guard before contacting the source, so a malicious or mistaken caller cannot skip the validation step and run a destructive statement.

Injects a row limit into the query (via add_row_limit()) when max_rows is positive, to prevent runaway result sets.

execute_database_query(driver: str, query: str, credentials: Optional[dict[str, Any]] = None, params: Optional[dict[str, Any]] = None, max_rows: int = 10000) -> Union[QueryResult, ValidationResult]

Parameter Type Default Description
driver str Canonical driver name or alias.
query str Query string to execute (must be a read-only query).
credentials Optional[dict[str, Any]] None Optional explicit connection credentials.
params Optional[dict[str, Any]] None Optional parameterised query values ({":name": value, ...} or driver-specific format).
max_rows int 10000 Maximum number of rows to return. Defaults to 10000. Pass 0 to disable the limit.

Returns: Union[QueryResult, ValidationResult] — QueryResult with a rows list and execution metadata on success. When the DDL/DML guard blocks the query, returns a ValidationResult with valid=False instead — callers that rely on type narrowing should account for both types. Serialized to dict via _post_execute.

Method DatabaseQueryToolkit.fetch_database_row

Execute a query and return at most one matching row or document.

Use this instead of execute_database_query when you expect a single result (e.g. lookup by primary key). Applies the same DDL/DML guard.

fetch_database_row(driver: str, query: str, credentials: Optional[dict[str, Any]] = None, params: Optional[dict[str, Any]] = None, max_rows: int = 1) -> Union[RowResult, ValidationResult]

Parameter Type Default Description
driver str Canonical driver name or alias.
query str Query string expected to return one row/document.
credentials Optional[dict[str, Any]] None Optional explicit connection credentials.
params Optional[dict[str, Any]] None Optional parameterised query values.
max_rows int 1 Maximum number of rows to consider (default 1). Passed to add_row_limit() before delegating to the source.

Returns: Union[RowResult, ValidationResult] — RowResult with a single row dict (or None) on success. When the DDL/DML guard blocks the query, returns a ValidationResult with valid=False instead — callers that rely on type narrowing should account for both types. Serialized to dict via _post_execute.

Method DatabaseQueryToolkit.save_result

Save a prior query result to a file on disk.

Converts the rows list in result to a DataFrame and writes it to the configured output_dir in the requested format. Only available when the toolkit was constructed with a valid output_dir.

save_result(result: dict[str, Any], filename: Optional[str] = None, file_format: str = 'csv') -> dict[str, Any]

Parameter Type Default Description
result dict[str, Any] A dict with at least a "rows" key (list of dicts), as returned by execute_database_query or get_database_metadata.
filename Optional[str] None Base filename (without extension). When omitted, a timestamp-based name is generated.
file_format str 'csv' One of "csv", "json", or "excel". Defaults to "csv".

Returns: dict[str, Any] — {"file_path": ..., "file_url": ..., "row_count": ..., "file_format": ...} on success, or {"error": "..."} on failure.

Alias MetadataResult

Re-exported from parrot.tools.databasequery.base.MetadataResult.

Alias QueryLanguage

Re-exported from parrot.security.QueryLanguage.

Alias QueryResult

Re-exported from parrot.tools.databasequery.base.QueryResult.

Alias QueryValidator

Re-exported from parrot.security.QueryValidator.

Alias RowResult

Re-exported from parrot.tools.databasequery.base.RowResult.

Alias ValidationResult

Re-exported from parrot.tools.databasequery.base.ValidationResult.

Alias add_row_limit

Re-exported from parrot.tools.databasequery.base.add_row_limit.

Alias get_source_class

Re-exported from parrot.tools.databasequery.sources.get_source_class.

Alias normalize_driver

Re-exported from parrot.tools.databasequery.sources.normalize_driver.

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