Implementation:Guardrails ai Guardrails SQL Utils
| 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_sqlto check a query and return a list of error strings, andget_schemato retrieve the database schema as a formatted string.
SimpleSqlDriver-- A lightweight driver that uses thesqlvalidatorlibrary to parse and validate SQL queries without connecting to any database. It does not understand SQL dialects and does not support schema retrieval (get_schemaraisesNotImplementedError).
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'sexecutescript). It validates queries by executing them against the live connection and captures any exceptions. It also supports schema introspection viasqlalchemy.inspect, producing a formatted text representation of tables, columns, types, and foreign keys.
create_sql_driver-- A factory function that returns aSimpleSqlDriverwhen no schema file or connection string is provided, and aSqlAlchemyDriverotherwise.
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 installedRuntimeError-- Ifschema_fileis provided without aconnValueError-- 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
- Guardrails_ai_Guardrails_Validators -- SQL validation validators use these drivers
- Guardrails_ai_Guardrails_ValidatorServiceBase -- Orchestrates validator execution including SQL validators