0
CREATE OR REPLACE FUNCTION public.defaultmapviewport(hasura_session json)
 RETURNS viewport_info
 STABLE
AS $function$
    case hasura_session ->> 'x-hasura-default-country-code'
        when 'FR' then select lat, lng from places where slug_en = 'city-paris' 
        when 'ES' then select lat, lng from places where slug_en = 'municipality-madrid'
    end;
END $function$ language SQL;

I'm getting a syntax error near case, even though it seems right. What could be the problem?

Viewport info:

create table viewport_info(
    lat float,
    lng float
);
PlayMa256
  • 6,603
  • 2
  • 34
  • 54
  • 2
    `CASE` cannot exist on its own, it needs to be part of larger query e.eg. `SELECT CASE ...`. In other words you inverted the statement. See [CASE](https://www.postgresql.org/docs/current/functions-conditional.html#FUNCTIONS-CASE). – Adrian Klaver Dec 29 '21 at 19:59

1 Answers1

2

As @AdrianKlaver commented, a CASE expression can't stand on its own, it must be part of a SELECT query. You'll want to use

CREATE OR REPLACE FUNCTION public.defaultmapviewport(hasura_session json)
RETURNS viewport_info
STABLE
AS $function$
  SELECT lat, lng
  FROM places
  WHERE slug_en = (CASE hasura_session ->> 'x-hasura-default-country-code'
    WHEN 'FR' THEN 'city-paris' 
    WHEN 'ES' THEN 'municipality-madrid'
  END);
$function$ language SQL;

(online demo)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • i'm getting a return type mismatch in function declared to return viewport_info, I'll update question with the viewport_info create statement – PlayMa256 Dec 29 '21 at 20:09
  • 1
    @PlayMa256 Ah, there was a stray `END` at the end that I copied from the question. Fixed! – Bergi Dec 29 '21 at 20:35