# Rules

Source: https://dbmcp.haymon.ai/privacy/rules/

Rewrite every value of named table columns, whatever the query does with them

Global [redaction](/privacy/redaction) finds sensitive values by their pattern. Column rules work from the other direction: you name the table columns that hold sensitive data, and dbmcp rewrites **every** value that comes from them, whether or not it looks sensitive. A rule covers the column wherever a query reads it: selected directly, through `*`, a view, a CTE, a subquery, or an expression such as `lower(email)`.

To do that, dbmcp works out which table columns feed each output column of a statement before it runs. A statement it cannot check, or one that would use a ruled column in a way that could reveal its values, is refused before it runs.

Rules apply to `readQuery`, `writeQuery` (including `RETURNING` rows), and `explainQuery` on MySQL, MariaDB, PostgreSQL, and SQLite. Output columns that no rule covers keep global detection under `full`.

> **Warning:** The guarantees on this page hold only on [Supported versions](/supported-versions). On other versions rules still apply and every statement is still checked, but the server's catalog facts may differ from what dbmcp was tested against. dbmcp logs a warning once it reads the server version.

## Settings

| YAML key | Env var | Type | Default | Description |
|----------|---------|------|---------|-------------|
| `privacy.rules` | — (YAML only) | map | *unset* | Named column rules |

`privacy.rules` exists only in config files. Rules apply under the `rules` and `full` [modes](/privacy#modes). Under `none` they are ignored but still validated: keys, repeats, and `database.name` problems stop startup in every mode. The last config file that sets `privacy.rules` wins it whole: rules from different files never merge, `null` leaves an earlier file's rules in place, and `{}` clears them.

Under `rules`, nothing else is detected: other cells and error messages come back as the database returned them, apart from withheld errors. Refusals and withheld errors work as under `full`.

```yaml
database:
  backend: postgres
  name: shop
privacy:
  mode: rules
  rules:
    customer-email:
      columns:
        - users.email
        - billing.invoices.email
      entity: EMAIL_ADDRESS
    national-id:
      columns:
        - users.ssn
      entity: US_SSN
      operator: redact
    card-number:
      columns:
        - users.credit_card
      entity: CREDIT_CARD
      operator: replace
```

With these rules, `SELECT email, ssn, credit_card FROM users` returns:

```json
{ "email": "<EMAIL_ADDRESS_3f9a1c07b2d4e855>", "ssn": "", "credit_card": "<CREDIT_CARD>" }
```

## Rule shape

Each entry under `privacy.rules` is one rule. The key is its name, which every error message about the rule uses; names use only `a-z`, `0-9`, `_`, and `-`.

| Field | Required | Description |
|-------|----------|-------------|
| `columns` | yes | Non-empty list of table columns, each written `table.column`, `schema.table.column`, or `catalog.schema.table.column` ([Column keys](#column-keys)) |
| `entity` | yes | The [data type](/privacy/data-types) of the values, such as `EMAIL_ADDRESS`, `PHONE_NUMBER`, or `PERSON` |
| `operator` | no | `hash`, `replace`, `mask`, or `redact`; defaults to `privacy.operator` |

A column may appear in only one rule, and only once in it, however its key is written; a repeat stops startup and names both places.

The entity only labels the values: a ruled column is rewritten whether or not its values look like that type, and no recognizer runs on it. Machine-learning entities such as `PERSON`, `LOCATION`, and `ORGANIZATION` work as labels without `privacy.model`, so a `name` column can be ruled as `PERSON` without the model.

### Column keys

A column key has two to four dot-separated segments, compared case-insensitively. Wildcards (`*`), quotes, and whitespace are not supported, so a name containing `.` cannot be ruled. Write each name as the catalog stores it.

A key names the column the way the engine's SQL qualifies it, and leading segments may be left out: dbmcp fills them from the backend and `database.name`. Every key becomes the full `catalog.schema.table.column` form:

| Engine | `table.column` | `schema.table.column` | Full form |
|--------|----------------|-----------------------|-----------|
| PostgreSQL | `<database.name>.public.users.email` | `<database.name>.<schema>.users.email` | `<database>.<schema>.<table>.<column>` |
| MySQL / MariaDB | `def.<database.name>.users.email` | `def.<database>.users.email` | `def.<database>.<table>.<column>` |
| SQLite | `main.main.users.email` | `main.<schema>.users.email`, where `<schema>` is `main` or an attached database's alias | `main.<schema>.<table>.<column>` |

On MySQL and MariaDB a database is a schema, so three segments are `database.table.column` and work with or without `database.name`. On PostgreSQL three segments are `schema.table.column`, as in a SQL column reference; the default schema is always `public`, not the session's `search_path`. A key that leaves out the database (`table.column` on MySQL and MariaDB, any short key on PostgreSQL) needs `database.name`; without it startup stops with `a key without its database requires database.name`.

Startup checks the first segment of a full key: it must be `def` on MySQL and MariaDB, `main` on SQLite, and on PostgreSQL the database in `database.name` when that is set. Without a pinned database, PostgreSQL accepts any first segment, and a rule applies when a statement runs in that database (including one chosen with a tool's `database` parameter).

Repeats are found after the segments are filled in: with `database.name: shop` on PostgreSQL, `users.email` and `shop.public.users.email` name the same column.

> **Check the names.** A rule for a column that does not exist (a typo, a renamed table, the database name in the wrong segment) never matches, and nothing warns you. Compare every key with `listTables` output.

Rules name **table** columns. A query that reads through a view gets the rules of the view's base table columns.

## How values are rewritten

Every non-null value of a ruled output column is rendered as text (JSON values included, keys and all) and replaced whole, so the result is always a string. JSON the server returns as a JSON type (MySQL `JSON`, PostgreSQL `json`/`jsonb`) has its keys sorted first; JSON stored as text (MariaDB `JSON`, SQLite) is used as written:

| Operator | Result for `jane.doe@example.com` |
|----------|-----------------------------------|
| `hash` | `<EMAIL_ADDRESS_3f9a1c07b2d4e855>`: the entity plus a keyed hash, as in [Redaction](/privacy/redaction#how-spans-are-rewritten) |
| `replace` | `<EMAIL_ADDRESS>` |
| `mask` | `********************`, one `*` per character |
| `redact` | `""` |

`NULL` stays `null` under every operator on plain columns; computed columns ([below](#derived-columns)) read as the placeholder, `NULL` included.

`hash` uses a key derived from [`privacy.key`](/privacy/redaction#hash-key) for rules only, and the token covers the entity as well as the value. So a value gets the same token in every column ruled with the same entity: an e-mail address in `users.email` and in `invoices.billing_email` hashes to one token when both rules say `EMAIL_ADDRESS`, and the assistant can match rows by token without seeing the address. The same address ruled as `PERSON` elsewhere gets an unrelated token, and so does the same address found by global detection: otherwise a query could select a guessed address as a literal, have global detection hash it, and compare the token with a ruled column's. Set [`privacy.key`](/privacy/redaction#hash-key); without it, tokens change on every restart and differ across replicas.

### Derived columns

An output column that passes a ruled column through unchanged keeps its rule: `email`, `u.email AS e`, `(email)`, and the same column read through a view, a materialized view, a CTE, a derived table, `*`, or `UNION ALL`.

An output column computed from a ruled column comes back as the entity placeholder (`<EMAIL_ADDRESS>`) on every row, `NULL` included, whatever the rule's operator: `lower(email)`, `min(email)`, and `count(DISTINCT email)` all read as `<EMAIL_ADDRESS>`. Otherwise a condition in the select list (`IF(email LIKE '%.de', NULL, 1)`, `CASE WHEN ssn LIKE '1%' THEN 'Y' ELSE 'N' END`, `LENGTH(phone) > 5`) would answer the same yes/no question a refused `WHERE` would, through `null`, distinct tokens, or `mask` length. The value never shows, but the label can look odd: a count comes back as an e-mail placeholder.

Everything except a plain column reference counts as computed:

- functions, including every aggregate and window function (`MIN`, `MAX`, `FIRST_VALUE`, `GROUP_CONCAT`, `string_agg`, `array_agg`, …)
- operators, `CASE`, `IF`, `COALESCE`
- casts (`CAST`, `::`, `CONVERT`) and `COLLATE`
- JSON access, subscripts, and scalar subqueries
- PostgreSQL whole-row references (`SELECT t FROM t`, `f(t.*)`)
- constants and parameters

`UNION ALL` or a multi-row `VALUES` list keeps a `hash` token in a column only if every branch is a plain column hashed under the same rule, or a literal `NULL`. `SELECT email FROM users UNION ALL SELECT billing_email FROM invoices` keeps the token; a branch with an unruled column turns the column into `replace`, and a branch with a constant or a computed value makes the whole column computed.

Unruled sources mixed in add nothing: `concat(name, ' <', email, '>')` reads as `email`'s placeholder. The ruled sources of a computed column must share the entity; their operators may differ. A plain column in a `UNION ALL` must agree with the other branches on operator and entity, except that `hash` and `replace` on the same entity merge into `replace`. `concat(email, phone)` over different entities is refused:

```text
column policy: output column 0 combines conflicting column rules
```

The message names only the 0-based position: an unaliased column name is expression text and can contain values.

## Where a ruled column may appear

A ruled column may be selected, but it may not appear in any other clause. A condition such as `WHERE ssn LIKE '123%'` would let the assistant learn the value one guess at a time without ever seeing it. The select list is allowed because a condition there is computed and comes back as the placeholder (see [Derived columns](#derived-columns)), as long as the number of rows does not depend on the value. These uses are refused:

| Clause | Examples |
|--------|----------|
| `JOIN` | `JOIN … ON`, `USING`, `NATURAL` join keys |
| `WHERE` | `WHERE`, `HAVING`, `UPDATE` / `DELETE … WHERE`, `MERGE … ON` |
| `GROUP BY` | `GROUP BY email` |
| `ORDER BY` | `ORDER BY ssn` |
| a window | `PARTITION BY` and `ORDER BY` inside `OVER (…)` |
| `DISTINCT` or a set operation | `SELECT DISTINCT ssn`, `UNION`, `INTERSECT`, `EXCEPT` (with or without `ALL`); `UNION ALL` is allowed |
| a set-returning function | `generate_series(1, ascii(ssn))`, `string_to_table(ssn, NULL)`, `unnest`, `json_each`, … |

Uses in `LIMIT` / `OFFSET` (through a subquery) are refused too, and reported as `WHERE`; `DISTINCT ON` is reported as `GROUP BY`. Deduplication compares values and a set-returning function turns one row into as many as its arguments ask for, so either would answer a condition through the row count: `SELECT ssn FROM users WHERE id = 5 UNION SELECT '123-45-6789'` returns one row exactly when the guess is right, even though every cell reads as a rewritten value. Inside an aggregate in the select list, `FILTER (WHERE …)` and `WITHIN GROUP (ORDER BY …)` count as sources of that output column, so it gets the rule instead.

A use inside a subquery takes the clause the subquery sits in, and uses inside a view body count the same as uses in the query. So a view that filters on a ruled column cannot be queried at all:

```text
column policy: column "public.users.email" (ruled) used in WHERE
column policy: column "public.users.ssn" (ruled) used in WHERE in view "public.users_with_ssn"
```

There is no way to allow a clause per rule yet. Filter, join, and group on unruled columns (an `id`, a foreign key) instead.

## Inheritance and partitions

On PostgreSQL, a plain `FROM parent` also reads the rows of every inheritance child and every partition. A rule therefore reaches across the whole inheritance tree, both legacy `INHERITS` and declarative partitioning, matching columns by name:

- **Upward.** A rule on a child or partition column also covers the same-named column of every ancestor. `SELECT email FROM ptab` is rewritten by the rule on `ptab_1.email`, for **every** row, including those of other partitions and of the parent itself.
- **Downward.** A rule on a parent column covers the same-named column of every descendant: with `ptab.email` ruled, `SELECT email FROM ptab_1` is rewritten too.
- **Siblings never.** A rule on `ptab_1.email` does not cover `SELECT email FROM ptab_2`.
- **Multiple inheritance.** Rows read through a parent also follow the rules of their table's other parents. If `child` inherits both `parent` and `other`, a rule on `other.email` covers `SELECT email FROM parent`, which reads `child`'s rows.
- **Writes.** Copying a ruled column into a tree checks every member a row can land in: the named table and each of its descendants must read the written column back under exactly the source's rule (their own or an ancestor's). `INSERT INTO ptab SELECT email FROM staging`, with `staging.email` ruled, is refused while `ptab_2.email` is unruled. Rule the top-most parent (`ptab.email`) the same way to cover every member.
- **Row movement.** An `UPDATE` or `MERGE` through a partitioned table is refused while its partitions read any ruled column under different rules: changing a partition key moves the row into another partition, where it would be read back under that partition's rules. With only `ptab_1.email` ruled, `UPDATE ptab SET id = 160` is refused. It is refused even when no row would move, every `MERGE` counts, whatever its actions, and so does an `EXPLAIN` of either. Name the partition instead (`UPDATE ptab_1 …`), or rule the partitioned table itself.

Every other check counts the tree the same way: a ruled column of any member cannot appear in a `WHERE` or `JOIN` through the parent, an `EXPLAIN` of the parent is pruned, its errors are withheld, `CREATE INDEX` on it is refused, and its whole-row references are rewritten or refused. Views over a parent get the same coverage. Columns that exist only on one child match nothing on the parent.

Two different rules that meet across a tree conflict: with `ptab.email` hashed and `ptab_1.email` masked, every read of `email` through `ptab` or `ptab_1` is refused as `combines conflicting column rules`. To rule a whole tree one way, rule its top-most parent only.

The tree is read again for every statement, so partitions attached after startup are covered, and checked again after the statement runs: if a table with a ruled column joined the tree of a table the statement read in between (`ATTACH PARTITION`, `INHERIT`), the statement is refused, nothing is returned, and a write is rolled back. Tables that left a tree meanwhile are ignored. `ONLY parent` and `parent *` are refused while rules exist.

This goes further than PostgreSQL itself: grants and row-level security check only the table a query names, not the children whose rows it reads, and PostgreSQL Anonymizer does not inherit masking rules either.

## What gets rejected

While any rule exists, dbmcp refuses every statement it cannot fully check, not only statements that touch a ruled table. Nothing runs. Every refusal starts with `column policy:` and names only clauses and identifiers, never a rule body or a value.

- **A server that is not the configured backend**: on MySQL and MariaDB every statement is refused while `database.backend` disagrees with the server's `VERSION()` (a MariaDB server with `mysql`, or the reverse); set `database.backend` / `DBMCP_DB_BACKEND` to match.
- **Statements it cannot analyze**: parse errors, unknown or ambiguous columns, nesting that is too deep, and SQL it does not model, including `WITH RECURSIVE`, `LATERAL`, table functions (`unnest`, `generate_series`, `JSON_TABLE`), and temporary tables. PostgreSQL `pg_toast` tables and SQLite's `sqlite_schema` (`sqlite_master`) are never resolved, so statements reading them are refused here too, and SQLite's implicit `rowid` is not a known column.
- **SQL the server reads differently from the parser**: MySQL and MariaDB with `ANSI_QUOTES` or `NO_BACKSLASH_ESCAPES` in `sql_mode`, or a client charset such as `gbk` or `sjis`; MySQL and MariaDB `@user` and `@@system` variables; PostgreSQL with `standard_conforming_strings = off`.
- **Index and optimizer hints**: MySQL and MariaDB `USE`, `FORCE`, and `IGNORE INDEX` (or `KEY`), SQLite `INDEXED BY` and `NOT INDEXED`, and every optimizer-hint comment (`/*+ … */`, such as MySQL `INDEX(…)` or PostgreSQL `pg_hint_plan` hints), wherever it appears. A hint can make the server scan an index on a ruled column and return rows in that column's order.
- **Unknown functions**: any function missing from the engine's built-in table, including every user-defined function, wherever it appears, view bodies included: a function body could return the values of columns it reads. Built-ins that read values outside the query are deliberately missing too (for example `current_setting`, `lo_get`, `EXTRACTVALUE`, `LOAD_FILE`).
- **Unknown cast types**: a cast (`CAST(… AS t)`, `::t`, MySQL `CONVERT(…, t)`) to a type missing from the engine's built-in table, including every extension type (such as `citext` or `hstore`) and user-defined type, wherever it appears. Built-in types whose input can quote the cast value in an error are deliberately missing too: PostgreSQL `tsvector`, `tsquery`, and `jsonpath`, and pseudo-types such as `record`. SQLite casts never fail, so any type is accepted there.
- **Relations that expose values outside the columns**: column statistics, other sessions' statement text, locked key values, raw pages, large objects, and server settings. They are refused by name, even when the connecting user cannot see them or the server version lacks them.
  - PostgreSQL (any schema): `pg_statistic`, `pg_stats`, `pg_stats_ext`, `pg_stats_ext_exprs`, `pg_statistic_ext_data`, `pg_stat_activity`, `pg_stat_statements`, `pg_largeobject`, `pg_largeobject_metadata`, `pg_settings`, `pg_file_settings`, `pg_db_role_setting`.
  - MySQL and MariaDB: `information_schema.COLUMN_STATISTICS`, `PROCESSLIST`, `INNODB_TRX`, `INNODB_LOCKS`, `INNODB_FT_*`, MariaDB's `SLAVE_STATUS`; `performance_schema.events_statements_*`, `threads`, `processlist`, `data_locks`, `prepared_statements_instances`, `user_variables_by_thread`, `replication_applier_status*`; `sys` views whose name contains `statement`, `processlist`, `session`, or `innodb_lock_waits`; every table in `mysql`.
  - SQLite: `sqlite_stat1` to `sqlite_stat4`, `sqlite_dbpage`, and **every virtual table**, including full-text search (FTS) tables. FTS cannot be queried while rules exist.
- **Views it cannot read**: a view whose body the connecting user cannot see is refused. On MySQL and MariaDB that needs the `SHOW VIEW` privilege.
- **`SHOW` forms**: every PostgreSQL `SHOW` (it reads settings). On MySQL and MariaDB, every `SHOW` except those that list schema objects or settings: `SHOW DATABASES` / `SCHEMAS`, `[EXTENDED] [FULL] TABLES`, `OPEN TABLES`, `TABLE STATUS`, `[EXTENDED] [FULL] COLUMNS` / `FIELDS`, `[EXTENDED] INDEX` / `INDEXES` / `KEYS`, `CREATE TABLE` / `VIEW` / `TRIGGER` / `FUNCTION` / `PROCEDURE` / `EVENT`, `TRIGGERS`, `EVENTS`, `FUNCTION` / `PROCEDURE STATUS`, `FUNCTION` / `PROCEDURE CODE`, `[GLOBAL | SESSION] VARIABLES`, `[GLOBAL | SESSION] STATUS`, `CHARACTER SET` / `CHARSET`, `COLLATION`, `[STORAGE] ENGINES`, `PLUGINS`, and `PRIVILEGES`. Every other form, such as `SHOW WARNINGS`, `PROCESSLIST`, `GRANTS`, or `CREATE USER`, is refused. An allowed form may filter only with `LIKE 'pattern'`: a `WHERE` filter is refused, because it can test any column's value.
- **`EXPLAIN` of ruled tables**: when the statement touches a table with a ruled column, only the plain plan forms `explainQuery` builds return a pruned plan (see [Plans of ruled tables](#plans-of-ruled-tables)). Every `ANALYZE`, and every other `EXPLAIN` form, is refused. `CREATE INDEX` on a ruled table is refused too.
- **Writes that could plant values in `hash`-ruled columns**: literals, parameters, unruled or computed values, defaults, generated columns, `ON UPDATE` columns, foreign-key cascades, and, while `hash` rules exist, every write to a table with triggers or rules (see [Writes](#writes)).
- **Row movement on PostgreSQL**: `UPDATE` and `MERGE` through a partitioned table whose partitions are ruled differently, even when no row would move; name the partition (see [Inheritance and partitions](#inheritance-and-partitions)).
- **A changed inheritance tree on PostgreSQL**: a table with a ruled column that joined the tree of a table the statement read while it ran. This one is caught after the statement runs: nothing is returned and a write is rolled back, with `column policy: an inheritance tree changed while the statement ran`. Retry the statement.
- **Schema changes and other statements**: only `SELECT`, `INSERT`, `UPDATE`, `DELETE`, `MERGE`, `CREATE TABLE` (with or without `AS`), PostgreSQL `SELECT INTO`, `CREATE [MATERIALIZED] VIEW`, `DROP`, `TRUNCATE`, `CREATE INDEX`, `SHOW`, `DESCRIBE`, and `EXPLAIN` are analyzed, and only their plain forms: DDL with expressions, `CHECK`, `REFERENCES`, or `CASCADE` is refused. Everything else is refused, including every `ALTER`, `RENAME`, `CREATE TRIGGER | FUNCTION | PROCEDURE`, `COPY`, `GRANT`, `LOAD DATA`, and SQLite `ATTACH` and `PRAGMA`. **Migrations cannot run through dbmcp while rules exist**; run them with your migration tool.

Output of `SHOW`, `DESCRIBE`, and `EXPLAIN` that is not refused gets global detection, as without rules.

## Plans of ruled tables

The plan of a statement that touches a ruled table is pruned to value-free keys: the plan structure, table and index names, access types, and row and cost estimates. Conditions, sort and group keys, and every other expression are dropped, since they can print literal values. Plans keep each engine's native shape; no flag marks what was dropped. Plans of statements that touch no ruled table are returned unchanged.

Only these forms are pruned, whether `explainQuery` builds them or they are written through `readQuery`:

- PostgreSQL: `EXPLAIN (FORMAT JSON) …`, with no other option.
- MySQL and MariaDB: `EXPLAIN FORMAT=JSON …`.
- SQLite: `EXPLAIN QUERY PLAN …`.

The statement inside must pass every other check, so a ruled column in a condition is still refused (see [Where a ruled column may appear](#where-a-ruled-column-may-appear)). Every other form on a ruled table is refused:

```text
column policy: EXPLAIN ANALYZE on ruled relation "public.users" is denied; actual row counts can reveal values, explain without ANALYZE
column policy: EXPLAIN touches ruled relation "public.users"; use explainQuery
```

The first answers any `ANALYZE`, `explainQuery`'s `analyze` included: actual row counts can reveal values. The second answers every other form, such as a text plan, `VERBOSE`, or any other PostgreSQL option. A plan that does not have the shape dbmcp expects is not returned; the error ends in `column policy: EXPLAIN plan has an unexpected shape`.

On MariaDB, `explainQuery` runs `analyze` as the `ANALYZE` statement, which dbmcp cannot analyze, so `analyze` is refused there on every statement while rules exist, ruled table or not:

```text
column policy: ANALYZE is denied on MariaDB while column rules exist; explain without ANALYZE
```

Estimates are kept, and they still say something about ruled columns:

- **Statistics of ruled columns.** Estimates come from column statistics: PostgreSQL `Plan Width` approximates the average width of a ruled value, `Plan Rows` over `DISTINCT` approximates its number of distinct values, and so do extended statistics and index cardinality on MySQL and MariaDB.
- **Fixed literals in the schema.** PostgreSQL row estimates reflect the selectivity of literals in row-level security policies, partial-index predicates, and rules.
- **Yes/no answers about unruled conditions.** MySQL and MariaDB `message` texts (such as `Impossible WHERE`) and the `const_row_not_found`, `unique_row_not_found`, and `impossible_on_condition` flags tell whether a condition on unruled columns matches.
- **SQLite skip-scan.** After `ANALYZE`, a skip-scan in the `detail` text hints that a column has few distinct values.

On MySQL, a pruned plan runs with `explain_json_format_version` set to `1` for its session, since version 2 (the MySQL 9.5 default) prints the statement text; the server default is restored afterwards. Plans of unruled tables keep the server's version. MySQL before 8.3 has no such setting and always uses version 1. MariaDB is not affected.

## Writes

With `DBMCP_DB_READ_ONLY=false`, `writeQuery` is checked like a read, and the rows of `RETURNING` are rewritten like query rows. A write must also not copy ruled values into a column that is not ruled the same way, which would launder them:

- A target column fed by a ruled column needs a rule with the same operator and entity, and the ruled column must pass through unchanged. An unruled target, or one ruled differently, is refused.
- A computed value over a ruled column (see [Derived columns](#derived-columns)) is laundering into any target, whatever its rule: stored, it would later read back as a plain column, not as the placeholder. `UPDATE users SET note = IF(email LIKE '%.de', NULL, 'x')` is refused even when `note` carries `email`'s rule; `INSERT INTO copy (email) SELECT email FROM users` passes when `copy.email` does. A column written by several clauses (an upsert's conflict clause, `MERGE` branches) counts as computed when one clause writes a constant or `DEFAULT` beside a plain copy, so `INSERT INTO copy (id, email) SELECT id, email FROM users ON CONFLICT (id) DO UPDATE SET email = DEFAULT` is refused too, as is `UPDATE users SET phone = trim(phone)`.
- A target fed only by literals or unruled columns copies no ruled values and is always allowed, except into a `hash`-ruled column (below).
- A new table's column that copies a ruled column unchanged must have a name a rule can match: `CREATE TABLE copy AS SELECT (email) FROM users` is refused until the column is aliased (`(email) AS email`) and ruled. A computed column such as `lower(email)` is laundering with or without an alias, and an unaliased one is reported by its position only, since its name is expression text.

This covers `INSERT`, `UPDATE`, `MERGE`, `CREATE TABLE … AS`, PostgreSQL `SELECT INTO`, and `CREATE MATERIALIZED VIEW`. For example, `INSERT INTO audit (note) SELECT ssn FROM users` is refused unless `audit.note` carries the `ssn` rule. To copy ruled data into a new table, add a rule for the new table's columns first. `CREATE VIEW` is not laundering, since reads through the view get the base table rules, but its body passes the other checks.

```text
column policy: writing column "public.audit.note" would weaken the rules of its source columns
```

A `hash`-ruled column also must not take a value the statement chose: its token would let the assistant hash a guess and compare it with stored tokens. Such a column takes only:

- copies of columns hashed with the same entity, passed through unchanged (a computed copy is laundering, see above);
- `NULL`;
- `DEFAULT`, or no value at all in an `INSERT`, only when the column has no default (no `DEFAULT`, identity, sequence, or auto-increment).

A write is also refused when the database could fill a `hash`-ruled column of its target itself: any `INSERT` or `MERGE` on a table whose `hash`-ruled column has a default, and any `INSERT`, `UPDATE`, or `MERGE` on a table whose `hash`-ruled column is generated or has MySQL's `ON UPDATE CURRENT_TIMESTAMP`. `DELETE` is allowed. Every `INSERT` and `MERGE` counts as leaving out each `hash`-ruled column, even one it writes: an upsert's conflict clause or a `MERGE` clause can write a column its insert leaves to the default, and the clauses are not told apart.

Foreign-key actions and triggers write too, so while `hash` rules exist a write is also refused when:

- it fires a cascade into a `hash`-ruled column of another table: an `ON UPDATE CASCADE` from a parent column not hashed with the same entity, or an `ON UPDATE` / `ON DELETE SET DEFAULT`. `SET NULL` and `ON DELETE CASCADE` are allowed. A cascade that changes a child column (anything but `ON DELETE CASCADE`) is also refused while the child has another `hash`-ruled column: the database may recompute it as a generated or `ON UPDATE` column. Cascades are followed through every table they reach. An `UPDATE` fires the update actions of the columns it writes, a `DELETE` the delete actions; every `INSERT` (an upsert updates, MySQL's `REPLACE` deletes), every `MERGE`, and every `UPDATE` through a PostgreSQL partitioned table (which may move rows by deleting them) fires both kinds.
- its target has a trigger (enabled or not) or, on PostgreSQL, a rule other than a view's `SELECT` rule, whether or not the target has a ruled column. This covers `TRUNCATE` too. On PostgreSQL that covers every descendant of the target, and on PostgreSQL and SQLite every table a fired cascade changes, since cascaded changes fire their triggers there. MySQL and MariaDB fire no triggers on cascaded changes.

For example, with `users.email` hashed, `INSERT INTO users (email) VALUES ('alice@example.com')` is refused, while `INSERT INTO users_archive (email) SELECT email FROM users` is allowed when `users_archive.email` is hashed as `EMAIL_ADDRESS` too.

```text
column policy: column "public.users.email" is hashed and only takes copies of columns hashed the same way, or NULL
column policy: column "public.users.email" is hashed and filled by the database, so this write is refused
column policy: relation "public.users" has triggers or rules, which may fill hashed columns, so writes to it are refused
```

Each statement runs in one transaction, and a result that does not fit the plan is rolled back before anything commits. Some writes cannot be undone that way:

- **MySQL and MariaDB DDL** (`CREATE TABLE`, `DROP`, `TRUNCATE`, `CREATE INDEX`) commits implicitly. A refusal after it ran leaves the change in place.
- **MySQL and MariaDB non-transactional tables** (MyISAM, MEMORY, Aria, …) ignore rollback. A write that reads a view must be able to roll back, so `CREATE TABLE … AS SELECT` from a view, and writes from a view into a table that is not InnoDB, are refused. Use `CREATE TABLE` followed by `INSERT … SELECT` into an InnoDB table instead.
- **PostgreSQL `CREATE INDEX`** runs outside the transaction, since its `CONCURRENTLY` form needs that.

On PostgreSQL, a `search_path` that puts `pg_temp` first refuses creates of unqualified names: the server would create them as temporary tables.

An unqualified `CREATE TABLE … AS` or `CREATE [MATERIALIZED] VIEW` name that resolves to an existing relation outside the schema the server creates in, such as a SQLite `temp` table, is refused; qualify it.

## Database errors

Database error messages can echo values, for example `invalid input syntax for type integer: "123-45-6789"`. When the failing statement touches a table with a ruled column, and for every PostgreSQL `CREATE INDEX` while rules exist, dbmcp keeps only messages whose error code never carries a value, and replaces every other message, including errors raised at `COMMIT`:

```text
query failed (SQLSTATE 22P02): error detail withheld under column policy
```

- **PostgreSQL** keeps a fixed list of SQLSTATE codes from classes `08` (connection), `25` (transaction state), `40` (rollback), `42` (syntax and access), `53` (resources), `54` (statement, column, and argument limits: `54001`, `54011`, `54023`), and `57` (operator intervention). It withholds `42601`, `42602`, `42P01`, `42704`, `42725`, and `42883`, which can echo a cast's input, and `54000`, whose `tsvector` and `tsquery` input errors quote the input or its byte count. Any code not on the list, including codes added by newer PostgreSQL releases or extensions, is withheld.
- **MySQL and MariaDB** keep a fixed list of error numbers: unknown column or table, syntax, access, unknown function, foreign key, `NOT NULL`, check constraint, and duplicate column name. Invalid JSON text errors (`3140`, `3141`) and out of range (`1264`) and data too long (`1406`) errors are withheld: the position or row number they report can encode a value. Everything else is withheld as `query failed (error <number>, SQLSTATE <state>): error detail withheld under column policy`.
- **SQLite** keeps constraint failures (`CHECK`, foreign key, `NOT NULL`, primary key, unique, rowid, datatype) and malformed-JSON errors, but not `RAISE()` messages from triggers, as `query failed (SQLite code <code>): …`.

Policy refusals, timeouts, and connection errors are returned as they are. Other errors, from statements that touch no ruled table, get global redaction, as without rules.

## Residual risks

Column rules narrow what the assistant can learn, but some channels stay open. Plan for them:

- **Rules that match nothing.** A key with a typo or the wrong segments (see [Column keys](#column-keys)) silently has no effect.
- **Unlisted columns.** Columns without a rule rely on global detection, which catches patterns such as e-mail addresses and IBANs but not names or street addresses (those need [Machine Learning](/privacy/machine-learning)). Rule every column that holds sensitive data.
- **Timing.** How long a query runs can depend on ruled values. Response times are not padded.
- **Errors as an oracle.** Whether a statement fails can depend on a value: `SELECT CASE WHEN ssn LIKE '1%' THEN 1/0 END FROM users` fails exactly when the condition holds, and `SELECT 1/(ascii(ssn) - 49) FROM users` fails exactly when `ssn` starts with `1`, with no condition at all. Withholding the message does not hide that an error happened. A `LIMIT` on an unruled column turns this into a row locator: the statement fails only when the matching row is among the first rows, so a search over the limit finds the row.
- **Plan estimates.** Pruned plans keep row and cost estimates, which derive from statistics of ruled columns; see [Plans of ruled tables](#plans-of-ruled-tables).
- **Row order.** Without `ORDER BY`, rows come back in the order of the plan the server picks, and that order can follow a ruled column. With `LIMIT` and `OFFSET` it becomes a rank oracle: `SELECT id FROM users LIMIT 1 OFFSET 5` names the row holding the sixth-smallest `email`, though no value is shown. Paging through `nextCursor` without `ORDER BY` walks the same order.
  - Where the order comes from: an index that contains the ruled column and covers the output (MySQL, MariaDB, SQLite; on PostgreSQL an index that leads on the ruled column and covers the output); a composite index `(x, email)`, where rows that tie on `x` (`WHERE x = 1`, or each group of `GROUP BY x`) come back in `email` order; a primary key on the ruled column on InnoDB or SQLite `WITHOUT ROWID` tables, where a table scan follows the key; a PostgreSQL table reordered with `CLUSTER` on the ruled column, or range partitions over it; and insertion order that tracks the ruled column (rows loaded sorted by it).
  - Nested forms carry the same order, nothing more: order-sensitive aggregates without their own `ORDER BY` (`group_concat(id)`, `string_agg`, `array_agg`, `json_agg`, `json_arrayagg`), `LIMIT` and `OFFSET` in a subquery, windows without `ORDER BY` (`row_number() OVER ()`, `lag`, `lead`), `DISTINCT ON`, `any_value`, `first_value`, and copies (`INSERT … SELECT` into an auto-increment key, `CREATE TABLE … AS`).
  - Hints that pick such an index are refused (see [What gets rejected](#what-gets-rejected)), and so is a ruled column in `ORDER BY`, but the server can still pick the index on its own.
  - On the database dbmcp reads, do not keep an index that contains a ruled column: make it invisible on MySQL (`ALTER TABLE … ALTER INDEX … INVISIBLE`) or ignored on MariaDB (`… IGNORED`), or point dbmcp at a replica without it. A primary key cannot be made invisible or ignored (on MySQL neither can the implicit one, a `UNIQUE NOT NULL` index on a table without a primary key), so do not key a table on a ruled column.
- **Nullness.** `NULL` stays `null` in plain columns, so the assistant learns which values are missing; computed columns hide it.
- **`mask` length.** `mask` keeps the length of the values of plain columns.
- **`hash` equality.** Equal tokens mean equal values, so the assistant can count how many rows share a value. Anyone holding [`privacy.key`](/privacy/redaction#hash-key) can hash a guess and compare it with a token: keep the key secret, and use `replace` or `redact` where equality itself is sensitive. Rule tokens appear only on bare stored values, and global detection hashes under another key, so a query cannot obtain a rule token for a value of its own choosing.
- **Concurrent schema changes.** The catalog is read and the statement runs on one connection. On PostgreSQL both happen in one transaction; on MySQL and MariaDB the catalog is read just before the transaction opens. A view body that changed meanwhile refuses the result, but table columns are not checked again. Another session can still change a table in between. Restrict DDL on ruled tables to trusted roles.
- **Triggers and generated columns.** A trigger on an unruled table can raise an error quoting a ruled value, and that message is not withheld. A generated column computed from a ruled column is not ruled by its source. Rule generated columns explicitly. On MySQL and MariaDB, triggers are visible only with the `TRIGGER` privilege on the table: a trigger dbmcp cannot see that writes a `hash`-ruled column lets the assistant plant a value and read its token back, a guess oracle. Grant `TRIGGER`, or keep such tables out of read-write mode.
- **MySQL GTID consistency.** With `enforce_gtid_consistency` on, writes to non-transactional tables fail inside the transaction dbmcp opens.

Metadata tools (`listTables`, `listViews`, …) are not covered by column rules: they return schema objects, not query rows.