【发布时间】:2017-11-02 14:05:49
【问题描述】:
在 Postgres 9.6 中使用函数转换为复合类型时,我遇到了一个奇怪的行为。
我已将复合类型“向量”声明为 x,y,z - 每个双精度以及如下强制类型转换:
create type vector as(
x double precision,
y double precision,
z double precision
);
create cast (text as vector)
with function vector_from_text(text) as implicit;
函数vector_from_text如下所示:
create or replace function vector_from_text(text, out result vector) strict immutable language plpgsql as $$
declare
d double precision[];
begin
result := null;
if ($1 is null) then
return;
end if;
begin
with c1 as (
select $1::jsonb src
)
select row((src->>'x')::double precision, (src->>'y')::double precision, (src->>'z')::double precision)::vector
**into result** -- see below
from c1;
exception
when others then
d := translate($1, '()', '{}')::double precision[];
result := row(d[1], d[2], d[3])::vector;
end;
end$$
;
该函数在 null 上返回 null,或者为两种输入格式返回一个向量类型,一个 json 字符串,如 '{"x":0, "y":0, "z":0}' 或一个构造函数表达式,如'(0,0,0)'。
问题:
对于 类似json 的输入,函数会返回错误
invalid input syntax for type double precision: "(0,0,0)"
只要选择语句包含 into result 行。如果我删除此行或将输出变量从 result 更改为 text 类型,则函数将按预期工作。
为什么不能将已经为类型 vector 转换的值分配到向量中?不明白!
【问题讨论】:
标签: postgresql types casting composite