Is it possible to extend an existing datatype in PostgreSQL? Essentially, I want the equivalent of this TypeScript but in SQL:
interface Meeting {
id: number;
start: Date;
end: Date;
description: string;
}
interface ServiceHour extends Meeting {
total: number;
hours: number;
}
Because I have a function that returns all the columns from a meetings
table and then the additional two total
and hours
columns that are computed at query time. Here's what that function looks like:
create or replace function user_hours(org_id text, user_id text)
returns table (like meeting_instances)
as $$
select (sum(hours) over (order by _.instance_time)) total, * from (
select
extract(epoch from ((meeting_instances.time).to - (meeting_instances.time).from)) / 60 / 60 as hours,
meeting_instances.*
from meeting_instances inner join relation_people on relation_people.meeting = meeting_instances.id
where relation_people.user = user_id
and meeting_instances.org = org_id
and meeting_instances.instance_time <= current_date
) as _;
$$
language sql stable;
And right now, I'm getting a type mismatch error because table (like meeting_instances)
isn't the same as a table with the meeting_instances
columns and the two new hours
and total
columns. What I want to be able to do is something like this (obviously the syntax below doesn't actually exist... but I'm not sure if there's another way to do this with a similar shorthand syntax):
returns table (total float, hours float, meeting_instances.*)
returns table (total float, hours float) intersect (like meeting_instances)
returns table (total float, hours float) extends (like meeting_instances)
My current workaround is to create a view and then have that function simply query that view and return the view's type.
CREATE TABLE ...
). Seems like you have multiple layers of nested composite types. You can do that in Postgres. Doesn't mean you should. – TaciturnLIKE
clause on a table definition)? – WattersonRETURNS
clause, not anywhere else. ActuallyRETURNS (LIKE tbl)
is not even documented syntax. I am in the process of unravelling the multiple layers in an answer ... – Taciturnmeeting_instances.time
is already a nested composite type. And we don't know how deep the rabbit hole goes. – Taciturn