Skip to content

API Reference parrot.tools.databasequery.base

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

parrot.tools.databasequery.base

View source

DatabaseToolkit — Result Types & AbstractDatabaseSource.

Defines all Pydantic v2 result models and the AbstractDatabaseSource ABC that every database source must implement.

Part of FEAT-062 — DatabaseToolkit. Part of FEAT-136 — database-toolkit-parity (add_row_limit, test_connection).

Class AbstractDatabaseSource

Abstract base class for all database source implementations.

Each concrete subclass represents a specific database driver (e.g., PostgreSQL, MongoDB, Elasticsearch) and provides driver-specific implementations of metadata discovery, query validation, and query execution.

Attributes:

Attribute Type Description
driver str
sqlglot_dialect str | None

Method AbstractDatabaseSource.resolve_credentials

Resolve credentials, using defaults if none provided.

resolve_credentials(credentials: dict[str, Any] | None) -> dict[str, Any]

Parameter Type Default Description
credentials dict[str, Any] | None Explicit credentials dictionary or None.

Returns: dict[str, Any] — Resolved credentials dictionary. Falls back to get_default_credentials() if credentials is None.

Method AbstractDatabaseSource.get_default_credentials

Return default credentials for this database driver.

get_default_credentials() -> dict[str, Any]

Returns: dict[str, Any] — Default credentials dictionary. May be empty if no defaults are configured.

Method AbstractDatabaseSource.validate_query

Validate a query using sqlglot for the configured dialect.

SQL sources (where sqlglot_dialect is set) use sqlglot for validation. Non-SQL sources must override this method.

validate_query(query: str) -> ValidationResult

Parameter Type Default Description
query str Query string to validate.

Returns: ValidationResult — ValidationResult indicating whether the query is valid.

Raises:

  • NotImplementedError — If sqlglot_dialect is None (non-SQL sources must override this method).

Method AbstractDatabaseSource.test_connection

Test database connectivity by executing a trivial query.

SQL sources run SELECT 1 via self.query(). Non-SQL sources (MongoDB, Elasticsearch, InfluxDB) should override this method with a driver-appropriate health check (e.g. ping, cluster-info, buckets()).

test_connection(credentials: dict[str, Any]) -> bool

Parameter Type Default Description
credentials dict[str, Any] Connection credentials to test.

Returns: bool — True if the connection succeeds, False on any exception. Never raises.

Method AbstractDatabaseSource.get_metadata

Discover database schema metadata.

get_metadata(credentials: dict[str, Any], tables: list[str] | None = None) -> MetadataResult

Parameter Type Default Description
credentials dict[str, Any] Connection credentials.
tables list[str] | None None Optional list of specific tables to inspect. If None, returns metadata for all accessible tables.

Returns: MetadataResult — MetadataResult with table and column definitions.

Method AbstractDatabaseSource.query

Execute a query and return all results.

query(credentials: dict[str, Any], sql: str, params: dict[str, Any] | None = None) -> QueryResult

Parameter Type Default Description
credentials dict[str, Any] Connection credentials.
sql str Query string (SQL for relational, JSON for NoSQL, etc.).
params dict[str, Any] | None None Optional query parameters.

Returns: QueryResult — QueryResult with rows and execution metadata.

Method AbstractDatabaseSource.query_row

Execute a query and return a single row.

query_row(credentials: dict[str, Any], sql: str, params: dict[str, Any] | None = None) -> RowResult

Parameter Type Default Description
credentials dict[str, Any] Connection credentials.
sql str Query string.
params dict[str, Any] | None None Optional query parameters.

Returns: RowResult — RowResult with a single row or found=False if no rows.

Method AbstractDatabaseSource.close

Release all cached AsyncDB pool instances.

Called automatically by DatabaseToolkit.cleanup(). Override if the source holds additional resources beyond the AsyncDB pool.

Does nothing if no pool has been created yet (safe to call on a fresh instance).

close() -> None

Class ColumnMeta

Metadata for a single database column or field.

Fields:

Field Type Default Description
name str Column name.
data_type str Column data type.
nullable bool True Whether the column allows null values.
primary_key bool False Whether this column is part of the primary key.
default Any None Default value for the column.

Class MetadataResult

Result of a metadata discovery operation.

Fields:

Field Type Default Description
driver str The database driver used.
tables list[TableMeta] List of table/collection metadata.
raw dict[str, Any] Raw metadata from the database (driver-specific).

Class QueryResult

Result of a multi-row query execution.

Fields:

Field Type Default Description
driver str The database driver used.
rows list[dict[str, Any]] List of rows as dictionaries.
row_count int Number of rows returned.
columns list[str] List of column names.
execution_time_ms float Query execution time in milliseconds.

Class RowResult

Result of a single-row fetch operation.

Fields:

Field Type Default Description
driver str The database driver used.
row dict[str, Any] | None The fetched row as a dictionary, or None if not found.
found bool Whether a row was found.
execution_time_ms float Query execution time in milliseconds.

Class TableMeta

Metadata for a single database table, collection, or measurement.

Fields:

Field Type Default Description
name str Table or collection name.
schema_name str | None None Schema or namespace (optional).
columns list[ColumnMeta] List of column/field metadata.
row_count int | None None Approximate row count (optional).

Class ValidationResult

Result of a query validation operation.

Fields:

Field Type Default Description
valid bool Whether the query is syntactically valid.
error str | None None Error message if validation failed.
dialect str | None None The query dialect that was validated against.

Function add_row_limit

Inject a dialect-specific row limit into a query string.

Ported from DatabaseQueryTool._add_row_limit() (tool.py:692-739) as a shared free function so both the toolkit and the legacy tool can reuse it.

Supported query languages:

  • SQL (pg, mysql, sqlite, clickhouse, duckdb, bigquery): Appends LIMIT N unless a LIMIT clause is already present.
  • SQL (no bare LIMIT) (oracle, mssql, sqlserver): Returns query unchanged. These dialects require SELECT TOP N (T-SQL) or FETCH FIRST N ROWS ONLY (Oracle 12c+) which cannot be injected safely without full query parsing. Callers must embed the limit in the query string itself.
  • Flux (influx): Appends |> limit(n: N) unless already present.
  • JSON/Elasticsearch (elastic): Sets "size": N in the JSON body unless "size" already exists with a smaller-or-equal value.
  • MQL/MongoDB (mongo, atlas, documentdb): Returns the query unchanged (MongoDB limits are passed as a parameter to the connection, not in the query string).

add_row_limit(query: str, max_rows: int, driver: str) -> str

Parameter Type Default Description
query str The original query string.
max_rows int Maximum number of rows/documents to return. If 0 or negative, the query is returned unchanged.
driver str Canonical driver name or alias (e.g. 'pg', 'postgres', 'influx', 'elastic', 'mongo').

Returns: str — The modified query string with a row limit injected, or the original query if already limited or the driver does not support string-level limit injection.

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