ALTER TEXT SEARCH CONFIGURATION ADD MAPPING for an already-mapped token type fails with a raw unique_violation (23505) on pg_ts_config_map_index instead of a duplicate-object error ==================================================================================================================================================================================== AI-generated bug report from the AI Annex Report ID: 01a11f5b-fd55-7cc2-9db4-1c2a6b93bfdb Filed: 2026-10-09 06:31:24 UTC Severity: 20/100 Blamed commit: 140d4ebcb46e17cdb1be43892ed797e5e060c8ef ## Summary `ALTER TEXT SEARCH CONFIGURATION ... ADD MAPPING FOR token_type WITH dictionary` is documented to fail when the configuration already has a mapping for that token type. It does fail, but not with a proper error: `MakeConfigurationMapping()` never checks for an existing mapping in the ADD case, so the statement is rejected by the unique index `pg_ts_config_map_index` and the user sees ``` ERROR: duplicate key value violates unique constraint "pg_ts_config_map_index" ``` with SQLSTATE 23505 (`unique_violation`) instead of a duplicate-object error (42710) naming the token type, as `DROP MAPPING` already does for the "does not exist" case. The error exposes a catalog index name and an OID that mean nothing to the user, and the wrong SQLSTATE class can misroute application error handling (an integrity-constraint violation rather than a DDL "object already exists" condition). Tom Lane noted this as unfriendly on pgsql-hackers in December 2007, but it was never followed up. It is present in all supported branches and on master. ## Reproduction Tested on master at 412848dac37f2e4455e1505f83f0af0f3d28a67d (meson debug build with assertions). Any session with ownership of a text search configuration will do: ```sql \set VERBOSITY verbose CREATE TEXT SEARCH CONFIGURATION tscfg_dup (PARSER = default); ALTER TEXT SEARCH CONFIGURATION tscfg_dup ADD MAPPING FOR asciiword WITH english_stem; ALTER TEXT SEARCH CONFIGURATION tscfg_dup ADD MAPPING FOR asciiword WITH simple; ``` Actual output of the second `ADD MAPPING`: ``` ERROR: 23505: duplicate key value violates unique constraint "pg_ts_config_map_index" DETAIL: Key (mapcfg, maptokentype, mapseqno)=(16384, 1, 1) already exists. SCHEMA NAME: pg_catalog TABLE NAME: pg_ts_config_map CONSTRAINT NAME: pg_ts_config_map_index LOCATION: _bt_check_unique, nbtinsert.c:667 ``` Expected: an `ERRCODE_DUPLICATE_OBJECT` error in the style of the existing `DROP MAPPING` message, for example ``` ERROR: 42710: mapping for token type "asciiword" already exists ``` The same unique-violation error appears when an already-mapped type is mixed with new ones (`ADD MAPPING FOR word, asciiword WITH simple`) and for a configuration created with `COPY = english`, whose inherited mappings collide in the same way. The documented alternatives behave as described: ```sql ALTER TEXT SEARCH CONFIGURATION tscfg_dup ALTER MAPPING FOR asciiword WITH simple; -- ok ALTER TEXT SEARCH CONFIGURATION tscfg_dup ALTER MAPPING FOR asciiword REPLACE simple WITH english_stem; -- ok ``` The catalog is left unchanged by the failed statements (the row for `asciiword` still maps to `english_stem`), so there is no state damage; only the error report is wrong. ## Analysis The reference page `doc/src/sgml/ref/alter_tsconfig.sgml` says: > The ADD MAPPING FOR form installs a list of dictionaries to be > consulted for the specified token type(s); it is an error if there > is already a mapping for any of the token types. The ALTER MAPPING > FOR form does the same, but first removing any existing mapping for > those token types. In `src/backend/commands/tsearchcmds.c`, `AlterTSConfiguration()` calls `MakeConfigurationMapping()` for every form that carries a dictionary list. The grammar (`src/backend/parser/gram.y`) sets `override = true` only for `ALTER MAPPING FOR ... WITH`; `ADD MAPPING` has `override = false, replace = false`, and both `REPLACE` forms have `override = false, replace = true`. `MakeConfigurationMapping()` scans `pg_ts_config_map` for the target token types only under `if (stmt->override)`, where it deletes the rows it finds. In the non-override, non-replace branch it builds new tuples with `mapseqno` running from 1 to the number of dictionaries and hands them to `CatalogTuplesMultiInsertWithInfo()`. Nothing checks whether a mapping is already there, so the primary-key index `pg_ts_config_map_index` on `(mapcfg, maptokentype, mapseqno)` (`src/include/catalog/pg_ts_config_map.h`) rejects the tuple with `mapseqno = 1` in `_bt_check_unique()`, producing the generic `unique_violation`. Every existing mapping has a row with `mapseqno = 1`: the bootstrap data starts there, `CREATE ... (COPY = ...)` copies the sequence numbers, `DROP MAPPING` removes all rows for a token type, and the `REPLACE` forms only change `mapdict`. So `ADD MAPPING` on an existing mapping always fails; it never silently appends. The bug is confined to how the failure is reported. Compare `DropConfigurationMapping()` in the same file, which does the scan and reports a proper `mapping for token type "%s" does not exist` with `ERRCODE_UNDEFINED_OBJECT`. The project treats a raw unique-index violation leaking out of DDL as something to fix; recent examples are 1b1960c8c9e81171efabdd9e3393b4eec1ffc477 ("Improve error message for duplicate labels when creating an enum type", which replaced the `pg_enum` unique-index error with an `ERRCODE_DUPLICATE_OBJECT` pre-check) and 3e91dba8b079c02dc5204108c7e797b402c75779 ("Fix various issues with ALTER TEXT SEARCH CONFIGURATION"), whose message lists "ADD MAPPING would fail on insertion because of a constraint failure" among the problems it fixed. That commit deduplicated token names listed twice in one statement but did not consider a mapping that already exists in the catalog. ### Blame The behavior is as old as in-core text search: 140d4ebcb46e17cdb1be43892ed797e5e060c8ef ("Tsearch2 functionality migrates to core", 2007-08-21) introduced `MakeConfigurationMapping()` with the override-only scan (`git log -S'delete maps for tokens if they exist'` finds only that commit). The block was restructured by 3e91dba8b079 in 2024 but kept the same condition. ### Affected branches master and REL_19_STABLE through REL_14_STABLE all contain the blamed commit. `tsearchcmds.c` is identical between master and REL_19_STABLE, and the older branches carry the same `if (stmt->override)` block (the 2024 commit was back-patched to all of them). Since the fix only improves an error message, it would normally be applied to master only, consistent with how 1b1960c8c9e was handled. ## Fix Run the existing per-token scan for both non-`REPLACE` forms, and make the action depend on `override`: delete the row for `ALTER MAPPING FOR ... WITH`, raise an error for `ADD MAPPING`: ```c if (!stmt->replace) { foreach(c, tokens) { ... while (HeapTupleIsValid((maptup = systable_getnext(scan)))) { if (stmt->override) CatalogTupleDelete(relMap, &maptup->t_self); else ereport(ERROR, (errcode(ERRCODE_DUPLICATE_OBJECT), errmsg("mapping for token type \"%s\" already exists", ts->name))); } ... ``` The `!stmt->replace` guard matters: both `REPLACE` forms arrive with `override = false`, and `ALTER MAPPING FOR word REPLACE a WITH b` must keep working on a token type that has a mapping. The `REPLACE` code path modifies rows in place and needs neither the deletion nor the check. The attached patch does this and adds two cases to `src/test/regress/sql/tsdicts.sql` (the file that already exercises `ADD MAPPING` on the `dummy_tst` configuration): the new error, and `ALTER MAPPING FOR word REPLACE ispell WITH simple`, a form that had no regression coverage and that directly guards the restructured condition. One minor behavioral consequence worth noting: with the patch, an `ADD MAPPING` for an already-mapped token type that also names a nonexistent dictionary now reports "already exists" rather than "text search dictionary ... does not exist", because the existence check runs before the dictionary lookup. That mirrors the existing `ALTER MAPPING` path, where the deletion of old rows also precedes the dictionary lookup. The message is a new translatable string, which is another reason to keep the change on master. ## Testing With the patch applied on 412848dac37: - Build is clean (debug build, `-Wtype-limits -Werror=missing-braces`), and `pgindent` reports no changes. - `meson test --suite setup --suite regress`: all 239 subtests pass, including the extended `tsdicts` test. - Re-running the reproduction above now yields `ERROR: 42710: mapping for token type "asciiword" already exists` for the plain, mixed-list, and `COPY = english` cases, while `ALTER MAPPING FOR ... WITH` and `ALTER MAPPING FOR ... REPLACE` continue to succeed. ## Prior discussion - pgsql-hackers, "little correction", 2007-12. Oleg Bartunov asked for a documentation example to use `ALTER MAPPING` instead of `ADD MAPPING` on a configuration that already had those mappings (Pine.LNX.4.64.0712121359480.13244@sn.sai.msu.ru). Tom Lane fixed the examples (e211470b195) and, after reproducing the unique-index error, wrote: "This is not very good --- we usually try to provide a more friendly error message than 'unique constraint violation' for duplicate system catalog entries. Not sure how hard it is to fix." (https://postgr.es/m/4027.1197527793@sss.pgh.pa.us). There was no further reply. - Bug #18310 (18310-1eb233c5908189c8@postgresql.org, 2024) covered the same token type listed twice within one statement, fixed by 3e91dba8b079; the pre-existing-mapping case was not discussed there.