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";
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; |
Top comments (0)