Python API reference
Import these names from sqlguardllm. The reference covers the package’s public exports and their documented members. See the package guide for the compatibility policy.
sqlguardllm.__version__ gives the installed package version as a string.
Validates and rewrites SQL written by an untrusted source, following a :class:Policy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
Policy
|
What queries may read. |
required |
language
|
str
|
Language of violation messages, |
'en'
|
pretty
|
bool
|
Pretty-print the rewritten SQL. |
False
|
audit
|
AuditLog | Callable[[AuditEvent], None] | None
|
Where to record every decision of :meth: |
None
|
role
|
str | None
|
Role name to put in audit events (set by :meth: |
None
|
Raises:
| Type | Description |
|---|---|
PolicyError
|
If the policy is invalid (checked once, here). |
check(sql, context=None)
Validate sql and, when it is allowed, return the rewritten SQL to execute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sql
|
str
|
The SQL written by the model, agent or user. |
required |
context
|
Mapping[str, Any] | None
|
Values for row-filter placeholders, from the authenticated user, never
from the model's output. |
None
|
enforce(sql, context=None)
Like :meth:check, but return the safe SQL or raise :class:GuardViolation.
explain(sql, context=None)
Describe what sql reads and what the guard does to it, allowed or not.
Runs the same pass as :meth:check, so both always agree, and adds the columns read
per table, the masks and minimum group sizes that apply. The explanation's text is in
the Guard's language and includes the bound row filters, so it is meant for users, UIs
and audit logs rather than for the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sql
|
str
|
The SQL written by the model, agent or user. |
required |
context
|
Mapping[str, Any] | None
|
Values for row-filter placeholders, as in :meth: |
None
|
wrap(execute, context_fn=None)
Wrap a function whose first argument is SQL so it only ever receives safe SQL.
context_fn is called on every call to get the current user's context.
What SQL written by an untrusted source may do.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dialect
|
str
|
Any dialect name sqlglot understands ( |
required |
tables
|
Collection[str] | None
|
Allowlisted tables, optionally qualified ( |
None
|
hidden_columns
|
Collection[str]
|
Columns that may never be referenced, as |
frozenset()
|
row_filters
|
Mapping[str, str]
|
Table → boolean SQL expression with |
dict()
|
max_rows
|
int | None
|
Maximum rows a query may return. |
1000
|
default_schema
|
str | None
|
Schema assumed for unqualified table references. |
None
|
denied_functions
|
Collection[str] | None
|
Replaces the built-in denylist for the dialect when given. |
None
|
extra_denied_functions
|
Collection[str]
|
Added to the denylist. |
frozenset()
|
function_policy
|
FunctionPolicy
|
|
'denylist'
|
allowed_functions
|
Collection[str] | None
|
Functions allowed in |
None
|
max_joins
|
int | None
|
Maximum joins in the whole query, across every scope. |
None
|
max_subquery_depth
|
int | None
|
Maximum nesting of subqueries, derived tables and CTEs. |
None
|
forbid_cartesian
|
bool
|
Reject joins with no |
False
|
required_filters
|
Mapping[str, Collection[str]]
|
Table → columns. Every read of the table must be filtered on at least
one of them in its own |
dict()
|
output_dialect
|
str | None
|
Generate the rewritten SQL in this dialect instead of |
None
|
masked_columns
|
Mapping[str, str]
|
|
dict()
|
aggregate_only
|
Mapping[str, int]
|
Table → minimum group size |
dict()
|
schema
|
Mapping[str, Collection[str]] | None
|
Table → its columns. Lets |
None
|
lint_suppress
|
Mapping[str, str]
|
|
dict()
|
from_database(url, *, include=None, exclude=None, schemas=None, **options)
classmethod
Build a policy whose tables and schema are read from a live database.
Experimental: this helper can change while the database introspection API evolves.
Needs pip install "sqlguardllm[db]" and your database driver. Only names are read.
include/exclude are glob patterns over table names ("invoice*",
"audit_*"); schemas limits which schemas are read. dialect is taken from the
URL unless you pass it. Every other option (hidden_columns, row_filters…) is
passed through. Check the result: reading a database is a starting point, not a review.
Policy.from_database("postgresql+psycopg://reader@host/db", exclude=["audit_*"])
from_dict(data)
classmethod
Build a policy from a mapping, rejecting unknown keys.
from_file(path)
classmethod
Load a policy from a .json, .yaml or .yml file.
YAML needs the optional extra: pip install "sqlguardllm[yaml]".
A base policy and named roles derived from it, loaded and validated once.
A role is a mapping of policy keys plus two keys of its own::
base:
dialect: postgres
tables: [invoices, branches]
row_filters: {invoices: "branch_id IN ({user.branches})"}
roles:
manager:
add:
tables: [payroll]
analyst:
extends: manager
max_rows: 100
add:
hidden_columns: [payroll.salary]
Merge rules, applied from base down the extends chain:
- A policy key set in a role replaces the inherited value, whether it is a scalar
(
max_rows), a list (tables) or a mapping (row_filters): what the role says is what it gets.row_filters: {}removes every inherited filter. - Keys under
addextend what is inherited: lists are joined (union) and mappings are merged key by key, the role's value winning for a key in both. Adding to a scalar, to a key the role also sets, or to an inheritednull(tables: null) is an error. extendsnames the role to start from; without it a role starts frombase.
Unknown roles, extends cycles and invalid policies raise :class:PolicyError when the
set is built, not when a user with that role first arrives: every role is resolved and
compiled up front.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base
|
Policy
|
The policy every role starts from. |
required |
roles
|
Mapping[str, Mapping[str, Any] | None] | None
|
Role name → changes to its parent policy, as described above. |
None
|
roles
property
The role names, sorted.
for_role(role)
The resolved policy of role. An unknown role is a :class:PolicyError.
from_dict(data)
classmethod
Build a policy set from {"base": {...}, "roles": {...}}.
from_file(path)
classmethod
Load a policy set from a .json, .yaml or .yml file.
YAML needs the optional extra: pip install "sqlguardllm[yaml]".
guard(role, *, language='en', pretty=False, audit=None)
A :class:Guard for role, compiled once and cached per language and pretty.
With audit the Guard is new each time (it is not cached) and its events carry the
role name.
Outcome of :meth:sqlguardllm.Guard.check.
Attributes:
| Name | Type | Description |
|---|---|---|
ok |
bool
|
True when the query may run. |
sql |
str | None
|
The rewritten SQL to execute (only when |
tables |
frozenset[str]
|
Physical tables the query reads, as normalized dotted names. |
applied_filters |
tuple[str, ...]
|
Row filters injected, one entry per filtered table occurrence. |
violations |
tuple[Violation, ...]
|
Every reason the query was rejected (empty when |
codes
property
The set of violation codes, handy for assertions and branching.
messages
property
Human-readable messages of every violation.
One reason a query was rejected.
Attributes:
| Name | Type | Description |
|---|---|---|
code |
ViolationCode
|
Stable machine-readable reason. |
message |
str
|
Human-readable explanation, safe to show to a model or a user. |
detail |
str
|
The offending SQL fragment or name, when there is one. |
What a query reads and what the guard does to it, from :meth:sqlguardllm.Guard.explain.
The text and row_filters contain the context values bound into the row filters (the
user's branches, tenant…): show them to the user or log them, but think twice before
handing them to the model.
Attributes:
| Name | Type | Description |
|---|---|---|
ok |
bool
|
True when the query may run, exactly as :meth: |
sql |
str | None
|
The rewritten SQL to execute (only when |
tables |
frozenset[str]
|
Allowed physical tables the query reads, as normalized dotted names, also when
it is rejected. Tables outside the allowlist appear in |
columns |
Mapping[str, frozenset[str]]
|
Table → columns the query references in it, in any clause and scope; |
unresolved_columns |
frozenset[str]
|
Unqualified columns of a |
masked_columns |
Mapping[str, str]
|
|
aggregate_only |
Mapping[str, int]
|
Aggregate-only table → minimum group size |
row_filters |
Mapping[str, str]
|
Table → row filter injected, with context values bound (only when |
limit |
int | None
|
Row limit of the rewritten query; |
violations |
tuple[Violation, ...]
|
Every reason the query is rejected (empty when |
language |
str
|
Language of |
codes
property
The set of violation codes.
text
property
A short sentence for people, in the Guard's language.
to_dict()
A JSON-ready dictionary, for audit logs and APIs.
to_text(language=None)
A short sentence for people, in language ("en" or "es").
"Reads branches.name and invoices.total, filtered by branch_id IN (1, 2) on invoices,
up to 1000 rows." or "Rejected: customers.email is a hidden column. It would read
customers.email."