From 7006f98e69935e0c363e7596918aa1f3e6244624 Mon Sep 17 00:00:00 2001 From: jmmana <33883620+jmmana@users.noreply.github.com> Date: Fri, 4 Dec 2026 20:04:22 -0500 Subject: [PATCH 1/3] Add llama-index-tools-sqlguardllm package GuardedSQLDatabase and SQLGuardToolSpec with SQLite tests and README. Co-Authored-By: Claude Opus 5.5 --- clients/llamaindex/README.md | 51 ++++++++ clients/llamaindex/pyproject.toml | 53 ++++++++ .../llama_index/tools/sqlguardllm/__init__.py | 11 ++ .../src/llama_index/tools/sqlguardllm/base.py | 110 ++++++++++++++++ .../llama_index/tools/sqlguardllm/py.typed | 0 clients/llamaindex/tests/test_guarded.py | 120 ++++++++++++++++++ 6 files changed, 345 insertions(+) create mode 100644 clients/llamaindex/README.md create mode 100644 clients/llamaindex/pyproject.toml create mode 100644 clients/llamaindex/src/llama_index/tools/sqlguardllm/__init__.py create mode 100644 clients/llamaindex/src/llama_index/tools/sqlguardllm/base.py create mode 100644 clients/llamaindex/src/llama_index/tools/sqlguardllm/py.typed create mode 100644 clients/llamaindex/tests/test_guarded.py diff --git a/clients/llamaindex/README.md b/clients/llamaindex/README.md new file mode 100644 index 0000000..e62646e --- /dev/null +++ b/clients/llamaindex/README.md @@ -0,0 +1,51 @@ +# llama-index-tools-sqlguardllm + +A guarded SQL database and tool spec for LlamaIndex, built on +[sqlguardllm](https://github.com/jmmana/sqlguardllm), a deterministic SQL firewall: the model +writes SQL, sqlguardllm checks and rewrites it against your policy, and only then does it run. + +**Status: alpha.** + +```bash +pip install --pre llama-index-tools-sqlguardllm +``` + +## Quick start + +```python +from llama_index.core.query_engine import NLSQLTableQueryEngine +from llama_index.tools.sqlguardllm import GuardedSQLDatabase, SQLGuardToolSpec +from sqlalchemy import create_engine +from sqlguardllm import Guard, Policy + +policy = Policy( + dialect="sqlite", + tables={"customers", "invoices"}, + hidden_columns={"customers.email"}, + row_filters={"invoices": "branch_id IN ({user.branches})"}, + max_rows=100, +) +db = GuardedSQLDatabase( + create_engine("sqlite:///sales.db"), # a read-only user in production + guard=Guard(policy), + context_fn=lambda: {"user": {"branches": [1, 2]}}, # from the session, never the model +) +engine = NLSQLTableQueryEngine(sql_database=db, tables=sorted(policy.tables), llm=llm) +tools = SQLGuardToolSpec(db).to_tool_list() # run_sql, list_tables, describe_table for agents +``` + +`GuardedSQLDatabase` is a drop-in for `NLSQLTableQueryEngine` and +`SQLTableRetrieverQueryEngine`. A refused query raises `QueryRefused` (a `GuardViolation`) whose +message lists the violation codes, for example +`Query refused: [hidden_column] customers.email is a hidden column`; the engines answer with it +and the tool spec returns it as `Error: ...` so the model can rewrite the query. + +## Safety notes + +- Hidden columns never appear in `describe_table` or in the schema shown to the model; only + tables in the policy are exposed. +- `sample_rows_in_table_info` must be `0` and `schema=` is not supported (both act outside the + guard); use the policy's `default_schema`. +- Keep the layers under the guard: a **read-only database user** and a statement timeout. + +More at https://github.com/jmmana/sqlguardllm. diff --git a/clients/llamaindex/pyproject.toml b/clients/llamaindex/pyproject.toml new file mode 100644 index 0000000..fe2c94c --- /dev/null +++ b/clients/llamaindex/pyproject.toml @@ -0,0 +1,53 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "llama-index-tools-sqlguardllm" +version = "0.1.0a1" +description = "LlamaIndex SQLDatabase and tool spec that only run SQL made safe by sqlguardllm." +readme = "README.md" +license = "Apache-2.0" +requires-python = ">=3.10" +classifiers = [ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Topic :: Database", + "Topic :: Security", + "Typing :: Typed", +] +dependencies = [ + "sqlguardllm>=0.5.0a8", + "llama-index-core>=0.14,<0.15", + "sqlalchemy>=2.0,<3", +] + +[project.optional-dependencies] +test = ["pytest>=8"] + +[project.urls] +Homepage = "https://github.com/jmmana/sqlguardllm" +Repository = "https://github.com/jmmana/sqlguardllm" +Issues = "https://github.com/jmmana/sqlguardllm/issues" + +[tool.hatch.build.targets.wheel] +packages = ["src/llama_index"] + +[tool.ruff] +line-length = 100 + +[tool.mypy] +strict = true +python_version = "3.10" +mypy_path = "src" +namespace_packages = true +explicit_package_bases = true + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/clients/llamaindex/src/llama_index/tools/sqlguardllm/__init__.py b/clients/llamaindex/src/llama_index/tools/sqlguardllm/__init__.py new file mode 100644 index 0000000..6ca9445 --- /dev/null +++ b/clients/llamaindex/src/llama_index/tools/sqlguardllm/__init__.py @@ -0,0 +1,11 @@ +"""LlamaIndex integrations for sqlguardllm: a guarded SQLDatabase and a tool spec.""" + +from llama_index.tools.sqlguardllm.base import ( + GuardedSQLDatabase, + QueryRefused, + SQLGuardToolSpec, +) + +__version__ = "0.1.0a1" + +__all__ = ["GuardedSQLDatabase", "QueryRefused", "SQLGuardToolSpec", "__version__"] diff --git a/clients/llamaindex/src/llama_index/tools/sqlguardllm/base.py b/clients/llamaindex/src/llama_index/tools/sqlguardllm/base.py new file mode 100644 index 0000000..b2c7eaa --- /dev/null +++ b/clients/llamaindex/src/llama_index/tools/sqlguardllm/base.py @@ -0,0 +1,110 @@ +"""A LlamaIndex ``SQLDatabase`` and tool spec that only run SQL sqlguardllm made safe.""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping +from typing import Any + +from llama_index.core import SQLDatabase +from llama_index.core.tools.tool_spec.base import BaseToolSpec + +from sqlguardllm import Guard, GuardViolation, Policy, Violation + + +class QueryRefused(GuardViolation): + """A query the guard rejected; the message carries the violation codes and reasons.""" + + def __init__(self, violations: tuple[Violation, ...]) -> None: + super().__init__(violations) + detail = "; ".join(f"[{v.code.value}] {v.message}" for v in violations) + self.args = (f"Query refused: {detail}",) + + def __str__(self) -> str: + return str(self.args[0]) + + +def _hidden(policy: Policy, table: str) -> set[str]: + prefix = f"{table.lower()}." + return { + c.lower()[len(prefix) :] + for c in policy.hidden_columns or () + if c.lower().startswith(prefix) + } + + +class GuardedSQLDatabase(SQLDatabase): + """A ``SQLDatabase`` whose ``run_sql`` only executes SQL rewritten by sqlguardllm. + + Drop-in for ``NLSQLTableQueryEngine`` and ``SQLTableRetrieverQueryEngine``. A rejected + query raises ``QueryRefused`` (a ``GuardViolation``); the engines turn it into an + ``"Error: ..."`` answer. The context comes from ``context_fn``, supplied by the + application, never by the model. Hidden columns are left out of the schema text. + + ``sample_rows_in_table_info`` must be 0 and ``schema=`` is not supported: sample rows are + read outside ``run_sql``, and ``schema`` makes LlamaIndex edit SQL after it was checked. + Use the policy's ``default_schema`` instead. + """ + + def __init__( + self, + engine: Any, + *, + guard: Guard, + context_fn: Callable[[], Mapping[str, Any]], + **kwargs: Any, + ) -> None: + if kwargs.get("schema"): + raise ValueError("GuardedSQLDatabase does not support schema=; use default_schema") + if kwargs.get("sample_rows_in_table_info", 0) != 0: + raise ValueError("GuardedSQLDatabase requires sample_rows_in_table_info=0") + kwargs["sample_rows_in_table_info"] = 0 + if not kwargs.get("include_tables") and not kwargs.get("ignore_tables"): + kwargs["include_tables"] = sorted(guard.policy.tables or ()) or None + super().__init__(engine, **kwargs) + self.guard = guard + self.context_fn = context_fn + + def run_sql(self, command: str) -> tuple[str, dict[str, Any]]: + result = self.guard.check(command, self.context_fn()) + if not result.ok or result.sql is None: + raise QueryRefused(tuple(result.violations)) + return super().run_sql(result.sql) + + def get_table_columns(self, table_name: str) -> list[Any]: + hidden = _hidden(self.guard.policy, table_name) + return [c for c in super().get_table_columns(table_name) if c["name"].lower() not in hidden] + + def get_single_table_info(self, table_name: str) -> str: + cols = [f"{c['name']} ({c['type']!s})" for c in self.get_table_columns(table_name)] + return f"Table '{table_name}' has columns: {', '.join(cols)}." + + +class SQLGuardToolSpec(BaseToolSpec): + """Agent tools ``run_sql``, ``list_tables`` and ``describe_table`` behind a guard.""" + + spec_functions: list[str | tuple[str, str]] = ["run_sql", "list_tables", "describe_table"] # noqa: RUF012 + + def __init__(self, database: GuardedSQLDatabase) -> None: + self.database = database + + def run_sql(self, query: str) -> str: + """Run one read-only SQL query on the allowed tables and return the rows. + + If the query is refused, the answer says why: rewrite it and try again. + """ + try: + return self.database.run_sql(query)[0] + except QueryRefused as exc: + return f"Error: {exc}" + except Exception: # noqa: BLE001 - the model must never see driver internals + return "Error: the query could not be executed." + + def list_tables(self) -> str: + """List the tables you may query.""" + return ", ".join(sorted(self.database.get_usable_table_names())) + + def describe_table(self, table_name: str) -> str: + """Describe the visible columns of one allowed table.""" + if table_name not in set(self.database.get_usable_table_names()): + return f"Error: unknown table {table_name!r}. Use list_tables." + return self.database.get_single_table_info(table_name) diff --git a/clients/llamaindex/src/llama_index/tools/sqlguardllm/py.typed b/clients/llamaindex/src/llama_index/tools/sqlguardllm/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/clients/llamaindex/tests/test_guarded.py b/clients/llamaindex/tests/test_guarded.py new file mode 100644 index 0000000..5dd75ca --- /dev/null +++ b/clients/llamaindex/tests/test_guarded.py @@ -0,0 +1,120 @@ +from __future__ import annotations + +import sqlite3 +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import pytest +import sqlalchemy +from llama_index.core.embeddings import MockEmbedding +from llama_index.core.llms import MockLLM +from llama_index.core.query_engine import NLSQLTableQueryEngine +from sqlalchemy.engine import Engine +from sqlguardllm import Guard, Policy + +from llama_index.tools.sqlguardllm import GuardedSQLDatabase, QueryRefused, SQLGuardToolSpec + +POLICY = Policy( + dialect="sqlite", + tables={"customers", "invoices"}, + hidden_columns={"customers.email"}, + row_filters={"invoices": "branch_id IN ({user.branches})"}, + max_rows=100, +) +CONTEXT: dict[str, Any] = {"user": {"branches": [1, 2]}} +SECRET = "ana@example.com" + + +@pytest.fixture() +def engine(tmp_path: Path) -> Iterator[Engine]: + path = tmp_path / "sales.db" + conn = sqlite3.connect(path) + conn.executescript( + f""" + CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, email TEXT); + CREATE TABLE invoices (id INTEGER PRIMARY KEY, branch_id INTEGER, total REAL); + CREATE TABLE secrets (id INTEGER PRIMARY KEY, v TEXT); + INSERT INTO customers VALUES (1, 'Ana', '{SECRET}'); + INSERT INTO invoices VALUES (10, 1, 100.0), (11, 2, 250.0), (12, 3, 900.0); + """ + ) + conn.commit() + conn.close() + eng = sqlalchemy.create_engine(f"sqlite:///{path}") + yield eng + eng.dispose() + + +@pytest.fixture() +def db(engine: Engine) -> GuardedSQLDatabase: + return GuardedSQLDatabase(engine, guard=Guard(POLICY), context_fn=lambda: CONTEXT) + + +def test_allowed_query_only_returns_user_rows(db: GuardedSQLDatabase) -> None: + text, meta = db.run_sql("SELECT id FROM invoices ORDER BY id") + assert meta["result"] == [(10,), (11,)] + assert "12" not in text + + +def test_executed_sql_has_row_filter_and_limit(db: GuardedSQLDatabase) -> None: + res = db.guard.check("SELECT id FROM invoices", CONTEXT) + assert res.sql is not None + assert "branch_id IN (1, 2)" in res.sql and "LIMIT 100" in res.sql + + +def test_write_in_cte_is_refused(db: GuardedSQLDatabase, engine: Engine) -> None: + with pytest.raises(QueryRefused, match="write_operation"): + db.run_sql("WITH x AS (DELETE FROM invoices RETURNING id) SELECT * FROM x") + with engine.connect() as c: + assert c.exec_driver_sql("SELECT count(*) FROM invoices").scalar() == 3 + + +def test_hidden_column_is_refused(db: GuardedSQLDatabase) -> None: + with pytest.raises(QueryRefused, match="hidden_column"): + db.run_sql("SELECT email FROM customers") + + +def test_unlisted_table_not_exposed(db: GuardedSQLDatabase) -> None: + assert "secrets" not in db.get_usable_table_names() + + +def test_rejects_sample_rows_and_schema(engine: Engine) -> None: + for kw in ({"sample_rows_in_table_info": 3}, {"schema": "main"}): + with pytest.raises(ValueError): + GuardedSQLDatabase(engine, guard=Guard(POLICY), context_fn=lambda: CONTEXT, **kw) + + +def test_toolspec(db: GuardedSQLDatabase) -> None: + spec = SQLGuardToolSpec(db) + assert [t.metadata.name for t in spec.to_tool_list()] == [ + "run_sql", + "list_tables", + "describe_table", + ] + assert spec.list_tables() == "customers, invoices" + info = spec.describe_table("customers") + assert "name" in info and "email" not in info + assert spec.describe_table("secrets").startswith("Error") + assert "hidden_column" in spec.run_sql("SELECT email FROM customers") + assert "not_a_query" in spec.run_sql("DELETE FROM invoices") + assert "10" in spec.run_sql("SELECT id FROM invoices") + + +def test_nl_sql_engine_with_fake_llm(db: GuardedSQLDatabase) -> None: + class FakeLLM(MockLLM): + def complete(self, prompt: str, formatted: bool = False, **kwargs: Any) -> Any: + out = super().complete(prompt, formatted=formatted, **kwargs) + out.text = "SQLQuery: SELECT email FROM customers" + return out + + engine = NLSQLTableQueryEngine( + sql_database=db, + tables=["customers", "invoices"], + llm=FakeLLM(), + embed_model=MockEmbedding(embed_dim=8), + synthesize_response=False, + ) + resp = engine.query("emails?") + assert SECRET not in str(resp.response) + assert "hidden_column" in str(resp.response) From 4015e12a784ed871040ff9bd4747625cf46f4522 Mon Sep 17 00:00:00 2001 From: jmmana <33883620+jmmana@users.noreply.github.com> Date: Fri, 4 Dec 2026 20:04:22 -0500 Subject: [PATCH 2/3] Add CI and publish workflows and docs entry for the LlamaIndex package Co-Authored-By: Claude Opus 5.5 --- .github/workflows/llamaindex-package.yml | 36 ++++++++++++ .github/workflows/publish-llamaindex.yml | 71 ++++++++++++++++++++++++ docs/INTEGRATIONS.md | 2 +- 3 files changed, 108 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/llamaindex-package.yml create mode 100644 .github/workflows/publish-llamaindex.yml diff --git a/.github/workflows/llamaindex-package.yml b/.github/workflows/llamaindex-package.yml new file mode 100644 index 0000000..cf06196 --- /dev/null +++ b/.github/workflows/llamaindex-package.yml @@ -0,0 +1,36 @@ +name: llama-index-tools-sqlguardllm + +on: + pull_request: + paths: + - "clients/llamaindex/**" + - ".github/workflows/llamaindex-package.yml" + workflow_dispatch: + schedule: + - cron: "0 6 * * 1" + +permissions: + contents: read + +jobs: + package: + name: Build, test and lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5 + with: + python-version: "3.12" + - name: Build + run: uv build clients/llamaindex --out-dir dist + - name: Smoke-test wheel with runtime dependencies only + run: | + wheel=$(find dist -maxdepth 1 -name 'llama_index_tools_sqlguardllm-*.whl') + test -n "$wheel" + uv run --isolated --no-project --with "./$wheel" python -c 'import llama_index.tools.sqlguardllm' + - name: Tests + run: > + uv run --with "./clients/llamaindex[test]" --with pytest + pytest clients/llamaindex/tests -q + - name: Lint + run: uvx ruff check clients/llamaindex diff --git a/.github/workflows/publish-llamaindex.yml b/.github/workflows/publish-llamaindex.yml new file mode 100644 index 0000000..d9595e3 --- /dev/null +++ b/.github/workflows/publish-llamaindex.yml @@ -0,0 +1,71 @@ +name: Publish llama-index-tools-sqlguardllm + +# Publishes the llama-index-tools-sqlguardllm package (clients/llamaindex) to PyPI with Trusted Publishing +# (OIDC): no token is stored. It is separate from release.yml on purpose: this package has its own +# version and release cadence. Run it by hand from main with the exact version. +# +# One-time setup, on PyPI (https://pypi.org/manage/account/publishing/), a pending publisher: +# project llama-index-tools-sqlguardllm +# owner jmmana repository sqlguardllm +# workflow publish-llamaindex.yml environment pypi-llamaindex +# and create the environment `pypi-llamaindex` in the repository settings. +on: + workflow_dispatch: + inputs: + version: + description: Exact version of clients/llamaindex on main (for example 0.1.0a1) + required: true + type: string + +permissions: + contents: read + +concurrency: + group: publish-llamaindex + cancel-in-progress: false + +jobs: + build: + name: Build and verify + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5 + - name: The requested version is the one in the package + env: + REQUESTED_VERSION: ${{ inputs.version }} + run: | + actual=$(grep -m1 '^version = ' clients/llamaindex/pyproject.toml | cut -d'"' -f2) + if [ "$actual" != "$REQUESTED_VERSION" ]; then + echo "clients/llamaindex is $actual, not $REQUESTED_VERSION" >&2 + exit 1 + fi + - name: Tests against the current LlamaIndex + run: uv run --with "./clients/llamaindex[test]" --with pytest pytest clients/llamaindex/tests -q + - run: uv build clients/llamaindex --out-dir dist + - name: Smoke-test wheel with runtime dependencies only + run: | + wheel=$(find dist -maxdepth 1 -name 'llama_index_tools_sqlguardllm-*.whl') + test -n "$wheel" + uv run --isolated --no-project --with "./$wheel" python -c 'import llama_index.tools.sqlguardllm' + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: dist + path: dist/ + + pypi: + name: Publish to PyPI + needs: build + runs-on: ubuntu-latest + environment: + name: pypi-llamaindex + url: https://pypi.org/project/llama-index-tools-sqlguardllm/ + permissions: + id-token: write + steps: + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: dist + path: dist/ + - uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # release/v1 diff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.md index 4ca1032..136d880 100644 --- a/docs/INTEGRATIONS.md +++ b/docs/INTEGRATIONS.md @@ -40,7 +40,7 @@ Runnable code for each stack, tested in CI with fake model output, is in **[RECI |---|---| | Plain Python (DB-API) / SQLAlchemy | Wrap the function that executes SQL (above): [`generic_wrapper.py`](../examples/generic_wrapper.py), [`sqlalchemy_wrapper.py`](../examples/sqlalchemy_wrapper.py) | | LangChain | `guard.enforce()` inside the `sql_db_query` tool, or a guarded `SQLDatabase` for langchain-community's toolkit: [`langchain_sql.py`](../examples/langchain_sql.py), [`langchain_community_sql.py`](../examples/langchain_community_sql.py) | -| LlamaIndex | A guarded `SQLDatabase.run_sql()` under its query engines: [`llamaindex_sql.py`](../examples/llamaindex_sql.py) | +| LlamaIndex | A guarded `SQLDatabase.run_sql()` under its query engines: [`llamaindex_sql.py`](../examples/llamaindex_sql.py), or the standalone package [`llama-index-tools-sqlguardllm`](../clients/llamaindex/README.md) (`GuardedSQLDatabase` and `SQLGuardToolSpec`) | | Vanna | A guarded `SqlRunner` for `RunSqlTool`: [`vanna_runner.py`](../examples/vanna_runner.py) | | MCP | The built-in server, `sqlguardllm mcp`: [MCP.md](MCP.md) | | [ChatIApp](https://github.com/jmmana/ChatIApp) | Uses sqlguardllm as its SQL guard; policies come from its semantic model | From 1e451c96065a67db44f4b184e1e49cd7dc6fb32a Mon Sep 17 00:00:00 2001 From: jmmana <33883620+jmmana@users.noreply.github.com> Date: Fri, 4 Dec 2026 20:05:50 -0500 Subject: [PATCH 3/3] llamaindex: refuse insert_into_table, which writes without the guard Co-Authored-By: Claude Opus 5.5 --- .../llamaindex/src/llama_index/tools/sqlguardllm/base.py | 6 ++++++ clients/llamaindex/tests/test_guarded.py | 9 +++++++++ 2 files changed, 15 insertions(+) diff --git a/clients/llamaindex/src/llama_index/tools/sqlguardllm/base.py b/clients/llamaindex/src/llama_index/tools/sqlguardllm/base.py index b2c7eaa..dca1834 100644 --- a/clients/llamaindex/src/llama_index/tools/sqlguardllm/base.py +++ b/clients/llamaindex/src/llama_index/tools/sqlguardllm/base.py @@ -70,6 +70,12 @@ def run_sql(self, command: str) -> tuple[str, dict[str, Any]]: raise QueryRefused(tuple(result.violations)) return super().run_sql(result.sql) + def insert_into_table(self, table_name: str, data: dict[str, Any]) -> None: + """Refused: ``SQLDatabase`` would write without going through the guard.""" + raise PermissionError( + "GuardedSQLDatabase is read-only: insert_into_table bypasses the guard" + ) + def get_table_columns(self, table_name: str) -> list[Any]: hidden = _hidden(self.guard.policy, table_name) return [c for c in super().get_table_columns(table_name) if c["name"].lower() not in hidden] diff --git a/clients/llamaindex/tests/test_guarded.py b/clients/llamaindex/tests/test_guarded.py index 5dd75ca..65a1120 100644 --- a/clients/llamaindex/tests/test_guarded.py +++ b/clients/llamaindex/tests/test_guarded.py @@ -118,3 +118,12 @@ def complete(self, prompt: str, formatted: bool = False, **kwargs: Any) -> Any: resp = engine.query("emails?") assert SECRET not in str(resp.response) assert "hidden_column" in str(resp.response) + + +def test_insert_into_table_is_refused(db: GuardedSQLDatabase, engine: Engine) -> None: + with engine.connect() as conn: + before = conn.execute(sqlalchemy.text("SELECT COUNT(*) FROM invoices")).scalar() + with pytest.raises(PermissionError): + db.insert_into_table("invoices", {"id": 999, "branch_id": 1, "total": 1.0}) + with engine.connect() as conn: + assert conn.execute(sqlalchemy.text("SELECT COUNT(*) FROM invoices")).scalar() == before