我有PostgreSQL函数 test(integer)采用整数参数和同名的重载函数 test(字符变化)。
当使用空值调用此函数时,Postgres总是执行函数 integer 参数。为什么会发生这种情况?为什么Postgres不选择带有 varchar 参数的函数?
函数调用示例:
select test(null); 解决方案www.postgresql/docs/current/interactive/typeconv-func.htmlrel =nofollow> 功能类型解析 。详细说明在手册中。相关:
- 有一种方法可以在Postgres中禁用函数重载
NULL没有显式类型转换开始类型未知:
SELECT pg_typeof(NULL) pg_typeof ----------- unknown实际上,我有可疑,并进行了一个快速测试,只是为了在Postgres 9.3和9.4找到不同的结果。 varchar 取自 integer (其中 奇怪 结果):
SQL Fiddle
我认为相应的规则是在列表中的点4e(没有更早的点决定匹配):
在每个位置,如果任何候选人接受该类别,请选择字符串类别。 (这种偏向字符串是适当的,因为未知类型的文字看起来像一个字符串。)
函数与输入类型 text 到重载的混合, text 将被选中 varchar 。
个人我几乎总是使用文本 code> varchar 。虽然是二进制兼容的(因此几乎但不完全相同), text 在各方面都更接近Postgres的核心。
我添加到小提琴,以及另一个例子,其中Postgres不能决定和引发一个发脾气。
如果你想选择一个特定的函数,add一个显式的类型转换(这就是这里的方式!):
select test(null :: int)AS func_int ,test(null :: varchar)AS func_vc;
I have PostgreSQL function named test(integer) taking an integer parameter and an overloaded function of the same name test(character varying).
When calling this function with a null value, Postgres always executes the function taking an integer parameter. Why does this happen? Why doesn't Postgres chose the function with a varchar parameter?
Function call example:
select test(null);解决方案
That's decided by the rules of Function Type Resolution. Detailed explanation in the manual. Related:
- Is there a way to disable function overloading in Postgres
NULL without explicit type cast starts out as type "unknown":
SELECT pg_typeof(NULL) pg_typeof ----------- unknownActually, I got suspicious and ran a quick test, just to find different results in Postgres 9.3 and 9.4. varchar is picked over integer (which oddly contradicts your findings):
SQL Fiddle.
I would think the according rule is point 4e in the list (none of the earlier points decide the match):
At each position, select the string category if any candidate accepts that category. (This bias towards string is appropriate since an unknown-type literal looks like a string.)
If you added another function with input type text to the overloaded mix, text would be picked over varchar.
Personally I almost always use text instead of varchar. While being binary compatible (so almost but not quite the same), text is closer to the heart of Postgres in every respect.
I added that to the fiddle, as well as another example where Postgres cannot decide and throws a tantrum.
If you want to pick a particular function, add an explicit type cast (that's the way to go here!):
select test(null::int) AS func_int , test(null::varchar) AS func_vc;
更多推荐
PostgreSQL函数调用
发布评论