explain_query
Analyze SQL query execution plans to understand performance and optimize database operations in CockroachDB.
Instructions
Get the execution plan for a query.
Args:
sql: SQL query to explain.
analyze: If True, actually execute to get runtime stats.
Returns:
Query execution plan.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| sql | Yes | ||
| analyze | No |
Implementation Reference
- src/cockroachdb_mcp/server.py:100-114 (handler)MCP tool handler for 'explain_query', registered via @mcp.tool() decorator. Thin wrapper that delegates to the underlying implementation in tools/query.py.@mcp.tool() async def explain_query(sql: str, analyze: bool = False) -> dict[str, Any]: """Get the execution plan for a query. Args: sql: SQL query to explain. analyze: If True, actually execute to get runtime stats. Returns: Query execution plan. """ try: return await query.explain_query(sql, analyze) except Exception as e: return {"status": "error", "error": str(e)}
- Core implementation of explain_query: validates query, constructs EXPLAIN or EXPLAIN ANALYZE SQL, executes it, and formats the execution plan output.async def explain_query(query: str, analyze: bool = False) -> dict[str, Any]: """Get the execution plan for a query. Args: query: SQL query to explain. analyze: If True, actually execute to get runtime stats. Returns: Execution plan. """ # Validate the underlying query validation = await validate_query(query) if not validation["is_valid"]: return { "status": "error", "error": "Query validation failed", "issues": validation["issues"], } # Build EXPLAIN query if analyze: explain_query_str = f"EXPLAIN ANALYZE {query}" else: explain_query_str = f"EXPLAIN {query}" result = await connection_manager.execute_query(explain_query_str) if result.get("status") == "error": return result # Format the plan output plan_lines = [] for row in result.get("rows", []): # CockroachDB returns plan in 'info' column if "info" in row: plan_lines.append(row["info"]) else: # Fallback for different column names plan_lines.append(str(list(row.values())[0]) if row else "") return { "status": "success", "query": query, "analyzed": analyze, "plan": "\n".join(plan_lines), }