1

Is there a way to define an enum using a table's column names?

I have a users table defined as follows:

create table public.users (
  "id" serial not null unique primary key,
  "name" text not null check(length(name) > 1),
  "photo" text,
  "phone" text not null unique,
  "email" text not null unique,
  "bio" text,
  "socials" social[] not null
);

And then I want to define a required_profile_fields column in another table to be an enum containing only the column names in that public.users table:

create type profile_fields as enum('name', 'photo', 'email', 'phone');
create table public.orgs (
  "required_profile_fields" profile_fields[] not null check(array_length(required_profile_fields) > 0)
);

Is there a way that I can define that profile_fields as an enum from the column names in public.users?

2 Answers 2

3

You can try something like this:

DO
$$
BEGIN
EXECUTE (
  SELECT
    format('CREATE TYPE profile_fields AS ENUM (%s)', 
            string_agg( DISTINCT quote_literal(column_name), ', ') )
  FROM
    INFORMATION_SCHEMA.COLUMNS
  WHERE
    TABLE_NAME = 'users'
);
END 
$$
Sign up to request clarification or add additional context in comments.

1 Comment

Is there a way to ensure that this only accesses the columns names from public.users (i.e. only tables in the public schema)? I'm using Supabase which defines an auth.users table that I don't want to include in this enum.
0

Try this one

DO
$$
BEGIN
EXECUTE (
  SELECT
    format('CREATE TYPE profile_fields AS ENUM (%s)', 
            string_agg( DISTINCT quote_literal(column_name), ', ') )
  FROM
    INFORMATION_SCHEMA.COLUMNS
  WHERE
    TABLE_NAME = 'users'
);
END 
$$

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.