DEV Community

Cover image for Quick conversion of Enums into Tables for Hasura
Olivier
Olivier

Posted on

Quick conversion of Enums into Tables for Hasura

tldr; I have a ton of Enums in my pretty schema but now Hasura tells me they want tables instead! Here is a script #regexForTheWin


Why?

Hasura recommends Tables versus Enum types see why here

How it works.js

Given a sql string with CREATE TYPEs. .. in it, convert them to CREATE TABLE.

Don't forget

Tell hasura to use those tables as enum tables and don't forget to update the fields that used to reference your enums by pointing to the table and adding foreign keys. For example:

ALTER TABLE myschema.users ADD CONSTRAINT
  myschema."usersStatus_fkey" FOREIGN KEY (status) REFERENCES myschema."Status";
Enter fullscreen mode Exit fullscreen mode

Here is the gist of it:

const regex = /(CREATE TYPE) ([^A]*) AS[^']*([^)]*)(\);)/gm;
const str = `--- put your Enum creates here ---
CREATE TYPE public."Status" AS ENUM (
'CONTACTED',
'INTERVIEWED',
'ACTIVE',
'COMPLETED',
'NOT_HIRED'
);
CREATE TYPE public."Method" AS ENUM (
'MAIL',
'PHONE',
'VISIT'
);
`;
const subst = `DROP TYPE IF EXISTS $2;\nCREATE TABLE $2 (value TEXT PRIMARY KEY);\nINSERT INTO $2 (value) SELECT unnest(ARRAY[$3]) as value;`;
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);

What you get

DROP TYPE IF EXISTS public."Status";
CREATE TABLE public."Status" (value TEXT PRIMARY KEY);
INSERT INTO public."Status" (value) SELECT unnest(ARRAY['CONTACTED',
'INTERVIEWED',
'ACTIVE',
'COMPLETED',
'NOT_HIRED'
]) as value;
DROP TYPE IF EXISTS public."Method";
CREATE TABLE public."Method" (value TEXT PRIMARY KEY);
INSERT INTO public."Method" (value) SELECT unnest(ARRAY['MAIL',
'PHONE',
'VISIT'
]) as value;
view raw output.sql hosted with ❤ by GitHub

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

Try REST API Generation for MS SQL Server.

DevOps for Private APIs. With DreamFactory API Generation, you get:

  • Auto-generated live APIs mapped from database schema
  • Interactive Swagger API documentation
  • Scripting engine to customize your API
  • Built-in role-based access control

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay