Skip to content

Controlled writes

By default sqlguardllm rejects every write. A policy can opt in to narrow, single-table INSERT, UPDATE and DELETE through Guard.check_write(). Guard.check() is unchanged and still rejects every write, so read-only callers can never reach this path.

from sqlguardllm import Guard, Policy, WritePolicy

policy = Policy(
    dialect="tsql",
    tables={"orders", "customers"},
    row_filters={"orders": "tenant_id = {user.tenant_id}"},
    writes=WritePolicy(
        tables={"orders": {"update": ["status", "notes"], "insert": True, "delete": False}},
        max_rows=50,
        require_where=True,
    ),
)
result = Guard(policy).check_write(
    "UPDATE orders SET status = 'cancelled' WHERE id = 42", {"user": {"tenant_id": 7}}
)
# result.sql: UPDATE orders SET status = 'cancelled' WHERE (id = 42) AND (tenant_id = 7)

What check_write() enforces

  • Exactly one statement: INSERT ... VALUES, UPDATE or DELETE on one plain table. MERGE, DDL, UPDATE ... FROM, CTEs, subqueries, INSERT ... SELECT, and any OUTPUT, RETURNING, INTO, LIMIT or ORDER BY supplied by the caller are write_not_allowed. Anything unknown is rejected, not ignored.
  • The table must be in writes.tables with the operation enabled (update lists the columns, insert and delete are booleans, all off by default).
  • UPDATE may only set the listed columns (write_column_not_allowed). INSERT needs an explicit column list. Hidden and masked columns can't be written, filtered on or referenced.
  • require_where (default on): UPDATE and DELETE without WHERE are missing_where. A tautology such as 1 = 1 passes this syntactic check, so the real limits are max_rows and the row filter.
  • Row filters are ANDed into UPDATE and DELETE as (user predicate) AND (filter), so an OR can't escape. On INSERT, a filter made of column = value terms is enforced: a missing column is filled in, a different value is write_not_allowed. Other filters can't be enforced on INSERT and reject it.
  • Denied functions are rejected as in reads. Missing or invalid context fails closed.
  • max_rows bounds the rows an INSERT lists (too_many_rows). The rows an UPDATE or DELETE change are only known by running it: the execution layer must roll back when the count exceeds max_rows.
  • approval is "required" by default. "none" is the only setting that skips the human check.

MCP tools

create_server(policy, database, write_database=..., ledger_path=...) and sqlguardllm mcp --write-db URL [--ledger PATH] register three tools, only when the policy has writes and a write database is given (use a credential separate from the read one; the same URL still works but logs a warning). With writes and no --write-db, no write tool exists and one warning is logged. The ledger defaults to ~/.sqlguardllm/ledger.db (directory 0700, file 0600) and is only created when writes are enabled.

  • propose_write(sql) returns change_id, operation, table, rows_affected, max_rows, preview_before, preview_after and approval. Nothing changes. A refusal is a tool error with the stable violation codes, never row values.
  • apply_write(change_id) with approval: required asks the person through MCP elicitation (the message names the operation, table and row count, no values). Only an explicit accept with approve: true applies it; decline, cancel, no context or a client without elicitation support refuse and change nothing. With approval: none it applies directly.
  • undo(change_id, force=False) follows the same approval rule, then restores the row images.

Each refusal, apply and undo goes through the audit sink with operation and table only.

Runtime and ledger

WriteRuntime(guard, engine, ledger, context=None, ttl_seconds=900) runs the checked writes:

  • propose(sql) runs the rewritten write in one transaction, counts the rows and always rolls back. It refuses (too_many_rows) above max_rows. The preview leaves out hidden columns and shows masked ones as None.
  • apply(change_id, approved) needs approved is True (the caller decides; writes.approval == "none" is the caller's business), re-checks the original SQL against the current policy, captures before-images by primary key, requires the same row count as proposed, commits and records the images. Tables without a primary key are refused for UPDATE and DELETE. Proposals expire after ttl_seconds.
  • undo(change_id, force=False) restores the before-images of an applied UPDATE or DELETE, refusing when the rows drifted since the write unless force=True. INSERT can't be undone in v1.

The ledger is a SQLite file (0600, parent directory 0700) whose before and after columns hold copies of database rows and whose sql column holds statement text. Treat it as sensitive data: it is never logged, entries older than retention_days (default 30) are removed by purge(), and purge_all() wipes it.

Recommendations when the execution layer exists: use a separate database credential for writes, and treat the ledger as row data (restrictive file permissions, retention, purge).

Runtime and ledger

WriteRuntime(guard, engine, ledger) runs writes in three steps:

  • propose(sql): runs check_write, captures the matching rows, executes the rewritten write and always rolls back. It refuses with too_many_rows above max_rows, and returns the count and a preview without hidden columns (masked columns are replaced).
  • apply(change_id, approved=True): refuses unless approved, re-checks the stored SQL against the current policy, executes in one transaction by primary key, requires the same row count as the proposal, then commits. UPDATE and DELETE on a table without a primary key are refused. Proposals expire after ttl_seconds.
  • undo(change_id, force=False): restores the before-images of an applied UPDATE or DELETE. It refuses when the current rows differ from the recorded after-images unless force=True. INSERT undo is not supported in v1.

The ledger is a SQLite file (mode 0600, directory 0700) holding real row values in sql, before and after: treat it as sensitive data, never log it, and purge it (Ledger.purge() uses retention_days, default 30; purge_all() clears it).

Runtime and ledger (engine side)

WriteRuntime(guard, engine, ledger, context=None, ttl_seconds=900) runs the flow on any SQLAlchemy engine; the MCP tools come later.

  • propose(sql) runs check_write, then in one transaction reads the affected rows, runs the rewritten write, reads the row count and always rolls back. More than max_rows is refused (too_many_rows). The preview omits hidden columns and masks masked ones.
  • apply(change_id, approved=True) refuses unless approved, re-checks the stored SQL against the current policy, requires the same rewritten statement and the same row count as proposed, and refuses UPDATE/DELETE on tables without a primary key. Proposals expire after ttl_seconds. Before and after images are stored in the ledger.
  • undo(change_id, force=False) restores UPDATE and DELETE by primary key after a drift check; force=True overrides drift. INSERT can't be undone in v1.
  • Row values are only bound as driver parameters; identifiers are quoted.

The ledger (Ledger(path, retention_days=30), SQLite, file mode 0600) holds full before/after rows, so it is as sensitive as the database: restrict access, keep a short retention and call purge() (or purge_all()). Row data is never logged.

Runtime (engine side)

WriteRuntime(guard, engine, ledger, context=None, ttl_seconds=900) runs the writes check_write() allows. It has no MCP wiring yet.

  • propose(sql) runs the rewritten statement in a transaction that is always rolled back, captures the rows it would change, and returns the count and a preview. Hidden columns are left out of the preview and masked columns are masked. More rows than max_rows is too_many_rows. Tables without a primary key are refused for UPDATE and DELETE (write_not_allowed).
  • apply(change_id, approved) only runs with approved=True, which the caller decides (what approval: "none" means is also the caller's business). It re-checks the stored SQL against the current policy, requires the same rewritten SQL and the proposed row count, and commits only then. A proposal expires after ttl_seconds.
  • undo(change_id, force=False) restores the before-images by primary key for applied UPDATE and DELETE. It refuses when the rows no longer match what the write produced, unless force=True. INSERT can't be undone in this version.
  • Values only travel as bound driver parameters and identifiers are quoted by SQLAlchemy. The before-image capture is a plain SELECT, so it works on any engine; the SQLite engine is the tested one.

Ledger

The ledger (Ledger(path, retention_days=30), SQLite) stores the SQL and the before/after images of every change. These are real row values: the file is created with mode 0600 (its folder 0700), nothing is logged, and you should restrict backups, set a retention and run purge() (older than the retention) or purge_all().

Concurrency on SQLite

On SQLite the snapshot and the write are not under a row lock: SQLite has no row locks, and apply does not pretend otherwise. The protection there is the checks inside the apply transaction: the number of affected rows must equal the proposed count (and stay within max_rows), and the set of primary keys captured at apply time must equal the set captured at proposal time. On PostgreSQL, MySQL and SQL Server the snapshot additionally uses FOR UPDATE / UPDLOCK, ROWLOCK.

What the ledger contains

DELETE snapshots hold every column of the deleted rows, hidden ones included, because the row can only be restored whole. The ledger is therefore as sensitive as the table itself: protect, back up, retain and purge it accordingly. UPDATE snapshots only hold the updatable columns and the primary key.

Ledger signatures and key

Every ledger record is signed with HMAC-SHA256 over a canonical JSON of its security-relevant fields (change_id, operation, table, original SQL, rewritten SQL, key columns, before and after images, owner and status). The signature is verified in Ledger.get before any use; a record edited by hand (in the SQLite file) is refused with write_not_allowed ("ledger record was modified"), and so are unsigned records from older ledgers. Each legitimate status or image update re-signs the record.

The key is 32 random bytes in <ledger path>.key, created with O_EXCL|O_NOFOLLOW and mode 0600 (an existing key file must be a regular, private, 32-byte file). Alternatively set the environment variable SQLGUARD_LEDGER_KEY to the key as 64 hex characters: it takes precedence and no key file is written. Keep the key apart from the ledger file in backups; whoever holds both can forge records.

Owner and undo rules

The owner is always compared: a record created with an owner can only be applied or undone with that same owner, and a record created without an owner only without one. Undo of an UPDATE whose images contain nothing but the primary key is refused (write_not_allowed) instead of silently doing nothing.

Triggers and the row count. apply refuses (and rolls back) when the driver's affected-row count differs from the proposal. A SQL Server trigger that returns a result set, or does not SET NOCOUNT ON while writing to other tables, can make the count differ; the write is refused, never applied with a wrong count. Add SET NOCOUNT ON to such triggers.

Demo: an agent deletes rows and undo restores them

uv run python examples/writes_demo.py

It runs the real MCP server in memory on a fictional SQLite database. The agent proposes a DELETE (nothing changes, and the hidden email column is not shown), a client that cannot ask the person is refused, the person approves and the rows disappear, and undo restores them exactly. tests/test_examples.py runs it on every change.