Compile literal rules once and match or replace them across text and bytea in a single pass.
This is the multi-page printable view of this section.
Docs
- 1: acdat
- 1.1: Getting started with acdat
- 1.2: Examples and workflows
- 1.3: Performance and tuning
- 1.4: Operations
- 1.5: acdat SQL reference
- 2: pgs3
- 3: opencc
First-party extensions
Turn PostgreSQL into a versioned S3 object endpoint with SQL transactions, bucket forks, and RLS isolation.
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.
Tokenize multilingual text inside PostgreSQL.
Query an Iceberg mirror of a PostgreSQL table.
Apply logical replication changes to Iceberg tables.
Scan Parquet and recent in-memory changes together.
1 - acdat
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) andbytea(arbitrary binary payloads including\x00). - One-pass deterministic rewriting:
acdat.replace()rewrites overlapping spans according to an explicit policy (leftmost_longestorleftmost_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)
| Need | Best tool | Why |
|---|---|---|
| Check, tag, or redact many exact literal phrases or binary signatures inside PostgreSQL | acdat | Single-pass scan with stable rule IDs, priorities, and deterministic replacement |
| Search by stemmed natural-language words or relevance ranking | PostgreSQL full-text search / vchord_bm25 | acdat 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 substrings | pg_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)"]- 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). - Compile once:
acdat.compile()turns arrays or table rows into an immutableacdat.machinevalue. A 1,114-rule real-world dictionary compiles in ~1.2 ms and caches in ~227 KiB per backend. - 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. - Scan in one pass: Pass the machine to
acdat.contains()to filter rows,acdat.matches()to extract rule IDs and offsets, oracdat.replace()to redact or rewrite values.
1.1 - Getting started with acdat
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.
Or build from the release tag
Point PG_CONFIG to your target PostgreSQL installation:
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:
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.
Create a rule table and sample comments:
Compile the rule table into a single
acdat.machine:Filter only the comments that match at least one rule (
acdat.containsstops on the first hit):Extract every match with its position and join back to your rule table for business labels:
Redact all matched spans in one non-recursive pass:
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:
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
psqltransaction.
1.2 - Examples and workflows
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 formatches): reports every candidate hit, including prefixes, suffixes, and duplicate text with distinct IDs.leftmost_longest(default forreplace): 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., priority10beats priority20), then longer pattern, then lower ID.
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"(priority10) beats"credit card fraud"(priority20) 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 isNULLraises 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(default10000) andmax_output_bytes(default256 MiB) when short inputs could expand into large outputs. The candidate limit counts raw overlaps before policy resolution, and an outer SQLLIMITdoes 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?”
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:
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.
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.
If version 2 triggers false positives, roll back immediately by reactivating version 1, then retire 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 to0. - 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.
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.
Export on the build database, validate and import on the target database:
source_fingerprint()hashes the canonical rule set;build_fingerprint()also includes engine, compiler, and format version;artifact_checksum()hashes the serialized payload.validate()returnsfalseon corrupted bytes whileimport()raises an error.- Transfer
textmachines only between databases with compatible server encodings;byteamachines are encoding-independent.
1.3 - Performance and tuning
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]| Operation | 1 backend | 4 workers | 8 workers | 8-worker speedup |
|---|---|---|---|---|
contains | 1.522 s | 0.398 s | 0.228 s | 6.67x |
replace (leftmost_longest) | 2.007 s | 0.510 s | 0.291 s | 6.89x |
matches (all_overlapping) | 3.678 s | 0.816 s | 0.476 s | 7.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 width | Rows | 1 backend | 4 workers | 8 workers |
|---|---|---|---|---|
| 33 B | 10,000,000 | 600.6 ms | 140.1 ms | 104.0 ms |
| 1 KiB | 262,144 | 281.6 ms | 73.3 ms | 49.9 ms |
| 64 KiB | 4,096 | 280.4 ms | 70.5 ms | 48.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:
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):
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 profile | Stored artifact | Cache / process | 9 processes (leader + 8 workers) |
|---|---|---|---|
| Real corpus (1,114 rules) | 269 KiB | 227 KiB | ~2.0 MiB |
| 100k shared-prefix rules | 5.94 MiB | 5.51 MiB | ~49.6 MiB |
| 100k random ASCII rules | 28.96 MiB | 23.93 MiB | ~215.4 MiB |
Four practical rules for fast scans:
- Compile once outside the row loop: Never put
acdat.compile()inside a per-rowWHEREorSELECTexpression. - Filter before scanning: Narrow candidate rows with B-tree, GIN, or time-range indexes first, and choose
acdat.contains()overacdat.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
COPYor a server-side cursor when exporting millions of matches or rewritten rows instead of buffering a giantSELECTin client memory.
1.4 - Operations
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:
2. Backup, restore, and replication
- Logical dumps (
pg_dump):acdatregisters its catalog tables viapg_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
acdatshared library on the recovery host before starting PostgreSQL. - Logical replication: Install
acdaton 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 message | Cause and fix |
|---|---|
acdat compile failed: pattern ID 1 is duplicated | Every rule in one dictionary must have a unique pattern_id. Deduplicate or assign distinct IDs. |
acdat scan failed: match count exceeds limit 2 | Raw 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 replacement | acdat.replace() selected a rule whose replacement was NULL. Supply a literal replacement (or '' to delete). |
cannot retire the active acdat build | Activate another ready build first, then retire the previous build. |
acdat machine input kind does not match function input | A 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 payload | Publish 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
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
Compile a dictionary
acdat.compile(patterns text[], pattern_ids bigint[], replacements text[], priorities integer[], options jsonb), ,- Compile parallel 1D text arrays into a machine. Omitted IDs default to
1..N;NULLpriorities default to0. acdat.compile(patterns bytea[], pattern_ids bigint[], replacements bytea[], priorities integer[], options jsonb), ,- Binary array overload preserving arbitrary bytes (including
\x00). acdat.compile(text, bigint), ,- Compile rows of
(pattern, pattern_id). ReturnsNULLfor zero rows. acdat.compile(text, bigint, text, integer), ,- Compile rows of
(pattern, pattern_id, replacement, priority). ReturnsNULLfor zero rows. acdat.compile(bytea, bigint), ,- Binary aggregate over
(pattern, pattern_id). ReturnsNULLfor zero rows. acdat.compile(bytea, bigint, bytea, integer), ,- Binary aggregate over
(pattern, pattern_id, replacement, priority). ReturnsNULLfor zero rows.
¹ Defaults apply starting at pattern_ids; patterns is required. options accepts NULL or {}.
Scan and replace
acdat.contains(text, acdat.machine), ,- Return
trueon the first literal match and stop scanning immediately. acdat.contains(bytea, acdat.machine), ,- Binary overload of
contains. acdat.matches(input text, machine acdat.machine, policy text, max_matches integer), ,- 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), ,- Binary overload;
start_charandchar_lengthare alwaysNULL. acdat.replace(input text, machine acdat.machine, policy text, max_replacements integer, max_output_bytes bigint), ,- Single non-recursive pass rewrite. Errors if a selected match has a
NULLreplacement or exceeds a limit. acdat.replace(input bytea, machine acdat.machine, policy text, max_replacements integer, max_output_bytes bigint), ,- Binary overload of
replace.
Overlap policies
all_overlapping, ,- Emit every candidate hit, including prefixes, suffixes, and duplicate literals with distinct IDs.
leftmost_longest, ,- Leftmost start offset → longer pattern → lower
priorityinteger → lowerpattern_id→ lower canonical ordinal. leftmost_priority, ,- Leftmost start offset → lower
priorityinteger → longer pattern → lowerpattern_id→ lower canonical ordinal.
Inspect and transport
acdat.info(acdat.machine), ,- Metadata JSON: engine, compiler/format versions, input kind, encoding, pattern/state/slot counts, and sizes.
acdat.export(acdat.machine), ,- Serialize a compiled machine into a portable binary image.
acdat.validate(bytea), ,- Verify a serialized image without raising an error on corruption.
acdat.import(bytea), ,- Validate and decode a serialized image; raises an error if malformed.
acdat.source_fingerprint(acdat.machine), ,- 32-byte SHA-256 digest of the canonical rule set and input kind.
acdat.build_fingerprint(acdat.machine), ,- 32-byte digest identifying rules plus compiler, engine, and format version.
acdat.artifact_checksum(acdat.machine), ,- 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), ,- Store an immutable
readybuild and return its 32-byte dictionary-scopedbuild_id. acdat.activate(p_dictionary_name text, p_build_id bytea), ,- Atomically point
acdat.active_dictionaryto areadybuild. acdat.retire_build(p_dictionary_name text, p_build_id bytea), ,- Mark an inactive build as
retired. acdat.active_machine, ,- Active ready machines:
name,input_kind,version,build_id,machine,info. acdat.dictionary, ,- Dictionary name and fixed
input_kind(textorbytea). acdat.dictionary_version, ,- Semantic version,
source_fingerprint, and optionalsource_refJSON. acdat.dictionary_build, ,- Build metadata, compiler/format/engine info, status (
ready/retired), and checksum. acdat.dictionary_build_data, ,- Compiled
acdat.machinepayload (STORAGE EXTERNAL) keyed bybuild_id. acdat.active_dictionary, ,- Current active
build_idpointer per dictionary.
Types and internal functions
acdat.machine, ,- Variable-length compiled automaton (
STORAGE = external). acdat.hit, ,(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, ,- Type I/O functions revoked from
PUBLIC; invoked by PostgreSQL. _compile_*_trans/_compile_final/_catalog_build_id, ,- Aggregate state transition/final and catalog digest helpers revoked from
PUBLIC.
2 - pgs3
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.
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
NOLOGINrole. 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)
| Workload | Recommendation | Why |
|---|---|---|
| Application attachments, invoices, configs, or AI agent artifacts that must stay consistent with relational rows | Use pgs3 | Shared transactions, unified PITR, and zero extra storage cluster to operate |
| Multi-tenant SaaS workspaces or experiment checkpoints needing cheap bucket forks | Use pgs3 | RLS 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 rules | Use a dedicated S3 store such as Silo | Dedicated 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"]- HTTP workers handle the wire protocol: Background workers listen on a shared
SO_REUSEPORTTCP port (default127.0.0.1:9000), verify AWS SigV4 signatures, and map each access key to its PostgreSQL tenant role. - SQL enforces all semantics: Inside short transactions, workers run
SET LOCAL ROLEand invoke the samepgs3.*SQL functions that direct SQL callers use. Versioning, preconditions, locking, and RLS isolation live in one place. - 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
1. Install pgs3
Install the pgs3 package on a Linux PostgreSQL 17–19 server (PG16 is best effort; see Downloads for platform availability):
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:
Confirm that the HTTP workers are listening on 127.0.0.1:9000:
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):
Add the alias and create a bucket:
Upload a file and read it back:
Overwrite the object and delete it—
pgs3keeps versioning permanently enabled, so an ordinary delete writes a delete marker instead of losing history:Recover the first revision by its version ID (
1):
4. Clean up
When you are done testing, stop the worker pool and remove the local alias:
Next steps
- Connect S3 clients — Full recipes for
mc,rclone, Python (boto3), DuckDB (httpfs), ands3fs. - SQL, versioning, and tenants — Commit objects in SQL transactions, restore versions, fork buckets, and isolate multiple tenants.
- Deploy and operate — Automatic startup, Nginx TLS proxy, backups, upgrades, and source/container builds.
- Performance and limits — Benchmark charts against MinIO and hard operational boundaries.
2.2 - Connect S3 clients
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):
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:
Everyday object operations
Work with object versions
pgs3 keeps versioning permanently enabled on every bucket:
Generate a temporary download URL
mc share download signs a presigned GET URL locally without calling any extra API:
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:
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
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
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.
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.
Generate a Parquet file and upload it with
mc:Query it directly from DuckDB (
ENDPOINTexpectshost:portwithout a scheme; setUSE_SSL truebehind a TLS proxy):
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:
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
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 inpgs3.blob. Larger blobs are split into 4 MiB chunks (pgs3.chunk_size) across hash-partitionedpgs3.chunktables; completed multipart uploads stitch orderedpgs3.blob_extentreferences 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:
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.
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:
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:
- Service role (
pgs3.server_role, defaultpgs3_server): Created automatically when the extension is installed. HTTP workers connect as this restrictedNOLOGIN NOINHERITrole only to look up credentials and switch roles. - Tenant roles: Ordinary, unprivileged
NOLOGIN NOINHERITroles that you create (one per customer, team, or agent workspace). When you bind a credential withpgs3.create_credential(),pgs3grantspgs3_serverSET-only membership in that tenant role. - 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 hasUSAGEmembership in.
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):
Verify isolation in SQL—tenant_bob cannot see or read tenant_alice’s bucket:
Rotate, suspend, and audit credentials
Issue separate access keys per client or service so you can rotate or revoke one without disrupting others:
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
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.
Add
pgs3topostgresql.conf(append to any existing preload entries):Size
max_worker_processesto cover the launcher (1), the GC worker (1),pgs3.workers, parallel query workers, and any other preloaded extensions.Run
CREATE EXTENSION IF NOT EXISTS pgs3;inpgs3.target_database(if provisioning in two stages, leavepgs3.enabled = offuntil the extension is created, then enable and restart).Restart PostgreSQL and confirm the pool is running before opening traffic:
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
Hostheader including any non-default port ($http_host). - Omit any trailing path or slash on
proxy_passso 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.
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 arerunninginpgs3.worker_state, and run a lightweight signed read (such asHeadBucket). - Safe retries: Before retrying an interrupted version-sensitive write, check whether it already committed or guard it with
If-None-Match: *orIf-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.
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:
- Verify
pgs3.extension_version()matches the installed shared library. - Check pending uploads and reference counts; sample inline and chunked objects to verify content hashes.
- Run an end-to-end signed read/write smoke test and confirm cross-tenant isolation.
- 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:
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.
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
| Symptom | What to check |
|---|---|
TCP connects, but HTTP returns 403 / 500 | Check pgs3.worker_state, pgs3.target_database, and whether pgs3.server_role attributes or grants drifted (launcher stops HTTP listeners on drift). |
SignatureDoesNotMatch behind Nginx | Confirm 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.upload | Check lease expiry (5 min) and pending retention (24 h), and verify the gc worker is running in pgs3.worker_state. |
Writes return 503 ServiceUnavailable | Traffic is hitting a read-only standby; route writes to the primary. |
Requests return 503 SlowDown | Queries 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.
Take a verified physical backup and drain S3 traffic.
Install the updated
pgs3package (matching the PostgreSQL major/minor) and restart PostgreSQL.Update the extension catalog in each database using
pgs3: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:
This creates a local pgs3-test:pg17 container image. Run a disposable instance exposing PostgreSQL on 55432 and the S3 endpoint on 9000:
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
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 size | PUT p50 | PUT ops/s | PUT MiB/s | GET p50 | GET ops/s | GET MiB/s |
|---|---|---|---|---|---|---|
| 4 KiB | 5.78 ms | 1,556 | 6.1 | 2.86 ms | 4,065 | 15.9 |
| 16 KiB | 4.66 ms | 2,444 | 38.2 | 3.34 ms | 3,990 | 62.3 |
| 64 KiB | 2.73 ms | 3,646 | 227.9 | 2.15 ms | 6,155 | 384.7 |
| 256 KiB | 8.56 ms | 1,034 | 258.4 | 2.81 ms | 5,030 | 1,257.4 |
| 1 MiB | 31.89 ms | 284 | 284.4 | 5.32 ms | 1,803 | 1,802.9 |
| 8 MiB | 47.40 ms | 21 | 167.9 | 39.47 ms | 99 | 793.2 |
| 64 MiB | 395.76 ms | 2.4 | 156.6 | 444.68 ms | 2.1 | 133.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
| Check | Target | Measured | Status |
|---|---|---|---|
| 8 MiB PUT throughput (1 connection) | ≥ 150 MiB/s | 167.9 MiB/s | Pass |
1,000,000-key SQL LIST (flat) | < 5 ms | 2.36 ms | Pass |
1,000,000-key SQL LIST (/ delimiter) | < 10 ms | 9.49 ms | Pass |
| Small-object GET (p50 / ops/s) | < 0.5 ms / ≥ 30,000/s | 3.34 ms / 3,990/s | Below target |
| Small-object PUT throughput | ≥ 5,000/s | 1,556/s | Below target |
100,000-object fork_bucket | < 1,000 ms | 1,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
GetObjectmaterializes a SQLbyteaand 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-chunkedchunk is capped at 1 MiB. - Single-database Linux listener: One
pgs3worker pool serves one PostgreSQL database on Linux (SO_REUSEPORT). HTTP/1.1 keep-alive connections process requests sequentially per connection. - Non-snapshot
LISTpagination: 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
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, ,- Register the static launcher on server startup when
pgs3is inshared_preload_libraries. Dynamicpgs3.start()ignores this flag. pgs3.workers, ,- Desired number of HTTP background workers. Each consumes one
max_worker_processesslot. pgs3.listen_addr, ,- IPv4 or IPv6 bind address for HTTP workers. Keep on loopback and terminate TLS in a reverse proxy.
pgs3.port, ,- Shared
SO_REUSEPORTTCP port for HTTP workers. pgs3.inline_threshold, ,- Largest physical blob stored inline in
pgs3.blobfor new writes. Direct single-transaction PUT has an additional 64 KiB cap. pgs3.chunk_size, ,- Chunk size for staged uploads exceeding the inline threshold; snapshotted per upload on admission.
pgs3.statement_timeout_ms, ,- PostgreSQL statement/lock timeout for each SPI semantic transaction. Applies to new transactions.
pgs3.target_database, ,- Database served by the preloaded static launcher. Changing the pool’s database requires a server restart.
pgs3.server_role, ,- Restricted service identity used by HTTP workers. Custom roles must exist beforehand and be
NOLOGIN NOINHERITwith no elevated attributes, no inbound members, andSET-only membership in tenant roles.
Inspect live values
Reload vs. restart
- Applies on
SIGHUPreload:pgs3.workers,pgs3.listen_addr,pgs3.port,pgs3.statement_timeout_ms,pgs3.inline_threshold(new blobs), andpgs3.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
pgs3toshared_preload_libraries, changingpgs3.enabledfromofftoonwhen the static launcher was not registered at boot, or changingpgs3.target_database. - Service role changes: Reconciling a changed
pgs3.server_roleon 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_limitcustom setting defaults to134217728bytes (128 MiB); packaged builds use Rust hash helpers instead.
S3 API compatibility
| Area | Supported APIs | Behavior and boundaries |
|---|---|---|
| Buckets | ListBuckets, CreateBucket, DeleteBucket, HeadBucket, GetBucketLocation, GetBucketVersioning | Versioning is permanently Enabled. DeleteBucket requires an empty bucket (including historical versions); pending uploads alone are aborted atomically on delete. |
| Objects | PutObject, GetObject, HeadObject, CopyObject, DeleteObject, DeleteObjects | Supports 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. |
| Listing | ListObjects (V1), ListObjectsV2, ListObjectVersions | Prefix, delimiter, encoding-type=url, max-keys (0–1000), V1 markers, and V2 continuation tokens. |
| Multipart | CreateMultipartUpload, UploadPart, ListParts, CompleteMultipartUpload, AbortMultipartUpload | Non-final parts must be ≥ 5 MiB. UploadPartCopy and ListMultipartUploads are not supported. |
| Version restore | POST /{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, andListMultipartUploads.
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), ,- Create a bucket owned by the current role (idempotent for the same owner).
pgs3.list_buckets(), ,- List buckets visible to the current role.
pgs3.delete_bucket(p_name text), ,- 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), ,- 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), ,- 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), ,- 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), ,- 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), ,- Copy an object or version by sharing its canonical SHA-256 blob.
pgs3.delete(p_bucket text, p_key text, p_version_id bigint), ,- Insert a delete marker when
p_version_idis 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), ,- 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), ,- 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), ,- 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), ,- Operator only. Create an S3 key pair bound to an unprivileged tenant role.
pgs3.rotate_credential(p_access_key text, p_new_secret text), ,- Operator only. Replace the signing secret for an existing key.
pgs3.set_credential_role(p_access_key text, p_role_name name), ,- Operator only. Reassign an access key to another unprivileged tenant role.
pgs3.set_credential_enabled(p_access_key text, p_enabled boolean), ,- Operator only. Suspend or re-enable an access key.
pgs3.delete_credential(p_access_key text), ,- Operator only. Delete an access key.
pgs3.start(), ,- Operator only. Start a dynamic worker pool for the current database.
pgs3.stop(), ,- Operator only. Stop the dynamic worker pool in the current database.
pgs3.extension_version(), ,- Return the installed SQL catalog version of
pgs3. pgs3.worker_state, ,- Live launcher, GC, and HTTP worker status, listener address, and heartbeats.
pgs3.stats, ,- Aggregated HTTP request counters, errors, latency buckets, bytes, and GC/upload backlog.
pgs3.gc_pending_uploads(p_max_age interval, p_limit integer), ,- Operator only. Clean up expired pending uploads in bounded batches.
pgs3.gc_blobs(p_limit integer), ,- Operator only. Delete unreferenced zero-refcount blobs in bounded batches.
SQLSTATE to S3 error mapping
| SQLSTATE | HTTP | S3 error code |
|---|---|---|
P3B01 | 404 | NoSuchBucket |
P3K01 | 404 | NoSuchKey / NoSuchVersion |
P3U01 | 404 | NoSuchUpload |
P3C01 | 412 | PreconditionFailed |
P3N01 | 304 | NotModified (no XML body) |
P3R01 | 416 | InvalidRange |
P3E01 | 409 | BucketAlreadyExists |
P3F01 | 409 | BucketNotEmpty |
P3H01 | 400 | BadDigest |
P3P01 | 400 | InvalidPart / InvalidPartOrder / EntityTooSmall |
P3S01 | 400 | EntityTooLarge |
42501 | 403 | AccessDenied |
25006 | 503 | ServiceUnavailable (read-only standby) |
57014 | 503 | SlowDown (statement timeout) |
0A000 | 501 | NotImplemented |
| other | 500 | InternalError |
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
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)oropencc.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
INSERTtime withCHECK (opencc.detect(body) = ...). - Context-aware phrases, not naive char maps: Compare character conversion (
s2t/s2tw) against phrase-aware localization (s2twp):
| Config | Input: 鼠标里面的硅二极管坏了,导致光标分辨率降低。 | What changed |
|---|---|---|
s2t | 鼠標裏面的硅二極管壞了,導致光標分辨率降低。 | OpenCC standard Traditional glyphs |
s2tw | 鼠標裡面的硅二極管壞了,導致光標分辨率降低。 | Taiwan glyph variant (裏 → 裡) |
s2twp | 滑鼠裡面的矽二極體壞了,導致游標解析度降低。 | Taiwan glyphs + regional vocabulary (鼠标→滑鼠, 硅→矽, 光标→游標, 分辨率→解析度) |
How opencc works
- Zero external dependencies: Dictionaries and configs are compiled into the extension binary with a SHA-256 digest (
opencc.version()). - 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.preloadso forked backends share read-only memory pages. - Safe dictionary upgrades: When a future release updates embedded dictionaries,
opencc.dependents()inspectspg_dependand generates the exactREINDEX,UPDATE,REFRESH, or constraint re-validation SQL for stored objects that rely onopencc.
3.1 - Getting started with opencc
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.
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:
Clone the tagged release and install (pass with_llvm=no if your pg_config enables JIT without clang installed):
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.
Calling text conversion in a non-UTF8 database raises opencc requires a UTF8 database.
3. Try your first conversions
Context-aware phrase conversion — Notice how
s2twptranslates the hardware term内存条while leaving the classical line海内存知己intact:Compare glyph-only vs. regional phrases — Every shorthand wrapper (such as
opencc.s2t,opencc.s2twp,opencc.tw2sp) is identical toopencc.convert(input, '<config>'):Target a locale with
opencc.localize()— Convert one Mainland source string into multiple regional variants in one query:List all built-in configs and routes:
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
1. Cross-script search with expression indexes
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:
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:
Inspect the exact config chain used for any region pair:
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):
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):
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:
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:
Restart PostgreSQL, then verify which configs are loaded in the current backend:
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:
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
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
| Config | Source → Target | Regional phrases | Maturity | Shorthand function |
|---|---|---|---|---|
s2t / t2s | zh-Hans ↔ zh-Hant | No | stable | opencc.s2t() / opencc.t2s() |
s2tw / tw2s | zh-Hans ↔ zh-TW | No | stable | opencc.s2tw() / opencc.tw2s() |
s2twp / tw2sp | zh-Hans ↔ zh-TW | Yes | stable | opencc.s2twp() / opencc.tw2sp() |
s2hk / hk2s | zh-Hans ↔ zh-HK | No | stable | opencc.s2hk() / opencc.hk2s() |
s2hkp / hk2sp | zh-Hans ↔ zh-HK | Yes | developing | opencc.s2hkp() / opencc.hk2sp() |
t2tw / tw2t | zh-Hant ↔ zh-TW | No | stable | opencc.t2tw() / opencc.tw2t() |
t2hk / hk2t | zh-Hant ↔ zh-HK | No | stable | opencc.t2hk() / opencc.hk2t() |
t2jp / jp2t | zh-Hant ↔ ja | No | experimental | opencc.t2jp() / opencc.jp2t() |
Conversion functions
opencc.convert(input text, config text), ,- Convert text using one of the 16 built-in config names above.
opencc.localize(input text, target text, source text), ,- Route between
zh-Hans,zh-Hant,zh-CN,zh-TW,zh-HK, andja. Namesourceexplicitly to translate regional phrases. opencc.<config>(input text), ,- Shorthand wrappers for all 16 configs (
s2t,t2s,s2tw,tw2s,s2twp,tw2sp,s2hk,hk2s,s2hkp,hk2sp,t2tw,tw2t,t2hk,hk2t,t2jp,jp2t), equivalent toopencc.convert(input, '<config>').
Script detection and inspection
opencc.detect(input text), ,- Heuristic script classification:
none,neutral,simplified,traditional,mixed, orjapanese. opencc.script_stats(input text), ,- Returns
(han integer, simplified integer, traditional integer, kana integer). opencc.explain(input text, config text), ,- Returns
(seq integer, source text, steps text[], output text)showing every conversion stage per segment. opencc.ambiguities(input text, config text), ,- Returns
(pos integer, len integer, source text, output text, candidates text[])for one-to-many dictionary spans. opencc.candidates(word text, config text), ,- Return every candidate output for
wordunderconfig(default first;{}if absent).
Views and operations
opencc.configs, ,- Lists all 16 configs (
name,source,target,phrases,maturity,description,loaded).loadedreflects the current backend. opencc.routes, ,- Lists all 36
localize()region pairs (source,target,chain,maturity). opencc.version(), ,STABLE. Returns(extension text, opencc text, dictionary text)including the SHA-256 digest of embedded dictionaries.opencc.dependents(), ,STABLE. Returns(kind text, object text, uses text, action text)for stored catalog dependents and their rebuild SQL.
Configuration (GUC)
opencc.preload, ,- Comma-separated config names (or
'all') to initialize when the library loads. Combine withshared_preload_libraries = 'opencc'and restart PostgreSQL to share read-only dictionary pages across backends.