PostgreSQL错误:函数to_tsvector(字符变化,未知)不存在

Dfr*_*Dfr 5 sql postgresql types full-text-search casting

这个psql会话片段应该是不言自明的:

psql (9.1.7)
Type "help" for help.
=> CREATE TABLE languages(language VARCHAR NOT NULL);
CREATE TABLE
=> INSERT INTO languages VALUES ('english'),('french'),('turkish');
INSERT 0 3
=> SELECT language, to_tsvector('english', 'hello world') FROM languages;
 language|     to_tsvector     
---------+---------------------
 english | 'hello':1 'world':2
 french  | 'hello':1 'world':2
 turkish | 'hello':1 'world':2
(3 rows)

=> SELECT language, to_tsvector(language, 'hello world') FROM languages;
ERROR:  function to_tsvector(character varying, unknown) does not exist
LINE 1: select language, to_tsvector(language, 'hello world')...
                         ^
HINT:  No function matches the given name and argument types.  
You might need to add explicit type casts.
Run Code Online (Sandbox Code Playgroud)

问题是Postgres函数to_tsvector不喜欢varchar字段类型,但根据文档,这个调用应该完全正确吗?

Erw*_*ter 8

使用显式类型转换:

SELECT language, to_tsvector(language::regconfig, 'hello world') FROM languages;
Run Code Online (Sandbox Code Playgroud)

或者将列更改languages.language为键入regconfig.请参阅@ Swav的回答.

为什么?

Postgres允许函数重载.函数签名由它们(可选的模式限定的)名称加上(列表)输入参数类型定义.to_tsvector()expect 参数的2参数形式regconfig作为第一个参数:

SELECT proname, pg_get_function_arguments(oid)
FROM   pg_catalog.pg_proc
WHERE  proname = 'to_tsvector'

   proname   | pg_get_function_arguments
-------------+---------------------------
 to_tsvector | text
 to_tsvector | regconfig, text             -- you are here
Run Code Online (Sandbox Code Playgroud)

如果没有现有函数完全匹配,则函数类型解析的规则决定最佳匹配 - 如果有的话.这是成功的 to_tsvector('english', 'hello world'),因为'english'它是一个无类型的字符串文字.但是输入varchar参数失败,因为没有注册的隐式强制varchar转换regconfig.手册:

丢弃输入类型不匹配且无法转换(使用隐式转换)匹配的候选函数.为此目的,假定未知文字可转换为任何东西.

大胆强调我的.
注册演员阵容regconfig:

SELECT castsource::regtype, casttarget::regtype, castcontext
FROM   pg_catalog.pg_cast
WHERE  casttarget = 'regconfig'::regtype;

 castsource | casttarget | castcontext
------------+------------+-------------
 oid        | regconfig  | i
 bigint     | regconfig  | i
 smallint   | regconfig  | i
 integer    | regconfig  | i
Run Code Online (Sandbox Code Playgroud)

解释castcontext:

castcontext char
指示可以调用强制转换的上下文.e仅表示显式强制转换(使用CAST::语法).a 意味着隐式地分配给目标列,也明确表示.i在表达式中隐含地表示,以及其他情况.

在CREATE CAST一章中阅读有关三种不同类型赋值的 更多信息.