Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Guardrails ai Guardrails SQL Utils

From Leeroopedia
Revision as of 12:51, 16 February 2026 by Admin (talk | contribs) (Auto-imported from implementations/Guardrails_ai_Guardrails_SQL_Utils.md)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Knowledge Sources
Domains Utilities, SQL Validation
Last Updated 2026-02-14 00:00 GMT

Overview

Provides SQL driver abstractions for validating SQL queries, with implementations for simple syntax validation and full database-backed validation via SQLAlchemy.

Description

The SQL Utils module defines an abstract base class and two concrete implementations for SQL query validation:

  • SQLDriver (ABC) -- The abstract base class defining the interface. It requires two methods: validate_sql to check a query and return a list of error strings, and get_schema to retrieve the database schema as a formatted string.
  • SimpleSqlDriver -- A lightweight driver that uses the sqlvalidator library to parse and validate SQL queries without connecting to any database. It does not understand SQL dialects and does not support schema retrieval (get_schema raises NotImplementedError).
  • SqlAlchemyDriver -- A full-featured driver that connects to a real database via SQLAlchemy. It can optionally load a schema file and apply it to the database backend (with special handling for SQLite's executescript). It validates queries by executing them against the live connection and captures any exceptions. It also supports schema introspection via sqlalchemy.inspect, producing a formatted text representation of tables, columns, types, and foreign keys.
  • create_sql_driver -- A factory function that returns a SimpleSqlDriver when no schema file or connection string is provided, and a SqlAlchemyDriver otherwise.

The SQLAlchemy dependency is optional and imported with graceful fallback.

Usage

Use this module when validators need to check whether LLM-generated SQL is syntactically or semantically valid. Use SimpleSqlDriver for quick syntax checks without a database, or SqlAlchemyDriver when you need to validate queries against an actual database schema. The create_sql_driver factory simplifies driver selection.

Code Reference

Source Location

  • Repository: Guardrails
  • File: guardrails/utils/sql_utils.py

Signature

class SQLDriver(ABC):
    @abstractmethod
    def validate_sql(self, query: str) -> List[str]: ...
    @abstractmethod
    def get_schema(self) -> str: ...

class SimpleSqlDriver(SQLDriver):
    def validate_sql(self, query: str) -> List[str]: ...
    def get_schema(self) -> str: ...  # raises NotImplementedError

class SqlAlchemyDriver(SQLDriver):
    def __init__(
        self,
        schema_file: Optional[str],
        conn: Optional[str],
    ) -> None: ...
    def validate_sql(self, query: str) -> List[str]: ...
    def get_schema(self) -> str: ...

def create_sql_driver(
    schema_file: Optional[str] = None,
    conn: Optional[str] = None,
) -> SQLDriver: ...

Import

from guardrails.utils.sql_utils import (
    SQLDriver,
    SimpleSqlDriver,
    SqlAlchemyDriver,
    create_sql_driver,
)

I/O Contract

SQLDriver.validate_sql / SimpleSqlDriver.validate_sql / SqlAlchemyDriver.validate_sql

Parameter Type Description
query str The SQL query string to validate

Returns: List[str] -- A list of error messages. An empty list indicates the query is valid.

SqlAlchemyDriver.__init__

Parameter Type Description
schema_file Optional[str] Path to a SQL schema file to apply to the database
conn Optional[str] SQLAlchemy connection string (e.g. "sqlite://")

Raises:

  • ImportError -- If SQLAlchemy is not installed
  • RuntimeError -- If schema_file is provided without a conn
  • ValueError -- If the connection cannot be established

SqlAlchemyDriver.get_schema

Returns: str -- A formatted multi-line string describing tables, columns, types, and foreign keys.

create_sql_driver

Parameter Type Default Description
schema_file Optional[str] None Path to a SQL schema file
conn Optional[str] None SQLAlchemy connection string

Returns: SQLDriver -- A SimpleSqlDriver if both arguments are None; a SqlAlchemyDriver otherwise.

Usage Examples

from guardrails.utils.sql_utils import create_sql_driver

# Simple syntax validation without a database
driver = create_sql_driver()
errors = driver.validate_sql("SELECT * FROM users WHERE id = 1")
if errors:
    print("Validation errors:", errors)
else:
    print("Query is valid")
from guardrails.utils.sql_utils import create_sql_driver

# Database-backed validation with SQLAlchemy
driver = create_sql_driver(
    schema_file="/path/to/schema.sql",
    conn="sqlite:///my_database.db",
)

errors = driver.validate_sql("SELECT name FROM users WHERE age > 21")
if not errors:
    print("Query validated against database schema")

# Retrieve the database schema
schema = driver.get_schema()
print(schema)
# Table: users
#     Column: id
#         type: INTEGER
#     Column: name
#         type: VARCHAR
#     Column: age
#         type: INTEGER

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment