Okay maybe I'm a complete idiot. But how can I cre...
# sql
d
Okay maybe I'm a complete idiot. But how can I create a function for
Copy code
RETURN QUERY SELECT ST_AsEWKT(location) AS location, *
  FROM public.users
  WHERE user_id = p_user_id
  LIMIT 1;
Where
p_user_id
is the function param of type
uuid
?
g
Did the function not get created if so what is the error. Seemed like you got it created based on your comment.
d
Copy code
[2022-03-09 13:50:58] [42P13] ERROR: return type mismatch in function declared to return users
[2022-03-09 13:50:58] Detail: Final statement returns too many columns.
[2022-03-09 13:50:58] Where: SQL function "get_user"
Copy code
CREATE OR REPLACE FUNCTION get_user(p_user_id uuid) RETURNS SETOF public.users AS
$func$
SELECT *, ST_AsEWKT(location) as location
FROM public.users
WHERE user_id = $1;
$func$ LANGUAGE sql;
I understand the error, I just don't know what to do?
I guess I'll remove the * and add each column manually 😦
g
setof requires an exact match to the public.users columns, can't add anything. record or setof record might work.
d
Hmm let me check
g
if not then you have to do table return and specify every column
d
With record I get
Copy code
a column definition list is required for functions returning "record"
g
Have to go with table then... I'm not great at this record stuff, it may just be you can't use *, but have to specify the columns for setof record to work.
This works, so something more than just extra column ...
Copy code
create or replace function test()
returns setof record as $$
select *,'1' from messages;
$$
language sql;
d
Yeah. The real issue is that I can't query with a parenthesis since the library's think it's an inner join which is why I'm trying to make this a function.
That doesn't work for me.
Copy code
postgres: public, extensions> SELECT * FROM test()
[2022-03-09 14:31:51] [42601] ERROR: a column definition list is required for functions returning "record"
[2022-03-09 14:31:51] Position: 15
g
Try just select test()
d
Yeah but it's in a weird tuple
g
It will return a table in the rpc call with rows like this:
With my limited knowledge I would go with table if I need select * to work as it defines all the columns
d
I figured out something 200iq
Copy code
DROP FUNCTION get_user(uuid);

CREATE OR REPLACE FUNCTION get_user(p_user_id uuid)
    RETURNS TABLE
            (
                users_row       public.users,
                ewkb_location text
            )
    LANGUAGE plpgsql
AS
$func$
BEGIN
    RETURN QUERY
        SELECT u, ST_AsEWKT(location) as location
        FROM public.users as u
        WHERE u.user_id = p_user_id;
END
$func$;
g
scott will come back and laugh at us...
d
Lmao it's rough out here