Skip to content

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

Return to the regular view of this page

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.

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.

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 - 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;