Skip to content

This is the multi-page printable view of this section.

Return to the regular view of this page

Docs

PGSTY develops acdat, pgs3, and opencc for PostgreSQL. The vchord and mooncake suites have their own documentation.

First-party extensions

acdatv0.1.1

Compile literal rules once and match or replace them across text and bytea in a single pass.

pgs3v0.1.2

Turn PostgreSQL into a versioned S3 object endpoint with SQL transactions, bucket forks, and RLS isolation.

openccv0.1.0

Convert Chinese scripts and regional vocabulary inside PostgreSQL with embedded OpenCC dictionaries.

Extension suites

Approximate nearest-neighbor indexes for pgvector types.

BM25 ranking for PostgreSQL full-text search.

Query an Iceberg mirror of a PostgreSQL table.

Apply logical replication changes to Iceberg tables.

1 - acdat

Compile hundreds to hundreds of thousands of literal patterns into a compact Aho–Corasick automaton and scan PostgreSQL text or bytea values in a single linear pass. Ideal for content moderation, log IOC tagging, entity extraction, and bulk redaction.

Checking a text column against thousands of keywords with LIKE ANY, ~ regex alternation, or repeated replace() calls slows down linearly as your rule list grows. acdat compiles an entire dictionary once into an Aho–Corasick automaton stored on a double-array trie (acdat.machine), then evaluates every rule simultaneously in one pass over each input value.

Why use acdat

  • Constant-cost rule scaling: Scan time scales with the length of the input string, not the number of keywords—whether your dictionary holds 20 rules or 100,000 rules.
  • Exact text and binary matching: Supports both text (reporting 1-based byte and Unicode character offsets) and bytea (arbitrary binary payloads including \x00).
  • One-pass deterministic rewriting: acdat.replace() rewrites overlapping spans according to an explicit policy (leftmost_longest or leftmost_priority) and never rescans already-replaced output.
  • Managed dictionary lifecycle: Publish immutable dictionary versions, switch active builds atomically via MVCC, or roll back instantly without taking queries offline.

When to use acdat (and when not to)

NeedBest toolWhy
Check, tag, or redact many exact literal phrases or binary signatures inside PostgreSQLacdatSingle-pass scan with stable rule IDs, priorities, and deterministic replacement
Search by stemmed natural-language words or relevance rankingPostgreSQL full-text search / vchord_bm25acdat matches exact literal bytes, not linguistic tokens or stem variants
Match variable patterns (\d{4}-\d{2}, lookaheads, wildcards)Regular expressions (~ / regexp_replace)acdat handles literal strings only
Filter a tiny fraction of rows out of a huge table by a few substringspg_trgm GIN/GiST index (or combine with acdat)Narrow candidate rows with an index first, then run acdat on the survivors

How acdat works

flowchart LR
    R["Application Rule Table (pattern, id, replacement, priority)"] -->|acdat.compile| M["acdat.machine (Double-Array Trie)"]
    M -->|acdat.publish + activate| CAT["acdat.active_machine (MVCC Pointer)"]
    CAT -->|acdat.contains| B["boolean (fast filter)"]
    CAT -->|acdat.matches| H["SETOF acdat.hit (id & offsets)"]
    CAT -->|acdat.replace| T["text / bytea (single-pass rewrite)"]
  1. Keep rules in your own table: Your application table owns the pattern text, business pattern_id, optional replacement text, priority, and metadata (such as risk level or category).
  2. Compile once: acdat.compile() turns arrays or table rows into an immutable acdat.machine value. A 1,114-rule real-world dictionary compiles in ~1.2 ms and caches in ~227 KiB per backend.
  3. Publish or pass directly: Store the compiled machine in your own table or publish it to acdat’s built-in catalog (acdat.publish + acdat.activate) for atomic rollouts and rollbacks.
  4. Scan in one pass: Pass the machine to acdat.contains() to filter rows, acdat.matches() to extract rule IDs and offsets, or acdat.replace() to redact or rewrite values.

1.1 - Getting started with acdat

Install acdat and build a complete comment moderation and redaction pipeline in PostgreSQL in three minutes.

1. Install acdat

Install from Pigsty packages

CI covers PostgreSQL 14–18, and Pigsty ships packages for PostgreSQL 15–19 across Linux distributions. Check Downloads for OS and architecture availability.

pig repo add pgsql -u
pig ext add acdat

Or build from the release tag

Point PG_CONFIG to your target PostgreSQL installation:

git clone --branch v0.1.1 --depth 1 https://github.com/pgsty/acdat.git
cd acdat
make PG_CONFIG=pg_config
sudo make install PG_CONFIG=pg_config

2. Enable the extension

Connect to a UTF8 database as a superuser and create the extension. All functions and types live in the fixed acdat schema:

CREATE EXTENSION IF NOT EXISTS acdat;

3. Build and run a moderation pipeline

Instead of scanning rows one keyword at a time, keep rules in a table, compile them into one acdat.machine, and run filtering, annotation, and redaction in a single pass.

  1. Create a rule table and sample comments:

    CREATE TEMP TABLE moderation_rules (
        pattern_id  bigint PRIMARY KEY,
        pattern     text NOT NULL,
        replacement text NOT NULL,
        priority    integer NOT NULL DEFAULT 0,
        category    text NOT NULL
    );
    
    INSERT INTO moderation_rules (pattern_id, pattern, replacement, priority, category) VALUES
        (101, 'insider tip',       '[BLOCKED]', 10, 'compliance'),
        (102, 'guaranteed return', '[BLOCKED]', 10, 'compliance'),
        (103, 'DM on Telegram',    '[CONTACT]',  5, 'spam');
    
    CREATE TEMP TABLE comments (
        comment_id bigint PRIMARY KEY,
        body       text NOT NULL
    );
    
    INSERT INTO comments VALUES
        (1, 'DM on Telegram for a guaranteed return today'),
        (2, 'PostgreSQL 18 release notes'),
        (3, 'Never act on an insider tip');
  2. Compile the rule table into a single acdat.machine:

    CREATE TEMP TABLE compiled_dict AS
    SELECT acdat.compile(pattern, pattern_id, replacement, priority) AS machine
    FROM moderation_rules;
  3. Filter only the comments that match at least one rule (acdat.contains stops on the first hit):

    SELECT comment_id, body
    FROM comments
    WHERE acdat.contains(body, (SELECT machine FROM compiled_dict))
    ORDER BY comment_id;
     comment_id |                     body
    ------------+----------------------------------------------
              1 | DM on Telegram for a guaranteed return today
              3 | Never act on an insider tip
  4. Extract every match with its position and join back to your rule table for business labels:

    SELECT c.comment_id,
           h.pattern_id,
           r.category,
           h.start_char,
           h.char_length,
           substring(c.body FROM h.start_char FOR h.char_length) AS matched_text
    FROM comments AS c
    CROSS JOIN LATERAL acdat.matches(c.body, (SELECT machine FROM compiled_dict)) AS h
    JOIN moderation_rules AS r USING (pattern_id)
    ORDER BY c.comment_id, h.start_byte, h.pattern_id;
     comment_id | pattern_id |  category  | start_char | char_length |   matched_text
    ------------+------------+------------+------------+-------------+-------------------
              1 |        103 | spam       |          1 |          14 | DM on Telegram
              1 |        102 | compliance |         22 |          17 | guaranteed return
              3 |        101 | compliance |         17 |          11 | insider tip
  5. Redact all matched spans in one non-recursive pass:

    SELECT comment_id,
           acdat.replace(body, (SELECT machine FROM compiled_dict)) AS sanitized
    FROM comments
    ORDER BY comment_id;
     comment_id |            sanitized
    ------------+----------------------------------
              1 | [CONTACT] for a [BLOCKED] today
              2 | PostgreSQL 18 release notes
              3 | Never act on an [BLOCKED]
Tip

Notice the scalar subquery (SELECT machine FROM compiled_dict) above. Writing the machine lookup as an uncorrelated subquery lets PostgreSQL load the automaton once in an InitPlan rather than re-reading it per row during parallel scans.

For one-off ad-hoc checks without a rule table, you can also compile an inline array directly:

SELECT acdat.contains('PostgreSQL timeout error', acdat.compile(ARRAY['timeout', 'deadlock'])) AS matched;
-- t

Next steps

  • Examples and workflows — Explore overlap policies, log IOC extraction, managed dictionary publishing & rollback, binary matching, and cross-database export/import.
  • Performance and tuning — Benchmark charts, avoiding the 22x parallel-plan trap, and per-worker memory budgets.
  • Operations — Separate dictionary admin privileges, backups, and error troubleshooting.
  • Run the tagged end-to-end SQL script examples/demo.sql inside a single rolled-back psql transaction.

1.2 - Examples and workflows

Five practical acdat recipes: resolving overlapping phrases, extracting log IOCs with a reverse-lookup index, rolling out versioned dictionaries atomically, scanning binary payloads, and shipping compiled artifacts across databases.

Every example below is self-contained and runs inside PostgreSQL using acdat v0.1.1.

1. Overlapping rules and redaction policies

Real dictionaries almost always contain overlapping phrases—for instance, "credit card", "credit card fraud", and "fraud". acdat resolves overlaps deterministically using three policies:

  • all_overlapping (default for matches): reports every candidate hit, including prefixes, suffixes, and duplicate text with distinct IDs.
  • leftmost_longest (default for replace): consumes the leftmost match; at the same start offset, prefers the longer pattern, then lower priority number, then lower ID.
  • leftmost_priority: consumes the leftmost match; at the same start offset, prefers the lower priority number first (e.g., priority 10 beats priority 20), then longer pattern, then lower ID.
WITH dict AS (
    SELECT acdat.compile(
        ARRAY['credit card', 'credit card fraud', 'fraud'],
        ARRAY[1, 2, 3]::bigint[],
        ARRAY['[PAYMENT]', '[HIGH-RISK]', '[RISK]'],
        ARRAY[10, 20, 5]::integer[]
    ) AS m
)
SELECT
    acdat.replace('report credit card fraud now', m, 'leftmost_longest')  AS longest,
    acdat.replace('report credit card fraud now', m, 'leftmost_priority') AS by_priority,
    (SELECT count(*) FROM acdat.matches('report credit card fraud now', m, 'all_overlapping')) AS total_hits
FROM dict;
         longest         |         by_priority         | total_hits
-------------------------+-----------------------------+------------
 report [HIGH-RISK] now  | report [PAYMENT] [RISK] now |          3

Why the two results differ:

  • Under leftmost_longest, "credit card fraud" (17 bytes) beats "credit card" (11 bytes) at byte 8 and consumes the entire span.
  • Under leftmost_priority, "credit card" (priority 10) beats "credit card fraud" (priority 20) at byte 8; scanning then resumes after byte 18 and also matches "fraud".

Practical rules for acdat.replace():

  • Delete spans with '': An empty replacement string deletes the matched span; selecting a rule whose replacement is NULL raises an error (acdat pattern ID <n> has no replacement).
  • Single non-recursive pass: Replacement output is never rescanned, so replacing "foo" with "foobar" cannot loop.
  • Guard against expansion: Pass explicit max_replacements (default 10000) and max_output_bytes (default 256 MiB) when short inputs could expand into large outputs. The candidate limit counts raw overlaps before policy resolution, and an outer SQL LIMIT does not cap it.

2. Extract log IOCs and build a reverse-lookup table

When auditing security logs or tagging documents against a large IOC (Indicator of Compromise) list, you often need two answers: “which indicators hit this log?” and later “which logs matched indicator #402?”

CREATE TEMP TABLE ioc_rules (
    pattern_id bigint PRIMARY KEY,
    pattern    text NOT NULL,
    severity   text NOT NULL
);

INSERT INTO ioc_rules VALUES
    (401, 'malicious.example', 'critical'),
    (402, '198.51.100.77',     'high'),
    (403, 'powershell -enc',   'critical');

CREATE TEMP TABLE ioc_machine AS
SELECT acdat.compile(pattern, pattern_id) AS machine
FROM ioc_rules;

CREATE TEMP TABLE access_logs (
    log_id bigint PRIMARY KEY,
    line   text NOT NULL
);

INSERT INTO access_logs VALUES
    (1, 'GET https://malicious.example/payload from 198.51.100.77'),
    (2, 'GET https://docs.example.org/index.html from 203.0.113.5'),
    (3, 'exec: PowerShell -Enc SQBFAFgA');

Notice log #3 has mixed casing (PowerShell -Enc). Because acdat compares exact UTF-8 bytes without case folding or Unicode normalization, normalize both rules and input identically (for example with lower()) when case-insensitive matching is required:

-- Materialize every hit along with position offsets for auditing and reverse lookup
CREATE TEMP TABLE log_ioc_hits AS
SELECT l.log_id,
       h.pattern_id,
       r.severity,
       h.start_byte,
       h.byte_length,
       h.start_char,
       h.char_length,
       substring(lower(l.line) FROM h.start_char FOR h.char_length) AS matched_token
FROM access_logs AS l
CROSS JOIN LATERAL acdat.matches(
    lower(l.line),
    (SELECT machine FROM ioc_machine),
    'all_overlapping',
    1000
) AS h
JOIN ioc_rules AS r USING (pattern_id);

CREATE INDEX ON log_ioc_hits (pattern_id, log_id);

SELECT log_id, pattern_id, severity, start_char, char_length, matched_token
FROM log_ioc_hits
ORDER BY log_id, start_byte;
 log_id | pattern_id | severity | start_char | char_length |   matched_token
--------+------------+----------+------------+-------------+-------------------
      1 |        401 | critical |         13 |          17 | malicious.example
      1 |        402 | high     |         44 |          13 | 198.51.100.77
      3 |        403 | critical |          7 |          15 | powershell -enc

With the index on (pattern_id, log_id), reverse lookups (WHERE pattern_id = 402) are instant. In production, store dictionary_version and build_id alongside each materialized hit so you know which rule build produced it and can rebuild cleanly when rules change.

Note

Offsets are 1-based. For UTF-8 text, start_byte/byte_length measure UTF-8 bytes while start_char/char_length measure Unicode code points (which plug directly into PostgreSQL substring(... FROM start_char FOR char_length)). Always add ORDER BY if you need stable output order.

3. Publish, atomically switch, and roll back dictionaries

For production dictionaries that change over time, use acdat’s built-in catalog instead of overwriting a single row. Publishing stores an immutable semantic version and returns a 32-byte build_id; activating flips a pointer in acdat.active_dictionary atomically under MVCC so concurrent readers switch cleanly without locks.

-- 1. Compile and publish version 1 from your rule table
CREATE TEMP TABLE dict_releases (version bigint PRIMARY KEY, build_id bytea NOT NULL);

INSERT INTO dict_releases (version, build_id)
SELECT 1,
       acdat.publish(
           'security_ioc',
           1,
           acdat.compile(pattern, pattern_id),
           '{"ticket":"SEC-101"}'::jsonb
       )
FROM ioc_rules;

-- 2. Activate version 1
SELECT acdat.activate('security_ioc', build_id)
FROM dict_releases WHERE version = 1;

-- 3. Add a new rule, publish version 2, and switch traffic atomically
INSERT INTO ioc_rules VALUES (404, 'credential-dump', 'critical');

INSERT INTO dict_releases (version, build_id)
SELECT 2,
       acdat.publish(
           'security_ioc',
           2,
           acdat.compile(pattern, pattern_id),
           '{"ticket":"SEC-102"}'::jsonb
       )
FROM ioc_rules;

SELECT acdat.activate('security_ioc', build_id)
FROM dict_releases WHERE version = 2;

-- Readers always query acdat.active_machine
SELECT name, version, acdat.contains('detected credential-dump', machine) AS hit
FROM acdat.active_machine
WHERE name = 'security_ioc';
     name     | version | hit
--------------+---------+-----
 security_ioc |       2 | t

If version 2 triggers false positives, roll back immediately by reactivating version 1, then retire version 2:

SELECT acdat.activate('security_ioc', build_id)     FROM dict_releases WHERE version = 1;
SELECT acdat.retire_build('security_ioc', build_id) FROM dict_releases WHERE version = 2;

Keep these compilation rules in mind:

  • Parallel arrays passed to acdat.compile() must be 1D and equal in length; patterns must be non-empty; explicit IDs must be non-NULL and unique (duplicate literal strings with distinct IDs are allowed); NULL priorities default to 0.
  • An aggregate over zero rows returns NULL; an explicitly typed empty array (ARRAY[]::text[]) builds an empty machine.
  • Canonical sorting makes source_fingerprint() independent of input row order when rule IDs are stable.

4. Scan and patch binary payloads (bytea)

Use the bytea overloads to match protocol headers, file magic bytes, or raw signatures containing \x00 or non-UTF-8 octets. Binary hits always return NULL for start_char and char_length.

WITH sigs AS (
    SELECT acdat.compile(
        ARRAY[decode('00ff', 'hex'), decode('beef', 'hex')],
        ARRAY[20, 21]::bigint[],
        ARRAY[decode('1122', 'hex'), decode('dead', 'hex')]
    ) AS m
)
SELECT
    (SELECT array_agg(pattern_id ORDER BY start_byte)
     FROM acdat.matches(decode('aa00ffbeef', 'hex'), m)) AS hit_ids,
    encode(acdat.replace(decode('aa00ffbeef', 'hex'), m), 'hex') AS patched
FROM sigs;
 hit_ids |  patched
---------+------------
 {20,21} | aa1122dead

Text machines reject bytea inputs and vice versa (acdat machine input kind does not match function input). On databases using encodings other than UTF8 or single-byte encodings, use bytea.

5. Inspect and ship compiled machines across databases

If you compile a 100,000-pattern dictionary in CI or on a build server, you can inspect its metadata and ship the compiled bytea artifact to production databases without recompiling there.

WITH d AS (
    SELECT acdat.compile(ARRAY['virus', 'signature'], ARRAY[1, 2]::bigint[]) AS m
)
SELECT acdat.info(m)->>'engine'                         AS engine,
       acdat.info(m)->>'pattern_count'                  AS patterns,
       encode(acdat.source_fingerprint(m), 'hex')       AS source_sha256,
       encode(acdat.artifact_checksum(m),  'hex')       AS artifact_sha256
FROM d;

Export on the build database, validate and import on the target database:

WITH exported AS (
    SELECT acdat.export(acdat.compile(ARRAY['virus', 'signature'])) AS blob
)
SELECT acdat.validate(blob) AS valid,
       acdat.contains('virus detected', acdat.import(blob)) AS works
FROM exported;
 valid | works
-------+-------
 t     | t
  • source_fingerprint() hashes the canonical rule set; build_fingerprint() also includes engine, compiler, and format version; artifact_checksum() hashes the serialized payload.
  • validate() returns false on corrupted bytes while import() raises an error.
  • Transfer text machines only between databases with compatible server encodings; bytea machines are encoding-independent.

1.3 - Performance and tuning

Reference throughput and memory measurements for acdat v0.1.1, how to avoid the 22x parallel-scan planning trap, and sizing rules for production rule sets.

acdat compiles fast and scans near memory bandwidth. In production, query latency is usually governed by PostgreSQL’s execution plan, row width, and parallel worker count rather than the automaton itself.

All benchmark figures below were measured on acdat v0.1.1 (Apple M5 Max, PostgreSQL 18.6, hot buffers, in-database aggregation without client transfer). Full methodology and raw logs: PERFORMANCE.md · BENCHMARK.md.

1. Real corpus throughput (10.3M rows, 1,114 rules)

Dataset: 10,318,163 short video titles (306.9 MiB total, ~31 bytes/row) scanned against a 1,114-rule real dictionary (compiled in 1.16 ms, 227 KiB runtime cache per process).

backgroundColor: transparent
tooltip:
  trigger: axis
  axisPointer:
    type: shadow
legend:
  top: 6
grid:
  left: 16
  right: 20
  top: 48
  bottom: 16
  containLabel: true
xAxis:
  type: category
  data: ["contains", "replace", "matches"]
yAxis:
  type: value
  name: "MiB/s"
series:
  - name: "1 backend"
    type: bar
    barMaxWidth: 36
    itemStyle:
      color: "#94a3b8"
      borderRadius: [4, 4, 0, 0]
    label:
      show: true
      position: top
    data: [202, 153, 83]
  - name: "4 workers"
    type: bar
    barMaxWidth: 36
    itemStyle:
      color: "#3b82f6"
      borderRadius: [4, 4, 0, 0]
    label:
      show: true
      position: top
    data: [772, 602, 376]
  - name: "8 workers"
    type: bar
    barMaxWidth: 36
    itemStyle:
      color: "#10b981"
      borderRadius: [4, 4, 0, 0]
    label:
      show: true
      position: top
    data: [1346, 1055, 645]
Operation1 backend4 workers8 workers8-worker speedup
contains1.522 s0.398 s0.228 s6.67x
replace (leftmost_longest)2.007 s0.510 s0.291 s6.89x
matches (all_overlapping)3.678 s0.816 s0.476 s7.73x

contains stops on the first match and allocates no output text or hit tuples, making it ~2.4x faster than matches on short rows.

2. Scaling to 100,000 rules across row widths

Dataset: 100,000 shared-prefix patterns (compiled in 36.9 ms, 5.51 MiB runtime cache) scanning 256–314 MiB of root-miss text across three row sizes.

backgroundColor: transparent
tooltip:
  trigger: axis
  axisPointer:
    type: shadow
legend:
  top: 6
grid:
  left: 16
  right: 20
  top: 48
  bottom: 16
  containLabel: true
xAxis:
  type: category
  data: ["33 B / row (10M rows)", "1 KiB / row (262k rows)", "64 KiB / row (4k rows)"]
yAxis:
  type: value
  name: "GiB/s"
series:
  - name: "1 backend"
    type: bar
    barMaxWidth: 36
    itemStyle:
      color: "#94a3b8"
      borderRadius: [4, 4, 0, 0]
    label:
      show: true
      position: top
    data: [0.51, 0.89, 0.89]
  - name: "4 workers"
    type: bar
    barMaxWidth: 36
    itemStyle:
      color: "#3b82f6"
      borderRadius: [4, 4, 0, 0]
    label:
      show: true
      position: top
    data: [2.19, 3.41, 3.55]
  - name: "8 workers"
    type: bar
    barMaxWidth: 36
    itemStyle:
      color: "#10b981"
      borderRadius: [4, 4, 0, 0]
    label:
      show: true
      position: top
    data: [2.94, 5.01, 5.13]
Row widthRows1 backend4 workers8 workers
33 B10,000,000600.6 ms140.1 ms104.0 ms
1 KiB262,144281.6 ms73.3 ms49.9 ms
64 KiB4,096280.4 ms70.5 ms48.8 ms

At 1 KiB and 64 KiB per row, a single PostgreSQL backend reaches ~94% of the standalone C core’s throughput (965 MiB/s). On 33-byte rows, executor per-row call overhead accounts for roughly half of runtime.

3. Avoid the 22x parallel matches trap

Joining a single-row machine table directly with CROSS JOIN can cause the parallel planner to place the machine scan inside the document loop—re-reading the machine row once per document:

-- SLOW: parallel Gather can rescan active_dict once per document row (10.43 s on 8 workers)
SELECT count(*)
FROM documents AS d
CROSS JOIN active_dict AS m
CROSS JOIN LATERAL acdat.matches(d.body, m.machine, 'all_overlapping') AS h;

Wrapping the lookup in an uncorrelated scalar subquery turns it into a once-per-query InitPlan. On the 10.3M-row corpus with 8 workers, runtime dropped from 10.43 s to 0.476 s (22x faster):

-- FAST: uncorrelated scalar subquery loads the machine once via InitPlan (0.476 s)
SELECT count(*)
FROM documents AS d
CROSS JOIN LATERAL acdat.matches(
    d.body,
    (SELECT machine FROM acdat.active_machine WHERE name = 'security_ioc'),
    'all_overlapping'
) AS h;

Always check EXPLAIN (ANALYZE, BUFFERS) before rolling out a large scan and verify that the machine scan runs with loops=1.

4. Memory budget and tuning rules

Each backend and parallel worker keeps its own materialized runtime cache. Budget (1 + max_parallel_workers_per_gather) copies for large dictionaries:

Dictionary profileStored artifactCache / process9 processes (leader + 8 workers)
Real corpus (1,114 rules)269 KiB227 KiB~2.0 MiB
100k shared-prefix rules5.94 MiB5.51 MiB~49.6 MiB
100k random ASCII rules28.96 MiB23.93 MiB~215.4 MiB

Four practical rules for fast scans:

  • Compile once outside the row loop: Never put acdat.compile() inside a per-row WHERE or SELECT expression.
  • Filter before scanning: Narrow candidate rows with B-tree, GIN, or time-range indexes first, and choose acdat.contains() over acdat.matches() when you only need a boolean match.
  • Benchmark your own dictionary: Root-miss workloads run much faster than dense-fallback ASCII workloads; rule count alone does not predict throughput.
  • Stream large exports: Use COPY or a server-side cursor when exporting millions of matches or rewritten rows instead of buffering a giant SELECT in client memory.

1.4 - Operations

Configure least-privilege roles for scanning vs. publishing dictionaries, plan logical and physical backups, diagnose common errors, and uninstall safely.

For throughput measurements, parallel execution plans, and per-worker cache sizing, see Performance and tuning.

1. Least-privilege permissions

A superuser installs acdat. By default, PUBLIC receives USAGE on the acdat schema and EXECUTE on scanning/compilation functions, while managed catalog tables and publish / activate / retire_build are revoked from PUBLIC.

Separate read-only scanning roles from dictionary administrators:

-- Scan-only role: reads currently active published machines
CREATE ROLE app_scanner;
GRANT SELECT ON acdat.active_machine TO app_scanner;

-- Dictionary admin role: publishes, activates, and retires managed builds
-- (management functions run SECURITY INVOKER, so both table and function grants are required)
CREATE ROLE dict_admin;
GRANT SELECT, INSERT, UPDATE, DELETE ON
    acdat.dictionary,
    acdat.dictionary_version,
    acdat.dictionary_build,
    acdat.dictionary_build_data,
    acdat.active_dictionary
TO dict_admin;

GRANT EXECUTE ON FUNCTION
    acdat.publish(text, bigint, acdat.machine, jsonb),
    acdat.activate(text, bytea),
    acdat.retire_build(text, bytea)
TO dict_admin;

2. Backup, restore, and replication

  • Logical dumps (pg_dump): acdat registers its catalog tables via pg_extension_config_dump(), dumping all dictionary, version, and build metadata, active pointers, and active machine payloads. Inactive historical payloads are excluded to keep dumps compact—back up your application rule tables so inactive versions can be recompiled on demand.
  • Physical backups and PITR: Include all logged active and inactive payloads automatically. Install a compatible acdat shared library on the recovery host before starting PostgreSQL.
  • Logical replication: Install acdat on subscribers beforehand, then either replicate metadata, payload, and activation atomically in one transaction or recompile dictionaries independently on subscribers from replicated source rules.

3. Common errors

Error messageCause and fix
acdat compile failed: pattern ID 1 is duplicatedEvery rule in one dictionary must have a unique pattern_id. Deduplicate or assign distinct IDs.
acdat scan failed: match count exceeds limit 2Raw overlapping hits exceeded max_matches (or max_replacements) before overlap resolution. Prune overlapping rules or raise the measured cap.
acdat pattern ID 1 has no replacementacdat.replace() selected a rule whose replacement was NULL. Supply a literal replacement (or '' to delete).
cannot retire the active acdat buildActivate another ready build first, then retire the previous build.
acdat machine input kind does not match function inputA text machine was passed to a bytea function (or vice versa). Keep machine and input types paired.
acdat build is absent, retired, or has no artifact payloadPublish or recompile the target build before calling acdat.activate().

Other quick checks: cast empty arrays explicitly (ARRAY[]::text[]), note that an aggregate over zero rows returns NULL, and on permission errors verify both table and function grants for SECURITY INVOKER management functions.

4. Uninstall

Warning

DROP EXTENSION acdat removes all managed catalog tables and compiled machines. Adding CASCADE also drops dependent application tables, views, or functions. Back up your source rules and inspect dependencies before removing the extension.

1.5 - acdat SQL reference

Complete SQL API lookup for acdat v0.1.1. All types, functions, and catalog tables live in the fixed acdat schema; always pair text or bytea inputs with a matching machine.

Compile a dictionary

acdat.compile(patterns text[], pattern_ids bigint[], replacements text[], priorities integer[], options jsonb) , acdat.machine , defaultNULL, NULL, NULL, '{}'¹
Compile parallel 1D text arrays into a machine. Omitted IDs default to 1..N; NULL priorities default to 0.
acdat.compile(patterns bytea[], pattern_ids bigint[], replacements bytea[], priorities integer[], options jsonb) , acdat.machine , defaultNULL, NULL, NULL, '{}'¹
Binary array overload preserving arbitrary bytes (including \x00).
acdat.compile(text, bigint) , aggregate → acdat.machine , default—
Compile rows of (pattern, pattern_id). Returns NULL for zero rows.
acdat.compile(text, bigint, text, integer) , aggregate → acdat.machine , default—
Compile rows of (pattern, pattern_id, replacement, priority). Returns NULL for zero rows.
acdat.compile(bytea, bigint) , aggregate → acdat.machine , default—
Binary aggregate over (pattern, pattern_id). Returns NULL for zero rows.
acdat.compile(bytea, bigint, bytea, integer) , aggregate → acdat.machine , default—
Binary aggregate over (pattern, pattern_id, replacement, priority). Returns NULL for zero rows.

¹ Defaults apply starting at pattern_ids; patterns is required. options accepts NULL or {}.

Scan and replace

acdat.contains(text, acdat.machine) , boolean , default—
Return true on the first literal match and stop scanning immediately.
acdat.contains(bytea, acdat.machine) , boolean , default—
Binary overload of contains.
acdat.matches(input text, machine acdat.machine, policy text, max_matches integer) , setof acdat.hit , default'all_overlapping', 10000
Return 1-based byte and character offsets for each hit. Candidate limit is checked before overlap resolution.
acdat.matches(input bytea, machine acdat.machine, policy text, max_matches integer) , setof acdat.hit , default'all_overlapping', 10000
Binary overload; start_char and char_length are always NULL.
acdat.replace(input text, machine acdat.machine, policy text, max_replacements integer, max_output_bytes bigint) , text , default'leftmost_longest', 10000, 268435456
Single non-recursive pass rewrite. Errors if a selected match has a NULL replacement or exceeds a limit.
acdat.replace(input bytea, machine acdat.machine, policy text, max_replacements integer, max_output_bytes bigint) , bytea , default'leftmost_longest', 10000, 268435456
Binary overload of replace.

Overlap policies

all_overlapping , matches , defaultdefault for matches
Emit every candidate hit, including prefixes, suffixes, and duplicate literals with distinct IDs.
leftmost_longest , matches / replace , defaultdefault for replace
Leftmost start offset → longer pattern → lower priority integer → lower pattern_id → lower canonical ordinal.
leftmost_priority , matches / replace , default—
Leftmost start offset → lower priority integer → longer pattern → lower pattern_id → lower canonical ordinal.

Inspect and transport

acdat.info(acdat.machine) , jsonb , default—
Metadata JSON: engine, compiler/format versions, input kind, encoding, pattern/state/slot counts, and sizes.
acdat.export(acdat.machine) , bytea , default—
Serialize a compiled machine into a portable binary image.
acdat.validate(bytea) , boolean , default—
Verify a serialized image without raising an error on corruption.
acdat.import(bytea) , acdat.machine , default—
Validate and decode a serialized image; raises an error if malformed.
acdat.source_fingerprint(acdat.machine) , bytea , default—
32-byte SHA-256 digest of the canonical rule set and input kind.
acdat.build_fingerprint(acdat.machine) , bytea , default—
32-byte digest identifying rules plus compiler, engine, and format version.
acdat.artifact_checksum(acdat.machine) , bytea , default—
32-byte checksum of the serialized artifact payload.

Managed dictionary catalog

acdat.publish(p_dictionary_name text, p_semantic_version bigint, p_compiled_machine acdat.machine, p_source_reference jsonb) , bytea , defaultp_source_reference = NULL
Store an immutable ready build and return its 32-byte dictionary-scoped build_id.
acdat.activate(p_dictionary_name text, p_build_id bytea) , void , default—
Atomically point acdat.active_dictionary to a ready build.
acdat.retire_build(p_dictionary_name text, p_build_id bytea) , void , default—
Mark an inactive build as retired.
acdat.active_machine , view , default—
Active ready machines: name, input_kind, version, build_id, machine, info.
acdat.dictionary , table , default—
Dictionary name and fixed input_kind (text or bytea).
acdat.dictionary_version , table , default—
Semantic version, source_fingerprint, and optional source_ref JSON.
acdat.dictionary_build , table , default—
Build metadata, compiler/format/engine info, status (ready / retired), and checksum.
acdat.dictionary_build_data , table , default—
Compiled acdat.machine payload (STORAGE EXTERNAL) keyed by build_id.
acdat.active_dictionary , table , default—
Current active build_id pointer per dictionary.

Types and internal functions

acdat.machine , base type , default—
Variable-length compiled automaton (STORAGE = external).
acdat.hit , composite type , default—
(pattern_id bigint, start_byte integer, byte_length integer, start_char integer, char_length integer, priority integer).
machine_in / machine_out / machine_recv / machine_send , internal I/O , default—
Type I/O functions revoked from PUBLIC; invoked by PostgreSQL.
_compile_*_trans / _compile_final / _catalog_build_id , internal helpers , default—
Aggregate state transition/final and catalog digest helpers revoked from PUBLIC.

2 - pgs3

Turn PostgreSQL into a versioned S3 object endpoint backed by ordinary database tables. Use it when application rows and tenant objects belong in the same transaction, backup, and point-in-time recovery window.

pgs3 embeds an S3-compatible HTTP server directly inside PostgreSQL background workers. S3 clients (mc, rclone, boto3, DuckDB, s3fs) talk to the endpoint over SigV4 path-style HTTP, while SQL sessions read and write the exact same buckets and objects inside normal database transactions.

Note

pgs3 is currently in early alpha (v0.1.2, release acceptance on PostgreSQL 17–19 on Linux). Small-object throughput targets and the 100,000-object bucket fork target are still being optimized. Review the measured performance and limits before sizing production workloads.

Why store objects in PostgreSQL

Running a separate object store alongside PostgreSQL splits state across two systems: a database rollback can leave orphan blobs behind, backups capture two different timestamps, and tenant isolation has to be maintained twice. pgs3 collapses those boundaries into one PostgreSQL database:

  • One transaction boundary: Write application metadata and object bytes in the same SQL transaction—commit together or roll back together.
  • One backup and PITR timeline: Physical base backups and WAL archiving recover relational tables, object payloads, versions, and credentials to the same point in time.
  • Database-native multi-tenancy: Every S3 access key maps to a PostgreSQL NOLOGIN role. Bucket and object visibility is enforced by PostgreSQL Row-Level Security (RLS).
  • Always-on versioning and instant forks: Overwrites append new versions, ordinary deletes insert delete markers, and pgs3.fork_bucket() clones a bucket’s latest state by sharing content-addressed SHA-256 blobs.

When to use pgs3 (and when not to)

WorkloadRecommendationWhy
Application attachments, invoices, configs, or AI agent artifacts that must stay consistent with relational rowsUse pgs3Shared transactions, unified PITR, and zero extra storage cluster to operate
Multi-tenant SaaS workspaces or experiment checkpoints needing cheap bucket forksUse pgs3RLS tenant isolation and copy-on-write pgs3.fork_bucket()
Multi-terabyte media archives, high-fanout public CDN origins, or workloads requiring bucket policies/ACLs/lifecycle rulesUse a dedicated S3 store such as SiloDedicated object stores avoid PostgreSQL WAL amplification, TOAST overhead, and full-GET buffering

How pgs3 works

flowchart LR
    C["S3 Client (mc / rclone / SDK)"] -->|SigV4 Path-Style HTTP| W["pgs3 HTTP Workers"]
    W -->|"SET LOCAL ROLE (RLS)"| SQL["pgs3 SQL API"]
    APP["SQL Session / App"] -->|Direct Transaction| SQL
    SQL --> META["pgs3.bucket & pgs3.object"]
    SQL --> BLOB["pgs3.blob (SHA-256 Dedup)"]
    BLOB -->|"<= 64 KiB"| INLINE["Inline bytea"]
    BLOB -->|"> 64 KiB"| CHUNK["Chunked / Multipart Extents"]
  1. HTTP workers handle the wire protocol: Background workers listen on a shared SO_REUSEPORT TCP port (default 127.0.0.1:9000), verify AWS SigV4 signatures, and map each access key to its PostgreSQL tenant role.
  2. SQL enforces all semantics: Inside short transactions, workers run SET LOCAL ROLE and invoke the same pgs3.* SQL functions that direct SQL callers use. Versioning, preconditions, locking, and RLS isolation live in one place.
  3. Blobs are deduplicated by SHA-256: Every object version points to a canonical content-addressed blob. Small payloads stay inline (pgs3.inline_threshold, default 64 KiB); larger uploads stream into 4 MiB chunks (pgs3.chunk_size) without holding long database transactions.

2.1 - Getting started with pgs3

Install pgs3, launch a local S3 endpoint inside PostgreSQL, and walk through uploading, overwriting, deleting, and recovering an earlier version with mc (MinIO Client) in three minutes.

1. Install pgs3

Install the pgs3 package on a Linux PostgreSQL 17–19 server (PG16 is best effort; see Downloads for platform availability):

pig repo add pgsql -u
pig ext add pgs3

Need to build from source or spin up a test container instead? See Build from source or Docker.

2. Enable the extension and start the endpoint

Connect to your database as an administrator, create an unprivileged tenant role with an S3 key pair, and start the HTTP worker pool:

CREATE EXTENSION IF NOT EXISTS pgs3;

CREATE ROLE pgs3_demo NOLOGIN NOINHERIT
    NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;

SELECT pgs3.create_credential('PGS3DEMOKEY01', 'change-me-in-production-secret', 'pgs3_demo');
SELECT pgs3.start();

Confirm that the HTTP workers are listening on 127.0.0.1:9000:

SELECT worker_kind, status, listen_addr, port
FROM pgs3.worker_state
ORDER BY worker_kind;
 worker_kind | status  | listen_addr | port
-------------+---------+-------------+------
 gc          | running |             |
 http        | running | 127.0.0.1   | 9000
 http        | running | 127.0.0.1   | 9000
 launcher    | running |             |

pgs3.start() starts a dynamic pool for the current database without editing postgresql.conf. For persistent endpoints that boot with PostgreSQL, see Automatic startup.

3. Upload, version, and recover with mc

Using the MinIO Client (mc, packaged as mcli on some Linux distributions), register the local endpoint with SigV4 and path-style addressing (--path on):

  1. Add the alias and create a bucket:

    mc alias set pgs3 http://127.0.0.1:9000 PGS3DEMOKEY01 change-me-in-production-secret --api S3v4 --path on
    mc mb pgs3/demo
  2. Upload a file and read it back:

    printf 'v1: hello pgs3\n' > hello.txt
    mc cp hello.txt pgs3/demo/notes/hello.txt
    mc cat pgs3/demo/notes/hello.txt
    v1: hello pgs3
  3. Overwrite the object and delete it—pgs3 keeps versioning permanently enabled, so an ordinary delete writes a delete marker instead of losing history:

    printf 'v2: updated\n' > hello.txt
    mc cp hello.txt pgs3/demo/notes/hello.txt
    mc rm pgs3/demo/notes/hello.txt
    mc ls --versions pgs3/demo/notes/hello.txt
    [2026-12-01 04:01:12 UTC]     0B 3 DEL v3 notes/hello.txt
    [2026-12-01 04:01:08 UTC]    12B 2 PUT v2 notes/hello.txt
    [2026-12-01 04:01:02 UTC]    15B 1 PUT v1 notes/hello.txt
  4. Recover the first revision by its version ID (1):

    mc cat --version-id 1 pgs3/demo/notes/hello.txt
    v1: hello pgs3

4. Clean up

When you are done testing, stop the worker pool and remove the local alias:

psql -c 'SELECT pgs3.stop()'
mc alias rm pgs3
rm -f hello.txt

Next steps

2.2 - Connect S3 clients

Configure mc, rclone, Python boto3, DuckDB httpfs, and s3fs to talk to pgs3. Every client needs three settings: SigV4 signing, path-style addressing, and an explicit endpoint URL.

Any S3 client that speaks AWS Signature Version 4 and path-style URLs (http://host:9000/bucket/key) works against pgs3. Because pgs3 does not implement virtual-host routing (http://bucket.host:9000/key), always disable virtual-host addressing in your client configuration.

All examples below reuse the shell variables from Getting started (or your production HTTPS proxy URL and tenant credentials):

export PGS3_ENDPOINT=http://127.0.0.1:9000
export PGS3_ACCESS_KEY=PGS3DEMOACCESS01
export PGS3_SECRET_KEY='<your-secret-key>'
export PGS3_BUCKET=my-artifacts

mc (MinIO Client)

mc (packaged as mcli on some Linux distributions) is the fastest day-to-day CLI for buckets, objects, directory mirrors, version history, and presigned download links.

Configure an alias

Pass --api S3v4 --path on so mc always signs with SigV4 and sends path-style requests:

mc alias set pgs3 "$PGS3_ENDPOINT" "$PGS3_ACCESS_KEY" "$PGS3_SECRET_KEY" --api S3v4 --path on
mc ls pgs3

Everyday object operations

# Create a bucket and upload with Content-Type and custom metadata
mc mb "pgs3/$PGS3_BUCKET"
printf 'hello pgs3\n' > hello.txt
mc cp --attr "Content-Type=text/plain;owner=docs" hello.txt "pgs3/$PGS3_BUCKET/notes/hello.txt"

# Inspect metadata, read content, and list a prefix
mc stat "pgs3/$PGS3_BUCKET/notes/hello.txt"
mc cat  "pgs3/$PGS3_BUCKET/notes/hello.txt"
mc ls   "pgs3/$PGS3_BUCKET/notes/"

# Server-side copy (reuses the underlying SHA-256 blob without re-uploading)
mc cp "pgs3/$PGS3_BUCKET/notes/hello.txt" "pgs3/$PGS3_BUCKET/archive/hello.txt"

# Mirror a local directory into a dedicated prefix
mc mirror ./reports "pgs3/$PGS3_BUCKET/reports"

Work with object versions

pgs3 keeps versioning permanently enabled on every bucket:

# List every revision and delete marker for a key
mc ls --versions "pgs3/$PGS3_BUCKET/notes/hello.txt"

# Read or download a specific historical version
mc cat --version-id 1 "pgs3/$PGS3_BUCKET/notes/hello.txt"
mc cp  --version-id 1 "pgs3/$PGS3_BUCKET/notes/hello.txt" ./hello-v1.txt

# Ordinary delete (writes a delete marker; earlier versions remain intact)
mc rm "pgs3/$PGS3_BUCKET/notes/hello.txt"

# Permanent delete of a single version
mc rm --version-id 1 "pgs3/$PGS3_BUCKET/notes/hello.txt"

Generate a temporary download URL

mc share download signs a presigned GET URL locally without calling any extra API:

mc share download --expire=10m "pgs3/$PGS3_BUCKET/archive/hello.txt"
Note

MinIO-specific and unsupported S3 subcommands (mc admin, mc anonymous, mc ilm, mc retention, mc tag) are outside the pgs3 API subset and return 501 NotImplemented.

rclone

rclone is part of the pgs3 release acceptance matrix and works well for automated sync jobs, integrity verification, and large multipart transfers.

Configuration file

Add a remote to ~/.config/rclone/rclone.conf:

[pgs3]
type = s3
provider = Other
endpoint = http://127.0.0.1:9000
region = us-east-1
force_path_style = true
access_key_id = PGS3DEMOACCESS01
secret_access_key = <your-secret-key>

To avoid storing secrets in a config file, replace access_key_id and secret_access_key with env_auth = true and export AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY, or configure the remote purely with environment variables (RCLONE_CONFIG_PGS3_TYPE=s3, RCLONE_CONFIG_PGS3_PROVIDER=Other, RCLONE_CONFIG_PGS3_ENDPOINT, RCLONE_CONFIG_PGS3_FORCE_PATH_STYLE=true, RCLONE_CONFIG_PGS3_REGION=us-east-1, plus access/secret keys).

Sync, verify, and restore

# Create a bucket (idempotent if you already own it)
rclone mkdir "pgs3:$PGS3_BUCKET"

# Mirror a local folder into a dedicated prefix
rclone sync ./reports "pgs3:$PGS3_BUCKET/reports" --checkers 4 --transfers 4

# Verify byte-for-byte integrity by downloading and comparing hashes
rclone check --download ./reports "pgs3:$PGS3_BUCKET/reports"

# Download back to a local directory
rclone copy "pgs3:$PGS3_BUCKET/reports" ./reports-restored
Warning

Only run rclone sync against a dedicated destination prefix. Any object under that destination prefix that does not exist in the local source directory receives a delete marker.

Python (boto3)

Set signature_version="s3v4" and addressing_style="path" in botocore.config.Config. Large files automatically use multipart upload (every non-final part must be at least 5 MiB).

Upload, conditional writes, and download

import os
import boto3
from botocore.config import Config

s3 = boto3.client(
    "s3",
    endpoint_url=os.environ["PGS3_ENDPOINT"],
    aws_access_key_id=os.environ["PGS3_ACCESS_KEY"],
    aws_secret_access_key=os.environ["PGS3_SECRET_KEY"],
    region_name="us-east-1",
    config=Config(
        signature_version="s3v4",
        s3={"addressing_style": "path"},
        retries={"max_attempts": 3},
        request_checksum_calculation="when_supported",
        response_checksum_validation="when_supported",
    ),
)

bucket = os.environ["PGS3_BUCKET"]

# Create only if the key does not exist yet (returns 412 PreconditionFailed otherwise)
put_res = s3.put_object(
    Bucket=bucket,
    Key="python/config.json",
    Body=b'{"mode":"v1"}\n',
    ContentType="application/json",
    Metadata={"service": "worker"},
    IfNoneMatch="*",
)
etag = put_res["ETag"]

# Compare-and-swap update guarded by the current ETag
s3.put_object(
    Bucket=bucket,
    Key="python/config.json",
    Body=b'{"mode":"v2"}\n',
    ContentType="application/json",
    IfMatch=etag,
)

# Read back the latest revision
obj = s3.get_object(Bucket=bucket, Key="python/config.json")
assert obj["Body"].read() == b'{"mode":"v2"}\n'

Presigned GET and PUT URLs

Presigned URLs delegate temporary read or write access to browsers or untrusted workers without sharing the tenant secret. They enforce the exact HTTP method, path, query string, expiry, and the underlying PostgreSQL role’s RLS visibility.

import urllib.request

put_url = s3.generate_presigned_url(
    "put_object",
    Params={"Bucket": bucket, "Key": "python/upload.txt"},
    ExpiresIn=300,
)
get_url = s3.generate_presigned_url(
    "get_object",
    Params={"Bucket": bucket, "Key": "python/upload.txt"},
    ExpiresIn=300,
)

req = urllib.request.Request(put_url, data=b"uploaded via presigned PUT\n", method="PUT")
with urllib.request.urlopen(req) as resp:
    assert resp.status == 200

with urllib.request.urlopen(get_url) as resp:
    assert resp.read() == b"uploaded via presigned PUT\n"

Always distribute presigned URLs over HTTPS through a TLS-terminating proxy in production.

DuckDB (httpfs)

DuckDB can query Parquet, CSV, or JSON files stored inside pgs3 over range-capable HTTP GET requests.

  1. Generate a Parquet file and upload it with mc:

    duckdb -c "COPY (SELECT i AS id, 'row-' || i AS label FROM range(100) t(i)) TO 'sample.parquet' (FORMAT PARQUET)"
    mc cp sample.parquet "pgs3/$PGS3_BUCKET/analytics/sample.parquet"
  2. Query it directly from DuckDB (ENDPOINT expects host:port without a scheme; set USE_SSL true behind a TLS proxy):

    INSTALL httpfs;
    LOAD httpfs;
    
    CREATE SECRET pgs3_local (
        TYPE s3,
        KEY_ID 'PGS3DEMOACCESS01',
        SECRET '<your-secret-key>',
        REGION 'us-east-1',
        ENDPOINT '127.0.0.1:9000',
        URL_STYLE 'path',
        USE_SSL false
    );
    
    SELECT count(*), min(id), max(id)
    FROM read_parquet('s3://my-artifacts/analytics/sample.parquet');
    ┌──────────────┬─────────┬─────────┐
    │ count_star() │ min(id) │ max(id) │
    │    int64     │  int64  │  int64  │
    ├──────────────┼─────────┼─────────┤
    │          100 │       0 │      99 │
    └──────────────┴─────────┴─────────┘

s3fs (Linux FUSE mount)

On Linux hosts with /dev/fuse and fusermount3, you can mount a pgs3 bucket as a local directory for legacy tools that only read and write filesystem paths:

umask 077
printf '%s:%s\n' "$PGS3_ACCESS_KEY" "$PGS3_SECRET_KEY" > /tmp/pgs3.passwd
mkdir -p /tmp/pgs3-mnt

s3fs "$PGS3_BUCKET" /tmp/pgs3-mnt \
  -o passwd_file=/tmp/pgs3.passwd \
  -o "url=$PGS3_ENDPOINT" \
  -o use_path_request_style

ls -la /tmp/pgs3-mnt
fusermount3 -u /tmp/pgs3-mnt
rm -f /tmp/pgs3.passwd

s3fs translates renames and in-place edits into multiple S3 API calls and does not provide POSIX file locking or atomic directory moves. Do not place databases, Git repositories, or lock-sensitive workloads on an s3fs mount.

2.3 - SQL workflows, versioning, and multi-tenancy

Go beyond standard S3 with PostgreSQL-native workflows: commit objects in the same transaction as relational rows, restore historical versions, fork whole buckets without copying bytes, and isolate tenants with RLS.

HTTP clients see pgs3 as an S3 endpoint, but inside PostgreSQL the exact same buckets and objects are accessible through SQL functions. That unlocks capabilities a standalone object store cannot offer: atomic cross-table transactions, zero-byte bucket forks, one-call version promotion, and PostgreSQL Row-Level Security (RLS).

How storage and deduplication work

Understanding three storage details explains why pgs3 operations behave the way they do:

  • Content-addressed blobs (pgs3.blob): Every non-delete object version references a physical blob keyed by its SHA-256 digest. Uploading the same bytes twice—or copying, restoring, or forking objects—increments a reference count instead of duplicating payload bytes.
  • Inline vs. chunked layout: Blobs up to pgs3.inline_threshold (default 64 KiB) store one inline copy in pgs3.blob. Larger blobs are split into 4 MiB chunks (pgs3.chunk_size) across hash-partitioned pgs3.chunk tables; completed multipart uploads stitch ordered pgs3.blob_extent references together without rewriting the uploaded parts.
  • Short-transaction concurrency: Same-key writes acquire a key-level lock so precondition checks (If-None-Match, If-Match) and version publication are serialized atomically. Streaming uploads commit each chunk in its own short transaction and stay invisible until the final commit publishes the object version.

For full schema diagrams and design rationale, see design.md, schema.md, and decisions.md.

1. Commit business rows and objects atomically

A classic failure mode with external object stores is writing a file to S3 and then failing to insert the matching database row (or rolling back the database row while leaving an orphan object behind). With pgs3, both live inside one PostgreSQL transaction.

Assume tenant_app is an unprivileged tenant role created as shown in Manage tenants and credentials:

CREATE TABLE app_reports (
    report_id   bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    title       text NOT NULL,
    bucket_name text NOT NULL,
    object_key  text NOT NULL,
    version_id  bigint NOT NULL,
    created_at  timestamptz NOT NULL DEFAULT now()
);
GRANT INSERT, SELECT ON app_reports TO tenant_app;

BEGIN;
SET LOCAL ROLE tenant_app;

SELECT pgs3.create_bucket('reports');

WITH uploaded AS (
    SELECT *
    FROM pgs3.put(
        'reports',
        '2026/q4-summary.json',
        convert_to('{"revenue":1280000,"currency":"USD"}', 'UTF8'),
        'application/json',
        '{"author":"billing"}'::jsonb
    )
)
INSERT INTO app_reports (title, bucket_name, object_key, version_id)
SELECT 'Q4 Summary', 'reports', u.key, u.version_id
FROM uploaded AS u
RETURNING report_id, bucket_name, object_key, version_id;

COMMIT;
 report_id | bucket_name |      object_key      | version_id
-----------+-------------+----------------------+------------
         1 | reports     | 2026/q4-summary.json |          1

If anything in the transaction fails before COMMIT, both the app_reports row and the pgs3 object disappear together. Once committed, any S3 client authenticated as tenant_app can immediately download reports/2026/q4-summary.json.

2. Version history and instant rollback

Every overwrite in pgs3 creates a new monotonically ordered version_id, and every ordinary delete inserts a delete marker. Calling pgs3.restore() promotes a chosen historical version back to the latest state by appending a new version row that points to the original SHA-256 blob—history is never rewritten.

BEGIN;
SET LOCAL ROLE tenant_app;

-- Write v1 and capture its version_id in psql
SELECT (pgs3.put('reports', 'prompts/system.txt', convert_to('v1: strict mode', 'UTF8'))).version_id
    AS v1_id \gset

-- Overwrite with a buggy v2
SELECT (pgs3.put('reports', 'prompts/system.txt', convert_to('v2: broken prompt', 'UTF8'))).version_id;

-- Promote v1 back to latest (creates v3 pointing to v1's blob)
SELECT version_id, size, etag
FROM pgs3.restore('reports', 'prompts/system.txt', :v1_id);

-- Verify the latest content is back to v1
SELECT convert_from((pgs3.get('reports', 'prompts/system.txt')).body, 'UTF8') AS current_body;

COMMIT;
 current_body
-----------------
 v1: strict mode

You can also pass p_if_match => '<current-etag>' to pgs3.restore() to abort the rollback if another writer updated the key in the meantime. Over HTTP, pgs3 exposes the same operation via its extension route POST /{bucket}/{key}?restore&versionId={id}.

3. Fork a bucket without copying payload bytes

pgs3.fork_bucket() creates a brand-new bucket populated with the latest object versions (and delete markers) of a source bucket. Underlying SHA-256 blobs are shared via reference counting; only metadata rows and reference counts are written. Subsequent writes to either bucket are completely independent.

This is especially useful for AI agent experiment branches, pre-release staging checkpoints, or reproducible evaluation snapshots:

BEGIN;
SET LOCAL ROLE tenant_app;

-- Fork the latest state of 'reports' into a new experiment bucket
SELECT pgs3.fork_bucket('reports', 'reports-exp-42') AS copied_entries;

-- Mutate the forked bucket freely
SELECT pgs3.put('reports-exp-42', 'prompts/system.txt', convert_to('experiment prompt', 'UTF8'));

-- Confirm the source bucket is untouched
SELECT 'source' AS side, convert_from((pgs3.get('reports', 'prompts/system.txt')).body, 'UTF8') AS body
UNION ALL
SELECT 'fork',   convert_from((pgs3.get('reports-exp-42', 'prompts/system.txt')).body, 'UTF8');

COMMIT;
  side  |       body
--------+-------------------
 source | v1: strict mode
 fork   | experiment prompt

Keep two constraints in mind:

  • The destination bucket must not already exist.
  • Forking shares physical bytes, so disk growth for large blobs is minimal, but it still inserts metadata rows, updates indexes, and generates WAL proportional to the number of latest entries in the source bucket.

4. Multi-tenancy and credential lifecycle

How tenant isolation works

pgs3 separates the runtime service identity from tenant identities:

  1. Service role (pgs3.server_role, default pgs3_server): Created automatically when the extension is installed. HTTP workers connect as this restricted NOLOGIN NOINHERIT role only to look up credentials and switch roles.
  2. Tenant roles: Ordinary, unprivileged NOLOGIN NOINHERIT roles that you create (one per customer, team, or agent workspace). When you bind a credential with pgs3.create_credential(), pgs3 grants pgs3_server SET-only membership in that tenant role.
  3. Per-request RLS: After verifying a request’s SigV4 signature, the HTTP worker executes SET LOCAL ROLE <tenant> inside the request transaction. Row-Level Security policies ensure each tenant only sees and modifies buckets owned by roles it has USAGE membership in.
Caution

Never bind a SUPERUSER, BYPASSRLS, CREATEROLE, CREATEDB, or REPLICATION role to an S3 credential—pgs3.create_credential() rejects elevated roles by design.

Provision two isolated tenants

Run credential administration as a database operator (credential functions are revoked from PUBLIC):

-- Create two isolated, unprivileged tenant roles
CREATE ROLE tenant_alice NOLOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;
CREATE ROLE tenant_bob   NOLOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;

-- Bind distinct access keys (generate secrets externally with openssl rand -hex 32)
SELECT pgs3.create_credential('AKIAALICE0000001', '<alice-secret>', 'tenant_alice');
SELECT pgs3.create_credential('AKIABOB000000001', '<bob-secret>',   'tenant_bob');

Verify isolation in SQL—tenant_bob cannot see or read tenant_alice’s bucket:

BEGIN;
SET LOCAL ROLE tenant_alice;
SELECT pgs3.create_bucket('alice-private');
SELECT pgs3.put('alice-private', 'secret.txt', convert_to('for alice only', 'UTF8'));
COMMIT;

BEGIN;
SET LOCAL ROLE tenant_bob;
SELECT * FROM pgs3.list_buckets();  -- returns 0 rows
COMMIT;

Rotate, suspend, and audit credentials

Issue separate access keys per client or service so you can rotate or revoke one without disrupting others:

-- Rotate the signing secret in place (run over a protected TLS/local session)
SELECT pgs3.rotate_credential('AKIAALICE0000001', '<new-alice-secret>');

-- Temporarily suspend a compromised key (immediately blocks new S3 requests)
SELECT pgs3.set_credential_enabled('AKIAALICE0000001', false);

-- Reassign a key to another unprivileged tenant role
SELECT pgs3.set_credential_role('AKIAALICE0000001', 'tenant_alice_v2');

-- Permanently remove an unused key
SELECT pgs3.delete_credential('AKIAALICE0000001');

-- Audit non-secret credential columns
SELECT access_key, role_name, enabled, created_at
FROM pgs3.credential
ORDER BY access_key;

Tenant SQL functions default to EXECUTE for PUBLIC, which allows any database role with CONNECT to create its own buckets while keeping other tenants’ buckets hidden via RLS. If bucket creation must be allowlisted, revoke EXECUTE on pgs3.create_bucket(text, jsonb) from PUBLIC and grant it only to approved roles. Never grant tenants SELECT on pgs3.credential.

For the full list of SQL signatures, see the SQL reference.

2.4 - Deploy and operate pgs3

Run pgs3 persistently on PostgreSQL startup, build from source or Docker, terminate TLS in Nginx, route primary/standby traffic, and handle backups, monitoring, and upgrades.

Each pgs3 endpoint serves one PostgreSQL database on Linux and speaks plain HTTP on a local SO_REUSEPORT listener. Treat pgs3 as a database-resident service: terminate TLS at a reverse proxy, budget background workers and WAL headroom, and recover objects with PostgreSQL physical backups.

For throughput benchmarks and workload boundaries, see Performance and limits.

1. Persistent automatic startup

While SELECT pgs3.start() is convenient for quick experiments, production instances should register the static launcher through shared_preload_libraries so the HTTP pool starts automatically with PostgreSQL.

  1. Add pgs3 to postgresql.conf (append to any existing preload entries):

    shared_preload_libraries = 'pgs3'
    pgs3.enabled = on
    pgs3.target_database = 'appdb'
    pgs3.listen_addr = '127.0.0.1'
    pgs3.port = 9000
    pgs3.workers = 4
    max_worker_processes = 16
  2. Size max_worker_processes to cover the launcher (1), the GC worker (1), pgs3.workers, parallel query workers, and any other preloaded extensions.

  3. Run CREATE EXTENSION IF NOT EXISTS pgs3; in pgs3.target_database (if provisioning in two stages, leave pgs3.enabled = off until the extension is created, then enable and restart).

  4. Restart PostgreSQL and confirm the pool is running before opening traffic:

    SELECT worker_kind, desired, status, count(*)
    FROM pgs3.worker_state
    GROUP BY 1, 2, 3
    ORDER BY 1, 2, 3;

2. Terminate TLS in Nginx

pgs3 does not terminate TLS. Bind pgs3.listen_addr to 127.0.0.1 and place Nginx in front of it.

Three proxy rules are essential for SigV4 verification:

  • Forward the exact client Host header including any non-default port ($http_host).
  • Omit any trailing path or slash on proxy_pass so Nginx preserves the raw signed URI verbatim.
  • Disable request and response buffering so large streaming PUTs and Range GETs do not stall on proxy disk.
upstream pgs3_backend {
    server 127.0.0.1:9000;
    keepalive 64;
}

server {
    listen 443 ssl;
    server_name s3.example.internal;

    ssl_certificate     /etc/nginx/tls/s3.crt;
    ssl_certificate_key /etc/nginx/tls/s3.key;

    # Cap upload size to match your tested memory and WAL budget
    client_max_body_size 100m;
    client_body_timeout 300s;

    location / {
        # No URI component on proxy_pass: preserves the signed raw path
        proxy_pass http://pgs3_backend;
        proxy_http_version 1.1;
        proxy_set_header Host $http_host;
        proxy_set_header Connection "";
        proxy_request_buffering off;
        proxy_buffering off;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }
}

3. Primary and standby routing

  • Route all writes and read-after-write traffic to the primary. A hot standby rejects write operations with 503 ServiceUnavailable.
  • Standby reads are eventually consistent: Streaming replication lag can return slightly older versions, and recovery conflicts may cancel long reads. Request metrics backed by writable tables are unavailable during recovery.
  • Health checks: Probe SELECT NOT pg_is_in_recovery(), confirm desired HTTP workers are running in pgs3.worker_state, and run a lightweight signed read (such as HeadBucket).
  • Safe retries: Before retrying an interrupted version-sensitive write, check whether it already committed or guard it with If-None-Match: * or If-Match: "<etag>". Fence the old primary during failover before reopening writes.

4. Backup, PITR, and recovery

Use PostgreSQL physical base backups (including all tablespaces) plus WAL archiving / PITR to recover relational tables, object payloads, versions, and credentials to one consistent point in time.

Caution

SigV4 verification requires recoverable signing secrets stored in pgs3.credential. Always encrypt physical backups and WAL archives and restrict access to them. Logical pg_dump / pg_restore and logical replication are not supported recovery paths for pgs3 object state.

Keep client traffic blocked after a restore until you complete this checklist:

  1. Verify pgs3.extension_version() matches the installed shared library.
  2. Check pending uploads and reference counts; sample inline and chunked objects to verify content hashes.
  3. Run an end-to-end signed read/write smoke test and confirm cross-tenant isolation.
  4. Disable or rotate any credentials that PITR resurrected from before an earlier revocation.

5. Monitor and troubleshoot

Inspect live worker status and aggregated S3 request counters from SQL:

SELECT worker_kind, desired, status, count(*)
FROM pgs3.worker_state
GROUP BY 1, 2, 3;

TABLE pgs3.stats;

Track desired vs. running workers, error counts, latency buckets, in-flight requests, transferred bytes, pending upload age, and GC backlog (counters flush periodically). At the PostgreSQL layer, monitor dead tuples, pgs3.chunk partitions, TOAST bloat, checkpoints, WAL generation, and replication lag. Keep autovacuum active and run ANALYZE after bulk loads or large bucket forks.

Note

LISTEN pgs3 emits operation classes only (not full payloads or replayable streams). Consumers that need durable event replay should record events in a separate table or queue.

Safe configuration changes

Change one GUC at a time, reload (SELECT pg_reload_conf()), and verify both pgs3.worker_state and a real signed request on the updated listener. A failed port bind can leave the previous listener active. Drain client traffic before calling pgs3.stop() or restarting PostgreSQL. See Reload vs. restart.

Common issues

SymptomWhat to check
TCP connects, but HTTP returns 403 / 500Check pgs3.worker_state, pgs3.target_database, and whether pgs3.server_role attributes or grants drifted (launcher stops HTTP listeners on drift).
SignatureDoesNotMatch behind NginxConfirm Host (with port), raw request URI (no URI suffix on proxy_pass), clock skew (≤ 15 min), path-style addressing, and us-east-1 region.
Pending uploads stay in pgs3.uploadCheck lease expiry (5 min) and pending retention (24 h), and verify the gc worker is running in pgs3.worker_state.
Writes return 503 ServiceUnavailableTraffic is hitting a read-only standby; route writes to the primary.
Requests return 503 SlowDownQueries hit pgs3.statement_timeout_ms; inspect lock contention or slow disk/WAL checkpoints.

6. Upgrade and rollback

Versions 0.1.0 and 0.1.1 support in-place SQL upgrades to 0.1.2.

  1. Take a verified physical backup and drain S3 traffic.

  2. Install the updated pgs3 package (matching the PostgreSQL major/minor) and restart PostgreSQL.

  3. Update the extension catalog in each database using pgs3:

    ALTER EXTENSION pgs3 UPDATE TO '0.1.2';
    SELECT pgs3.extension_version();
  4. Re-verify bucket listing, object reads/writes, and tenant isolation before reopening traffic. If rollback is needed, restore the physical backup from step 1.

7. Build from source or Docker

When packages are not available for your environment—or when testing locally in Docker—build directly from the release tag:

git clone --branch v0.1.2 --depth 1 https://github.com/pgsty/pgs3.git
cd pgs3
make image PG_MAJOR=17

This creates a local pgs3-test:pg17 container image. Run a disposable instance exposing PostgreSQL on 55432 and the S3 endpoint on 9000:

docker run -d --name pgs3-demo \
  -e POSTGRES_PASSWORD=postgres \
  -p 127.0.0.1:55432:5432 \
  -p 127.0.0.1:9000:9000 \
  pgs3-test:pg17 \
  postgres -c max_worker_processes=16 -c pgs3.listen_addr=0.0.0.0 -c pgs3.workers=2

For a native Linux build, install Rust ≥ 1.99.1, PostgreSQL server headers, and cargo-pgrx 0.20.1, then run make package PG_MAJOR=17 and copy the staged shared library, control file, and SQL scripts into your PostgreSQL directories. Packages built against PG17.12 or PG18.7 headers require at least that server minor version.

2.5 - Performance and limits

Measured PUT/GET throughput and latency curves comparing pgs3 v0.1.2 against MinIO on the same host, scale benchmarks for LIST and bucket forks, and hard workload boundaries.

All figures below come from the v0.1.2 release acceptance sweep on Apple M5 Max (Docker Desktop arm64, 16 vCPU, PostgreSQL 17.10, 16 pgs3 HTTP workers, shared_buffers = 1GB, fsync = on, synchronous_commit = on, default 4 MiB chunks) compared against single-disk MinIO (RELEASE.2026-08-04) on the same machine, with zero request or integrity errors across all 11 tested sizes.

Full raw curves and environment details: perf.md · acceptance.md.

1. PUT throughput: pgs3 vs. MinIO

Objects up to 64 KiB take the single-transaction direct-PUT path; larger objects stream into 4 MiB chunks.

backgroundColor: transparent
tooltip:
  trigger: axis
  axisPointer:
    type: shadow
legend:
  top: 6
grid:
  left: 16
  right: 20
  top: 48
  bottom: 16
  containLabel: true
xAxis:
  type: category
  data: ["4 KiB", "16 KiB", "64 KiB", "256 KiB", "1 MiB", "4 MiB", "8 MiB", "16 MiB", "64 MiB"]
yAxis:
  type: value
  name: "MiB/s"
series:
  - name: "pgs3"
    type: bar
    barMaxWidth: 26
    itemStyle:
      color: "#3b82f6"
      borderRadius: [4, 4, 0, 0]
    data: [6.1, 38.2, 227.9, 258.4, 284.4, 258.4, 167.9, 170.3, 156.6]
  - name: "MinIO"
    type: bar
    barMaxWidth: 26
    itemStyle:
      color: "#94a3b8"
      borderRadius: [4, 4, 0, 0]
    data: [6.5, 26.6, 105.8, 415.4, 1054.9, 705.2, 393.3, 441.6, 324.0]

2. GET throughput: pgs3 vs. MinIO

pgs3 is strongest on small-to-medium payloads (4 KiB – 4 MiB), peaking at 1.80 GiB/s on 1 MiB reads. Above 8 MiB, full-object GET currently materializes a SQL bytea and a Rust buffer before sending, which caps throughput on very large single-shot reads.

backgroundColor: transparent
tooltip:
  trigger: axis
  axisPointer:
    type: shadow
legend:
  top: 6
grid:
  left: 16
  right: 20
  top: 48
  bottom: 16
  containLabel: true
xAxis:
  type: category
  data: ["4 KiB", "16 KiB", "64 KiB", "256 KiB", "1 MiB", "4 MiB", "8 MiB", "16 MiB", "64 MiB"]
yAxis:
  type: value
  name: "MiB/s"
series:
  - name: "pgs3"
    type: bar
    barMaxWidth: 26
    itemStyle:
      color: "#10b981"
      borderRadius: [4, 4, 0, 0]
    data: [15.9, 62.3, 384.7, 1257.4, 1802.9, 1476.4, 793.2, 506.3, 133.6]
  - name: "MinIO"
    type: bar
    barMaxWidth: 26
    itemStyle:
      color: "#94a3b8"
      borderRadius: [4, 4, 0, 0]
    data: [16.2, 40.3, 286.0, 1375.5, 2927.4, 4373.4, 4271.4, 3071.9, 1008.4]

3. Latency and IOPS summary

Object sizePUT p50PUT ops/sPUT MiB/sGET p50GET ops/sGET MiB/s
4 KiB5.78 ms1,5566.12.86 ms4,06515.9
16 KiB4.66 ms2,44438.23.34 ms3,99062.3
64 KiB2.73 ms3,646227.92.15 ms6,155384.7
256 KiB8.56 ms1,034258.42.81 ms5,0301,257.4
1 MiB31.89 ms284284.45.32 ms1,8031,802.9
8 MiB47.40 ms21167.939.47 ms99793.2
64 MiB395.76 ms2.4156.6444.68 ms2.1133.6

Notice the direct-PUT boundary at 64 KiB: 64 KiB completes in 2.73 ms p50, whereas 65,537 bytes crosses into the staged upload path at 8.16 ms p50.

4. Scale tests and release acceptance gates

CheckTargetMeasuredStatus
8 MiB PUT throughput (1 connection)≥ 150 MiB/s167.9 MiB/sPass
1,000,000-key SQL LIST (flat)< 5 ms2.36 msPass
1,000,000-key SQL LIST (/ delimiter)< 10 ms9.49 msPass
Small-object GET (p50 / ops/s)< 0.5 ms / ≥ 30,000/s3.34 ms / 3,990/sBelow target
Small-object PUT throughput≥ 5,000/s1,556/sBelow target
100,000-object fork_bucket< 1,000 ms1,944 ms (154 MiB WAL)Below target

Always re-benchmark your own object-size distribution, concurrency, and disk durability settings on target hardware before capacity planning.

5. Known limits and boundaries

  • Memory budgeting on full GET: A non-ranged GetObject materializes a SQL bytea and a Rust buffer before streaming out. Use Range GET for partial reads, and enforce a conservative upload cap (client_max_body_size) in your reverse proxy rather than relying on the 5 GiB protocol parser ceiling.
  • Key and chunk limits: Object keys hold up to 1,024 UTF-8 bytes and cannot contain NUL. Each signed aws-chunked chunk is capped at 1 MiB.
  • Single-database Linux listener: One pgs3 worker pool serves one PostgreSQL database on Linux (SO_REUSEPORT). HTTP/1.1 keep-alive connections process requests sequentially per connection.
  • Non-snapshot LIST pagination: Continuation tokens walk indexed key order without holding a cross-page snapshot across concurrent writes.
  • Shared cluster resources: HTTP workers, TOAST storage, and blob writes share CPU, RAM, I/O, and WAL bandwidth with relational queries on the same instance.
  • API subset: Bucket policies, ACLs, CORS, object tagging, lifecycle/TTL rules, virtual-host addressing, and multi-range GET are outside the S3 API subset.

2.6 - pgs3 reference

Complete lookup for pgs3 v0.1.2: server GUCs, S3 API compatibility subset, SQL functions, and SQLSTATE-to-S3 error mappings.

Server configuration (GUCs)

All nine pgs3.* parameters have SIGHUP context, though some changes only take effect for new requests or require a restart as noted below.

pgs3.enabled , boolean , defaultoff
Register the static launcher on server startup when pgs3 is in shared_preload_libraries. Dynamic pgs3.start() ignores this flag.
pgs3.workers , integer (1–64) , default4
Desired number of HTTP background workers. Each consumes one max_worker_processes slot.
pgs3.listen_addr , string (IP) , default127.0.0.1
IPv4 or IPv6 bind address for HTTP workers. Keep on loopback and terminate TLS in a reverse proxy.
pgs3.port , integer (1–65535) , default9000
Shared SO_REUSEPORT TCP port for HTTP workers.
pgs3.inline_threshold , integer (bytes, 0–1 GiB) , default65536
Largest physical blob stored inline in pgs3.blob for new writes. Direct single-transaction PUT has an additional 64 KiB cap.
pgs3.chunk_size , integer (bytes, 64 KiB–16 MiB) , default4194304
Chunk size for staged uploads exceeding the inline threshold; snapshotted per upload on admission.
pgs3.statement_timeout_ms , integer (ms, 1–3600000) , default30000
PostgreSQL statement/lock timeout for each SPI semantic transaction. Applies to new transactions.
pgs3.target_database , string , defaultpostgres
Database served by the preloaded static launcher. Changing the pool’s database requires a server restart.
pgs3.server_role , string , defaultpgs3_server
Restricted service identity used by HTTP workers. Custom roles must exist beforehand and be NOLOGIN NOINHERIT with no elevated attributes, no inbound members, and SET-only membership in tenant roles.

Inspect live values

SELECT name, setting, unit, context, source, pending_restart
FROM pg_settings
WHERE name LIKE 'pgs3.%'
ORDER BY name;

Reload vs. restart

  • Applies on SIGHUP reload: pgs3.workers, pgs3.listen_addr, pgs3.port, pgs3.statement_timeout_ms, pgs3.inline_threshold (new blobs), and pgs3.chunk_size (new uploads). Existing blobs keep their original physical layout. Always verify a real signed request after a port/address rebind because a failed bind can keep the old listener running.
  • Requires a server restart: Adding pgs3 to shared_preload_libraries, changing pgs3.enabled from off to on when the static launcher was not registered at boot, or changing pgs3.target_database.
  • Service role changes: Reconciling a changed pgs3.server_role on reload requires matching grants and lacks release acceptance testing; prefer a planned restart.

Fixed implementation thresholds

These limits are built into v0.1.2 and have no registered GUC:

  • Upload lease: 5 minutes; body-idle timeout: 60 seconds (renewed on subsequent body progress).
  • Pending upload retention: 24 hours; GC interval: every 60 seconds, up to 1,000 rows per batch.
  • SQL hash fallback limit: Optional pgs3.sql_hash_fallback_limit custom setting defaults to 134217728 bytes (128 MiB); packaged builds use Rust hash helpers instead.

S3 API compatibility

AreaSupported APIsBehavior and boundaries
BucketsListBuckets, CreateBucket, DeleteBucket, HeadBucket, GetBucketLocation, GetBucketVersioningVersioning is permanently Enabled. DeleteBucket requires an empty bucket (including historical versions); pending uploads alone are aborted atomically on delete.
ObjectsPutObject, GetObject, HeadObject, CopyObject, DeleteObject, DeleteObjectsSupports single Range, If-Match/If-None-Match/date conditions, x-amz-meta-* metadata, source versionId copies, and SHA-256 / MD5 / flexible checksums. DeleteObjects accepts up to 1,000 keys per batch.
ListingListObjects (V1), ListObjectsV2, ListObjectVersionsPrefix, delimiter, encoding-type=url, max-keys (0–1000), V1 markers, and V2 continuation tokens.
MultipartCreateMultipartUpload, UploadPart, ListParts, CompleteMultipartUpload, AbortMultipartUploadNon-final parts must be ≥ 5 MiB. UploadPartCopy and ListMultipartUploads are not supported.
Version restorePOST /{bucket}/{key}?restore&versionId={id}pgs3 extension route that publishes an older version as the new latest version (not AWS Glacier archival restore).

Signing and unsupported features

  • Supported auth: Header-based AWS SigV4 (FullHash, UNSIGNED-PAYLOAD, STREAMING-AWS4-HMAC-SHA256-PAYLOAD, STREAMING-UNSIGNED-PAYLOAD-TRAILER) and query-parameter presigned GET/PUT URLs (max expiry 7 days, clock skew ±15 minutes).
  • Outside the subset: Virtual-host bucket addressing, TLS termination, bucket policies, ACLs, CORS, object tagging, lifecycle/TTL rules, object lock/retention, multi-range GET, UploadPartCopy, and ListMultipartUploads.

SQL API

Tenant operations run under the caller’s PostgreSQL role (with RLS isolation); operator functions are revoked from PUBLIC.

Buckets and objects

pgs3.create_bucket(p_name text, p_config jsonb) , bucket_info , defaultp_config = '{}'
Create a bucket owned by the current role (idempotent for the same owner).
pgs3.list_buckets() , setof bucket_info , default—
List buckets visible to the current role.
pgs3.delete_bucket(p_name text) , boolean , default—
Delete an empty bucket (aborts leftover pending uploads).
pgs3.put(p_bucket text, p_key text, p_body bytea, p_content_type text, p_meta jsonb, p_if_none_match text, p_if_match text, p_checksum_sha256 bytea) , object_info , default'application/octet-stream', '{}', NULL, NULL, NULL
Atomically write a new object version; supports ETag preconditions and SHA-256 verification.
pgs3.head(p_bucket text, p_key text, p_version_id bigint, p_if_match text, p_if_none_match text) , object_info , defaultNULL, NULL, NULL
Read object metadata for the latest or specified version.
pgs3.get(p_bucket text, p_key text, p_version_id bigint, p_if_match text, p_if_none_match text) , object_data , defaultNULL, NULL, NULL
Read object metadata and full body bytea.
pgs3.get_range(p_bucket text, p_key text, p_start bigint, p_end bigint, p_version_id bigint, p_if_match text, p_if_none_match text) , bytea , defaultNULL, NULL, NULL, NULL
Read an inclusive 0-based byte slice of an object.
pgs3.copy(p_source_bucket text, p_source_key text, p_destination_bucket text, p_destination_key text, p_source_version_id bigint, p_content_type text, p_meta jsonb, p_if_none_match text, p_if_match text, p_source_if_match text) , object_info , defaultNULL for optional params
Copy an object or version by sharing its canonical SHA-256 blob.
pgs3.delete(p_bucket text, p_key text, p_version_id bigint) , delete_result , defaultp_version_id = NULL
Insert a delete marker when p_version_id is NULL, or permanently delete that version.
pgs3.list(p_bucket text, p_prefix text, p_delimiter text, p_start_after text, p_continuation_token text, p_max_keys integer) , setof list_entry , default'', NULL, NULL, NULL, 1000
List keys and common prefixes in indexed key order.
pgs3.restore(p_bucket text, p_key text, p_version_id bigint, p_if_match text) , object_info , defaultp_if_match = NULL
Publish a historical version’s payload as a new latest version.
pgs3.fork_bucket(p_source_bucket text, p_destination_bucket text, p_destination_config jsonb) , bigint , defaultp_destination_config = NULL
Create a new bucket sharing the source’s latest blobs and return the number of entries copied.

Credentials and runtime operations

pgs3.create_credential(p_access_key text, p_secret text, p_role_name name, p_enabled boolean) , boolean , defaultp_enabled = true
Operator only. Create an S3 key pair bound to an unprivileged tenant role.
pgs3.rotate_credential(p_access_key text, p_new_secret text) , boolean , default—
Operator only. Replace the signing secret for an existing key.
pgs3.set_credential_role(p_access_key text, p_role_name name) , boolean , default—
Operator only. Reassign an access key to another unprivileged tenant role.
pgs3.set_credential_enabled(p_access_key text, p_enabled boolean) , boolean , default—
Operator only. Suspend or re-enable an access key.
pgs3.delete_credential(p_access_key text) , boolean , default—
Operator only. Delete an access key.
pgs3.start() , boolean , default—
Operator only. Start a dynamic worker pool for the current database.
pgs3.stop() , boolean , default—
Operator only. Stop the dynamic worker pool in the current database.
pgs3.extension_version() , text , default—
Return the installed SQL catalog version of pgs3.
pgs3.worker_state , table , default—
Live launcher, GC, and HTTP worker status, listener address, and heartbeats.
pgs3.stats , view , default—
Aggregated HTTP request counters, errors, latency buckets, bytes, and GC/upload backlog.
pgs3.gc_pending_uploads(p_max_age interval, p_limit integer) , bigint , default—
Operator only. Clean up expired pending uploads in bounded batches.
pgs3.gc_blobs(p_limit integer) , bigint , default1000
Operator only. Delete unreferenced zero-refcount blobs in bounded batches.

SQLSTATE to S3 error mapping

SQLSTATEHTTPS3 error code
P3B01404NoSuchBucket
P3K01404NoSuchKey / NoSuchVersion
P3U01404NoSuchUpload
P3C01412PreconditionFailed
P3N01304NotModified (no XML body)
P3R01416InvalidRange
P3E01409BucketAlreadyExists
P3F01409BucketNotEmpty
P3H01400BadDigest
P3P01400InvalidPart / InvalidPartOrder / EntityTooSmall
P3S01400EntityTooLarge
42501403AccessDenied
25006503ServiceUnavailable (read-only standby)
57014503SlowDown (statement timeout)
0A000501NotImplemented
other500InternalError

An allowlisted pgs3.error=<code> diagnostic detail takes precedence to distinguish finer variants such as NoSuchVersion, InvalidBucketName, or EntityTooSmall. HEAD and 304 responses omit XML bodies. For the complete protocol-to-SQL mapping, see api-sql-mapping.md.

3 - opencc

Convert Chinese scripts and Mainland, Taiwan, and Hong Kong vocabulary directly inside PostgreSQL with embedded OpenCC dictionaries. Ideal for cross-script search indexes, regional content localization, script validation, and editorial proofreading.

opencc (developed in the pgsty/pg_opencc repository) compiles OpenCC and its full dictionary set directly into a single PostgreSQL shared library—no external dictionary files or system libopencc required at runtime.

Why run OpenCC inside PostgreSQL

Converting Simplified and Traditional Chinese in application code leaves your database unable to index or constrain normalized text. Because opencc embeds versioned dictionaries directly inside the extension, every conversion function is IMMUTABLE and PARALLEL SAFE within a release:

  • Cross-script search indexes: Index opencc.tw2sp(title) or opencc.t2s(title) so a search for 英伟达 or 算法 finds rows written as 輝達 or 演算法 using a normal B-tree index scan.
  • Stored generated columns and constraints: Maintain localized regional columns automatically or reject mixed-script text at INSERT time with CHECK (opencc.detect(body) = ...).
  • Context-aware phrases, not naive char maps: Compare character conversion (s2t / s2tw) against phrase-aware localization (s2twp):
ConfigInput: 鼠标里面的硅二极管坏了,导致光标分辨率降低。What changed
s2t鼠標裏面的硅二極管壞了,導致光標分辨率降低。OpenCC standard Traditional glyphs
s2tw鼠標裡面的硅二極管壞了,導致光標分辨率降低。Taiwan glyph variant (裏 → 裡)
s2twp滑鼠裡面的矽二極體壞了,導致游標解析度降低。Taiwan glyphs + regional vocabulary (鼠标→滑鼠, 硅→矽, 光标→游標, 分辨率→解析度)

How opencc works

  1. Zero external dependencies: Dictionaries and configs are compiled into the extension binary with a SHA-256 digest (opencc.version()).
  2. Lazy per-backend loading (or shared preload): Each PostgreSQL backend loads a converter the first time it is called. For high-connection workloads using the same configs, preload them via opencc.preload so forked backends share read-only memory pages.
  3. Safe dictionary upgrades: When a future release updates embedded dictionaries, opencc.dependents() inspects pg_depend and generates the exact REINDEX, UPDATE, REFRESH, or constraint re-validation SQL for stored objects that rely on opencc.

3.1 - Getting started with opencc

Install opencc in a UTF8 PostgreSQL database and run your first script, phrase, and regional conversions in under three minutes.

1. Install opencc

Install from Pigsty packages

CI tests PostgreSQL 14–18, and Pigsty ships packages for PostgreSQL 15–19 across Linux distributions (pg_opencc_18 on EL, postgresql-18-opencc on Debian/Ubuntu). Check Downloads for exact platform coverage.

pig repo add pgsql -u
pig ext add opencc

Or build from source (PGXS)

Building from the release tag requires PostgreSQL server headers, CMake ≥ 3.12, a C++17 compiler, Python 3, and Make:

# On RHEL / Rocky / AlmaLinux (example for PG18)
sudo dnf install postgresql18-devel cmake gcc-c++ make python3
export PG_CONFIG=/usr/pgsql-18/bin/pg_config

# On Debian / Ubuntu (example for PG18)
sudo apt install postgresql-server-dev-18 cmake g++ make python3
export PG_CONFIG=/usr/lib/postgresql/18/bin/pg_config

Clone the tagged release and install (pass with_llvm=no if your pg_config enables JIT without clang installed):

git clone --branch v0.1.0 --depth 1 https://github.com/pgsty/pg_opencc.git
cd pg_opencc
make PG_CONFIG="$PG_CONFIG"
sudo make install PG_CONFIG="$PG_CONFIG"

CMake builds static OpenCC and marisa libraries and compiles the dictionaries directly into the shared library.

2. Enable in a UTF8 database

opencc is a trusted extension—any role with CREATE privilege on the database can enable it without superuser rights. The SQL schema is fixed at opencc.

SHOW server_encoding;
CREATE EXTENSION IF NOT EXISTS opencc;
SELECT * FROM opencc.version();
 server_encoding
-----------------
 UTF8

 extension | opencc |                           dictionary
-----------+--------+-----------------------------------------------------------------
 0.1.0     | 1.4.2  | sha256:...
Note

Calling text conversion in a non-UTF8 database raises opencc requires a UTF8 database.

3. Try your first conversions

  1. Context-aware phrase conversion — Notice how s2twp translates the hardware term 内存条 while leaving the classical line 海内存知己 intact:

    SELECT opencc.s2twp('海内存知己') AS poem,
           opencc.s2twp('安装内存条') AS hardware;
        poem    |    hardware
    ------------+----------------
     海內存知己 | 安裝記憶體模組
  2. Compare glyph-only vs. regional phrases — Every shorthand wrapper (such as opencc.s2t, opencc.s2twp, opencc.tw2sp) is identical to opencc.convert(input, '<config>'):

    SELECT opencc.s2t('鼠标里面的硅二极管坏了,导致光标分辨率降低。')   AS s2t,
           opencc.s2twp('鼠标里面的硅二极管坏了,导致光标分辨率降低。') AS s2twp;
                         s2t                      |                    s2twp
    ----------------------------------------------+----------------------------------------------
     鼠標裏面的硅二極管壞了,導致光標分辨率降低。 | 滑鼠裡面的矽二極體壞了,導致游標解析度降低。
  3. Target a locale with opencc.localize() — Convert one Mainland source string into multiple regional variants in one query:

    SELECT r AS target,
           opencc.localize('克里斯托弗·诺兰的电影,安装内存条', r, 'zh-CN') AS output
    FROM unnest(ARRAY['zh-Hant', 'zh-TW', 'zh-HK']) AS r;
     target  |                output
    ---------+---------------------------------------
     zh-Hant | 克里斯托弗·諾蘭的電影,安裝內存條
     zh-TW   | 克里斯多福·諾蘭的電影,安裝記憶體模組
     zh-HK   | 基斯杜化·路蘭的電影,安裝記憶體模組
  4. List all built-in configs and routes:

    SELECT name, source, target, phrases, maturity FROM opencc.configs ORDER BY name;

Non-Chinese text, emoji, empty strings, and NULL pass through unchanged.

Next steps

  • Guides and operations — Build cross-script search indexes, validate incoming text, proofread ambiguous conversions, preload dictionaries, and handle upgrades.
  • SQL reference — Look up all 16 built-in configs, function signatures, and opencc.preload.

3.2 - Guides and operations

Use opencc in real PostgreSQL workloads: cross-script search indexes, regional localization routing, script CHECK constraints, editorial ambiguity proofreading, shared memory preloading, and safe upgrades.

Because opencc functions are IMMUTABLE, you can normalize titles inside an expression index. Folding Taiwan Traditional and regional vocabulary into Simplified Chinese (opencc.tw2sp) lets a single query find every spelling variant via an index scan:

CREATE TEMP TABLE articles (
    id       int PRIMARY KEY,
    title    text NOT NULL,
    title_tw text GENERATED ALWAYS AS (opencc.s2twp(title)) STORED
);

INSERT INTO articles (id, title) VALUES
    (1, '輝達'), (2, '英伟达'), (3, '辉达'), (4, '演算法'), (5, '算法');

CREATE INDEX articles_fold_idx ON articles (opencc.tw2sp(title));

SELECT q,
       (SELECT string_agg(title, ' / ' ORDER BY id)
        FROM articles WHERE opencc.t2s(title) = opencc.t2s(q))     AS glyph_only,
       (SELECT string_agg(title, ' / ' ORDER BY id)
        FROM articles WHERE opencc.tw2sp(title) = opencc.tw2sp(q)) AS phrase_aware
FROM (VALUES ('英伟达'), ('算法')) AS v(q);
   q    | glyph_only | phrase_aware
--------+------------+---------------
 英伟达 | 英伟达     | 輝達 / 英伟达
 算法   | 算法       | 演算法 / 算法

Both opencc.tw2sp(title) and opencc.convert(title, 'tw2sp') expand to the same SQL expression, so either form hits articles_fold_idx. On PostgreSQL 18+, write STORED explicitly on generated columns that call extension functions.

2. Regional localization with opencc.localize()

Use opencc.localize(input, target, source => 'auto') when your application works with locale tags (zh-Hans, zh-Hant, zh-CN, zh-TW, zh-HK, ja) instead of raw OpenCC config names. Region tags are case-insensitive and accept _ in place of - (zh-tw equals ZH_TW).

Important: source => 'auto' detects script, not region

Auto-detection tells Simplified from Traditional or Japanese, so converting from Taiwan or Hong Kong regional vocabulary back to Mainland terms requires naming source explicitly:

SELECT opencc.localize('滑鼠裡面的矽二極體壞了', 'zh-CN', source => 'zh-TW') AS explicit_tw,
       opencc.localize('滑鼠裡面的矽二極體壞了', 'zh-CN')                    AS auto_detect;
      explicit_tw       |      auto_detect
------------------------+------------------------
 鼠标里面的硅二极管坏了 | 滑鼠里面的矽二极体坏了

Inspect the exact config chain used for any region pair:

SELECT source, target, chain, maturity
FROM opencc.routes
WHERE target = 'zh-HK'
ORDER BY source;

3. Script detection and CHECK constraints

opencc.detect() classifies text as simplified, traditional, mixed, japanese, neutral (Han characters shared across scripts, such as 中文), or none (no CJK characters). opencc.script_stats() returns the exact counts (han, simplified, traditional, kana):

SELECT x AS input, opencc.detect(x) AS script, s.*
FROM (VALUES
    ('为什么你在床里面睡着?'),
    ('為什麼你在床裡面睡著?'),
    ('抬头 擡头 抬頭 擡頭'),
    ('旧字体の歴史'),
    ('中文'),
    ('PostgreSQL 18')
) AS v(x),
LATERAL opencc.script_stats(x) AS s;
         input          |   script    | han | simplified | traditional | kana
------------------------+-------------+-----+------------+-------------+------
 为什么你在床里面睡着? | simplified  |  10 |          1 |           0 |    0
 為什麼你在床裡面睡著? | traditional |  10 |          0 |           3 |    0
 抬头 擡头 抬頭 擡頭    | mixed       |   8 |          2 |           4 |    0
 旧字体の歴史           | japanese    |   5 |          2 |           0 |    1
 中文                   | neutral     |   2 |          0 |           0 |    0
 PostgreSQL 18          | none        |   0 |          0 |           0 |    0

Because opencc.detect() is IMMUTABLE, you can enforce a single script right in a table CHECK constraint (use full sentences rather than isolated characters, since shared characters classify as neutral):

CREATE TABLE zh_cn_posts (
    id   int PRIMARY KEY,
    body text NOT NULL
        CONSTRAINT body_is_simplified
        CHECK (opencc.detect(body) IN ('simplified', 'neutral', 'none'))
);

4. Editorial proofreading and tracing

When publishing books, subtitles, or formal documents, Simplified-to-Traditional conversion has classic one-to-many traps (such as personal names like 文丑 or polysemous characters like 里). Use opencc.ambiguities(), opencc.candidates(), and opencc.explain() to flag spans for human review:

-- Find one-to-many ambiguous spans and every candidate form
SELECT * FROM opencc.ambiguities('大战文丑的时候,他的头发很干燥', 's2t');
 pos | len | source | output | candidates
-----+-----+--------+--------+-------------
   3 |   2 | 文丑   | 文丑   | {文丑,文醜}
-- Inspect all candidate forms for a single word (default choice first)
SELECT opencc.candidates('里', 's2t')  AS s2t,
       opencc.candidates('里', 's2tw') AS s2tw;
    s2t     |    s2tw
------------+------------
 {裏,里,哩} | {裡,里,哩}
-- Trace how each segment moves through intermediate dictionary stages
SELECT * FROM opencc.explain('数据库连接池', 's2twp');
 seq | source |      steps      | output
-----+--------+-----------------+--------
   1 | 数据库 | {數據庫,資料庫} | 資料庫
   2 | 连接池 | {連接池,連線池} | 連線池

5. Preloading, memory, and safe upgrades

Share converter memory across connections

By default, each backend loads a config into private memory on its first call. For servers with hundreds of connections calling the same configs, preload only those configs at startup so forked backends share read-only pages via copy-on-write:

shared_preload_libraries = 'opencc'
opencc.preload = 's2twp,tw2sp'

Restart PostgreSQL, then verify which configs are loaded in the current backend:

SELECT name, loaded FROM opencc.configs WHERE loaded ORDER BY name;

See the initial release memory and throughput measurements for per-config footprint details.

Upgrade safely when dictionaries change

A new opencc release may ship updated OpenCC dictionaries whose conversion output differs slightly from the previous release. After upgrading, run opencc.dependents() to inventory every stored object (indexes, stored generated columns, CHECK constraints, materialized views) that directly calls opencc functions, together with the exact SQL to rebuild or revalidate each one:

SELECT kind, object, uses, action
FROM opencc.dependents();
       kind        |                    object                    |              uses               |                    action
-------------------+----------------------------------------------+---------------------------------+-----------------------------------------------
 constraint        | constraint body_simplified on table app.post | opencc.detect(text)             | ALTER TABLE app.post DROP CONSTRAINT ...
 generated column  | column body_tw of table app.post             | opencc.localize(text,text,text) | UPDATE app.post SET body_tw = DEFAULT
 index             | index app.post_fold_idx                      | opencc.t2s(text)                | REINDEX INDEX CONCURRENTLY app.post_fold_idx
 materialized view | materialized view app.post_hk                | opencc.s2hk(text)               | REFRESH MATERIALIZED VIEW app.post_hk

Note that opencc.dependents() reports direct catalog dependencies; calls wrapped inside application PL/pgSQL functions require a manual check. Running DROP EXTENSION opencc leaves the empty fixed opencc schema in place.

3.3 - opencc SQL reference

Complete SQL API lookup for opencc v0.1.0 (vendored OpenCC 1.4.2): all 16 built-in configs, conversion and inspection functions, catalog views, and the opencc.preload GUC.

All functions and views live in the fixed opencc schema. Conversion, detection, and inspection functions are IMMUTABLE and PARALLEL SAFE within a release and require a UTF8 database.

Built-in configs

ConfigSource → TargetRegional phrasesMaturityShorthand function
s2t / t2szh-Hans ↔ zh-HantNostableopencc.s2t() / opencc.t2s()
s2tw / tw2szh-Hans ↔ zh-TWNostableopencc.s2tw() / opencc.tw2s()
s2twp / tw2spzh-Hans ↔ zh-TWYesstableopencc.s2twp() / opencc.tw2sp()
s2hk / hk2szh-Hans ↔ zh-HKNostableopencc.s2hk() / opencc.hk2s()
s2hkp / hk2spzh-Hans ↔ zh-HKYesdevelopingopencc.s2hkp() / opencc.hk2sp()
t2tw / tw2tzh-Hant ↔ zh-TWNostableopencc.t2tw() / opencc.tw2t()
t2hk / hk2tzh-Hant ↔ zh-HKNostableopencc.t2hk() / opencc.hk2t()
t2jp / jp2tzh-Hant ↔ jaNoexperimentalopencc.t2jp() / opencc.jp2t()

Conversion functions

opencc.convert(input text, config text) , text , default—
Convert text using one of the 16 built-in config names above.
opencc.localize(input text, target text, source text) , text , defaultsource = 'auto'
Route between zh-Hans, zh-Hant, zh-CN, zh-TW, zh-HK, and ja. Name source explicitly to translate regional phrases.
opencc.<config>(input text) , text , default—
Shorthand wrappers for all 16 configs (s2t, t2s, s2tw, tw2s, s2twp, tw2sp, s2hk, hk2s, s2hkp, hk2sp, t2tw, tw2t, t2hk, hk2t, t2jp, jp2t), equivalent to opencc.convert(input, '<config>').

Script detection and inspection

opencc.detect(input text) , text , default—
Heuristic script classification: none, neutral, simplified, traditional, mixed, or japanese.
opencc.script_stats(input text) , record , default—
Returns (han integer, simplified integer, traditional integer, kana integer).
opencc.explain(input text, config text) , table , default—
Returns (seq integer, source text, steps text[], output text) showing every conversion stage per segment.
opencc.ambiguities(input text, config text) , table , default—
Returns (pos integer, len integer, source text, output text, candidates text[]) for one-to-many dictionary spans.
opencc.candidates(word text, config text) , text[] , default—
Return every candidate output for word under config (default first; {} if absent).

Views and operations

opencc.configs , view , default—
Lists all 16 configs (name, source, target, phrases, maturity, description, loaded). loaded reflects the current backend.
opencc.routes , view , default—
Lists all 36 localize() region pairs (source, target, chain, maturity).
opencc.version() , record , default—
STABLE. Returns (extension text, opencc text, dictionary text) including the SHA-256 digest of embedded dictionaries.
opencc.dependents() , table , default—
STABLE. Returns (kind text, object text, uses text, action text) for stored catalog dependents and their rebuild SQL.

Configuration (GUC)

opencc.preload , string , default''
Comma-separated config names (or 'all') to initialize when the library loads. Combine with shared_preload_libraries = 'opencc' and restart PostgreSQL to share read-only dictionary pages across backends.
SELECT name, loaded FROM opencc.configs ORDER BY name;