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,UPDATEorDELETEon one plain table.MERGE, DDL,UPDATE ... FROM, CTEs, subqueries,INSERT ... SELECT, and anyOUTPUT,RETURNING,INTO,LIMITorORDER BYsupplied by the caller arewrite_not_allowed. Anything unknown is rejected, not ignored. - The table must be in
writes.tableswith the operation enabled (updatelists the columns,insertanddeleteare booleans, all off by default). UPDATEmay only set the listed columns (write_column_not_allowed).INSERTneeds an explicit column list. Hidden and masked columns can't be written, filtered on or referenced.require_where(default on):UPDATEandDELETEwithoutWHEREaremissing_where. A tautology such as1 = 1passes this syntactic check, so the real limits aremax_rowsand the row filter.- Row filters are ANDed into
UPDATEandDELETEas(user predicate) AND (filter), so anORcan't escape. OnINSERT, a filter made ofcolumn = valueterms is enforced: a missing column is filled in, a different value iswrite_not_allowed. Other filters can't be enforced onINSERTand reject it. - Denied functions are rejected as in reads. Missing or invalid context fails closed.
max_rowsbounds the rows anINSERTlists (too_many_rows). The rows anUPDATEorDELETEchange are only known by running it: the execution layer must roll back when the count exceedsmax_rows.approvalis"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)returnschange_id,operation,table,rows_affected,max_rows,preview_before,preview_afterandapproval. Nothing changes. A refusal is a tool error with the stable violation codes, never row values.apply_write(change_id)withapproval: requiredasks the person through MCP elicitation (the message names the operation, table and row count, no values). Only an explicit accept withapprove: trueapplies it; decline, cancel, no context or a client without elicitation support refuse and change nothing. Withapproval: noneit 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) abovemax_rows. The preview leaves out hidden columns and shows masked ones asNone.apply(change_id, approved)needsapproved 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 forUPDATEandDELETE. Proposals expire afterttl_seconds.undo(change_id, force=False)restores the before-images of an appliedUPDATEorDELETE, refusing when the rows drifted since the write unlessforce=True.INSERTcan'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): runscheck_write, captures the matching rows, executes the rewritten write and always rolls back. It refuses withtoo_many_rowsabovemax_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.UPDATEandDELETEon a table without a primary key are refused. Proposals expire afterttl_seconds.undo(change_id, force=False): restores the before-images of an appliedUPDATEorDELETE. It refuses when the current rows differ from the recorded after-images unlessforce=True.INSERTundo 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)runscheck_write, then in one transaction reads the affected rows, runs the rewritten write, reads the row count and always rolls back. More thanmax_rowsis 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 refusesUPDATE/DELETEon tables without a primary key. Proposals expire afterttl_seconds. Before and after images are stored in the ledger.undo(change_id, force=False)restoresUPDATEandDELETEby primary key after a drift check;force=Trueoverrides drift.INSERTcan'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 thanmax_rowsistoo_many_rows. Tables without a primary key are refused forUPDATEandDELETE(write_not_allowed).apply(change_id, approved)only runs withapproved=True, which the caller decides (whatapproval: "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 afterttl_seconds.undo(change_id, force=False)restores the before-images by primary key for appliedUPDATEandDELETE. It refuses when the rows no longer match what the write produced, unlessforce=True.INSERTcan'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.