Postgres - Could not determine polymorphic type using ANY, ARRAY_AGG

1.7k views Asked by At

I'm trying to indicate superusers in a USERS/GROUPS data model as follows:

create table users (user_id int);
create table groups (group_id int, superuser boolean);
create table usergroup( user_id int, group_id int );

select users.user_id,
('t' = any( array_agg('superuser')  ))
from users 
left join usergroup using(user_id)
left join groups using (group_id)
group by user_id

but Postgres (9.1) tells me:

error : ERROR:  could not determine polymorphic type because input has type "unknown"

From this I gather that I should be adding an explicit Cast somewhere, but I can't figure out where. Can anyone advise?
I'd like an explained answer if possible, so I can learn from this

1

There are 1 answers

0
maniek On BEST ANSWER

Your query can be fixed like this:

select users.user_id,
(true = any( array_agg(superuser)  ))
from users 
left join usergroup using(user_id)
left join groups using (group_id)
group by user_id

You were doing array_agg on 'superuser' text literal, instead of the superuser column.

I would write it like so:

select users.user_id,
exists (
    select * 
    from usergroup ug, groups g 
    where ug.user_id = users.id
    and ug.group_id = g.id
    and ug.superuser
) as is_superuser
from users