7

I have the following enum declaration:
CREATE TYPE known_roles_list AS ENUM ('role1', 'role2')

When the DB executes a certain query, I wish to check if they're doing it with one of these roles, and if not - let the query go through. Something like:

IF current_user NOT IN known_roles_list THEN
    RETURN OLD; 
END IF;

Obviously, that code above didn't work (raised runtime comparison errors). Nor did unnest()-ing the enum values and searching within them.

How can I make that search - and see if any of the enum's values match the current_user value? (The current_user value is just an example - later, I need to compare these enum values to a row value, denoted by column)

Thanks!

2
  • You could use row level security and add a policy on each table. Commented Aug 20, 2018 at 4:16
  • Also, use a table rather than an enum. Commented Aug 20, 2018 at 5:45

2 Answers 2

10

You can use enum_range(null::known_roles_list) to get array listing elements of enum and then just use standard array operators. You need to cast that array to name[] or it won't be able to compare name and known_roles_list[].

postgres=> SELECT enum_range(null::known_roles_list);
  enum_range
---------------
 {role1,role2}

postgres=> SELECT current_user;
 current_user
--------------
 lkaminski

postgres=> SELECT current_user = any(enum_range(null::known_roles_list)::name[]);
 ?column?
----------
 f

postgres=> SELECT 'role2'::name = any(enum_range(null::known_roles_list)::name[]);
 ?column?
----------
 t

Enum functions: https://www.postgresql.org/docs/current/static/functions-enum.html

Any/Some: https://www.postgresql.org/docs/current/static/functions-comparisons.html#id-1.5.8.28.16

Sign up to request clarification or add additional context in comments.

Comments

4

Enumerated (enum) types are data types, so should be used when creating table structures

CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');
CREATE TABLE person (
    name text,
    current_mood mood
);
INSERT INTO person VALUES ('Moe', 'happy');
SELECT * FROM person WHERE current_mood = 'happy';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.