Skip to content

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" (default) or "es".

'en'
pretty bool

Pretty-print the rewritten SQL.

False
audit AuditLog | Callable[[AuditEvent], None] | None

Where to record every decision of :meth:check: an :class:AuditLog or a callable taking the :class:AuditEvent. None (default) records nothing.

None
role str | None

Role name to put in audit events (set by :meth:PolicySet.guard).

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. {"user": {"branches": [1, 2]}} fills {user.branches}.

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:check.

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 ("postgres", "tsql", "oracle"…).

required
tables Collection[str] | None

Allowlisted tables, optionally qualified ("sales.customers"). None disables the table allowlist, which is not recommended.

None
hidden_columns Collection[str]

Columns that may never be referenced, as "table.column".

frozenset()
row_filters Mapping[str, str]

Table → boolean SQL expression with {context.path} placeholders.

dict()
max_rows int | None

Maximum rows a query may return. None disables the limit.

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" (default) or "allowlist".

'denylist'
allowed_functions Collection[str] | None

Functions allowed in "allowlist" mode.

None
max_joins int | None

Maximum joins in the whole query, across every scope. None = no limit.

None
max_subquery_depth int | None

Maximum nesting of subqueries, derived tables and CTEs. 0 allows none. None = no limit.

None
forbid_cartesian bool

Reject joins with no ON/USING whose tables aren't linked by an equality in WHERE, and every explicit CROSS JOIN.

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 WHERE or JOIN … ON, such as a date range on a large fact table.

dict()
output_dialect str | None

Generate the rewritten SQL in this dialect instead of dialect.

None
masked_columns Mapping[str, str]

"table.column" → null, redact, hash or partial. The column may be selected but comes back masked; using it to filter, join, group or sort is hidden_column.

dict()
aggregate_only Mapping[str, int]

Table → minimum group size k. The table can only be read through aggregates, and groups smaller than k never come back.

dict()
schema Mapping[str, Collection[str]] | None

Table → its columns. Lets * over a table with masked columns be expanded with the masks instead of rejected.

None
lint_suppress Mapping[str, str]

sqlguardllm lint warning code → why it doesn't apply to this policy. Only the linter reads it: checking SQL ignores it.

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 add extend 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 inherited null (tables: null) is an error.
  • extends names the role to start from; without it a role starts from base.

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 ok).

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 ok).

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.

Bases: str, Enum

Stable reasons why a query is rejected. Codes never change within a major version.

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:~sqlguardllm.Guard.check decides.

sql str | None

The rewritten SQL to execute (only when ok).

tables frozenset[str]

Allowed physical tables the query reads, as normalized dotted names, also when it is rejected. Tables outside the allowlist appear in violations instead.

columns Mapping[str, frozenset[str]]

Table → columns the query references in it, in any clause and scope; "*" for a star. A table read without naming columns (COUNT(*)) maps to an empty set.

unresolved_columns frozenset[str]

Unqualified columns of a SELECT with several sources, whose table can't be known (the policy's schema resolves them when it lists the tables).

masked_columns Mapping[str, str]

"table.column" → mask strategy, for the masked columns the query returns (only when ok).

aggregate_only Mapping[str, int]

Aggregate-only table → minimum group size k enforced on the query (only when ok).

row_filters Mapping[str, str]

Table → row filter injected, with context values bound (only when ok).

limit int | None

Row limit of the rewritten query; None when rejected or unlimited.

violations tuple[Violation, ...]

Every reason the query is rejected (empty when ok).

language str

Language of text and of the violation messages.

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."

Bases: Exception

Raised by :meth:sqlguardllm.Guard.enforce when a query is rejected.

Bases: ValueError

The policy itself is invalid. Raised when a :class:~sqlguardllm.Guard is created.