Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more succinct way to cast query results to a type?

I'm often casting query results to user defined types. Consider this simplistic example:

test=# create type test_type as  (a int, b int);
CREATE TYPE
test=# create table test_table (a int, b int);
CREATE TABLE
test=# insert into test_table values (1,2);
INSERT 0 1
test=# select r::test_type from (select * from test_table t) as r;
   r   
-------
 (1,2)
(1 row)

For a lot of my queries having a subquery is necessary and that works great. However, sometimes it's a simple 1 to 1 mapping from table to type, like in the example above.

Is there an easier way to express this?

When I try what seems obvious to me I get errors:

test=# select t::test_type from test_table t;
ERROR:  cannot cast type test_table to test_type
LINE 1: select t::test_type from test_table t;
                ^
like image 556
bhirt Avatar asked Oct 22 '25 04:10

bhirt


2 Answers

You can use the ROW construct with wildcard column expansion for this.

regress=> select ROW(t.*)::testtype from testtable t;
  row  
-------
 (1,2)
(1 row)
like image 84
Craig Ringer Avatar answered Oct 23 '25 19:10

Craig Ringer


A bit easier

select t::test_type
from (table test_table) t;

or create your own cast

create function test_table_2_test_type (test_table_value test_table)
returns test_type as $$
    select test_table_value.a, test_table_value.b;
$$ language sql;

create cast (test_table as test_type)
with function test_table_2_test_type (test_table);

select t::test_type 
from test_table t;
   t   
-------
 (1,2)

http://www.postgresql.org/docs/current/static/sql-createcast.html

like image 35
Clodoaldo Neto Avatar answered Oct 23 '25 19:10

Clodoaldo Neto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!