我有一个包含复合类型字段的表。当我尝试对这些字段执行递归联合时,我得到了一个错误。

drop type example_t cascade;
create type example_t as (
    value text,
    key text
);

drop table if exists example cascade;
create table example (
    inbound example_t,
    outbound example_t,

    primary key (inbound, outbound)
);

create or replace function example_fn(_attrs example_t[])
returns table (attr example_t) as $$
    with recursive target as (
        select outbound
            from example
            where array[inbound] <@ _attrs
        union
        select r.outbound
            from target as t
            inner join example as r on r.inbound = t.outbound
    )
    select unnest(_attrs)
    union
    select * from target;
$$ language sql immutable;


select example_fn(array[('foo', 'bar') ::example_t]);
ERROR: could not implement recursive UNION DETAIL: All column datatypes must be hashable. CONTEXT: SQL function "example_fn" during startup SQL state: 0A000

非递归联合只起作用
create or replace function example_fn(_attrs example_t[])
returns table (attr example_t) as $$
    select unnest(_attrs)
    union
    select * from example;
$$ language sql immutable;

select example_fn(array[('foo', 'bar') ::example_t]);

我可以用这种方法重构我的函数以使其工作。但看起来很奇怪。我是说它不太可读。有没有更好的方法?
create or replace function example_fn(_attrs example_t[])
returns table (attr example_t) as $$
    with recursive target as (
        select (outbound).value, (outbound).key
            from example
            where array[inbound] <@ _attrs
        union
        select (r.outbound).value, (r.outbound).key
            from target as t
            inner join example as r on r.inbound = (t.value, t.key) ::example_t
    )
    select (unnest(_attrs)).*
    union
    select * from target;
$$ language sql immutable;

最佳答案

这里有a thread on PostgreSQL hackers mailing list和tom lane的简短解释:
一般来说,我们认为数据类型的相等概念可以由其默认的btree操作类(支持基于排序的查询算法)或其默认的哈希操作类(支持基于哈希的查询算法)定义。
普通的union代码支持排序或散列,但是我们还没有开始支持基于排序的递归联合方法。我不认为这值得做…
作为解决方法使用:

with recursive target as (
    select outbound
    from example
    where inbound = ('a', 'a')::example_t
    union all
    select r.outbound
    from target as t
    inner join example as r on r.inbound = t.outbound
)
select *
-- or, if necessary
-- select distinct *
from target

07-28 10:34