Skip to content

API Reference parrot.bots.database.toolkits.postgres

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.bots.database.toolkits.postgres

View source

PostgresToolkit — PostgreSQL-specific overrides of SQLToolkit.

Provides PG-specific EXPLAIN format, pg_class/pg_namespace introspection, column comments via col_description(), postgresql+asyncpg:// DSN mapping, and full first-class CRUD tools: insert_row, upsert_row, update_row, delete_row, select_rows.

Write tools are hidden from the LLM when read_only=True (the default) by extending exclude_tools before AbstractToolkit._generate_tools() runs.

Class PostgresToolkit

PostgreSQL-specific toolkit with first-class CRUD tools.

Overrides dialect hooks for PostgreSQL's richer introspection and EXPLAIN output. When read_only=False, five LLM-callable tools are exposed: db_insert_row, db_upsert_row, db_update_row, db_delete_row, and db_select_rows.

All write tools enforce a table whitelist (self.tables), validate input via a per-table dynamic Pydantic model, and cache parameterized SQL templates per instance.

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
use_pool bool False
pool_params Optional[Dict[str, Any]] None
**kwargs Any {}

Method PostgresToolkit.insert_row

Insert a single row into table.

Validates data against the table's dynamic Pydantic model (extra="forbid" — unknown fields raise ValidationError), builds and caches the INSERT SQL, then executes via asyncdb.

insert_row(table: str, data: Dict[str, Any], returning: Optional[List[str]] = None, conn: Optional[Any] = None) -> Dict[str, Any]

Parameter Type Default Description
table str Target table as "schema.table" or bare name (uses primary_schema).
data Dict[str, Any] Column-value mapping. Unknown keys are rejected.
returning Optional[List[str]] None Optional list of columns to RETURN. When None only a {"status": "ok"} dict is returned.
conn Optional[Any] None Optional existing transaction connection. When provided, the CRUD method reuses it instead of acquiring a new one.

Returns: Dict[str, Any] — The RETURNING row as a dict, or {"status": "ok"} when no RETURNING clause was requested.

Raises:

  • ValueError — Table not in whitelist.
  • pydantic.ValidationError — Unknown or invalid field in data.

Method PostgresToolkit.upsert_row

Upsert a single row into table using ON CONFLICT.

Defaults conflict_cols to meta.primary_keys when None. Defaults update_cols to all non-conflict data keys when None.

When returning is provided but the DO UPDATE fires against an identical row (PG RETURNING yields 0 rows), a follow-up SELECT using conflict_cols is performed to return the existing row.

upsert_row(table: str, data: Dict[str, Any], conflict_cols: Optional[List[str]] = None, update_cols: Optional[List[str]] = None, returning: Optional[List[str]] = None, conn: Optional[Any] = None) -> Dict[str, Any]

Parameter Type Default Description
table str Target table.
data Dict[str, Any] Column-value mapping.
conflict_cols Optional[List[str]] None Conflict target columns. Defaults to PK columns.
update_cols Optional[List[str]] None Columns to update on conflict. [] = DO NOTHING.
returning Optional[List[str]] None Optional RETURNING columns.
conn Optional[Any] None Optional existing transaction connection.

Returns: Dict[str, Any] — The upserted / existing row as dict, or {"status": "ok"}.

Raises:

  • ValueError — Table not in whitelist or conflict_cols is empty.
  • pydantic.ValidationError — Invalid field in data.

Method PostgresToolkit.update_row

Update columns in table matching where.

Enforces require_pk_in_where=True via :meth:parrot.security.QueryValidator.validate_sql_ast.

update_row(table: str, data: Dict[str, Any], where: Dict[str, Any], returning: Optional[List[str]] = None, conn: Optional[Any] = None) -> Dict[str, Any]

Parameter Type Default Description
table str Target table.
data Dict[str, Any] Columns to SET and their new values.
where Dict[str, Any] Columns and values for the WHERE clause (PK must be present).
returning Optional[List[str]] None Optional RETURNING columns.
conn Optional[Any] None Optional existing transaction connection.

Returns: Dict[str, Any] — Updated row dict, or {"status": "ok"}.

Raises:

  • ValueError — Table not in whitelist or WHERE lacks a PK column.
  • pydantic.ValidationError — Invalid field in data.
  • RuntimeError — QueryValidator rejects the generated SQL.

Method PostgresToolkit.delete_row

Delete rows from table matching where.

Enforces require_pk_in_where=True via :meth:parrot.security.QueryValidator.validate_sql_ast.

delete_row(table: str, where: Dict[str, Any], returning: Optional[List[str]] = None, conn: Optional[Any] = None) -> Dict[str, Any]

Parameter Type Default Description
table str Target table.
where Dict[str, Any] Columns and values for the WHERE clause (PK must be present).
returning Optional[List[str]] None Optional RETURNING columns.
conn Optional[Any] None Optional existing transaction connection.

Returns: Dict[str, Any] — Deleted row dict, or {"status": "ok"}.

Raises:

  • ValueError — Table not in whitelist or WHERE lacks a PK column.
  • RuntimeError — QueryValidator rejects the generated SQL.

Method PostgresToolkit.select_rows

Select rows from table.

select_rows(table: str, where: Optional[Dict[str, Any]] = None, columns: Optional[List[str]] = None, order_by: Optional[List[str]] = None, limit: Optional[int] = None, conn: Optional[Any] = None, distinct: bool = False, column_casts: Optional[Dict[str, str]] = None) -> List[Dict[str, Any]]

Parameter Type Default Description
table str Target table.
where Optional[Dict[str, Any]] None Optional equality filter (AND-joined).
columns Optional[List[str]] None Columns to retrieve. None → all.
order_by Optional[List[str]] None ORDER BY expressions, e.g. ["created_at DESC"].
limit Optional[int] None Max rows.
conn Optional[Any] None Optional existing connection.
distinct bool False If True, emit SELECT DISTINCT.
column_casts Optional[Dict[str, str]] None Optional {column: cast_type} mapping. Each named column is emitted as col::type AS col. Cast types must be in the whitelist (text, uuid, json, jsonb, integer, bigint, numeric, timestamp, date). When columns is None, it is expanded to all table columns from metadata so that the cast can be applied to the correct position.

Returns: List[Dict[str, Any]] — List of row dicts.

Raises:

  • ValueError — Table not in whitelist, unsupported cast type, or cast column not present in columns.

Method PostgresToolkit.execute_sql

Execute a parameterized SQL statement, optionally within a transaction.

Unlike :meth:execute_query (which wraps results in a QueryExecutionResponse and always acquires its own connection), this method accepts positional params, honours conn for transaction reuse, and returns raw row dicts.

Use this as the escape hatch for SQL that cannot be expressed through the CRUD primitives — e.g. INSERT … ON CONFLICT … DO UPDATE, SELECT … = ANY($1::int[]), or scalar sub-queries.

Example::

# Parameterised SELECT sharing the caller's transaction
async with self.transaction() as tx:
    rows = await self.execute_sql(
        "SELECT client_id FROM auth.clients "
        "WHERE client_id = ANY($1::int[])",
        params=(client_ids,),
        conn=tx,
    )

# DML without returning (INSERT … ON CONFLICT … DO UPDATE)
async with self.transaction() as tx:
    await self.execute_sql(
        "INSERT INTO auth.program_clients "
        "(program_id, client_id, program_slug, client_slug, active) "
        "VALUES ($1,$2,$3,$4,true) "
        "ON CONFLICT (program_id, client_id) "
        "DO UPDATE SET active = EXCLUDED.active, "
        "              client_slug = EXCLUDED.client_slug",
        params=(pid, cid, program_slug, c_slug),
        conn=tx,
        returning=False,
    )

execute_sql(sql: str, params: tuple[Any, ...] = (), conn: Optional[Any] = None, returning: bool = True, single_row: bool = False) -> Any

Parameter Type Default Description
sql str Parameterized SQL string with $1, $2, … positional placeholders.
params tuple[Any, ...] () Positional parameters tuple (default: empty tuple).
conn Optional[Any] None Optional existing connection, e.g. one yielded by :meth:transaction. When provided the call participates in the caller's transaction without acquiring a new one.
returning bool True When True (default) rows are fetched from the result via fetch / fetchrow. When False the statement is executed with execute and no rows are returned (DML-only path).
single_row bool False When True and returning is True, fetch exactly one row via fetchrow and return a dict (empty dict when no row matched). When False (default) all matching rows are returned as a list via fetch.

Returns: Any — * List[Dict[str, Any]] — when returning=True and single_row=False. * Dict[str, Any] (possibly {}) — when returning=True and single_row=True. * {"status": "ok"} — when returning=False.

Method PostgresToolkit.transaction

Yield a raw asyncpg connection inside a transaction block.

Commits on normal exit, rolls back on exception. Supports nested savepoints: callers can open an inner async with conn.transaction(): block inside the yielded context — asyncpg automatically uses a SAVEPOINT for the inner block and rolls back only that savepoint on exception without aborting the outer transaction.

Example::

async with toolkit.transaction() as tx:
    await toolkit.insert_row("auth.programs", data, conn=tx)
    await toolkit.upsert_row("auth.program_clients", pc, conn=tx)

# Nested savepoint (inner rollback preserves outer):
async with toolkit.transaction() as tx:
    await toolkit.insert_row("auth.programs", data, conn=tx)
    async with tx.transaction():   # SAVEPOINT
        await toolkit.insert_row("auth.clients", c, conn=tx)
        raise SomeError()          # ROLLBACK TO SAVEPOINT
    # outer transaction still active — will COMMIT

transaction() -> AsyncIterator[Any]

Returns: AsyncIterator[Any]

Method PostgresToolkit.reload_metadata

Purge and lazily re-warm cached metadata + templates for (schema_name, table).

Clears:

  • The cache_partition entry for schema_name.table (both schema_cache and hot_cache if accessible).
  • All _prepared_cache keys containing |schema_name|table|.
  • The global Pydantic model LRU cache (whole cache — documented blast radius; see implementation notes).

The next CRUD call will trigger a lazy re-warm via _resolve_table → _build_table_metadata.

reload_metadata(schema_name: str, table: str) -> None

Parameter Type Default Description
schema_name str Schema of the table to invalidate. Named schema_name (not schema) to avoid the Pydantic v2 BaseModel.schema class-method shadowing warning when the tool-args model is generated.
table str Table name to invalidate.

Alias SQLToolkit

Re-exported from parrot.bots.database.toolkits.sql.SQLToolkit.

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