2018-09-11 14:11:24 +03:00
|
|
|
Enum type fields
|
|
|
|
================
|
|
|
|
|
2018-12-03 15:12:24 +03:00
|
|
|
.. contents:: Table of contents
|
|
|
|
:backlinks: none
|
|
|
|
:depth: 1
|
|
|
|
:local:
|
|
|
|
|
2018-09-11 14:11:24 +03:00
|
|
|
Enum type fields can only take a value from a fixed set of allowed values.
|
|
|
|
|
|
|
|
In a relational database such as Postgres, an enum type field in a table can be defined by setting a foreign-key
|
|
|
|
to another table which contains the reference list of allowed values. This ensures a value can be set into the field
|
|
|
|
only if it exists in the reference table.
|
|
|
|
|
2018-12-03 15:12:24 +03:00
|
|
|
**For example**, let's say we have a table ``magazine`` with fields ``(id, title, issue_month, issue_year)``
|
2018-10-10 09:32:03 +03:00
|
|
|
and we would like to restrict the values of the ``issue_month`` field to just the months of the year (i.e. January,
|
|
|
|
February, and so on).
|
2018-09-11 14:11:24 +03:00
|
|
|
|
2018-12-03 15:12:24 +03:00
|
|
|
Create a reference table for the enum
|
|
|
|
-------------------------------------
|
2018-09-11 14:11:24 +03:00
|
|
|
|
|
|
|
Open the Hasura console and head to the ``Data -> Create table`` interface.
|
|
|
|
|
2018-10-10 09:32:03 +03:00
|
|
|
Create a table ``months_of_the_year`` with just one column ``month``, which is the primary key:
|
2018-09-11 14:11:24 +03:00
|
|
|
|
2019-03-13 13:03:45 +03:00
|
|
|
.. thumbnail:: ../../../img/graphql/manual/schema/enum-create-ref-table.png
|
2018-09-11 14:11:24 +03:00
|
|
|
|
2018-12-03 15:12:24 +03:00
|
|
|
Add the allowed enum values to the reference table
|
|
|
|
--------------------------------------------------
|
2018-09-11 14:11:24 +03:00
|
|
|
|
2018-10-10 09:32:03 +03:00
|
|
|
Head to the ``GraphiQL`` tab of the console and run an insert mutation to insert the allowed enum values:
|
2018-09-11 14:11:24 +03:00
|
|
|
|
2019-03-13 13:03:45 +03:00
|
|
|
.. thumbnail:: ../../../img/graphql/manual/schema/enum-insert-ref-values.png
|
2018-09-11 14:11:24 +03:00
|
|
|
|
2018-12-03 15:12:24 +03:00
|
|
|
Add a foreign-key constraint to the reference table
|
|
|
|
---------------------------------------------------
|
2018-09-11 14:11:24 +03:00
|
|
|
|
2018-10-10 09:32:03 +03:00
|
|
|
Head to the ``Data -> magazine -> Modify`` tab of the console and set a foreign-key to the ``months_of_the_year`` table
|
|
|
|
using the fields: ``issue_month -> months_of_the_year :: month``:
|
2018-09-11 14:11:24 +03:00
|
|
|
|
2019-03-13 13:03:45 +03:00
|
|
|
.. thumbnail:: ../../../img/graphql/manual/schema/enum-set-foreign-key.png
|
2018-09-11 14:11:24 +03:00
|
|
|
|
|
|
|
Now the ``issue_month`` field can only take values from the months of the year.
|
|
|
|
|
2019-01-15 13:49:58 +03:00
|
|
|
.. admonition:: Current limitation
|
|
|
|
|
|
|
|
This does not generate GraphQL schema enums as of now but it ensures consistency in the database.
|