I.3. pg_anon#

I.3. pg_anon

I.3. pg_anon #

pg_anon — masking (pseudonymization) tool for Tantor SE

I.3.1. Overview #

Version: 1.12.0

Download from nexus-public

pg_anon clones a Tantor SE database and replaces the sensitive fields on the way. The copy keeps the structure, the row counts and the relations, so it can be used where the original must not go — test and staging environments, analytics, support and training, demos, work with contractors.

This is masking (pseudonymization): it lowers the exposure of personal data, but it is not irreversible anonymization — see Security & limitations.

I.3.2. Requirements #

  • Python: 3.11+

  • Tantor SE client utilities (must match the server’s major version):

    • pg_dump – used to export the database schema

    • pg_restore – used to restore that schema into the target database

The data itself is read and written by pg_anon, not by these utilities.

The target server must be of the same major version as the source or newer: a dump taken from Tantor SE 15 restores into 17, but not the other way round.

For details, see: Installation and configuring

I.3.3. Terminology #

Term Description
Personal (sensitive) data Data that must not be shared with third parties. Includes personal or confidential business information.
Source database The original database that contains sensitive data.
Target database An empty database where the masked data will be restored.
Meta-dictionary A Python file describing rules for detecting sensitive data. Created manually and used as the basis for generating the sensitive dictionary during scanning. See more
Prepared sensitive dictionary A Python file that defines which tables and fields contain sensitive data and how to mask them. Created automatically or manually. See more
Prepared non-sensitive dictionary A Python file listing schemas, tables, and fields without sensitive data. Used to speed up repeated scans. See more
Table dictionary A Python file listing tables. Used to include or exclude tables from dump & restore operations. See more
Create-dict (scan) The process of scanning the source database to detect sensitive fields and create dictionary files. See more
Dump Exporting data from the source database into files using a dictionary. This is where masking happens. See more
Restore Importing masked data from files into the target database. See more
Masking (pseudonymization) Full process of cloning and sanitizing data (dump → restore), replacing sensitive values with random or hashed ones. It reduces exposure, but is not irreversible anonymization in the GDPR sense — the result stays personal data unless you make it otherwise.
Masking function A Tantor SE function (built-in or from the anon_funcs schema) that replaces a sensitive value with a random or hashed one. New functions can be added to extend the masking logic.

I.3.4. Quick Start #

Find the personal data in a demo database, make a masked dump and restore it into a second database. The demo database, the dictionary and a container to run them in are all in demo/.

I.3.4.1. Get a Tantor SE server #

You need a Tantor SE 14+ server where you may create databases, pg_dump and pg_restore of its major version, and pg_anon itself. The steps below also use psql to prepare the demo and to compare the results — pg_anon itself does not need it. Clone the repository in any case — the demo files live in it:

git clone https://github.com/TantorLabs/pg_anon.git
cd pg_anon
pip install .

If you have no server at hand, demo/ starts a container that already has the server, the client utilities and pg_anon inside. This needs Docker with the Compose plugin, nothing else:

docker compose -f demo/docker-compose.yml up -d --build --wait
docker compose -f demo/docker-compose.yml exec pg_anon_demo bash

Everything below runs the same way in both cases, from the directory that holds demo/ — in the container that is /pg_anon, where the demo files are mounted, and the shell starts there. Set the connection once; on your own server, put your values here:

export PGHOST=localhost PGPORT=5432 PGUSER=demo
export DEMO_PASSWORD=demo        # the role's password; `demo` in the container

I.3.4.2. Prepare the databases and the password file #

Two databases: the source with the demo data, and an empty target for the masked copy. The password goes into a passfile in the current directory, so it stays out of the shell history and out of ps — psql and pg_anon both read it from there.

printf "$PGHOST:$PGPORT:*:$PGUSER:$DEMO_PASSWORD\n" > pgpass.conf && chmod 600 pgpass.conf
export PGPASSFILE=$PWD/pgpass.conf

psql -d postgres -c "CREATE DATABASE demo_source" -c "CREATE DATABASE demo_target"
psql -d demo_source -f demo/data.sql

The source database now holds two schemas — shop and hr, five tables, ~255 rows. The chmod matters: a passfile with wider permissions is ignored. psql picks the file up from PGPASSFILE, pg_anon is told about it with --db-passfile in every command below.

Creating the two databases needs the CREATEDB privilege; in the container the demo role is a superuser and has it.

I.3.4.3. Install the masking functions #

init creates the anon_funcs schema with the SQL functions that replace values later on. Scan and dump both need it.

Note

This writes to the source database: init creates a schema there, so the user needs the right to create one. On your own server, remove it when you are done — DROP SCHEMA anon_funcs CASCADE — the container needs no cleanup.

pg_anon init \
    --db-host=$PGHOST --db-port=$PGPORT --db-user=$PGUSER \
    --db-passfile=$PWD/pgpass.conf \
    --db-name=demo_source
Finished pg_anon in mode: init, result_code = done

The dump carries everything the source database has, anon_funcs included, so the schema shows up in the target database as well.

I.3.4.4. Scan the database for sensitive data #

create-dict reads demo/meta_dict.py — the rules describing what counts as sensitive — and writes out the fields it found, with a masking rule for each. Both output files go to /tmp/demo/, a scratch directory for everything this guide produces.

mkdir -p /tmp/demo

pg_anon create-dict \
    --db-host=$PGHOST --db-port=$PGPORT --db-user=$PGUSER \
    --db-passfile=$PWD/pgpass.conf \
    --db-name=demo_source \
    --meta-dict-file=demo/meta_dict.py \
    --output-sens-dict-file=/tmp/demo/sens_dict.py \
    --output-no-sens-dict-file=/tmp/demo/no_sens_dict.py

The command prints its progress; the result is the file /tmp/demo/sens_dict.py, shortened here to two tables out of four:

{
    "dictionary": [
        {
            "schema": "shop",
            "table": "customer_order",
            "fields": {
                "note": "regexp_replace(\"note\", '[^ ]+@[^ ]+', 'customer@example.com', 'g')"
            }
        },
        {
            "schema": "hr",
            "table": "employee",
            "fields": {
                "full_name": "anon_funcs.random_in(array['Nora Fisher', 'Paul Adler', 'Rita Lang', 'Simon Falk', 'Vera Roth'])",
                "email": "lower(anon_funcs.random_string(8)) || '@example.com'",
                "phone": "anon_funcs.random_phone('+1')",
                "ssn": "anon_funcs.partial(\"ssn\", 0, 'XXX-XX-', 4)",
                "salary": "round(anon_funcs.noise(\"salary\", 0.2), 2)"
            }
        },
        ...
    ]
}

shop.customer_order.note is in the list although its name gives nothing away — the data_regex rules of the meta-dictionary look at the values, not at the names. shop.product is absent: the catalogue is excluded by skip_rules. The second file, no_sens_dict.py, lists the fields that were checked and found harmless; the rest of this guide does not use it.

Scanning is optional. The file above is an ordinary dictionary: keep it in your repository, edit it by hand, or write one from scratch — see sensitive dictionary.

I.3.4.5. Check what will happen #

view-fields shows the rule chosen for every field, view-data applies those rules to real rows. Neither writes anything.

pg_anon view-fields \
    --db-host=$PGHOST --db-port=$PGPORT --db-user=$PGUSER \
    --db-passfile=$PWD/pgpass.conf \
    --db-name=demo_source \
    --prepared-sens-dict-file=/tmp/demo/sens_dict.py \
    --schema-name=hr --table-name=employee
┌────────┬──────────┬────────────┬────────────────────────┬────────────────────────┬──────────────────────────────────────────────────────────────────────────────────────────────────┐
│ schema │ table    │ field      │ type                   │ dict_file_name         │ rule                                                                                             │
├────────┼──────────┼────────────┼────────────────────────┼────────────────────────┼──────────────────────────────────────────────────────────────────────────────────────────────────┤
│ hr     │ employee │ full_name  │ character varying(120) │ /tmp/demo/sens_dict.py │ anon_funcs.random_in(array['Nora Fisher', 'Paul Adler', 'Rita Lang', 'Simon Falk', 'Vera Roth']) │
│ hr     │ employee │ email      │ character varying(100) │ /tmp/demo/sens_dict.py │ lower(anon_funcs.random_string(8)) || '@example.com'                                             │
│ hr     │ employee │ phone      │ character varying(20)  │ /tmp/demo/sens_dict.py │ anon_funcs.random_phone('+1')                                                                    │
│ hr     │ employee │ ssn        │ character varying(11)  │ /tmp/demo/sens_dict.py │ anon_funcs.partial("ssn", 0, 'XXX-XX-', 4)                                                       │
│ hr     │ employee │ department │ character varying(60)  │ ---                    │ ---                                                                                              │
│ hr     │ employee │ salary     │ numeric(10,2)          │ /tmp/demo/sens_dict.py │ round(anon_funcs.noise("salary", 0.2), 2)                                                        │
│ hr     │ employee │ hired_on   │ date                   │ ---                    │ ---                                                                                              │
└────────┴──────────┴────────────┴────────────────────────┴────────────────────────┴──────────────────────────────────────────────────────────────────────────────────────────────────┘

Fields with --- are dumped as they are. Every rule keeps the shape of the original value: a name stays a name, an SSN keeps its last four digits, a salary stays a two-decimal number.

pg_anon view-data \
    --db-host=$PGHOST --db-port=$PGPORT --db-user=$PGUSER \
    --db-passfile=$PWD/pgpass.conf \
    --db-name=demo_source \
    --prepared-sens-dict-file=/tmp/demo/sens_dict.py \
    --schema-name=hr --table-name=employee --limit=3
┌────┬─────────────┬──────────────────────┬─────────────┬─────────────┬─────────────┬──────────┬────────────┐
│ id │ * full_name │       * email        │   * phone   │    * ssn    │  department │ * salary │  hired_on  │
├────┼─────────────┼──────────────────────┼─────────────┼─────────────┼─────────────┼──────────┼────────────┤
│ 1  │  Simon Falk │ hmi19nto@example.com │ +1959073807 │ XXX-XX-1001 │   Support   │ 40943.27 │ 2018-02-23 │
│ 2  │  Paul Adler │ 48uvc6zv@example.com │ +1463593776 │ XXX-XX-1002 │  Warehouse  │ 44023.59 │ 2018-04-17 │
│ 3  │  Simon Falk │ lyxoalon@example.com │ +1945863438 │ XXX-XX-1003 │ Engineering │ 48401.45 │ 2018-06-09 │
└────┴─────────────┴──────────────────────┴─────────────┴─────────────┴─────────────┴──────────┴────────────┘

A * before the column name means the column is masked. Most rules pick random values, so your output will not match this one literally.

The same table that made the scan interesting is worth a look too — in shop.customer_order the personal data sits inside free text:

pg_anon view-data \
    --db-host=$PGHOST --db-port=$PGPORT --db-user=$PGUSER \
    --db-passfile=$PWD/pgpass.conf \
    --db-name=demo_source \
    --prepared-sens-dict-file=/tmp/demo/sens_dict.py \
    --schema-name=shop --table-name=customer_order --limit=4
┌────┬─────────────┬────────────┬────────────┬──────────┬──────────────┬────────┬────────────────────────────────────────────┐
│ id │ customer_id │ product_id │ ordered_at │ quantity │ total_amount │ status │                   * note                   │
├────┼─────────────┼────────────┼────────────┼──────────┼──────────────┼────────┼────────────────────────────────────────────┤
│ 9  │      10     │     10     │ 2025-01-10 │    2     │    38.00     │  paid  │ delivery confirmed by customer@example.com │
│ 69 │      10     │     10     │ 2025-03-11 │    2     │    158.00    │  paid  │ delivery confirmed by customer@example.com │
│ 12 │      13     │     13     │ 2025-01-13 │    1     │    22.00     │  new   │ delivery confirmed by customer@example.com │
│ 72 │      13     │     13     │ 2025-03-14 │    1     │    82.00     │  new   │ delivery confirmed by customer@example.com │
└────┴─────────────┴────────────┴────────────┴──────────┴──────────────┴────────┴────────────────────────────────────────────┘

Only note carries a *: the order itself is business data and stays as it is. The rule rewrites the address inside the sentence and leaves everything around it readable — and the notes that hold no address, two thirds of the table, pass through untouched. Which rows you get here is up to Tantor SE: the ids and the order may differ from the output above.

I.3.4.6. Make a masked dump #

Values are replaced by the source database itself while the data is read, so the plain ones never leave it.

pg_anon dump \
    --db-host=$PGHOST --db-port=$PGPORT --db-user=$PGUSER \
    --db-passfile=$PWD/pgpass.conf \
    --db-name=demo_source \
    --prepared-sens-dict-file=/tmp/demo/sens_dict.py \
    --output-dir=/tmp/demo/dump
Finished pg_anon in mode: dump, result_code = done

I.3.4.7. Restore it into the target database #

The target database has to be empty — demo_target was created that way in step 2.

pg_anon restore \
    --db-host=$PGHOST --db-port=$PGPORT --db-user=$PGUSER \
    --db-passfile=$PWD/pgpass.conf \
    --db-name=demo_target \
    --input-dir=/tmp/demo/dump
Finished pg_anon in mode: restore, result_code = done

I.3.4.8. Compare the two databases #

psql -d demo_source -c "SELECT id, full_name, email, phone, ssn, salary FROM hr.employee ORDER BY id LIMIT 3"
psql -d demo_target -c "SELECT id, full_name, email, phone, ssn, salary FROM hr.employee ORDER BY id LIMIT 3"
 id |  full_name   |         email         |    phone    |     ssn     |  salary
----+--------------+-----------------------+-------------+-------------+----------
  1 | Hugo Costa   | employee1@example.com | +1202566001 | 101-11-1001 | 45750.00
  2 | Irina Dvorak | employee2@example.com | +1202566002 | 102-12-1002 | 46500.00
  3 | Jonas Egger  | employee3@example.com | +1202566003 | 103-13-1003 | 47250.00

 id |  full_name  |        email         |    phone    |     ssn     |  salary
----+-------------+----------------------+-------------+-------------+----------
  1 | Nora Fisher | i6ev14rk@example.com | +1566461072 | XXX-XX-1001 | 48905.61
  2 | Vera Roth   | sz4li87c@example.com | +1143189653 | XXX-XX-1002 | 49078.04
  3 | Vera Roth   | 6kvn8sbf@example.com | +1485805625 | XXX-XX-1003 | 38450.22

Same tables, same row counts, and every field the dictionary lists is masked. What the dictionary does not list is kept as it is, on purpose: the city, the department, the identifiers and the hire dates are unchanged, the salary is the real one shifted by up to 20%, the card number keeps its last four digits. The product catalogue is identical in both databases, because nothing in it was marked sensitive.

The masks are random and independent of each other: the same person gets one name in shop.customer and another in shop.payment_card. Keep that in mind — and treat demo/meta_dict.py as an example that shows the mechanics, not as a dictionary ready for your own database.

Everything left untouched here is a quasi-identifier: city, department, hire date, the row identifiers, a salary within 20% of the real one, the last four digits of an SSN. Each is harmless alone, and together they can still point back at a person — deciding what to keep is the part no tool does for you. See Security & limitations.

I.3.4.9. What's next #

Done with the demo? Leave the container shell with exit, then:

docker compose -f demo/docker-compose.yml down -v     # container and databases
docker image rm pg_anon_demo                          # the image itself

The container publishes the server on the host as port 55432 (user demo, password demo), in case you would rather look at the two databases with your own client.

I.3.5. Security & limitations #

  • Masking is not irreversible anonymization. pg_anon replaces values; it does not prove that the result cannot be linked back. Treat masked copies as personal data unless your own analysis says otherwise.

  • What you keep can identify people. Dates, cities, departments, identifiers and format-preserving masks are quasi-identifiers, and combining them can be enough to re-identify someone. Which fields to mask, and how far, is your call.

  • Deterministic rules need a secret salt. A hash such as anon_funcs.digest("%s", 'salt', 'sha256') gives the same output for the same input — convenient for keeping relations, but reversible by brute force for low-entropy values (phone numbers, e-mails, identifiers). Keep the salt out of the dictionary you commit.

  • A dictionary ages with the schema. It is a snapshot of what the scan saw. New tables, new columns or new partitions of a partitioned table are not in it, and a dump made with the old dictionary carries them unmasked. Re-run create-dict and review the result whenever the source schema changes.

  • The source database is written to. init creates the anon_funcs schema there, and the masking functions run inside the source while the dump is read.

  • Dumps are ordinary files. Nothing in a dump is encrypted; a masked dump still deserves the storage and access rules of a database backup.

A dump can also hold secrets that masking does not change — FDW credentials, function bodies, planner statistics. pg_anon handles some of these by default and warns about the rest. See Security for details.

See How it works and the dictionary schemas for what each rule does.

I.3.6. Installation & Configuration #

You can use several options for installing pg_anon:

I.3.6.1. Before you install #

Requires Python 3.11+

pg_anon provides 2 ways to run: CLI and REST API

The REST API service is optional to install. This service is designed to integrate pg_anon functionality into any system or pipelines via HTTP requests. It works just as a thin wrapper around the CLI version of pg_anon. REST API calls prepare CLI parameters and run the CLI version of pg_anon in the background.

It doesn't keep state or store data in a database, so it can be scaled easily without extra setup.

However, this means that the system that integrates pg_anon must implement its own storage for dictionaries, dump tasks, and restore tasks.

Note

Not suitable for fully autonomous operation.

All operation runs logs and info will be stored in the directory pg_anon_runs/ (relative to the working directory or PG_ANON_HOME). All dumps will be stored in the directory pg_anon_output/ (relative to the working directory or PG_ANON_HOME). If the REST API service is scaled, you must create a symlink to these directories on a shared disk. This is required because restore operations also read dumps from pg_anon_output/.

I.3.6.2. Using db_extension_installer.sh locally from the downloaded package #

  1. Download the pg_anon package suitable for your OS from nexus-public.

  2. Download the installation script db_extension_installer.sh and make it executable:

    wget https://public.tantorlabs.ru/db_extension_installer.sh && \
    chmod +x db_extension_installer.sh
    
  3. Run the pg_anon installation using db_extension_installer.sh from the downloaded package:

    ./db_extension_installer.sh \
      --from-file=<path to pg_anon package>
    

I.3.6.3. Using db_extension_installer.sh automatically from the package repository #

  1. Download the installation script db_extension_installer.sh and make it executable:

    wget https://public.tantorlabs.ru/db_extension_installer.sh && \
    chmod +x db_extension_installer.sh
    
  2. Set the value of the environment variable NEXUS_URL:

    export NEXUS_URL="nexus-public.tantorlabs.ru"
    
  3. Run the pg_anon installation using db_extension_installer.sh with the following parameters:

    ./db_extension_installer.sh \
      --database-type=tantor \
      --edition=all \
      --extension=pg_anon
    

I.3.6.4. Using pip #

Requires Python 3.11+.

pip install pg_anon              # CLI only
pip install "pg_anon[api]"       # CLI + REST API service

This installs two commands: pg_anon (CLI) and, with the api extra, pg_anon_api (REST API service).

I.3.6.5. From the GitHub repository (Python) #

  1. Install Python 3.11+ if it is not installed: sudo apt-get install python3.11 (for Ubuntu)

  2. Clone the repository: git clone https://github.com/TantorLabs/pg_anon.git

  3. Go to the project directory: cd pg_anon

  4. Set up a virtual environment:

    • Install the virtual environment: python3 -m venv venv

    • Activate the virtual environment: source venv/bin/activate

  5. Install the package:

    • CLI only: pip install .

    • CLI + REST API: pip install ".[api]"

    Alternatively, build and install from wheel:

    pip install build
    python -m build
    pip install dist/pg_anon-*.whl           # CLI only
    pip install "dist/pg_anon-*.whl[api]"    # CLI + REST API
    

I.3.6.6. Configuring pg_anon #

By default pg_anon calls /usr/bin/pg_dump and /usr/bin/pg_restore. To use other binaries, pass the --pg-dump and --pg-restore parameters.

Advanced configuration is also available:

  • CLI - use run parameter --config

  • REST API - config must be placed at config.yml in the working directory (or $PG_ANON_HOME/config.yml)

pg-utils-versions:
  <postgres_major_version>:
    pg_dump: "/path/to/<postgres_major_version>/pg_dump"
    pg_restore: "/path/to/<postgres_major_version>/pg_restore"
  <another_postgres_major_version>:
    pg_dump: "/path/to/<postgres_major_version>/pg_dump"
    pg_restore: "/path/to/<postgres_major_version>/pg_restore"
  default:
    pg_dump: "/path/to/default_postgres_version/pg_dump"
    pg_restore: "/path/to/default_postgres_version/pg_restore"

For example, you can specify a configuration for Tantor SE 15 and 17:

pg-utils-versions:
  15:
    pg_dump: "/opt/tantor/db/15/bin/pg_dump"
    pg_restore: "/opt/tantor/db/15/bin/pg_restore"
  17:
    pg_dump: "/opt/tantor/db/17/bin/pg_dump"
    pg_restore: "/opt/tantor/db/17/bin/pg_restore"
  default:
    pg_dump: "/opt/tantor/db/17/bin/pg_dump"
    pg_restore: "/opt/tantor/db/17/bin/pg_restore"

If the current Tantor SE version does not match any version in this config, the utilities from the default section will be used. For example, pg_anon can be run with this config on Tantor SE 16. In this case, pg_dump 17 and pg_restore 17 will be used.

I.3.6.7. Working directory & PG_ANON_HOME #

pg_anon stores runtime data (operation logs, dumps) relative to the current working directory:

DirectoryContents
pg_anon_runs/<year>/<month>/<day>/<operation_id>/Operation logs and metadata
pg_anon_output/Dump files (used by REST API)
config.ymlOptional configuration file for pg_dump/pg_restore paths

By default, these paths are resolved from the current working directory.

To override the base directory, set the PG_ANON_HOME environment variable:

export PG_ANON_HOME=/opt/pg_anon/data
pg_anon init --db-host=... --db-port=...

This is useful for systemd services, Docker containers, or any deployment where the working directory differs from the data directory.

When PG_ANON_HOME is set:

  • pg_anon_runs/ → $PG_ANON_HOME/pg_anon_runs/

  • pg_anon_output/ → $PG_ANON_HOME/pg_anon_output/

  • config.yml → $PG_ANON_HOME/config.yml

I.3.6.8. Running REST API #

Run service command:

pg_anon_api --host 0.0.0.0 --port 8000 --workers=3

To specify a custom data directory:

PG_ANON_HOME=/opt/pg_anon/data pg_anon_api --host 0.0.0.0 --port 8000 --workers=3
  • Recommended worker count = 2 * CPU_CORES + 1

  • Service OpenAPI documentation is available at http://0.0.0.0:8000/docs#/

  • Also, you can see API documentation

I.3.7. How it works #

I.3.7.1. Masking (pseudonymization) #

The diagram below illustrates how data is transferred from the source DB to the target DB.

The source database contains sensitive information and is typically located in a production environment with strictly limited access.

Figure I.1. Dump-Resore-Terms.drawio.png

Dump-Resore-Terms.drawio.png

A trusted administrator runs pg_anon with credentials for the source DB. Using the prepared and approved sensitive dictionary, pg_anon creates a masked dump in the specified directory. The dictionary must be created in advance and validated by the security team.

The resulting dump directory is then transferred to the host of the target database. Compression during transfer is unnecessary because the dump files are already compressed.

Once the directory is placed on the target host, the restore process is started using target database credentials. The target database must be created beforehand using CREATE DATABASE and must be empty.

After a successful restore, the masked database is ready to be used outside production. Because the sensitive values were replaced on the source side, it can be shared with far more people than the original — how many, and under which rules, stays your decision.

I.3.7.2. What kind of work does pg_anon do inside during dump and restore? The simplest representation. #

I.3.7.2.1. For example, we have data that we want to mask: #
  1. Create the source table:

create table users (
    id bigserial,
    email text,
    login text
);

-- Checking the contents of the source table
select * from users;
>>
    id |  email  | login 
   ----+---------+-------
  1. Populating the source table:

insert into users (email, login)
select
 'user' || generate_series(1001, 1020) || '@example.com',
 'user' || generate_series(1001, 1020);

-- Checking the contents of the source table
select * from users;
>>
    id |    email         |  login   
   ----+----------------------+----------
     1 | user1001@example.com | user1001
     2 | user1002@example.com | user1002
    ...

The ‘email’ field contains sensitive data. We need to mask it.

I.3.7.2.2. What is the process of creating a dump with masking? #
  1. Data dump from the source table to a CSV file (without masking):

copy (
    select *
    from users
) to '/tmp/users.csv' with csv;
cat /tmp/users.csv
>>
   1,user1001@example.com,user1001
   2,user1002@example.com,user1002
   ...
  1. Masking the contents of the source table:

select
   id,
   md5(email) || '@abc.com' as email, -- hashing the email (masking rule in prepared sens dict file)
   login
from users;
>>
    id |                email                     |  login   
   ----+------------------------------------------+----------
     1 | 385513d80895c4c5e19c91d1df9eacae@abc.com | user1001
     2 | 9f4c0c30f85b0353c4d5fe3c9cc633e3@abc.com | user1002
    ...
  1. Data dump from the source table to a CSV file (with masking):

copy (
  select
    id,
    md5(email) || '@abc.com' as email, -- hashing the email (masking rule in prepared sens dict file)
    login
  from users
) to '/tmp/users_anonymized.csv' with csv;
cat /tmp/users_anonymized.csv
>>
   1,385513d80895c4c5e19c91d1df9eacae@abc.com,user1001
   2,9f4c0c30f85b0353c4d5fe3c9cc633e3@abc.com,user1002
   ...

The prepared sens dict file contains masking rules like hashing

I.3.7.2.3. What is the process for restoring a masked dump? #
  1. Reproducing of the structure. Creating the target table:

create table users_anonymized (
    id bigserial,
    email text,
    login text
);

-- Checking the contents of the target table
select * from users_anonymized;
>>
    id |  email  | login 
   ----+---------+-------
  1. Loading data from the source table data dump (CSV file) to target table:

copy users_anonymized
from '/tmp/users_anonymized.csv'
with csv;

-- Checking the contents of the target table
select * from users_anonymized;
>>
    id |                email                     |  login   
   ----+------------------------------------------+----------
     1 | 385513d80895c4c5e19c91d1df9eacae@abc.com | user1001
     2 | 9f4c0c30f85b0353c4d5fe3c9cc633e3@abc.com | user1002
    ...
I.3.7.2.4. Differences between original work of pg_anon and that representation #
  • pg_anon operates on the entire database (not only one table)

  • pg_anon uses .bin.gz files to save data (not csv)

  • Masking rules are provided to pg_anon via a prepared sens dict file

I.3.8. Extensions #

pg_anon creates extensions itself, before it restores the structure. An extension goes into the same schema it had in the source, and pg_anon creates that schema if it is missing. You cannot move an extension to another schema: objects in the dump use the source schema name.

  • A schema excluded with --exclude-schema-name still appears on the target if an extension lives in it. It holds only the extension and stays empty. The log shows a warning. Drop both by hand if you do not need them.

  • Schemas that belong to an extension are created by CREATE EXTENSION, for example columnar_internal of citus_columnar. pg_anon does not create them, and schema options do not apply to them. User tables in such schemas are dumped as usual.

  • Data of extension tables is not dumped — an extension fills them itself. The exception is configuration tables (pg_extension_config_dump): their rows are dumped.

  • You need enough rights. The database owner can create trusted ones. If your role cannot, create the extensions on the target first — pg_anon skips existing ones.

I.3.9. Operations #

I.3.9.1. Init #

This mode creates the anon_funcs schema in the source database and loads the predefined SQL functions from init.sql. These functions are required for processing data in the source database.

I.3.9.1.1. Run example #
pg_anon init \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=source_db
I.3.9.1.2. Options #

Common pg_anon options

OptionRequiredDescription
--configNoPath to the config file that can specify pg_dump and pg_restore utilities. (default: none)
--verboseNoSets the log verbosity level: info, debug, error. (default: info)
--debugNoEnables debug mode (equivalent to --verbose=debug) and adds extra debug logs. (default: false)
--application-name-suffixNoAppends a suffix to the database connection name. Useful for automation. (default: none)
--internal-operation-idNoPre-generated operation ID. If not set, a random UUID is generated.
--versionNoShow the version number and exit.

Database configuration options

Option Required Description
--db-host Yes Database host.
--db-port No Database port.
--db-name Yes Database name.
--db-user Yes Database user.
--db-user-password No Database user password.
--db-passfile No Path to a file containing the password used for authentication.
--db-ssl-key-file No Path to the client SSL key file for secure connections.
--db-ssl-cert-file No Path to the client SSL certificate file.
--db-ssl-ca-file No Path to the CA certificate used to verify the server’s certificate.

I.3.9.2. Scan #

The scan operation analyzes your Tantor SE database to detect potentially sensitive data and generate dictionaries files. It used for dump and repeat scan.

I.3.9.2.1. Prerequisites #
  • Manually created meta-dictionary

  • Already run init mode for source database

I.3.9.2.2. Usage #

To scan source database and create dictionary for dump, run pg_anon in create-dict mode. You need:

  • meta-dictionary file with scan rules.

pg_anon create-dict \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=test_source_db \
    --meta-dict-file=test_meta_dict.py \
    --prepared-sens-dict-file=test_sens_dict_output_previous_use.py \
    --prepared-no-sens-dict-file=test_no_sens_dict_output_previous_use.py \
    --output-sens-dict-file=test_sens_dict_output.py \
    --output-no-sens-dict-file=test_no_sens_dict_output.py
I.3.9.2.3. Options #

Common pg_anon options

Option Required Description
--config No Path to the config file that can specify pg_dump and pg_restore utilities. (default: none)
--db-connectionsNoNumber of concurrent database connections. (default: 4)
--verbose No Sets the log verbosity level: info, debug, error. (default: info)
--debug No Enables debug mode (equivalent to --verbose=debug) and adds extra debug logs. (default: false)
--application-name-suffixNoAppends a suffix to the database connection name. Useful for automation. (default: none)
--internal-operation-idNoPre-generated operation ID. If not set, a random UUID is generated.
--versionNoShow the version number and exit.

Database configuration options

Option Required Description
--db-host Yes Database host.
--db-port No Database port.
--db-name Yes Database name.
--db-user Yes Database user.
--db-user-password No Database user password.
--db-passfile No Path to a file containing the password used for authentication.
--db-ssl-key-file No Path to the client SSL key file for secure connections.
--db-ssl-cert-file No Path to the client SSL certificate file.
--db-ssl-ca-file No Path to the CA certificate used to verify the server’s certificate.

Create-dict (scan) mode options

Option Required Description
--meta-dict-file Yes Input file or file list contains meta-dictionary, which was prepared manually. In rules collision case, priority has rules in last file from the list
--prepared-sens-dict-file No Input file or file list contains sensitive dictionary, which was obtained in previous use by option --output-sens-dict-file or prepared manually. In rules collision case, priority has rules in last file from the list
--prepared-no-sens-dict-file No Input file or file list contains not sensitive dictionary, which was obtained in previous use by option --output-no-sens-dict-file or prepared manually. In rules collision case, priority has rules in last file from the list
--output-sens-dict-file Yes Output file path for saving sensitive dictionary
--output-no-sens-dict-file No Output file path for saving not sensitive dictionary
--scan-mode No Defines whether to scan all data or only part of it [“full”, “partial”] (default “partial”)
--scan-partial-rows No In --scan-mode partial defines amount of rows to scan (default 10000). Actual rows count count can be smaller after getting unique values
--disable-checksNoDisable the pre-flight check for available database connections. (default: false)
--save-dictsNoDuplicate all input and output dictionaries into the operation's run directory under pg_anon_runs. Useful for debugging or integration purposes.

I.3.9.3. Dump #

This mode creates a masked backup using rules from the sensitive dictionary.

Note

This backup can only be restored using pg_anon and cannot be restored with pg_restore

I.3.9.3.1. Prerequisites #
  • The anon_funcs schema with masking functions must already exist. See init mode.

  • A sensitive dictionary containing data about database fields and their masking rules must be prepared beforehand. See create-dict (scan) mode.

I.3.9.3.2. Full dump (dump) mode #

Creates a backup containing both the database structure and masked data.

This backup can be restored using the following modes:

Run example

pg_anon dump \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=source_db \
    --prepared-sens-dict-file=sens_dict.py
I.3.9.3.3. Structure dump (sync-struct-dump) mode #

Creates a backup containing only the database structure without masked data.

This backup can be restored in this mode:

This mode is useful when used together with the data dump (sync-data-dump) mode.

Run example

pg_anon sync-struct-dump \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=source_db \
    --output-dir=test_sync_struct_dump \
    --prepared-sens-dict-file=sens_dict.py
I.3.9.3.4. Data dump (sync-data-dump) mode #

Create backup contains only masked data without database structure.

This backup can be restored in this mode:

This mode can be useful for scheduling database synchronization, for example using cron.

Run example

pg_anon sync-data-dump \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=source_db \
    --output-dir=test_sync_data_dump \
    --prepared-sens-dict-file=sens_dict.py
I.3.9.3.5. Create partial dump #

Partial dumps are used to create a backup excluding certain tables from the source database.

Partial dump can be run in all dump modes:

Partial dumps use a tables dictionary containing a list of tables. This dictionary can act as either a whitelist or a blacklist. See tables dictionary.

Run example

Dump only need tables (whitelist)

pg_anon dump \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=source_db \
    --output-dir=partial_dump_white_list \
    --prepared-sens-dict-file=sens_dict.py \
    --partial-tables-dict-file=include_tables.py

Dump all tables without some specified tables (blacklist)

pg_anon dump \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=source_db \
    --output-dir=partial_dump_black_list \
    --prepared-sens-dict-file=sens_dict.py \
    --partial-tables-exclude-dict-file=exclude_tables.py

Dump only specified tables with excluding some of them (whitelist + blacklist)

pg_anon dump \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=source_db \
    --output-dir=partial_dump_white_list_and_black_list \
    --prepared-sens-dict-file=sens_dict.py \
    --partial-tables-dict-file=include_tables.py \
    --partial-tables-exclude-dict-file=exclude_tables.py
I.3.9.3.6. Exclude schemas #

Schema options are used to create a backup without certain schemas, in all dump modes. An excluded schema has no structure and no data in the dump.

--schema-name and --schema-mask keep only the selected schemas, --exclude-schema-name and --exclude-schema-mask leave schemas out. If a schema is selected by both, it is excluded.

  • Each option takes one value or a comma-separated list. A comma inside brackets, like in tmp_{1,2}, does not split the value.

  • A name matches only the same name. A mask is a regular expression and matches any part of the name. For example, --exclude-schema-name=audit leaves out only audit, and --exclude-schema-mask=audit also leaves out audit_old.

  • anon_funcs and schemas that belong to extensions are never excluded.

  • An event trigger is not restored if its function is in an excluded schema.

  • For sync-struct-dump and sync-data-dump, use the same schema options. Otherwise the data does not fit the structure.

If a table that stays in the dump uses a type from an excluded schema, or is a partition or a child of a table there, the dump stops with an error. Exclude these tables too, or keep the schema. sync-data-dump has no structure, so it does not check this.

Run example

pg_anon dump \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=source_db \
    --output-dir=dump_without_audit \
    --prepared-sens-dict-file=sens_dict.py \
    --exclude-schema-name=audit \
    --exclude-schema-mask='^tmp_'

Structure or data

ToolLeaves out of the dump
Schema optionsSchemas, with structure and data
Tables dictionaryTables, with structure and data
dictionary_exclude in the sensitive dictionaryData of tables. The structure stays
I.3.9.3.7. Options #

Common pg_anon options

Option Required Description
--config No Path to the config file that can specify pg_dump and pg_restore utilities. (default: none)
--db-connectionsNoNumber of concurrent database connections. (default: 4)
--verbose No Sets the log verbosity level: info, debug, error. (default: info)
--debug No Enables debug mode (equivalent to --verbose=debug) and adds extra debug logs. (default: false)
--application-name-suffixNoAppends a suffix to the database connection name. Useful for automation. (default: none)
--internal-operation-idNoPre-generated operation ID. If not set, a random UUID is generated.
--versionNoShow the version number and exit.

Database configuration options

Option Required Description
--db-host Yes Database host.
--db-port No Database port.
--db-name Yes Database name.
--db-user Yes Database user.
--db-user-password No Database user password.
--db-passfile No Path to a file containing the password used for authentication.
--db-ssl-key-file No Path to the client SSL key file for secure connections.
--db-ssl-cert-file No Path to the client SSL certificate file.
--db-ssl-ca-file No Path to the CA certificate used to verify the server’s certificate.

Dump mode options

Option Required Description
--prepared-sens-dict-file Yes Input file or file list contains sensitive dictionary, which was generated by the create-dict (scan) mode or created manually. In rules collision case, priority has rules in last file from the list
--partial-tables-dict-file No Input file or file list contains tables dictionary for include specific tables in the dump. All tables not listed in these files will be excluded. These files must be prepared manually (acts as a whitelist)
--partial-tables-exclude-dict-file No Input file or file list contains tables dictionary for exclude specific tables from the dump. All tables listed in these files will be excluded. These files must be prepared manually (acts as a blacklist)
--schema-nameNoOne schema name or a comma-separated list to keep in the dump. Other schemas are left out. See Exclude schemas.
--schema-maskNoOne regular expression or a comma-separated list to select the schemas to keep in the dump. See Exclude schemas.
--exclude-schema-nameNoOne schema name or a comma-separated list to leave out of the dump. See Exclude schemas.
--exclude-schema-maskNoOne regular expression or a comma-separated list to select the schemas to leave out of the dump. See Exclude schemas.
--disable-checksNoDisable the pre-flight check for available database connections. (default: false)
--dbg-stage-1-validate-dict No Validate dictionary, show the tables and run SQL queries without data export (default: false)
--dbg-stage-2-validate-data No Validate data, show the tables and run SQL queries with data export in prepared database (default: false)
--dbg-stage-3-validate-full No Makes all logic with “limit” in SQL queries (default: false)
--clear-output-dir No Clears the output directory from previous dumps or other files. (default: false)
--pg-dump No Path to the pg_dump Postgres tool (default /usr/bin/pg_dump).
--pg-dump-optionsNoAdditional options passed to pg_dump as is, at your own risk. Example: "--no-comments --encoding=LATIN1". See Options for pg_dump.
--allow-fdw-credentialsNoAllow FDW user-mapping credentials (OPTIONS) into the dump; blocked by default. (default: false)
--output-dirNoOutput directory for dump files. (default: ./<sens-dict-file-name>)
--ignore-privileges No Ignore privileges from source db.
--save-dictsNoDuplicate all input dictionaries into the operation's run directory under pg_anon_runs. Useful for debugging or integration purposes.

Options for pg_dump

--pg-dump-options are passed to pg_dump as is, at your own risk. They change only the structure of the dump: pg_anon dumps the data itself. If you change the list of dumped objects with them, the structure and the data may not match. To choose schemas and tables, use schema options and tables dictionaries. The sync-data-dump mode does not run pg_dump, so the options have no effect there.

Security defaults

In dump mode, pg_anon passes a few extra flags to pg_dump to leave out data that a masked backup does not need:

  • --no-subscriptions is always added (pg_dump ≥ 10). A subscription can store a password in its CONNECTION string.

  • --no-statistics is added when the pg_dump binary is version 18 or newer. Statistics can hold real column values.

pg_anon also stops the dump when the current user can see FDW user-mapping credentials (OPTIONS), because they would go into the backup. Use --allow-fdw-credentials to dump anyway.

This lowers common leaks but does not make the backup fully clean. Some objects, such as function or trigger bodies, are still dumped as they are. See the Security page for the full list.

I.3.9.4. Restore #

This mode restores a masked backup created using pg_anon in the dump mode.

Note

Only backups created with pg_anon can be restored. Backups created with pg_dump cannot be restored.

Extensions are created before the structure — see Extensions.

I.3.9.4.1. Full restore (restore) mode #

Restores both the database structure and data.

Prerequisites

Run example

pg_anon restore \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=target_db \
    --input-dir=path/to/my_full_dump \
    --verbose=debug
I.3.9.4.2. Structure restore (sync-struct-restore) mode #

Restores only the database structure.

Prerequisites

Run example

pg_anon sync-struct-restore \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=target_db \
    --input-dir=path/to/my_sync_struct_dump \
    --verbose=debug
I.3.9.4.3. Data restore (sync-data-restore) mode #

Restores data only.

Prerequisites

Run example

pg_anon sync-data-restore \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=target_db \
    --input-dir=path/to/my_sync_data_dump \
    --verbose=debug
I.3.9.4.4. Create partial restore #

Partial restores are used to restore only part of a backup, excluding certain tables if needed.

Partial restore can be run in all restore modes:

Partial restores use a tables dictionary containing a list of tables. This dictionary can act as either a whitelist (only listed tables are restored) or a blacklist (listed tables are excluded). See tables dictionary.

Run example

Restore only need tables (whitelist)

pg_anon restore \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=target_db \
    --input-dir=partial_dump_white_list \
    --partial-tables-dict-file=include_tables.py

Restore all tables without some specified tables (blacklist)

pg_anon restore \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=target_db \
    --input-dir=partial_dump_black_list \
    --partial-tables-exclude-dict-file=exclude_tables.py

Restore only specified tables with excluding some of them (whitelist + blacklist)

pg_anon restore \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=target_db \
    --input-dir=partial_dump_white_list_and_black_list \
    --partial-tables-dict-file=include_tables.py \
    --partial-tables-exclude-dict-file=exclude_tables.py
I.3.9.4.5. Exclude schemas #

Schema options work on restore as on dump, in all restore modes. An excluded schema, its objects and its data are not restored. Foreign keys and views of other schemas that refer to it are not restored either.

Note

If a table of a kept schema uses a type from an excluded schema, or is a partition or a child of a table there, the restore fails. Exclude such schemas on dump instead: the dump checks this case before it starts.

Run example

pg_anon restore \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=target_db \
    --input-dir=full_dump \
    --exclude-schema-name=audit
I.3.9.4.6. Checks during restore #
  • Missing tables. Before data loading, pg_anon checks that the target has all tables to restore. If not, the restore stops and no data is loaded. Without --clean-db, extra tables in the target are fine.

  • Foreign keys to tables without data. If the dump has no data for the table that a foreign key points to, but the table with the key has rows, the key is created as NOT VALID: new rows are checked, old rows are not. The log lists such keys. Load the missing data and run ALTER TABLE ... VALIDATE CONSTRAINT ....

I.3.9.4.7. Options #

Common pg_anon options

Option Required Description
--config No Path to the config file that can specify pg_dump and pg_restore utilities. (default: none)
--db-connectionsNoNumber of concurrent database connections, also passed to pg_restore as -j. (default: 4)
--verbose No Sets the log verbosity level: info, debug, error. (default: info)
--debug No Enables debug mode (equivalent to --verbose=debug) and adds extra debug logs. (default: false)
--application-name-suffixNoAppends a suffix to the database connection name. Useful for automation. (default: none)
--internal-operation-idNoPre-generated operation ID. If not set, a random UUID is generated.
--versionNoShow the version number and exit.

Database configuration options

Option Required Description
--db-host Yes Database host.
--db-port No Database port.
--db-name Yes Database name.
--db-user Yes Database user.
--db-user-password No Database user password.
--db-passfile No Path to a file containing the password used for authentication.
--db-ssl-key-file No Path to the client SSL key file for secure connections.
--db-ssl-cert-file No Path to the client SSL certificate file.
--db-ssl-ca-file No Path to the CA certificate used to verify the server’s certificate.

Restore mode options

Option Required Description
--input-dir Yes Path to the directory containing dump files created in dump mode.
--partial-tables-dict-file No Input Input file or file list contains tables dictionary for include specific tables in the dump. All tables not listed in these files will be excluded. These files must be prepared manually (acts as a whitelist).
--partial-tables-exclude-dict-file No Input Input file or file list contains tables dictionary for exclude specific tables from the dump. All tables listed in these files will be excluded. These files must be prepared manually (acts as a blacklist)
--schema-nameNoOne schema name or a comma-separated list to keep in the restore. Other schemas are left out. See Exclude schemas.
--schema-maskNoOne regular expression or a comma-separated list to select the schemas to keep in the restore. See Exclude schemas.
--exclude-schema-nameNoOne schema name or a comma-separated list to leave out of the restore. See Exclude schemas.
--exclude-schema-maskNoOne regular expression or a comma-separated list to select the schemas to leave out of the restore. See Exclude schemas.
--disable-checksNoDisable pre-flight checks: Tantor SE version compatibility and available database connections. Does not disable the empty-target and extra-tables safety checks. (default: false)
--seq-init-by-max-value No Initialize sequences based on maximum values. Otherwise, the sequences will be initialized based on the values of the source database.
--drop-custom-check-constr No Drops all CHECK constraints that contain user-defined procedures to avoid performance degradation during data loading.
--pg-restoreNoPath to the pg_restore Postgres tool (default /usr/bin/pg_restore).
--pg-restore-optionsNoAdditional options passed to pg_restore as is, at your own risk. Example: "--no-comments --no-table-access-method". See Options for pg_restore.
--keep-fdw-user-mappingsNoRestore FDW USER MAPPING entries instead of stripping them; stripped by default. See Security. (default: false)
--clean-db No Cleans the database objects before restoring (if they exist in the dump). Mutually exclusive with --drop-db.
--drop-db No Drop target database before restore. Mutually exclusive with --clean-db.
--ignore-privileges No Ignore privileges from source db.
--save-dictsNoDuplicate all input dictionaries into the operation's run directory under pg_anon_runs. Useful for debugging or integration purposes.

Options for pg_restore

--pg-restore-options are passed to pg_restore as is, at your own risk. They change only how the structure is restored: pg_anon loads the data itself. If you change the list of restored objects with them, the structure and the data may not match. To choose schemas and tables, use schema options and tables dictionaries. The sync-data-restore mode does not run pg_restore, so the options have no effect there.

I.3.9.5. View Fields #

This mode displays how database fields match the masking rules.

I.3.9.5.1. Prerequisites #
  • The anon_funcs schema with masking functions must already exist. See init mode.

  • A sensitive dictionary containing data about database fields and their masking rules must be prepared beforehand. See create-dict (scan) mode.

I.3.9.5.2. Run example #
pg_anon view-fields \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=source_db \
    --prepared-sens-dict-file=sens_dict.py
I.3.9.5.3. Options #

Common pg_anon options

Option Required Description
--config No Path to the config file that can specify pg_dump and pg_restore utilities. (default: none)
--verbose No Sets the log verbosity level: info, debug, error. (default: info)
--debug No Enables debug mode (equivalent to --verbose=debug) and adds extra debug logs. (default: false)
--application-name-suffixNoAppends a suffix to the database connection name. Useful for automation. (default: none)
--internal-operation-idNoPre-generated operation ID. If not set, a random UUID is generated.
--versionNoShow the version number and exit.

Database configuration options

OptionRequiredDescription
--db-hostYesDatabase host.
--db-portNoDatabase port.
--db-nameYesDatabase name.
--db-userYesDatabase user.
--db-user-passwordNoDatabase user password.
--db-passfileNoPath to a file containing the password used for authentication.
--db-ssl-key-fileNoPath to the client SSL key file for secure connections.
--db-ssl-cert-fileNoPath to the client SSL certificate file.
--db-ssl-ca-fileNoPath to the CA certificate used to verify the server’s certificate.

View-fields mode options

Option Required Description
--prepared-sens-dict-file Yes Path to Input file or file list contains sensitive dictionary, which was generated by the create-dict (scan) mode or created manually. In rules collision case, priority has rules in last file from the list.
--view-only-sensitive-fields No Displays only sensitive fields. (default: all fields)
--fields-count No Truncates the output to the given number of fields, applied after filters. (default: no limit)
--schema-name No Filter by schema name
--schema-mask No Filter by schema name using a regular expression
--table-name No Filter by table name
--table-mask No Filter by table name using a regular expression
--json No Outputs results in JSON format instead of a table.
--orm-dict-fileNoPath to a JSON file with the ORM storage structure. Replaces table and field names in the output with their ORM names.
I.3.9.5.4. ORM names translation #

For databases created by an ORM (such as 1C:Enterprise), SQL names like _reference77815 are hard to read. Pass --orm-dict-file with a JSON file describing the storage structure to see ORM names in the output instead.

The file is a JSON list of table descriptors. Each descriptor maps a schema-qualified SQL table name to its ORM alias and a mapping of SQL field names to their aliases:

[
    {
        "schema": "public",
        "table_name": "_Reference77815X1",
        "table_alias": "Guide.ExchangeSetup",
        "fields": {
            "_IDRRef": "Reference",
            "_Fld77818": "COMDatabaseName"
        },
        "comment": "Main"
    }
]

Descriptor fields:

FieldRequiredDescription
schemaYesSQL schema name the table belongs to. Matching is schema-qualified.
table_nameYesPhysical SQL table name.
table_aliasNoORM display name for the table. An empty value keeps the SQL name.
fieldsNoMapping of physical SQL column names to their ORM display names. An empty value keeps the SQL name.
commentNoFree-form note for the operator. Ignored by pg_anon and not shown in the output.

Matching is case-insensitive (_reference77815x1 matches _Reference77815X1) and schema-qualified, so tables with the same name in different schemas are translated independently. Filters (--table-name, --table-mask, ...) still apply to SQL names. Tables and fields missing from the file keep their SQL names.

The format is ORM-agnostic. For 1C:Enterprise databases such a file can be produced from the configuration metadata; a typical 1C infobase contains about 15,000 tables, and the generated file can be reused for any pg_anon run against that infobase until the configuration changes.

I.3.9.6. View Data #

This mode displays masked table data without creating a dump.

I.3.9.6.1. Prerequisites #
  • The anon_funcs schema with masking functions must already exist. See init mode.

  • A sensitive dictionary containing data about database fields and their masking rules must be prepared beforehand. See create-dict (scan) mode.

I.3.9.6.2. Run example #
pg_anon view-data \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=source_db \
    --prepared-sens-dict-file=sens_dict.py \
    --schema-name=public \
    --table-name=users \
    --limit=10 \
    --offset=0
I.3.9.6.3. Options #

Common pg_anon options

Option Required Description
--config No Path to the config file that can specify pg_dump and pg_restore utilities. (default: none)
--verbose No Sets the log verbosity level: info, debug, error. (default: info)
--debug No Enables debug mode (equivalent to --verbose=debug) and adds extra debug logs. (default: false)
--application-name-suffixNoAppends a suffix to the database connection name. Useful for automation. (default: none)
--internal-operation-idNoPre-generated operation ID. If not set, a random UUID is generated.
--versionNoShow the version number and exit.

Database configuration options

Option Required Description
--db-host Yes Database host.
--db-port No Database port.
--db-name Yes Database name.
--db-user Yes Database user.
--db-user-password No Database user password.
--db-passfile No Path to a file containing the password used for authentication.
--db-ssl-key-file No Path to the client SSL key file for secure connections.
--db-ssl-cert-file No Path to the client SSL certificate file.
--db-ssl-ca-file No Path to the CA certificate used to verify the server’s certificate.

View-data mode options

Option Required Description
--prepared-sens-dict-file Yes Path to Input file or file list contains sensitive dictionary, which was generated by the create-dict (scan) mode or created manually. In rules collision case, priority has rules in last file from the list.
--schema-name Yes Schema name.
--table-name Yes Table name.
--limit No Number of rows to display. (default: 100)
--offset No Row offset for pagination. (default: 0)
--json No Outputs results in JSON format instead of a table.

I.3.10. Dictionary Schemas #

I.3.10.1. Meta Dictionary #

The meta-dictionary defines the rules used by pg_anon to detect sensitive fields during the create-dict (scan) mode

This dictionary is not generated automatically — it must be created manually. It provides powerful configuration options that let you fine-tune scanning behavior.

During scanning, pg_anon analyzes all database schemas, tables, and fields.

The meta-dictionary allows you to:

  • include or exclude specific objects

  • detect sensitive fields by:

    • field names

    • data patterns (regex)

    • exact or partial constants

    • custom SQL functions

    • SQL filtering conditions

    • select which Tantor SE types should be scanned

    • specify masking functions per data type

All dictionary parameters accept a list of files. pg_anon merges them into a single meta-dictionary before scanning, so a rule defined in any file applies to the whole run.

To make it easier to navigate, each section of the meta-dictionary is described separately below, with purpose, schema, and example.

At the end, a complete combined schema is shown.

I.3.10.1.1. Scan priority #
Priority Meta-dictionary section Required Description
1 skip_rules + include_rules No Narrow the set of fields to be scanned
2 Fields from sensitive dictionary + field + fields from non-sensitive Dictionary No Match by field names. Does not inspect data inside tables
3 sens_pg_types No Match by field type. Types not included in this section are ignored
4 data_sql_condition No Narrow the dataset to be scanned for specific tables using SQL conditions
5 data_func No Match data by custom data-scanning functions
6 data_const No Match data by constant values
7 data_regex No Match data by regular expressions
8 funcs No Assign masking functions according to detected data type

Figure I.2. Scan workflow


I.3.10.1.2. Section: skip_rules #

Purpose

Defines what parts of the database should be excluded from scanning. You can skip entire schemas, specific tables, or individual fields. Useful for large schemas without sensitive data or for reducing processing time.

Schema

{
    "skip_rules": [
        {
            "schema": "<schema_name: string>",             # Skip this schema from scanning
            "schema_mask": "<schema_regex_mask: string>",  # Or skip from scanning schemas matching regex pattern
            "table": "<table_name: string>",               # Skip from scanning only this table
            "table_mask": "<table_regex_mask: string>",    # Or skip from scanning tables matching regex pattern
            "fields": [  # Skip from scanning fields of tables
                "<field_name: string>"
            ]
        }
    ]
}

Rule Combinations

  1. schema or schema_mask — required

    • You must specify one of schema or schema_mask

    • This defines where the rule applies.

  2. table or table_mask — optional

    • You may (but don’t have to) narrow the rule to specific tables.

    • If table or table_mask is specified → rule applies only to those tables.

    • If both are omitted → the rule applies to the entire schema.

  3. fields — optional

    • You may also specify particular fields to skip.

    • If fields is specified → only these fields are skipped.

    • If fields is omitted → the entire table is skipped.

    • And if no table is specified → the entire schema is skipped.

Using this section

Example meta-dictionary

{
    "skip_rules": [
        {
          "schema_mask": "^tmp.*"
        },
      {
        "schema": "ecommerce",
        "table_mask": "^client_.*"
      },
      {
        "schema": "public",
        "fields": ["currency", "id", "employee_id"]
      },
      {
        "schema": "ecommerce",
        "table": "orders",
        "fields": ["count"]
      }
    ]
}

Example Tables Structure with following dictionary matches

Schema Table Field Is skipped
public employees id Yes
public employees full_name No
public employees email No
public employees password No
public employees phone No
public employees hire_date No
public salaries employee_id Yes
public salaries monthly_salary No
public salaries currency Yes
ecommerce orders product_id No
ecommerce orders client_name Yes
ecommerce orders client_phone Yes
ecommerce orders client_delivery_address Yes
ecommerce orders count Yes
ecommerce orders created No
ecommerce orders status No
tmp_some_1 tbl_1 content Yes
tmp_some_2 tbl_2 content Yes
I.3.10.1.3. Section: include_rules #

Purpose

Restrict scanning to specific schemas/tables/fields. Useful when:

  • scanning only part of a large database

  • debugging detection rules

  • running focused scans

Schema

{
    "include_rules": [
        {
            "schema": "<schema_name: string>",             # Include only this schema
            "schema_mask": "<schema_regex_mask: string>",  # Or include schemas matching regex pattern
            "table": "<table_name: string>",               # Include only this table
            "table_mask": "<table_regex_mask: string>",    # Or include tables matching regex pattern
            "fields": [  # Include only this fields of tables for scanning
                "<field_name: string>"
            ]
        }
    ]
}

Combination rules

  1. schema or schema_mask — required

    • You must specify one of schema or schema_mask

    • This defines where the rule applies.

  2. table or table_mask — optional

    • You may (but don’t have to) narrow the rule to specific tables.

    • If table or table_mask is specified → rule applies only to those tables.

    • If both are omitted → the rule applies to the entire schema.

  3. fields — optional

    • You may also specify particular fields to skip.

    • If fields is specified → only these fields are skipped.

    • If fields is omitted → the entire table is skipped.

    • And if no table is specified → the entire schema is skipped.

Using this section

Example meta-dictionary

{
    "include_rules": [
        {
          "schema_mask": "^tmp.*"
        },
      {
        "schema": "ecommerce",
        "table_mask": "^client_.*"
      },
      {
        "schema": "public",
        "fields": ["currency", "id", "employee_id"]
      },
      {
        "schema": "ecommerce",
        "table": "orders",
        "fields": ["count"]
      }
    ]
}

Example Tables Structure with following dictionary matches

Schema Table Field Is skipped
public employees id No
public employees full_name Yes
public employees email Yes
public employees password Yes
public employees phone Yes
public employees hire_date Yes
public salaries employee_id No
public salaries monthly_salary Yes
public salaries currency No
ecommerce orders product_id Yes
ecommerce orders client_name No
ecommerce orders client_phone No
ecommerce orders client_delivery_address No
ecommerce orders count No
ecommerce orders created Yes
ecommerce orders status Yes
tmp_some_1 tbl_1 content No
tmp_some_2 tbl_2 content No
I.3.10.1.4. Section: field #

Purpose

Detect sensitive fields based solely on field name, without scanning the data inside.

Useful when already known fields contains sensitive data (e.g., email, password)

Schema

{
    "field": {
        "rules": [
            "<field_name_regex: string>",
        ],
        "constants": [
            "<field_name: string>",
        ]
    }
}
Key Meaning
rules List of regex patterns. Field names matching these patterns are always considered sensitive.
constants Exact field names to be treated as sensitive.

Using this section

Example meta-dictionary

{
    "field": {
        "rules": [
            "^client_",
            ".*phone.*"
        ],
        "constants": [
            "password",
            "email"
        ]
    }
}

Example Tables Structure with following dictionary matches

Schema Table Field Is sensitive Rule
public employees id No -
public employees full_name No -
public employees email Yes email
public employees password Yes password
public employees phone Yes .*phone.*
public employees hire_date No -
public salaries employee_id No -
public salaries monthly_salary No -
public salaries currency No -
ecommerce orders product_id No -
ecommerce orders client_name Yes ^client_
ecommerce orders client_phone Yes .*phone.*
ecommerce orders client_delivery_address Yes ^client_
ecommerce orders count No -
ecommerce orders created No -
ecommerce orders status No -
I.3.10.1.5. Section: sens_pg_types #

Purpose

Define which Tantor SE types are scanned. Field types not included in this list are not scanned.

If omitted or empty → default types are used: text, character, varchar, mvarchar, json, integer, bigint

Defaults apply only when no meta-dictionary file defines this section; otherwise the union of all listed types is used.

Schema

{
    "sens_pg_types": [
        "<field_type: string>",
    ]
}

Using this section

Example meta-dictionary

{
    "sens_pg_types": [
        "text",
        "integer",
        "bigint",
        "numeric(10,2)",
        "varchar",
        "mchar",
        "json"
    ]
}

Field Type Resolution Priorities:

  1. Exact type match (varchar(20), numeric(10,2))

  2. Base type match (varchar, numeric)

  3. Fields with another types are not scanned.

I.3.10.1.6. Section: data_sql_condition #

Purpose

Specify custom SQL WHERE conditions to sample the data instead of scanning the whole table.

Schema

{
    "data_sql_condition": [
        {
            "schema": "<schema_name: string>",             # Check only this schema
            "schema_mask": "<schema_regex_mask: string>",  # Or check schemas matching regex pattern
            "table": "<table_name: string>",               # Check only this table
            "table_mask": "<table_regex_mask: string>",    # Or check tables matching regex pattern
            "sql_condition": # Condition in raw SQL format for filtering the data to scan
                """
                <raw_SQL_WHERE_condition: string>
                """
        }
    ]
}

Rules

  1. schema or schema_mask — required

    • You must specify one of schema or schema_mask

  2. table or table_mask — optional

    • You must specify one of table or table_mask; a rule without either never matches.

    • To apply the condition to every table in the schema, use "table_mask": "*".

  3. sql_condition — required

    • Must specify SQL condition for WHERE section

    • Keyword WHERE into sql_condition is not required

Using this section

Example meta-dictionary

{
    "data_sql_condition": [
        {
            "schema": "public",
            "table": "salaries",
            "sql_condition": """
                WHERE hire_date >= '2024-01-01' and hire_date <= '2024-02-01'
            """
        }
    ]
}

Result

For data scan of table public.salaries will be used only data by January 2024.

I.3.10.1.7. Section: data_func #

Purpose

Using custom SQL functions to detect sensitive fields and apply the appropriate masking function.

Schema

{
    "data_func": {
        "<field_type: string>": [
            {
                "scan_func_per_field": "<scan_function_for_whole_field: string>",  
                "anon_func": "<masking_rule_template_for_field: string>", 
            },   
            {
                "scan_func": "<scan_function_for_field_per_row: string>",
                "anon_func": "<masking_rule_template_for_field: string>",
                "n_count": "<how_many_checks_must_be_passed: integer>",
            },
        ],
    }
}
KeyMeaning
field_typeTantor SE type (or custom type). "anyelement" applies to all types.
scan_func_per_fieldSQL function called once for the whole field. Must return Boolean.
scan_funcSQL function called for each field value. Must return Boolean.
anon_funcMasking rule for the field. May contain the %s placeholder, which is replaced with the field name; without it the rule is used as is.
n_countThe field is considered sensitive if the scan function returned True at least n times for field values. Uses only for scan_func. (default: 1)
I.3.10.1.8. Rule Combinations #
  1. scan_func or scan_func_per_field — required

    • You must specify one of scan_func or scan_func_per_field

    • This defines where the rule applies.

Note

Functions for scan_func_per_field must follow this template:

CREATE OR REPLACE FUNCTION <schema>.<function_name>(
  schema_name TEXT,
  table_name TEXT,
  field_name TEXT,
  field_type TEXT
)
RETURNS boolean AS $$
BEGIN
  <function_logic>;
END;
$$ LANGUAGE plpgsql;

Functions for scan_func must follow this template:

CREATE OR REPLACE FUNCTION <schema>.<function_name>(
  value TEXT,
  schema_name TEXT,
  table_name TEXT,
  field_name TEXT
)
RETURNS boolean AS $$
BEGIN
  <function_logic>;
END;
$$ LANGUAGE plpgsql;

Using this section

Example meta-dictionary

{
    "data_func": {
        "anyelement": [
            {
                "scan_func_per_field": "custom_funcs.fulltext_search_by_organizations",
                "anon_func": "anon_funcs.digest(\"%s\", 'salt', 'md5')",
            },
            {
                "scan_func": "custom_funcs.is_employee_email",
                "anon_func": "anon_funcs.digest(\"%s\", 'salt', 'md5')",
                "n_count": 5
            }
        ]
    }
}

Field Type Resolution Priorities:

  1. Exact type match (varchar(20), numeric(10,2))

  2. Base type match (varchar, numeric)

  3. anyelement

Example Tables Structure with following dictionary matches

Schema Table Field Is sensitive Rule
public employees id No -
public employees full_name No -
public employees email Yes custom_funcs.is_employee_email
public employees password No -
public employees phone No -
public employees hire_date No -
public salaries employee_id No -
public salaries monthly_salary No -
public salaries currency No -
ecommerce orders product_id No -
ecommerce orders client_name No -
ecommerce orders client_phone No -
ecommerce orders client_delivery_address No -
ecommerce orders count No -
ecommerce orders created No -
ecommerce orders status No -
I.3.10.1.9. Section: data_const #

Purpose

Detect sensitive fields by matching full or partial constants.

Schema

{
    "data_const": {
        "constants": [
            "<field_value_full: string>",
        ],
        "partial_constants": [
            "<field_value_partial: string>",
        ]
    }
}
Key Meaning
constants Matching full field value.
partial_constants Matching substring anywhere in the field value.

Note

Must be specified one of constants or partial_constants

Using this section

Example meta-dictionary

{
    "data_const": {
        "constants": [
            "done",
        ],
        "partial_constants": [
            "@example.com",
        ]
    }
}

Example Tables Structure with following dictionary matches

Schema Table Field Is sensitive Rule
public employees id No -
public employees full_name No -
public employees email Yes @example.com
public employees password No -
public employees phone No -
public employees hire_date No -
public salaries employee_id No -
public salaries monthly_salary No -
public salaries currency No -
ecommerce orders product_id No -
ecommerce orders client_name No -
ecommerce orders client_phone No -
ecommerce orders client_delivery_address No -
ecommerce orders count No -
ecommerce orders created No -
ecommerce orders status Yes done
I.3.10.1.10. Section: data_regex #

Purpose

Detect sensitive data by scanning field values using regular expressions.

Schema

{
    "data_regex": {
        "rules": [
            "<regex_rule: string>",
        ]
    }
}

Using this section

Example meta-dictionary

{
    "data_regex": {
        "rules": [
            """[A-Za-z0-9]+([._-][A-Za-z0-9]+)*@[A-Za-z0-9-]+(\.[A-Za-z]{2,})+""",  # email
            "^(7?\d{10})$",             # phone 7XXXXXXXXXX
        ]
    }
}

Example Tables Structure with following dictionary matches

Schema Table Field Is sensitive Rule
public employees id No -
public employees full_name No -
public employees email Yes [A-Za-z0-9]+([._-][A-Za-z0-9]+)*@[A-Za-z0-9-]+(.[A-Za-z]{2,})+
public employees password No -
public employees phone Yes ^(7?)$
public employees hire_date No -
public salaries employee_id No -
public salaries monthly_salary No -
public salaries currency No -
ecommerce orders product_id No -
ecommerce orders client_name No -
ecommerce orders client_phone Yes ^(7?)$
ecommerce orders client_delivery_address No -
ecommerce orders count No -
ecommerce orders created No -
ecommerce orders status No -
I.3.10.1.11. Section: funcs #

Purpose

Configure masking functions per Tantor SE type.

Schema

{
    "funcs": {
        "<field_type: string>": "<masking_function_for_field_type: string>", 
        "default": "<universal_masking_function_for_all_field_types: string>"
    }
}

Using this section

Example meta-dictionary

{
    "funcs": {
        "text": "anon_funcs.digest(\"%s\", 'salt_word', 'md5')",
        "numeric(10,2)": "anon_funcs.noise(\"%s\", 10)",
        "numeric": "anon_funcs.noise(\"%s\", 30)",
        "varchar(10)": "anon_funcs.random_string(10)",
        "varchar(20)": "anon_funcs.random_string(20)",
        "varchar": "anon_funcs.digest(\"%s\", 'varchar_salt_word', 'sha256')",
        "timestamp": "anon_funcs.dnoise(\"%s\",  interval '6 month')",
        "default": "anon_funcs.digest(\"%s\", 'MySecretSaltWord', 'sha256')"
    }
}

Field Type Resolution Priorities:

  1. Exact type match (varchar(20), numeric(10,2))

  2. Base type match (varchar, numeric)

  3. Function from default

  4. Built-in fallback function: anon_funcs.digest("%s", 'salt_word', 'md5')

I.3.10.1.12. General meta-dict schema #
{
    "skip_rules": [
        {
            "schema": "<schema_name: string>",             # Skip this schema from scanning
            "schema_mask": "<schema_regex_mask: string>",  # Or skip from scanning schemas matching regex pattern
            "table": "<table_name: string>",               # Skip from scanning only this table
            "table_mask": "<table_regex_mask: string>",    # Or skip from scanning tables matching regex pattern
            "fields": [  # Skip from scanning fields of tables
                "<field_name: string>"
            ]
        }
    ],
    "include_rules": [
        {
            "schema": "<schema_name: string>",             # Include only this schema
            "schema_mask": "<schema_regex_mask: string>",  # Or include schemas matching regex pattern
            "table": "<table_name: string>",               # Include only this table
            "table_mask": "<table_regex_mask: string>",    # Or include tables matching regex pattern
            "fields": [  # Include only this fields of tables for scanning
                "<field_name: string>"
            ]
        }
    ],
    "field": {
        "rules": [
            "<field_name_regex: string>",
        ],
        "constants": [
            "<field_name: string>",
        ]
    },
    "sens_pg_types": [
        "<field_type: string>",
    ],
    "data_sql_condition": [
        {
            "schema": "<schema_name: string>",             # Check only this schema
            "schema_mask": "<schema_regex_mask: string>",  # Or check schemas matching regex pattern
            "table": "<table_name: string>",               # Check only this table
            "table_mask": "<table_regex_mask: string>",    # Or check tables matching regex pattern
            "sql_condition": # Condition in raw SQL format for filtering the data to scan
                """
                <raw_SQL_WHERE_condition: string>
                """
        }
    ],
    "data_func": {  
        "<field_type: string>": [ 
            {
                "scan_func_per_field": "<scan_function_for_whole_field: string>",  
                "anon_func": "<masking_rule_template_for_field: string>", 
            },
            {
                "scan_func": "<scan_function_for_field_per_row: string>",  
                "anon_func": "<masking_rule_template_for_field: string>",
                "n_count": "<how_many_checks_must_be_passed: integer>", 
            },
        ],
    },
    "data_const": {
        "constants": [
            "<field_value_full: string>",
        ],
        "partial_constants": [
            "<field_value_partial: string>",
        ]
    },
    "data_regex": {
        "rules": [
            "<regex_rule: string>",
        ]
    },
    "funcs": {
        "<field_type: string>": "<masking_function_for_field_type: string>", 
        "default": "<universal_masking_function_for_all_field_types: string>"
    }
}

I.3.10.2. Sensitive Dictionary #

The sensitive dictionary defines explicit masking rules for fields. It is used in four operation modes, and its behavior differs slightly across them:

  1. Dump mode

    Fields listed in the dictionary are masked using the defined rules. All other fields are dumped as-is.

  2. Create-dict (scan) mode

    Fields listed in the sensitive dictionary are treated as known sensitive fields, which skips sensitivity detection for them. This speeds up scanning process.

  3. View fields mode

    Shows which masking rules would be applied to fields.

  4. View data mode

    Shows how the rules would affect sample data, without performing a dump.

This dictionary can be created manually or generated automatically using create-dict (scan) mode.

Note

If a field appears both in the sensitive dictionary and the non-sensitive dictionary, the sensitive dictionary takes priority.

I.3.10.2.1. Schema #
{    
    "dictionary": [
        {
            "schema": "<schema_name: string>",
            "table": "<table_name: string>",
            "fields": {
                "<field_name: string>": "<masking_rule_for_field: string>",
            },
            "sql_condition": # Optional. Condition in raw SQL format for filtering the data to dump. (This section ignored for create-dict (scan) mode
                """
                <raw_SQL_WHERE_condition: string>
                """
        }
    ],
    # Optional section. It is used to leave the data of tables out of the dump. The structure stays.
    "dictionary_exclude": [
        {
            "schema": "<schema_name: string>",             # Only this schema
            "schema_mask": "<schema_regex_mask: string>",  # Or schemas matching a regular expression
            "table": "<table_name: string>",               # Only this table
            "table_mask": "<table_regex_mask: string>",    # Or tables matching a regular expression
        }
    ]
}

Note

sql_condition in dictionary section is optional. It can be used for taking a part of data. Example: getting table data only by last week.

  • dictionary_exclude is optional section. If a table appears in both the “dictionary_exclude” and “dictionary” sections, then table will be dumped. It can be used for particular dump and debugging of the masking process.

  • In dictionary_exclude, you must use either schema or schema_mask → not both.

  • In dictionary_exclude, you must use either table or table_mask → not both.

  • dictionary_exclude leaves out data only, also with table_mask: "*": the tables stay in the dump, but empty. To leave out a whole schema, use --exclude-schema-name.

  • A foreign key to a table without data is restored as NOT VALID, see Checks during restore.

I.3.10.2.2. Using the Dictionary #

Example Database Structure

Schema Table Field
public employees id
public employees full_name
public employees email
public employees hire_date
public salaries employee_id
public salaries monthly_salary
public salaries currency
ecommerce orders product_id
ecommerce orders count
ecommerce orders client_name
ecommerce orders delivery_address
ecommerce orders created
ecommerce orders status
tenant_a projects title
tenant_a projects description
tenant_b projects title
tenant_b projects description
tenant_c projects title
tenant_c projects description

Example Sensitive Dictionary

{    
    "dictionary": [
        {
            "schema": "public",
            "table": "employees",
            "fields": {
                "full_name": "anon_funcs.digest(\"full_name\", 'salt_word', 'sha256')",  # hashing employees names 
                "email": "md5(\"email\") || '@abc.com'",  # hashing employee emails while preserving email format
            },
        },
        {
            "schema": "public",
            "table": "salaries",
            "fields": {
                "monthly_salary": "10000",  # just defines one value for the field for all rows
            },
        },
        {
            "schema": "ecommerce",
            "table": "orders",
            "fields": {
                "client_name": "anon_funcs.digest(\"client_name\", 'salt_word', 'sha256')",
                "delivery_address": "anon_funcs.digest(\"delivery_address\", 'salt_word', 'sha256')",
            },
            "sql_condition":  # Dumping only the orders completed within the last week
                """
                WHERE created > NOW() - '7 days'::interval
                AND status = 'done'
                """
        }
    ],
    # Leaving out the data of all tables in schemas `tenant_a`, `tenant_b`, `tenant_c`; their structure stays
    "dictionary_exclude": [
        {
            "schema_mask": "tenant_.*",
            "table_mask": "*",
        }
    ]
}

This dictionary matches the following table fields:

Schema Table Field Used in dump mode Used in create-dict (scan) mode
public employees id Dumped as is Fields scanned using meta-dictionary rules
public employees full_name Dumped with masking Excluded from sensitivity checks as a “sensitive” field
public employees email Dumped with masking Excluded from sensitivity checks as a “sensitive” field
public employees hire_date Dumped as is Fields scanned using meta-dictionary rules
public salaries employee_id Dumped as is Fields scanned using meta-dictionary rules
public salaries monthly_salary Dumped with masking Excluded from sensitivity checks as a “sensitive” field
public salaries currency Dumped as is Fields scanned using meta-dictionary rules
ecommerce orders product_id Dumped as is Fields scanned using meta-dictionary rules
ecommerce orders client_name Dumped with masking Excluded from sensitivity checks as a “sensitive” field
ecommerce orders delivery_address Dumped with masking Excluded from sensitivity checks as a “sensitive” field
ecommerce orders count Dumped as is Fields scanned using meta-dictionary rules
ecommerce orders created Dumped as is Fields scanned using meta-dictionary rules
ecommerce orders status Dumped as is Fields scanned using meta-dictionary rules

I.3.10.3. Non-Sensitive Dictionary #

The non-sensitive dictionary is used only during the create-dict (scan) mode to speed up processing. It defines which fields should be treated as non-sensitive. Fields listed here are excluded from all sensitivity checks according to meta-dictionary rules.

This dictionary can be created manually or generated automatically using create-dict (scan) mode with --output-no-sens-dict-file option.

Note

If a field appears both in the sensitive dictionary and the non-sensitive dictionary, the sensitive dictionary takes priority.

I.3.10.3.1. Schema #
{    
    "no_sens_dictionary": [
        {
            "schema": "<schema_name: string>",
            "table": "<table_name: string>",
            "fields": [
                "<field_name: string>",
            ]
        },
    ]
}
I.3.10.3.2. Using the Dictionary #

Example Tables Structure

Schema Table Field
public employees id
public employees full_name
public employees email
public employees hire_date
public salaries employee_id
public salaries monthly_salary
public salaries currency

Example Non-Sensitive Dictionary

{
    "no_sens_dictionary": [
        {
            "schema": "public",
            "table": "employees",
            "fields": [
                "id",
                "hire_date",
            ]
        },
        {
            "schema": "public",
            "table": "salaries",
            "fields": [
                "employee_id",
                "currency",
            ]
        },
    ]
}

This dictionary matches the following table fields:

Schema Table Field Used in create-dict (scan) mode
public employees id Excluded from sensitivity checks as a “no sensitive” field
public employees full_name Fields scanned using meta-dictionary rules
public employees email Fields scanned using meta-dictionary rules
public employees hire_date Excluded from sensitivity checks as a “no sensitive” field
public salaries employee_id Excluded from sensitivity checks as a “no sensitive” field
public salaries monthly_salary Fields scanned using meta-dictionary rules
public salaries currency Excluded from sensitivity checks as a “no sensitive” field

I.3.10.4. Tables dictionary #

The tables dictionary defines which tables participate in the partial dump and partial restore operations. It can act as either a whitelist (include-only) or a blacklist (exclude-only).

Use this dictionary when you need to:

  • dump or restore only specific tables

  • exclude unwanted tables from the dump or restore

I.3.10.4.1. Schema #
{
    "tables": [
        {
            "schema": "<schema_name: string>",             # Include only this schema
            "schema_mask": "<schema_regex_mask: string>",  # Or include schemas matching regex pattern
            "table": "<table_name: string>",               # Include only this table
            "table_mask": "<table_regex_mask: string>",    # Or include tables matching regex pattern
        }
    ]
}

Note

  • You must use either schema or schema_mask → not both.

  • You must use either table or table_mask → not both.

I.3.10.4.2. Using the Dictionary #

You can use the same dictionary in two different roles:

  • Whitelist — dump/restore only the matched tables

  • Blacklist — dump/restore all tables except the matched ones

Example Database Structure

Schema Table
public employees
public departments
public positions
public salaries
public users
ecommerce products
ecommerce categories
ecommerce orders
ecommerce order_items
tenant_a users
tenant_a projects
tenant_a tasks
tenant_a comments
tenant_b users
tenant_b projects
tenant_b tasks
tenant_b comments
tenant_c users
tenant_c projects
tenant_c tasks
tenant_c comments

Example Tables Dictionary

{
    "tables": [  
        {
            "schema": "public",
            "table": "employees"
        },
        {
            "schema": "ecommerce",
            "table_mask": "^orders"
        },
        {
            "schema_mask": "_a$",
            "table": "projects"
        },
        {
            "schema_mask": "*",
            "table_mask": "users"
        },
    ]
}

This dictionary matches the following tables:

Schema Table Matched by rule
ecommerce orders schema="ecommerce", table_mask="^orders"
ecommerce order_items schema="ecommerce", table_mask="^orders"
tenant_a projects schema_mask="_a$", table="projects"
tenant_a users schema_mask="*", table_mask="users"
tenant_b users schema_mask="*", table_mask="users"
tenant_c users schema_mask="*", table_mask="users"
public users schema_mask="*", table_mask="users"
public employees schema="public", table="employees"

I.3.11. Debug stages for the masking process #

The debug stages allow you to test and troubleshoot the masking workflow without performing a full dump or restore, saving significant time and resources.

Each stage emulates a specific part of the masking pipeline:

  • Stage 1 — Validate Dict

    Validates the sensitive dictionary and checks SQL logic without exporting any data.

  • Stage 2 — Validate Data

    Performs masking checks on real data with a limited sample (LIMIT 100) using a prepared database schema.

  • Stage 3 — Validate Full

    Executes the full masking logic with data sampling (LIMIT 100), but without requiring a prepared database.

These stages help you quickly debug rules, masking functions, SQL conditions, and dictionary configuration before running a full dump/restore.

I.3.11.1. Stage 1: Validate dict #

This stage validate dictionary, show the tables and run SQL queries without data export into the disk or database. So if program works without errors => the stage is passed.

Figure I.3. dbg-stage-1.png

dbg-stage-1.png

pg_anon dump \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=test_source_db \
    --output-dir=test_dbg_stages \
    --prepared-sens-dict-file=test_dbg_stages.py \
    --clear-output-dir \
    --debug \
    --dbg-stage-1-validate-dict

I.3.11.2. Stage 2: Validate data #

Validate data, show the tables and run SQL queries with data export and limit 100 in prepared database. This stage requires a target database that already holds the source structure, and only its pre-data part: tables without indexes, constraints and triggers. pg_anon loads data with session_replication_role = 'replica', so a fully built target would accept the truncated sample without error and end up holding rows its own foreign keys do not allow.

One way to prepare such a database quickly is a structure dump with --dbg-stage-3-validate-full: the flag drops the post-data section. Stage 3 below uses the same flag on its own.

One-time structure dump:

pg_anon sync-struct-dump \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=test_source_db \
    --output-dir=test_stage_2 \
    --prepared-sens-dict-file=test_dbg_stages.py \
    --clear-output-dir \
    --debug \
    --dbg-stage-3-validate-full

And then as many times as you want structure restore:

su - postgres -c "psql -U postgres -d postgres -c \"DROP DATABASE IF EXISTS test_target_db_7\""
su - postgres -c "psql -U postgres -d postgres -c \"CREATE DATABASE test_target_db_7\""
pg_anon sync-struct-restore \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=test_target_db_7 \
    --input-dir=test_stage_2 \
    --debug
  • Validate data stage in dump:

Figure I.4. dbg-stage-2.png

dbg-stage-2.png

pg_anon dump \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=test_source_db \
    --output-dir=test_dbg_stages \
    --prepared-sens-dict-file=test_dbg_stages.py \
    --clear-output-dir \
    --debug \
    --dbg-stage-2-validate-data
  • Validate data stage in data-restore:

pg_anon sync-data-restore \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=test_target_db_7 \
    --input-dir=test_dbg_stages \
    --debug
# And for example view all data in every table:
su - postgres -c "psql -U postgres -d test_target_db_7 -c \"SELECT * FROM <schema>.<table>\""

I.3.11.3. Stage 3: Validate full #

Figure I.5. dbg-stage-3.png

dbg-stage-3.png

Makes all logic with “limit 100” in SQL queries. In this stage you don’t need prepared database, just run:

su - postgres -c "psql -U postgres -d postgres -c \"DROP DATABASE IF EXISTS test_target_db_8\""
su - postgres -c "psql -U postgres -d postgres -c \"CREATE DATABASE test_target_db_8\""
  • Validate full stage in dump:

pg_anon dump \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=test_source_db \
    --output-dir=test_dbg_stages \
    --prepared-sens-dict-file=test_dbg_stages.py \
    --clear-output-dir \
    --debug \
    --dbg-stage-3-validate-full
  • Validate full stage in restore:

pg_anon restore \
    --db-host=127.0.0.1 \
    --db-user=postgres \
    --db-user-password=postgres \
    --db-name=test_target_db_8 \
    --input-dir=test_dbg_stages \
    --debug
# And for example view all data in every table:
su - postgres -c "psql -U postgres -d test_target_db_8 -c \"SELECT * FROM <schema>.<table>\""

I.3.12. Security #

pg_anon masks the table data you select, but a dump also carries schema objects that can leak secrets or personal data by themselves — foreign-server credentials, function bodies, planner statistics. This page explains what pg_anon handles by default, what it only warns about, and how to clean a dump yourself. For the limits of masking itself, see Security & limitations.

I.3.12.1. What else can leak #

Besides table data, a dump carries schema objects. Some can hold credentials or personal data that masking does not change. pg_anon removes what it safely can without breaking the restore, warns about the rest, and leaves the final call to you.

ObjectRiskpg_anon defaultWhat you can do
FDW user mapping (USER MAPPING)Remote-server user/passwordDump blocked when credentials are visible; mappings stripped on restore--allow-fdw-credentials / --keep-fdw-user-mappings
FDW server (SERVER OPTIONS)Internal host/port addressesWarned at dump time; kept in the dumpStrip manually — see Maximum cleanup
SubscriptionsPublisher password in CONNECTION stringExcluded via pg_dump --no-subscriptions (pg_dump ≥ 10)—
Planner statistics (PG 18+)Real (unmasked) column valuesExcluded via pg_dump --no-statistics (pg_dump ≥ 18)—
Function / procedure / trigger bodiesHard-coded secrets or personal dataWarned at dump time; restored as-isReview bodies; exclude their schema if needed

pg_anon does not inspect other objects — security labels, GUC settings (ALTER ROLE/DATABASE ... SET), comments, or extension table data. If any of them may hold secrets, review them yourself: exclude suspicious schemas with --exclude-schema-name, and restore the dump structure onto a throwaway instance to check what it contains before you share it.

Note

An excluded schema can still appear on the target

If an extension lives in that schema, pg_anon creates the schema on the target to install the extension. It stays empty, so nothing leaks — see Extensions.

I.3.13. Foreign Data Wrappers (FDW) #

FDW CREATE USER MAPPING statements must carry OPTIONS (for oracle_fdw, a user and usually a password). What ends up in the dump depends on whether the dumping role can see those options:

Dumping roleIn the dumpRestoreSide effect
superuser / mapping ownerUSER MAPPING ... OPTIONS (user '…', password '…')worksremote-server credentials leak into the dump
unprivilegedUSER MAPPING ... ; (no OPTIONS)fails with missing required option "user"no credentials, but the restore breaks

This is pg_dump behavior, not a pg_anon bug — pg_anon inherits it. Its defaults cover both cases:

At dump time — block credential leaks. If any FDW user mapping exposes OPTIONS visible to the dumping role, the dump is refused (error CREDENTIALS_LEAK): pg_dump would otherwise write the remote credentials into the archive. Two ways forward:

  • Dump with a less-privileged role that owns the foreign server (so the dump stays self-contained, keeping CREATE SERVER) but cannot read the mapping OPTIONS. The minimal grants for such a role: USAGE on the dumped schemas, SELECT on their tables and sequences, and USAGE + EXECUTE on the anon_funcs schema after init.

  • Or pass --allow-fdw-credentials to include them intentionally (an informed decision; the dump logs a warning that credentials are inside).

Independently, whenever a foreign server exists pg_anon warns that its SERVER OPTIONS (remote host/port of your infrastructure) go into the dump. Those are not stripped automatically — removing a SERVER would break the FOREIGN TABLEs that depend on it. Strip them manually if they matter (Maximum cleanup).

At restore time — strip mappings. By default pg_anon removes USER MAPPING entries from the restore. This fixes the unprivileged-dump failure automatically, and it also means that even a dump taken with --allow-fdw-credentials does not recreate the credentials in the target. Pass --keep-fdw-user-mappings to restore them (a mapping without OPTIONS still fails on wrappers that require them — that is the original pg_dump behavior).

Foreign servers (SERVER) and foreign tables (FOREIGN TABLE) are always kept, so querying a foreign table in the restored copy needs its mapping recreated by hand (or a restore with --keep-fdw-user-mappings).

I.3.13.1. Maximum cleanup (manual) #

To fully remove infrastructure objects and keep the dump reliable, do it by hand:

  1. pg_anon dump — a full dump.

  2. pg_anon sync-struct-restore — restore only the structure into a throwaway database.

  3. Clean the throwaway database: drop FDW objects, functions, triggers, extensions, GUC settings — anything that must not be shared.

  4. pg_anon sync-struct-dump — dump the cleaned structure.

  5. Replace pre_data.backup / post_data.backup in the original dump with the cleaned ones.

This cannot be automated in general (the objects are not known in advance), but it can be scripted in CI/CD for a specific database.

I.3.14. FAQ #

I.3.14.1. Where can I find operation logs and launch parameters? #

All run data is stored in the /pg_anon_runs/ directory (relative to the working directory or $PG_ANON_HOME). Inside, the structure is: <year>/<month>/<day>/<operation_id>.

Each operation folder contains:

  • a logs directory with all log files

  • a run_options.json file with all parameters used to run pg_anon

If the --save-dicts option was used, the folders input and output will also appear. They contain all input and output dictionaries for that run.

I.3.14.2. Can I restore a pg_anon dump using pg_dump? #

No. The pg_anon dump format is not compatible with pg_dump due to the specifics of masking.

For the same reason, a regular backup created with pg_dump cannot be restored using pg_anon.

I.3.14.3. Does pg_anon modify the structure or data of the source database during scan, dump, view-data, or view-fields? #

pg_anon does not modify either the structure or the data of the source database.

The anon_funcs schema is created by the separate init mode; the modes listed above only read from the source database.

I.3.14.4. Can I use custom functions for scanning? #

Yes. The meta-dictionary has a data_func section. In this section, you can use any custom SQL function for sensitivity validation.

This allows you to implement checks using full-text search or any other SQL capabilities.

Such functions must follow this template:

CREATE OR REPLACE FUNCTION <schema>.<function_name>(
  value TEXT,
  schema_name TEXT,
  table_name TEXT,
  field_name TEXT
)
RETURNS boolean AS $$
BEGIN
  <function_logic>;
END;
$$ LANGUAGE plpgsql;

I.3.14.5. Can I use custom functions for masking? #

Yes. You can use any functions and values available in the source database.

You must ensure that masked values match the field format. For example, if the field type is varchar(15), you must manually ensure the generated value does not exceed 15 characters.

If the format is violated, the dump may be created successfully, but restoring it may fail.

Also for this cases can be used data_func section with scan_func for field length comparison and specific anon_function for specific length.

For example, scan function bellow getting only fields with length less than 20 symbols and containing emails:

CREATE OR REPLACE FUNCTION my_scan_funcs.is_email_field_with_len_20_chars(
  value TEXT,
  schema_name TEXT,
  table_name TEXT,
  field_name TEXT
)
RETURNS boolean AS $$
DECLARE
    max_len integer;
    is_email boolean;
BEGIN
    SELECT c.character_maximum_length
    INTO max_len
    FROM information_schema.columns c
    WHERE c.table_schema = $2
      AND c.table_name = $3
      AND c.column_name = $4;

    -- field length must be 20 characters
    if max_len != 20 then
        return false;
    end if;  	
   
   -- value must be not null for comparison
    if $1 is null then
    	return false;
    end if;  	
   
    -- check email format by regexp
    return $1 ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$';
END;
$$ LANGUAGE plpgsql;

The meta-dict rule below can be used to detect email fields with a length of 20 characters and mask them while preserving both format and length.

{
    "data_func": {
        "varchar": [
            {
                "scan_func": "my_scan_funcs.is_email_field_with_len_20_chars",
                "anon_func": "lower(anon_funcs.random_string(9)) || '@secret.com'",
                "n_count": 10
            }
        ]
    }
}

I.3.14.6. Is the scanning stage required? #

No. You can create all required dictionaries manually or reuse previously generated dictionaries.

I.3.14.7. Why load sensitive and non-sensitive dictionaries during scanning? #

They are used only to speed up scanning.

These dictionaries act as a cache, allowing pg_anon to immediately know which fields are sensitive and which are not.

This way, repeated scans of the same database will run very quickly.

If new fields appear that are not present in the dictionaries, pg_anon will evaluate them using the rules from the meta-dictionary.

I.3.14.8. When should I use --config with a configuration file? #

If you plan to use pg_anon with different Tantor SE major versions, you should define a config file.

It is much easier to configure this once rather than repeatedly passing paths to pg_dump and pg_restore.

If you always use a single Tantor SE version, the system pg_dump and pg_restore will be used, and a config file is unnecessary.

I.3.14.9. Can I split one large dictionary into multiple smaller ones? #

Yes. All dictionary-related parameters accept lists of files.

At startup, pg_anon merges them into a single dictionary internally.

This makes it easy to separate different groups of rules into different files and combine them as needed. This is especially helpful for the meta-dictionary, which contains many optional sections.

I.3.14.10. Restore error: “Database is not empty” #

Restore mode checks that the target database is empty.

This is done to prevent accidental data loss in the target database.

If needed, use the --drop-db or --clean-db options during restore.

I.3.14.11. Restore error: “Database is being accessed by other users” #

When using the --drop-db option, the target database will be recreated using DROP DATABASE and CREATE DATABASE.

If there are active connections, the DROP DATABASE command cannot be executed.

You must terminate all active sessions and run the restore operation again.

I.3.14.12. Difference between options --drop-db and --clean-db for restore mode #

  • --drop-db — recreate target database using commands DROP DATABASE and CREATE DATABASE. After that running restore process on empty db.

  • --clean-db — performs a restore similar to pg_restore –clean –if-exists. It creates missing tables from the backup in the target database. It also preserves extra tables that exist in the target DB and are not contained in the restoring backup. This option does not require an empty target database.

I.3.14.13. Determining the Optimal Connection Count #

pg_anon runs as a single process and opens one pool of --db-connections connections, plus one control connection that stays open for the whole operation.

To choose a value, identify these system parameters:

  • max_connections - maximum connections allowed by your Tantor SE database

  • reserved connections - superuser_reserved_connections, plus reserved_connections on Tantor SE 16 and above

  • connections already used by other applications

Important considerations:

  • Exceeding max_connections may cause pg_anon failures and affect other database applications

  • Ensure sufficient connection headroom for other services

I.3.14.13.2. Example Calculation: #
  • max_connections: 100

  • reserved connections: 5

  • used by other applications: 20

  • --db-connections: 100 - 5 - 20 - 2 = 73

pg_anon performs this check itself before starting and fails early with a clear message if the database cannot provide the requested number of connections. To skip it, use --disable-checks.

I.3.14.14. Restore error: missing required option "user" #

An FDW USER MAPPING was dumped without its OPTIONS (the dumping role could not see them), and the wrapper requires them. Current pg_anon strips USER MAPPING entries on restore by default, so upgrading resolves this; if you restored with --keep-fdw-user-mappings, drop that flag. See Security → Foreign Data Wrappers.

I.3.15. SQL Functions Library #

All functions are contained in the init.sql file. After run pg_anon in init mode, they will reside in the anon_funcs schema in the source database. If you want to write a new function, simply create it in the anon_funcs schema in your source database.

List of some functions available for use in dictionaries:

I.3.15.1. Functions list #

I.3.15.1.1. noise #

Add random noise to a numeric value by scaling it with a random factor within ±ratio.

Signature:

anon_funcs.noise(noise_value ANYELEMENT, ratio DOUBLE PRECISION) RETURNS ANYELEMENT
ArgumentTypeDescription
noise_valueANYELEMENTNumeric value to add noise to
ratioDOUBLE PRECISIONMaximum relative deviation (e.g. 0.2 = ±20%)

Returns: ANYELEMENT — the same numeric type as the input value. The magnitude stays close to the original (within the given ratio); precision is that of the input type.

Example:

SELECT anon_funcs.noise(100, 1.2);
>> 123
I.3.15.1.2. dnoise #

Add random noise to a date or timestamp by shifting it by a random interval within ±noise_range.

Signature:

anon_funcs.dnoise(noise_value ANYELEMENT, noise_range INTERVAL) RETURNS ANYELEMENT
ArgumentTypeDescription
noise_valueANYELEMENTDate/time value to add noise to
noise_rangeINTERVALMaximum shift in either direction

Returns: ANYELEMENT — the same date/time type as the input value; precision is unchanged.

Example:

SELECT anon_funcs.dnoise('2020-02-02 10:10:10'::timestamp, interval '1 month');
>> 2020-03-02 10:10:10
I.3.15.1.3. digest #

Hash a string value with a specified hash algorithm (seed + salt).

Signature:

anon_funcs.digest(seed TEXT, salt TEXT, algorithm TEXT) RETURNS TEXT
ArgumentTypeDescription
seedTEXTInput string to hash
saltTEXTSalt appended to the seed before hashing
algorithmTEXTHash algorithm: md5, sha1, sha224, sha256, sha384, sha512

Returns: TEXT — a hex-encoded hash. Length depends on the algorithm: md5 → 32, sha1 → 40, sha224 → 56, sha256 → 64, sha384 → 96, sha512 → 128 hex characters.

Example:

SELECT anon_funcs.digest('text', 'salt', 'sha256');
>> '3353e....'
I.3.15.1.4. partial #

Keep the first prefix characters and the last suffix characters of the string, inserting the padding constant in between.

Signature:

anon_funcs.partial(ov TEXT, prefix INT, padding TEXT, suffix INT) RETURNS TEXT
ArgumentTypeDescription
ovTEXTOriginal value to mask
prefixINTNumber of leading characters to keep
paddingTEXTConstant inserted between the kept prefix and suffix
suffixINTNumber of trailing characters to keep

Returns: TEXT. Length = prefix + length(padding) + suffix characters.

Example:

SELECT anon_funcs.partial('123456789', 2, '***', 3);
>> 12***789
I.3.15.1.5. partial_email #

Mask an email address.

Signature:

anon_funcs.partial_email(ov TEXT) RETURNS TEXT
ArgumentTypeDescription
ovTEXTOriginal email address to mask

Returns: TEXT — a masked email of variable length: first 2 characters of the local part + ****** + @ + first characters of the domain + ****** + original top-level domain (e.g. .com).

Example:

SELECT anon_funcs.partial_email('example@gmail.com');
>> ex******@gm******.com
I.3.15.1.6. random_string #

Generate a random string of the specified length using characters A–Z and 0–9.

Signature:

anon_funcs.random_string(l INTEGER) RETURNS TEXT
ArgumentTypeDescription
lINTEGERLength of the generated string

Returns: TEXT of exactly l characters.

Example:

SELECT anon_funcs.random_string(7);
>> H3ZVL5P
I.3.15.1.7. random_zip #

Generate a random ZIP code.

Signature:

anon_funcs.random_zip() RETURNS TEXT

Returns: TEXT — exactly 6 digits.

Example:

SELECT anon_funcs.random_zip();
>> 851467
I.3.15.1.8. random_inn #

Generate a random numeric identifier (e.g. an INN-like value).

Signature:

anon_funcs.random_inn() RETURNS TEXT

Returns: TEXT — exactly 8 digits.

Example:

SELECT anon_funcs.random_inn();
>> 50734812
I.3.15.1.9. random_date_between #

Generate a random date and time within the [date_start, date_end] range.

Signature:

anon_funcs.random_date_between(date_start TIMESTAMPTZ, date_end TIMESTAMPTZ) RETURNS TIMESTAMPTZ
ArgumentTypeDescription
date_startTIMESTAMPTZLower bound of the range (inclusive)
date_endTIMESTAMPTZUpper bound of the range (inclusive)

Returns: timestamp with time zone within the given range.

Example:

SELECT anon_funcs.random_date_between(
   '2020-02-02 10:10:10'::timestamp,
   '2022-02-05 10:10:10'::timestamp
);
>> 2021-11-08 06:47:48.057
I.3.15.1.10. random_date #

Generate a random date and time between 1900-01-01 and the current moment.

Signature:

anon_funcs.random_date() RETURNS TIMESTAMPTZ

Returns: timestamp with time zone.

Example:

SELECT anon_funcs.random_date();
>> 1911-04-18 21:54:13.139
I.3.15.1.11. random_int_between #

Generate a random integer within the specified range.

Signature:

anon_funcs.random_int_between(int_start INTEGER, int_stop INTEGER) RETURNS INTEGER
ArgumentTypeDescription
int_startINTEGERLower bound (inclusive)
int_stopINTEGERUpper bound (exclusive)

Returns: INTEGER in the range [int_start, int_stop).

Example:

SELECT anon_funcs.random_int_between(100, 200);
>> 159
I.3.15.1.12. random_bigint_between #

Generate a random bigint within the specified range.

Signature:

anon_funcs.random_bigint_between(int_start BIGINT, int_stop BIGINT) RETURNS BIGINT
ArgumentTypeDescription
int_startBIGINTLower bound (inclusive)
int_stopBIGINTUpper bound (exclusive)

Returns: BIGINT in the range [int_start, int_stop).

Example:

SELECT anon_funcs.random_bigint_between(6000000000, 7000000000);
>> 6268278565
I.3.15.1.13. random_phone #

Generate a random phone number with the given prefix (defaults to 0).

Signature:

anon_funcs.random_phone(phone_prefix TEXT DEFAULT '0') RETURNS TEXT
ArgumentTypeDescription
phone_prefixTEXTPrefix prepended to a random 9-digit number (default '0')

Returns: TEXT — phone_prefix followed by a random 9-digit number. Length = length(phone_prefix) + 9.

Example:

SELECT anon_funcs.random_phone('+7');
>> +7297479867
I.3.15.1.14. random_hash #

Generate a hash of seed with the specified algorithm, using a random 6-character salt (so the result differs between calls).

Signature:

anon_funcs.random_hash(seed TEXT, algorithm TEXT) RETURNS TEXT
ArgumentTypeDescription
seedTEXTInput string to hash
algorithmTEXTHash algorithm: md5, sha1, sha224, sha256, sha384, sha512

Returns: TEXT — a hex-encoded hash. Length depends on the algorithm (same as digest): md5 → 32, sha1 → 40, sha224 → 56, sha256 → 64, sha384 → 96, sha512 → 128 hex characters.

Example:

SELECT anon_funcs.random_hash('seed', 'sha512');
>> b972f895ebea9cf2f65e19abc151b8031926c4a332471dc5c40fab608950870d6dbddcd18c7e467563f9b527e63d4d13870e4961c0ff2a62f021827654ae51fd
I.3.15.1.15. random_in #

Select a random element from an array.

Signature:

anon_funcs.random_in(a ANYARRAY) RETURNS ANYELEMENT
ArgumentTypeDescription
aANYARRAYArray to pick a random element from

Returns: ANYELEMENT — one element of the input array; type and length match the array element.

Example:

SELECT anon_funcs.random_in(array['a', 'b', 'c']);
>> a
I.3.15.1.16. hex_to_int #

Convert a hexadecimal value to decimal.

Signature:

anon_funcs.hex_to_int(hexval TEXT) RETURNS INT
ArgumentTypeDescription
hexvalTEXTHexadecimal string to convert

Returns: INT — the decimal value (must fit into a 4-byte INT).

Example:

SELECT anon_funcs.hex_to_int('8AB');
>> 2219

I.3.15.2. pgcrypto #

In addition to the existing functions in the anon_funcs schema, functions from the pgcrypto extension can also be used.

CREATE EXTENSION IF NOT EXISTS pgcrypto;

Example of using encryption with base64 encoding to store the encrypted value in a text field:

SELECT encode((SELECT encrypt('data', 'password', 'bf')), 'base64');
>> cSMq9gb1vOw=

SELECT decrypt(
(
SELECT decode('cSMq9gb1vOw=', 'base64')
), 'password', 'bf');
>> data

I.3.15.3. How to add your own functions #

Also, adding new masking functions can be performed by adding init.sql to the file and then run pg_anon in init mode.

I.3.16. API #

I.3.16.1. Operation Endpoints #

I.3.16.1.1. Check DB connection #

POST /api/stateless/check_db_connection

Description

Checks whether pg_anon can connect to the specified database.

If the connection is successful, the endpoint returns status code 200.

Check DB connection request body schema

Field Type Required Description
host string Yes Database host.
port integer Yes Database port.
db_name string Yes Database name.
user_login string Yes Database username.
user_password string Yes Database user password.

Example

curl -X POST http://127.0.0.1:8000/api/stateless/check_db_connection \
-H "Content-Type: application/json" \
-d '{
  "host": "localhost",
  "port": "5432",
  "db_name":  "source_db",
  "user_login": "postgres",
  "user_password":  "postgres"
}'

Responses

Status Code Description Component
200 Database is reachable -
400 Bad Request ErrorResponse
500 Internal Server Error ErrorResponse
422 Validation Error HTTPValidationError
I.3.16.1.2. Run create-dict (scan) operation #

POST /api/stateless/scan

Description

Runs pg_anon in create-dict (scan) mode in the background.

Operation lifecycle:

  1. The client calls this endpoint.

  2. The API returns one of the following status codes:

    • 201 — the scan operation has been successfully started.

    • 400 or 422 — the request is invalid; the operation is not started.

  3. The service sends a webhook request with status in_progress to the webhook_status_url. The payload format is described in the scan webhook request schema

  4. The operation executes in the background.

  5. If an error occurs during processing, the service sends a webhook request with status error.

  6. If the operation completes successfully, the service sends a webhook request with status success.

Scan request body schema

Field Type Required Description
operation_id string Yes External operation ID. Accepts any string. Returned unchanged in webhook requests.
db_connection_params db connection params Yes Source database connection credentials.
webhook_status_url string Yes Callback URL that receives POST requests in the format described in the scan webhook request schema.
webhook_metadata Any No Arbitrary metadata payload. Sent unchanged in webhook requests.
webhook_extra_headers JSON No Additional HTTP headers added to webhook requests. Useful for integration, e.g., to include an Authorization header.
webhook_verify_ssl boolean No Enables or disables SSL certificate verification for webhook requests.
web_debugbooleanNoEnables writing webhook logs to the operation's log file in the pg_anon_runs/ directory. Default: false.
save_dictsbooleanNoSaves all input and output dictionaries into the pg_anon_runs/ directory. Useful for debugging or integration. Default: false.
type string Yes Defines the scan mode: full or partial.
depth integer No Maximum number of table rows used for partial scan. Applies only when type = partial. Default: 10000.
meta_dict_contents array of dictionary content Yes Contents of the meta dictionary, defining rules for scanning fields.
sens_dict_contents array of dictionary content No Contents of the sensitive dictionary. Used to improve scan performance.
no_sens_dict_contents array of dictionary content No Contents of the non-sensitive dictionary. Used to improve scan performance.
need_no_sens_dict boolean No If true, generates a non-sensitive dictionary and returns it in the no_sens_dict_contents field of the webhook payload.
conn_countintegerNoNumber of concurrent database connections. Default: 4.
log_levelstringNoLog verbosity of the pg_anon run: info, debug or error. Default: info.
proc_conn_countintegerNoDeprecated, use conn_count. Still accepted; ignored when conn_count is also sent.
proc_countintegerNoDeprecated. Still accepted, but has no effect.

Example

curl -X POST http://127.0.0.1:8000/api/stateless/scan \
-H "Content-Type: application/json" \
-d '{
  "operation_id": "my-uniq-scan-id-0001",
  "db_connection_params": {
     "host": "localhost",
     "port": "5432",
     "db_name":  "source_db",
     "user_login": "postgres",
     "user_password":  "postgres"
  },
  "webhook_status_url": "https://my-service/pg-anon-result-processor",
  "webhook_metadata": {"extra_field_1": "extra_data", "extra_field_2": {"fld1": [1,2,3], "fld2": 123}},
  "webhook_extra_headers": {"Authorization": "Api-key my_super_secret_api_key", "X-my-service-extra-header": "header value"},
  "webhook_verify_ssl": true,
  "save_dicts": true,
  "type": "partial",
  "depth": 10000,
  "meta_dict_contents": [{
    "name": "my simple meta dict with email scan rule",
    "content": "{\"data_regex\": {\"rules\": [\".*@.*\"]}, \"funcs\": {\"text\": \"md5(%s)\"}}"
  }],
  "sens_dict_contents": [{
    "name": "sens dict for email masking",
    "content": "{\"dictionary\": [{\"schema\": \"public\", \"table\": \"users\", \"fields\": {\"email\": \"md5(email)\"}}, {\"schema\": \"public\", \"table\": \"clients\", \"fields\": {\"email\": \"md5(email)\"}}]}"
  }],
  "no_sens_dict_contents": [{
    "name": "non-sens dict example",
    "content": "{\"no_sens_dictionary\": [{\"schema\": \"public\", \"table\": \"users\", \"fields\": [\"id\", \"created\"]}, {\"schema\": \"public\", \"table\": \"clients\", \"fields\": [\"id\", \"registered\"]}]}"
  }],
  "need_no_sens_dict": true,
  "proc_count": 4
}'

Scan webhook request schema

Field Type Required Description
operation_id string Yes External operation ID. Copied from the operation_id of the original scan request.
internal_operation_id string No Internal pg_anon operation ID generated automatically. Present for all statuses. Can be used to correlate the webhook event with operation data and logs stored in the pg_anon_runs/ directory. Also used in the Operation endpoints.
status_id integer Yes Numeric status code. Possible values: 2 — success, 3 — error, 4 — in_progress.
status string Yes Human-readable status. Possible values: success, error, in_progress.
webhook_metadata Any No Metadata payload passed “as is”. Copied from the webhook_metadata field of the scan request.
started string No Operation start timestamp in ISO8601 format (UTC+0). Present only for statuses success or error.
ended string No Operation end timestamp in ISO8601 format (UTC+0). Present only for statuses success or error.
error string No Error message. Present only when status = error.
error_codestringNoMachine-readable error code for i18n mapping. Present only when status = error.
run_options JSON No Snapshot of the operation’s runtime options. Useful for analysis, debugging, and rerunning the operation. Present only when status = success or error.
sens_dict_content dictionary content No Resulting Sensitive dictionary. Returned only when the scan completes successfully. Used for dump operations or repeated scans.
no_sens_dict_content dictionary content No Resulting Non-Sensitive dictionary. Present only when the scan completes successfully and the original request specified need_no_sens_dict = true.

Responses

Status Code Description Component
201 Operation successfully started -
400 Bad Request ErrorResponse
500 Internal Server Error ErrorResponse
422 Validation Error HTTPValidationError
I.3.16.1.3. Display database fields with masking rules #

POST /api/stateless/view-fields

Description

Runs pg_anon in view-fields mode and returns the result in the response.

The anon_funcs schema must already exist in the source database — see init mode. Without it the endpoint answers 400 with the error code SCHEMA_NOT_INITIALIZED.

View-fields request body schema

Field Type Required Description
db_connection_params db connection params Yes Source database credentials.
sens_dict_contents array of dictionary content Yes Sensitive dictionary content that defines rules for sensitive fields.
schema_name string No Filter by schema name.
schema_mask string No Filter by schema name using a regular expression.
table_name string No Filter by table name.
table_mask string No Filter by table name using a regular expression.
view_only_sensitive_fields boolean No Displays only sensitive fields (default: all fields).
fields_limit_count integer No Maximum number of fields to include for output (default: no limit).
orm_dict_contentstringNoJSON content of the ORM structure file. When set, table and field names in the output are replaced with their ORM names.

Example

curl -X POST http://127.0.0.1:8000/api/stateless/view-fields \
-H "Content-Type: application/json" \
-d '{
  "db_connection_params": {
     "host": "localhost",
     "port": "5432",
     "db_name":  "source_db",
     "user_login": "postgres",
     "user_password":  "postgres"
  },
  "sens_dict_contents": [{
    "name": "sens dict for email masking",
    "content": "{\"dictionary\": [{\"schema\": \"public\", \"table\": \"users\", \"fields\": {\"email\": \"md5(email)\"}}, {\"schema\": \"public\", \"table\": \"clients\", \"fields\": {\"email\": \"md5(email)\"}}]}"
  }],
  "schema_name": "public",
  "table_mask": "^client",
  "view_only_sensitive_fields": true,
  "fields_limit_count": 1000
}'

Responses

Status Code Description Component
200 Successful Response ViewFieldsResponse
400 Bad Request ErrorResponse
500 Internal Server Error ErrorResponse
422 Validation Error HTTPValidationError
I.3.16.1.4. Display table with masked data #

POST /api/stateless/view-data

Description

Displays table data in original and masked variants for comparison. Runs pg_anon in view-data mode and returns the result in the response.

The anon_funcs schema must already exist in the source database — see init mode. Without it the endpoint answers 400 with the error code SCHEMA_NOT_INITIALIZED.

View-data request body schema

Field Type Required Description
db_connection_params db connection params Yes Source database credentials.
sens_dict_contents array of dictionary content Yes Sensitive dictionary content defining rules for sensitive fields.
schema_name string Yes Schema name.
table_name string Yes Table name.
limit integer No Number of rows to display (default: 10).
offset integer No Row offset for pagination (default: 0).

Example

curl -X POST http://127.0.0.1:8000/api/stateless/view-data \
-H "Content-Type: application/json" \
-d '{
  "db_connection_params": {
     "host": "localhost",
     "port": "5432",
     "db_name":  "source_db",
     "user_login": "postgres",
     "user_password":  "postgres"
  },
  "sens_dict_contents": [{
    "name": "sens dict for email masking",
    "content": "{\"dictionary\": [{\"schema\": \"public\", \"table\": \"users\", \"fields\": {\"email\": \"md5(email)\"}}, {\"schema\": \"public\", \"table\": \"clients\", \"fields\": {\"email\": \"md5(email)\"}}]}"
  }],
  "schema_name": "public",
  "table_name": "clients",
  "limit": 10,
  "offset": 20
}'

Responses

Status Code Description Component
200 Successful Response ViewDataResponse
400 Bad Request ErrorResponse
500 Internal Server Error ErrorResponse
422 Validation Error HTTPValidationError
I.3.16.1.5. Display database schemas only for preview #
POST /api/stateless/preview

Description

Returns a list of database schemas. Can be filtered by schema name substring.

Preview schemas request body schema

FieldTypeRequiredDescription
db_connection_paramsdb connection paramsYesSource database credentials.
schema_filterstringNoFilter schemas by name substring (case-sensitive).

Example

curl -X POST http://127.0.0.1:8000/api/stateless/preview \
-H "Content-Type: application/json" \
-d '{
  "db_connection_params": {
     "host": "localhost",
     "port": "5432",
     "db_name":  "source_db",
     "user_login": "postgres",
     "user_password":  "postgres"
  },
  "schema_filter": "public"
}'

Responses

Status CodeDescriptionComponent
200Successful ResponsePreviewSchemasResponse
400Bad RequestErrorResponse
500Internal Server ErrorErrorResponse
422Validation ErrorHTTPValidationError
I.3.16.1.6. Display database tables with fields for preview #
POST /api/stateless/preview/{schema}

Description

Returns a list of tables in the specified schema with their fields and sensitivity/exclusion status based on the provided sensitive dictionary.

Preview schema tables request body schema

FieldTypeRequiredDescription
db_connection_paramsdb connection paramsYesSource database credentials.
sens_dict_contentsarray of dictionary contentYesSensitive dictionary content that defines rules for sensitive fields.
limitintegerNoMaximum number of tables to return (default: 20).
offsetintegerNoNumber of tables to skip for pagination (default: 0).
table_filterstringNoFilter tables by name substring (case-sensitive).
view_only_sensitive_tablesbooleanNoIf true, returns only tables that match the sensitive dictionary (default: false).

Path parameters

FieldTypeRequiredDescription
schemastringYesSchema name

Example

curl -X POST http://127.0.0.1:8000/api/stateless/preview/public \
-H "Content-Type: application/json" \
-d '{
  "db_connection_params": {
     "host": "localhost",
     "port": "5432",
     "db_name":  "source_db",
     "user_login": "postgres",
     "user_password":  "postgres"
  },
  "sens_dict_contents": [{
    "name": "sens dict for email masking",
    "content": "{\"dictionary\": [{\"schema\": \"public\", \"table\": \"users\", \"fields\": {\"email\": \"md5(email)\"}}]}"
  }],
  "limit": 20,
  "offset": 0,
  "table_filter": "user",
  "view_only_sensitive_tables": false
}'

Responses

Status CodeDescriptionComponent
200Successful ResponsePreviewSchemaTablesResponse
400Bad RequestErrorResponse
500Internal Server ErrorErrorResponse
422Validation ErrorHTTPValidationError
I.3.16.1.7. Run dump operation #

POST /api/stateless/dump

Description

Runs pg_anon in dump mode in the background.

Operation lifecycle:

  1. The client calls this endpoint.

  2. The API returns one of the following status codes:

    • 201 — the dump operation has been successfully started.

    • 400 or 422 — the request is invalid; the operation is not started.

  3. The service sends a webhook request with status in_progress to the webhook_status_url. The payload format is described in the dump webhook request schema.

  4. The operation executes in the background.

  5. If an error occurs during processing, the service sends a webhook request with status error.

  6. If the operation completes successfully, the service sends a webhook request with status success.

Dump request body schema

Field Type Required Description
operation_id string Yes External operation ID. Accepts any string. Returned unchanged in webhook requests.
db_connection_params db connection params Yes Source database connection credentials.
webhook_status_url string Yes Callback URL that receives POST requests in the format described in the dump webhook request schema.
webhook_metadata Any No Arbitrary metadata payload. Sent unchanged in webhook requests.
webhook_extra_headers JSON No Additional HTTP headers added to webhook requests. Useful for integration, e.g., to include an Authorization header.
webhook_verify_ssl boolean No Enables or disables SSL certificate verification for webhook requests.
web_debugbooleanNoEnables writing webhook logs to the operation's log file in the pg_anon_runs/ directory. Default: false.
save_dictsbooleanNoSaves all input and output dictionaries into the pg_anon_runs/ directory. Useful for debugging or integration. Default: false.
type string Yes Defines the dump type. Options: dump, sync-struct-dump, sync-data-dump.
sens_dict_contents array of dictionary content Yes Contents of the sensitive dictionary, defining the masking rules applied during the dump.
partial_tables_dict_contents array of dictionary content No Contents of the tables dictionary specifying tables to include in a partial dump.
partial_tables_exclude_dict_contents array of dictionary content No Contents of the tables dictionary specifying tables to exclude from a partial dump.
schema_masksarray of stringNoRegular expressions that select the schemas to keep in the dump. See Exclude schemas.
exclude_schema_namesarray of stringNoSchema names to leave out of the dump. See Exclude schemas.
exclude_schema_masksarray of stringNoRegular expressions that select the schemas to leave out of the dump. See Exclude schemas.
output_pathstringYesPath where the dump will be created under pg_anon_output/. For example, "my_dump" will be located at pg_anon_output/my_dump.
pg_dump_path string No Path to the pg_dump Postgres tool. Default: /usr/bin/pg_dump.
pg_dump_optionsstringNoAdditional options passed to pg_dump as is, at your own risk. Example: "--no-comments --encoding=LATIN1". See Options for pg_dump.
ignore_privileges boolean No Ignore privileges from source db.
conn_countintegerNoNumber of concurrent database connections. Default: 4.
log_levelstringNoLog verbosity of the pg_anon run: info, debug or error. Default: info.
proc_conn_countintegerNoDeprecated, use conn_count. Still accepted; ignored when conn_count is also sent.
proc_countintegerNoDeprecated. Still accepted, but has no effect.

Example

curl -X POST http://127.0.0.1:8000/api/stateless/dump \
-H "Content-Type: application/json" \
-d '{
  "operation_id": "my-uniq-scan-id-0001",
  "db_connection_params": {
     "host": "localhost",
     "port": "5432",
     "db_name":  "source_db",
     "user_login": "postgres",
     "user_password":  "postgres"
  },
  "webhook_status_url": "https://my-service/pg-anon-result-processor",
  "webhook_metadata": {"extra_field_1": "extra_data", "extra_field_2": {"fld1": [1,2,3], "fld2": 123}},
  "webhook_extra_headers": {"Authorization": "Api-key my_super_secret_api_key", "X-my-service-extra-header": "header value"},
  "webhook_verify_ssl": true,
  "save_dicts": true,
  "type": "dump",
  "sens_dict_contents": [{
    "name": "sens dict for email masking",
    "content": "{\"dictionary\": [{\"schema\": \"public\", \"table\": \"users\", \"fields\": {\"email\": \"md5(email)\"}}, {\"schema\": \"public\", \"table\": \"clients\", \"fields\": {\"email\": \"md5(email)\"}}]}"
  }],
  "partial_tables_dict_contents": [{
    "name": "tables to include",
    "content": "{\"tables\": [{\"schema\": \"public\", \"table\": \"users\"}, {\"schema\": \"public\", \"table\": \"clients\"}]}"
  }],
  "partial_tables_exclude_dict_contents": [{
    "name": "tables to exclude",
    "content": "{\"tables\": [{\"schema\": \"public\", \"table_mask\": \"^tmp_\"}]}"
  }],
  "output_path": "my_dump",
  "pg_dump_path": "/usr/lib/postgresql/17/bin/pg_dump",
  "ignore_privileges": false,
  "proc_count": 4
}'

Dump webhook request schema

Field Type Required Description
operation_id string Yes External operation ID. Copied from the operation_id of the original dump request.
internal_operation_id string No Internal pg_anon operation ID generated automatically. Present for all statuses. Can be used to correlate the webhook event with operation data and logs stored in the pg_anon_runs/ directory. Also used in the Operation endpoints.
status_id integer Yes Numeric status code. Possible values: 2 — success, 3 — error, 4 — in_progress.
status string Yes Human-readable status. Possible values: success, error, in_progress.
webhook_metadata Any No Metadata payload passed “as is”. Copied from the webhook_metadata field of the scan request.
started string No Operation start timestamp in ISO8601 format (UTC+0). Present only for statuses success or error.
ended string No Operation end timestamp in ISO8601 format (UTC+0). Present only for statuses success or error.
error string No Error message. Present only when status = error.
error_codestringNoMachine-readable error code for i18n mapping. Present only when status = error.
run_options JSON No Snapshot of the operation’s runtime options. Useful for analysis, debugging, and rerunning the operation. Present only when status = success or error.
size integer No Size of the dump in bytes.

Responses

Status Code Description Component
201 Operation successfully started -
400 Bad Request ErrorResponse
500 Internal Server Error ErrorResponse
422 Validation Error HTTPValidationError
I.3.16.1.8. Run restore operation #

POST /api/stateless/restore

Description

Runs pg_anon in restore mode in the background.

Operation lifecycle:

  1. The client calls this endpoint.

  2. The API returns one of the following status codes:

    • 201 — the restore operation has been successfully started.

    • 400 or 422 — the request is invalid; the operation is not started.

  3. The service sends a webhook request with status in_progress to the webhook_status_url. The payload format is described in the restore webhook request schema.

  4. The operation executes in the background.

  5. If an error occurs during processing, the service sends a webhook request with status error.

  6. If the operation completes successfully, the service sends a webhook request with status success.

Restore request body schema

Field Type Required Description
operation_id string Yes External operation ID. Accepts any string. Returned unchanged in webhook requests.
db_connection_params db connection params Yes Source database connection credentials.
webhook_status_url string Yes Callback URL that receives POST requests in the format described in the restore webhook request schema.
webhook_metadata Any No Arbitrary metadata payload. Sent unchanged in webhook requests.
webhook_extra_headers JSON No Additional HTTP headers added to webhook requests. Useful for integration, e.g., to include an Authorization header.
webhook_verify_ssl boolean No Enables or disables SSL certificate verification for webhook requests.
web_debugbooleanNoEnables writing webhook logs to the operation's log file in the pg_anon_runs/ directory. Default: false.
save_dictsbooleanNoSaves all input and output dictionaries into the pg_anon_runs/ directory. Useful for debugging or integration. Default: false.
type string Yes Defines the restore type. Options: restore, sync-struct-restore, sync-data-restore.
input_pathstringYesPath to the dump to restore, relative to pg_anon_output/. Example: "my_dump" will restore from pg_anon_output/my_dump.
partial_tables_dict_contents array of dictionary content No Contents of the tables dictionary specifying tables to include in a partial restore
partial_tables_exclude_dict_contents array of dictionary content No Contents of the tables dictionary specifying tables to exclude from a partial restore
schema_namesarray of stringNoSchema names to keep in the restore. Other schemas are left out. See Exclude schemas.
schema_masksarray of stringNoRegular expressions that select the schemas to keep in the restore. See Exclude schemas.
exclude_schema_namesarray of stringNoSchema names to leave out of the restore. See Exclude schemas.
exclude_schema_masksarray of stringNoRegular expressions that select the schemas to leave out of the restore. See Exclude schemas.
pg_restore_path string No Path to the pg_restore Postgres tool. Default: /usr/bin/pg_restore.
pg_restore_optionsstringNoAdditional options passed to pg_restore as is, at your own risk. Example: "--no-comments --no-table-access-method". See Options for pg_restore.
drop_custom_check_constr boolean No Drops all CHECK constraints that contain user-defined procedures to avoid performance degradation during data loading. Default: false.
clean_db boolean No Cleans existing database objects before restoring. Mutually exclusive with drop_db.
drop_db boolean No Drops the target database before restoring. Mutually exclusive with clean_db.
ignore_privileges boolean No Ignore privileges from source db.
conn_countintegerNoNumber of concurrent database connections, also passed to pg_restore as -j. Default: 4.
log_levelstringNoLog verbosity of the pg_anon run: info, debug or error. Default: info.
proc_conn_countintegerNoDeprecated, use conn_count. Still accepted; ignored when conn_count is also sent.

Example

curl -X POST http://127.0.0.1:8000/api/stateless/restore \
-H "Content-Type: application/json" \
-d '{
  "operation_id": "my-uniq-scan-id-0001",
  "db_connection_params": {
     "host": "localhost",
     "port": "5432",
     "db_name":  "source_db",
     "user_login": "postgres",
     "user_password":  "postgres"
  },
  "webhook_status_url": "https://my-service/pg-anon-result-processor",
  "webhook_metadata": {"extra_field_1": "extra_data", "extra_field_2": {"fld1": [1,2,3], "fld2": 123}},
  "webhook_extra_headers": {"Authorization": "Api-key my_super_secret_api_key", "X-my-service-extra-header": "header value"},
  "webhook_verify_ssl": true,
  "save_dicts": true,
  "type": "restore",
  "input_path": "my_dump",
  "partial_tables_dict_contents": [{
    "name": "tables to include",
    "content": "{\"tables\": [{\"schema\": \"public\", \"table\": \"users\"}, {\"schema\": \"public\", \"table\": \"clients\"}]}"
  }],
  "partial_tables_exclude_dict_contents": [{
    "name": "tables to exclude",
    "content": "{\"tables\": [{\"schema\": \"public\", \"table_mask\": \"^tmp_\"}]}"
  }],
  "pg_restore_path": "/usr/lib/postgresql/17/bin/pg_restore",
  "drop_custom_check_constr": false,
  "clean_db": false,
  "drop_db": false,
  "ignore_privileges": false,
  "proc_count": 4
}'

Restore webhook request schema

Field Type Required Description
operation_id string Yes External operation ID. Copied from the operation_id of the original restore request.
internal_operation_id string No Internal pg_anon operation ID generated automatically. Present for all statuses. Can be used to correlate the webhook event with operation data and logs stored in the pg_anon_runs/ directory. Also used in the Operation endpoints.
status_id integer Yes Numeric status code. Possible values: 2 — success, 3 — error, 4 — in_progress.
status string Yes Human-readable status. Possible values: success, error, in_progress.
webhook_metadata Any No Metadata payload passed “as is”. Copied from the webhook_metadata field of the scan request.
started string No Operation start timestamp in ISO8601 format (UTC+0). Present only for statuses success or error.
ended string No Operation end timestamp in ISO8601 format (UTC+0). Present only for statuses success or error.
error string No Error message. Present only when status = error.
error_codestringNoMachine-readable error code for i18n mapping. Present only when status = error.
run_options JSON No Snapshot of the operation’s runtime options. Useful for analysis, debugging, and rerunning the operation. Present only when status = success or error.

Responses

Status Code Description Component
201 Operation successfully started -
400 Bad Request ErrorResponse
500 Internal Server Error ErrorResponse
422 Validation Error HTTPValidationError

I.3.16.2. Integration Endpoints #

I.3.16.2.1. Operations list #

GET /operation

Description

Returns a list of background operation directories (scan, dump, restore). Only operations executed with save_dicts enabled are included. Useful for integration purposes.

Operations list request params

Field Type Required Description
date_before date No Filter: operations before this date. Date format ISO 8601
date_after date No Filter: operations after this date. Date format ISO 8601

Example

curl -X GET http://127.0.0.1:8000/operation?date_after=2025-01-01&date_before=2025-12-31

Responses

Status Code Description Component
200 List of operation paths array of strings
422 Validation Error HTTPValidationError
I.3.16.2.2. Operation details #

GET /operation/{internal_operation_id}

Description

Returns detailed information about a background operation (scan, dump, restore). Only operations executed with save_dicts enabled are included. Useful for integration purposes.

Operations details request params

Field Type Required Description
internal_operation_id string Yes Internal pg_anon operation ID.

Example

curl -X GET http://127.0.0.1:8000/operation/c6c98133-856f-46b3-ba9e-3a0092b8d9aa

Responses

Status Code Description Component
200 Operation details OperationDataResponse
404 Operation directory not found HTTPValidationError
422 Validation Error HTTPValidationError
I.3.16.2.3. Delete operation data #

DELETE /operation/{internal_operation_id}

Description

Deletes the operation data directory in pg_anon_runs/. Also removes the dump directory from the output path if the operation type is dump.

Example

curl -X DELETE http://127.0.0.1:8000/operation/c6c98133-856f-46b3-ba9e-3a0092b8d9aa

Delete operation data request params

Field Type Required Description
internal_operation_id string Yes Internal pg_anon operation ID.

Responses

Status Code Description Component
204 Operation data successfully deleted -
400 Bad Request ErrorResponse
422 Validation Error HTTPValidationError
500 Internal Server Error ErrorResponse
I.3.16.2.4. Operation logs #

GET /operation/{internal_operation_id}/logs

Description

Returns log output for a background operation (scan, dump, restore). Available for any operation whose internal_operation_id you know — unlike the two endpoints above, it does not require save_dicts. Useful for integration purposes.

Operations logs request body schema

Name Type Required Description
internal_operation_id string Yes Internal pg_anon operation ID.
tail_lines integer No Number of log lines to read from the end of the file. Default: 1000

Example

curl -X GET http://127.0.0.1:8000/operation/c6c98133-856f-46b3-ba9e-3a0092b8d9aa/logs

Responses

Status Code Description Component
200 Successful Response array of strings
422 Validation Error HTTPValidationError

I.3.17. General schemas #

I.3.17.1. DbConnectionParams #

Field Type Required Description
host string Yes Database host.
port integer Yes Database port.
db_name string Yes Database name.
user_login string Yes Database user.
user_password string Yes Database user password.

I.3.17.2. DictionaryContent #

Field Type Required Description
name string Yes Dictionary name. For example can be used as dictionary filename
content string Yes Dictionary content that using for operations processing
additional_info string No Extra data for integration purposes. Will be sent on webhook “as is”.

I.3.17.3. DictionaryMetadata #

Field Type Required Description
name string Yes Dictionary name. For example can be used as dictionary filename
additional_info string No Extra data for integration purposes. Will be sent on webhook “as is”.

I.3.17.4. OperationDataResponse #

Field Type Required Description
run_status RunStatus Yes Operation status.
run_options JSON Yes Snapshot of the operation’s runtime options. Useful for analysis, debugging, and rerunning the operation.
dictionaries DictionariesData Yes Used and resulted dictionary contents by types.
extra_data JSON No For dump operations contains dump size info. In other cases is empty.

I.3.17.5. RunStatus #

Field Type Required Description
status_id integer Yes Numeric status code. Possible values: 2 — success, 3 — error.
status string Yes Human-readable status. Possible values: success, error.
started string No Operation start timestamp in ISO8601 format (UTC+0).
ended string No Operation end timestamp in ISO8601 format (UTC+0).

I.3.17.6. DictionariesData #

Field Type Required Description
meta_dict_files array of dictionary content No Contents of the input meta dictionary.
prepared_sens_dict_files array of dictionary content No Contents of the input sensitive dictionary.
prepared_no_sens_dict_files array of dictionary content No Contents of the input non-sensitive dictionary.
partial_tables_dict_files array of dictionary content No Contents of the input tables dictionary.
partial_tables_exclude_dict_files array of dictionary content No Contents of the input tables dictionary.
output_sens_dict_file dictionary content No Contents of the output sensitive dictionary.
output_no_sens_dict_file dictionary content No Contents of the output non-Sensitive dictionary.

I.3.17.7. ViewDataResponse #

Field Type Required Description
status_id integer Yes Integer code of operation status. Can be: 2 — success, 3 — error
status string Yes Human readable operation status. Can be: success, error
content ViewDataContent No Operation result data

I.3.17.8. ViewDataContent #

Field Type Required Description
schema_name string Yes Schema name
table_name string Yes Table name
field_names array Yes Table field names. It needs for rendering table header
total_rows_count integer Yes Total rows count in table. It useful for pagination
rows_before array Yes Source rows data “as is”, without masking
rows_after array Yes Masked rows, showing how the rules will work on the source data

I.3.17.9. ViewFieldsResponse #

Field Type Required Description
status_id integer Yes Integer code of operation status. Can be: 2 — success, 3 — error
status string Yes Human readable operation status. Can be: success, error
content array of ViewFieldsContent No Operation result data

I.3.17.10. ViewFieldsContent #

Field Type Required Description
schema_name string Yes Schema name
table_name string Yes Table name
field_name string Yes Field name
type string Yes Field data type
dict_data DictionaryMetadata No Matched dictionary metadata containing the masking rule
rule str No Matched masking rule if field is sensitive

I.3.17.11. PreviewSchemasResponse #

FieldTypeRequiredDescription
status_idintegerYesInteger code of operation status. Can be: 2 - success, 3 - error
statusstringYesHuman readable operation status. Can be: success, error
contentarray of stringNoList of schema names

I.3.17.12. PreviewSchemaTablesResponse #

FieldTypeRequiredDescription
status_idintegerYesInteger code of operation status. Can be: 2 - success, 3 - error
statusstringYesHuman readable operation status. Can be: success, error
contentarray of PreviewTableContentNoList of tables with sensitivity info

I.3.17.13. PreviewTableContent #

FieldTypeRequiredDescription
table_namestringYesTable name
is_sensitivebooleanYesWhether the table matches the sensitive dictionary
is_excludedbooleanYesWhether the table is excluded by dictionary_exclude
fieldsarray of PreviewFieldContentNoList of fields with their types and sensitivity info

I.3.17.14. PreviewFieldContent #

FieldTypeRequiredDescription
field_namestringYesField name
typestringYesField data type
is_sensitivebooleanYesWhether the field matches a masking rule
rulestringNoMatched masking rule if field is sensitive

I.3.17.15. ErrorResponse #

Field Type Required Description
error_codestringYesMachine-readable error code for i18n mapping.
messagestringYesHuman-readable error message.

I.3.17.16. HTTPValidationError #

Field Type Required Description
detail array Yes Error details.

I.3.17.17. ValidationError #

Field Type Required Description
loc array Yes Wrong parameter.
msg string Yes Error message.
type string Yes Error type.