This is the multi-page printable view of this section.
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.
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.
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 - 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.