I wrote the following function:
-- Authenticate: Get session_id with user_id
CREATE OR REPLACE FUNCTION sessions_get(bigint) RETURNS SETOF char(32) AS
$$
SELECT strip_hyphens(id) as id FROM sessions WHERE user_id = $1;
$$
LANGUAGE SQL;
I want to be able to run the query SELECT sessions_get(1)
to get the session ID with user ID 1. And, I want the name of the column returned to be id
.
Is that possible? Or, would the query have to be SELECT * FROM sessions_get(1)
? In that case, it'd be shorter to just write SELECT sessions_get(1) as id
. Which is better?
Can I remove SETOF
since I know this function will always return 0 or 1 rows? I know this because user_id
is the primary key of the sessions
table.
Change the function to:
-- Authenticate: Get session_id with user_id CREATE FUNCTION sessions_get(bigint, OUT id char(32)) RETURNS SETOF char(32) AS $$ SELECT strip_hyphens(id) FROM sessions WHERE user_id = $1; $$ LANGUAGE SQL;
Then, use the query: SELECT * FROM sessions_get(1)
.
Use SETOF
so that 0 rows are returned when none exist. Otherwise, you'll get 1 empty row.
To avoid returning SETOF you can always do this:
CREATE OR REPLACE FUNCTION sessions_get(IN a bigint, OUT id char(32)) RETURNS char(32) AS
$$
SELECT strip_hyphens(id) INTO id FROM sessions WHERE user_id = $1;
RETURN;
$$
LANGUAGE SQL;
Hope it helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.