-1

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;
  1. 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?

  2. 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.

ma11hew28
  • 121,420
  • 116
  • 450
  • 651

2 Answers2

0
  1. 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).

  2. Use SETOF so that 0 rows are returned when none exist. Otherwise, you'll get 1 empty row.

ma11hew28
  • 121,420
  • 116
  • 450
  • 651
0

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.

NAmorim
  • 706
  • 6
  • 12