ahvn.tool.builtins.db.exec_sql module

ahvn.tool.builtins.db.exec_sql.execute_sql(db, query)[源代码]

Execute a SQL statement on the database and return the results.

This function executes a SQL query using the provided Database instance. For SELECT queries, it returns the results as a list of dictionaries. For INSERT, UPDATE, DELETE queries, it returns an empty list. If an error occurs, it returns a SQLErrorResponse.

参数:
  • db -- The Database instance to execute the query on.

  • query (str) -- The SQL query to execute.

返回:

The query results as a list of dictionaries,

an empty list for write operations, or a SQLErrorResponse on error.

返回类型:

Union[List[Dict[str, Any]], SQLErrorResponse]

示例

>>> db = Database(provider="sqlite", database="test.db")
>>> result = execute_sql(db, "SELECT * FROM users LIMIT 5")
>>> if isinstance(result, SQLErrorResponse):
>>>     print(result.to_string())
>>> else:
>>>     print(result)
[{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, ...]
ahvn.tool.builtins.db.exec_sql.toolspec_factory_builtins_execute_sql(db, max_rows=None, max_width=None, style=None, name='exec_sql', **table_display_kwargs)[源代码]

Create a ToolSpec for executing SQL queries with a specific Database instance bound.

This factory function creates a ToolSpec from the execute_sql function, binds the database parameter to a specific Database instance, and wraps the output with table_display for formatted results.

Display parameters default to values from config (db.display section). Explicitly provided parameters override config defaults.

参数:
  • db (Database) -- The Database instance to bind to the tool.

  • max_rows (int, optional) -- Maximum number of rows to display. Defaults to config value (db.display.max_rows).

  • max_width (int, optional) -- Maximum width for each column. Defaults to config value (db.display.max_width).

  • style (Literal, optional) -- The style to use for table display. Defaults to config value (db.display.style).

  • **table_display_kwargs -- Additional keyword arguments passed to table_display.

  • name (str | None)

返回:

A ToolSpec with the database parameter bound, ready to execute SQL queries with formatted output.

返回类型:

ToolSpec

示例

>>> db = Database(provider="sqlite", database="test.db")
>>> # Use config defaults
>>> tool = toolspec_factory_builtins_execute_sql(db)
>>> # Override specific parameters
>>> tool = toolspec_factory_builtins_execute_sql(db, max_rows=20, style="SINGLE_BORDER")
>>> result = tool.call(query="SELECT * FROM users LIMIT 5")
>>> print(result)
# Formatted table output