Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update enums docs #2813

Merged
merged 14 commits into from Sep 3, 2019
Expand Up @@ -3,7 +3,7 @@ import Toggle from 'react-toggle';
import styles from '../../../../Common/Common.scss';

const enumCompatibilityDocsUrl =
'https://docs.hasura.io/1.0/graphql/manual/schema/enums.html#create-an-enum-table';
'https://docs.hasura.io/1.0/graphql/manual/schema/enums.html#create-enum-table';

export const EnumTableModifyWarning = ({ isEnum }) => {
if (!isEnum) {
Expand Down
Expand Up @@ -52,14 +52,14 @@ Args syntax
* - is_enum
- false
- Boolean
- When set to ``true``, creates the table as an :ref:`enum table <enum table>`.
- When set to ``true``, creates the table as an :ref:`enum table <create_enum_table>`.

.. _set_table_is_enum:

set_table_is_enum
-----------------

``set_table_is_enum`` sets whether an already-tracked table should be used as an :ref:`enum table <enum table>`.
``set_table_is_enum`` sets whether an already-tracked table should be used as an :ref:`enum table <create_enum_table>`.

Use table ``user_role`` as an enum table:

Expand Down
192 changes: 129 additions & 63 deletions docs/graphql/manual/schema/enums.rst
@@ -1,41 +1,59 @@
Enum type fields
================

Enum type fields are restricted to a fixed set of allowed values. In a relational database such as
Postgres, an enum type field in a table can be defined in two ways:
.. contents:: Table of contents
:backlinks: none
:depth: 2
:local:

1. Using `native Postgres enum types <https://www.postgresql.org/docs/current/datatype-enum.html>`__.
Enum type fields are restricted to a fixed set of allowed values.

While the most obvious solution, native enum types have significant drawbacks: they are not easily mutable.
New values cannot be added to an enum inside a transaction (that is, ``ALTER TYPE ... ADD VALUE`` is not
supported by transactional DDL), and values cannot be removed from an enum at all without completely dropping
and recreating it (which cannot be done if the enum is in use by *any* tables, views, or functions). Therefore,
native enum types should only be used for enums that are guaranteed to *never* change, such as days of the
week.
Enums in a database
-------------------

2. Using `foreign-key references <https://www.postgresql.org/docs/current/tutorial-fk.html>`__ to a single-column
table.
In a relational database such as Postgres, an enum type field in a table can be defined in two ways:

This approach represents an enum using ordinary relational database concepts. The enum type is represented by a
table, and the values of the enum are rows in the table. Columns in other tables that use the enum are ordinary
foreign-key references to the enum table.
.. _native_pg_enum:

For enums with values that are dynamic and may require updates, such as a list of tags or user roles, this
approach is strongly recommended. Modifying an enum defined this way is easy: simply insert, update, or delete
rows in the enum table (and updates or deletes can even be cascaded to references, and they may be done within
a transaction).
Using `native Postgres enum types <https://www.postgresql.org/docs/current/datatype-enum.html>`__
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Given the limitations of native Postgres enum types, Hasura currently only generates GraphQL enum types for enums
defined using the second approach (i.e. referenced tables). You may use native Postgres enum types in your database
schema, but they will essentially be treated like text fields in the generated GraphQL schema. Therefore, this guide
focuses primarily on modeling an enum using a reference table, but you may still use native Postgres enum types to
help maintain data consistency in your database.
While the most obvious solution, native enum types have significant drawbacks: they are not easily mutable.
New values cannot be added to an enum inside a transaction (that is, ``ALTER TYPE ... ADD VALUE`` is not
supported by transactional DDL), and values cannot be removed from an enum at all without completely dropping
and recreating it (which cannot be done if the enum is in use by *any* tables, views, or functions). Therefore,
native enum types should only be used for enums that are guaranteed to *never* change, such as days of the
week.

Example: Modeling an enum using an enum table
---------------------------------------------
.. _reference_table_enum:

Let’s say we have a database that tracks user information, and users may only have one of three specific roles: user,
moderator, or administrator. To represent that, we might have a ``users`` table with the following schema:
Using `foreign-key references <https://www.postgresql.org/docs/current/tutorial-fk.html>`__ to a single-column table
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

This approach represents an enum using ordinary relational database concepts. The enum type is represented by a
table, and the values of the enum are rows in the table. Columns in other tables that use the enum are ordinary
foreign-key references to the enum table.

For enums with values that are dynamic and may require updates, such as a list of tags or user roles, this
approach is strongly recommended. Modifying an enum defined this way is easy: simply insert, update, or delete
rows in the enum table (and updates or deletes can even be cascaded to references, and they may be done within
a transaction).

Enums in the Hasura GraphQL engine
----------------------------------

Given the limitations of native Postgres enum types (as described :ref:`above <native_pg_enum>`), Hasura
currently only generates GraphQL enum types for enums defined using the
:ref:`referenced tables <reference_table_enum>` approach.

You may use native Postgres enum types in your database schema, but they will essentially be treated like text
fields in the generated GraphQL schema. Therefore, this guide focuses primarily on modeling an enum using a
reference table, but you may still use native Postgres enum types to help maintain data consistency in your
database. You can always choose to create a table with the values of a Postgres enum as shown in the
:ref:`section below <create_enum_table_from_pg_enum>`.

**Example:** Let’s say we have a database that tracks user information, and users may only have one of three specific
roles: user, moderator, or administrator. To represent that, we might have a ``users`` table with the following schema:

.. code-block:: sql

Expand All @@ -61,12 +79,14 @@ This works alright, but it doesn’t prevent us from inserting nonsensical value
INSERT INTO users (name, role) VALUES
('Hal', 'spaghetti');

which we certainly don’t want. Let’s create an enum to restrict the allowed values.
which we certainly don’t want. Hence we should create an enum to restrict the allowed values.

Create an enum table
^^^^^^^^^^^^^^^^^^^^
.. _create_enum_table:

To represent our enum, we’re going to create an _`enum table`, which for Hasura’s purposes is any table that meets
Creating an enum compatible table
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

To represent an enum, we’re going to create an _`enum table`, which for Hasura’s purposes is any table that meets
the following restrictions:

1. The table must have a single-column primary key of type ``text``. The values of this column are the legal values
Expand All @@ -75,8 +95,9 @@ the following restrictions:
2. Optionally, the table may have a second column, also of type ``text``, which will be used as a description of each
value in the generated GraphQL schema.
3. The table may not contain any other columns.
4. The table must contain at least 1 row.

For example, to create an enum that represents our user roles, we would create the following table:
**For example**, to create an enum that represents our user roles, we would create the following table:

.. code-block:: sql

Expand All @@ -90,42 +111,63 @@ For example, to create an enum that represents our user roles, we would create t
('moderator', 'Users with the privilege to ban users'),
('administrator', 'Users with the privilege to set users’ roles');

Use the enum table
^^^^^^^^^^^^^^^^^^
.. _create_enum_table_from_pg_enum:

Now that we’ve created an enum table, we need to update our ``users`` table to reference it:
.. admonition:: Creating an enum table from a native PG enum

.. code-block:: sql
You can create a table containing the values of a PG enum by executing the following SQL:

ALTER TABLE users ADD CONSTRAINT
users_role_fkey FOREIGN KEY (role) REFERENCES user_role;
.. code-block:: sql

Next, we need to tell Hasura that this table represents an enum. We can do that by passing ``true`` for the
``is_enum`` option of the :ref:`track_table` API, or we can use the :ref:`set_table_is_enum` API to change whether or
not an already-tracked table should be used as an enum:
CREATE TABLE "<my_enum_table>" (value TEXT PRIMARY KEY);
INSERT INTO "<my_enum_table>" (value) (SELECT unnest(enum_range(NULL::"<my_enum>")))::text);

.. code-block:: http
Next, we need to tell Hasura that this table represents an enum.

POST /v1/query HTTP/1.1
Content-Type: application/json
X-Hasura-Role: admin
Setting a table as an enum table
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

{
"type": "track_table",
"args": {
"table": {
"schema": "public",
"name": "user_role"
},
"is_enum": true
}
}
Once we have a table which satisfies the conditions for an enum table as described :ref:`above <create_enum_table>`,
we need to tell Hasura that this table represents an enum.

.. rst-class:: api_tabs
.. tabs::

.. tab:: Console

Head to the ``Modify`` tab of the table and toggle the switch in the
``Set table as enum`` section:

.. thumbnail:: ../../../img/graphql/manual/schema/enum-set.png

.. tab:: API

Make queries using enum values
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
A table can be set as an enum via the following 2 methods:

Once the table has been tracked as an enum, the GraphQL schema will be updated to reflect that the ``role`` column of
the ``users`` table only permits the values in the ``user_role`` table:
- passing ``true`` for the ``is_enum`` option of the :ref:`track_table` API while tracking a table
- using the :ref:`set_table_is_enum` API to change whether or not an already-tracked table should be used as
an enum

Using an enum table
^^^^^^^^^^^^^^^^^^^

To set a field of a table as an enum in the GraphQL schema, we need to set a reference from it to the enum table
via a foreign key.

**For example**, to update our ``users`` table to reference the ``user_role`` enum table:

.. code-block:: sql

ALTER TABLE users ADD CONSTRAINT
users_role_fkey FOREIGN KEY (role) REFERENCES user_role;

Making queries using enum values
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Once a table has been tracked as an enum, the GraphQL schema will be updated to expose the values of the
table as GraphQL enum values i.e. only the exposed values will be permitted for all fields referencing to it.

**For example**, the ``role`` column of the ``users`` table only permits the values in the ``user_role`` table:

.. code-block:: graphql

Expand Down Expand Up @@ -153,7 +195,11 @@ a string:
:view_only:
:query:
{
users(where: {role: {_eq: administrator}}) {
users(
where: {
role: {_eq: administrator}
}
) {
id
name
}
Expand All @@ -170,7 +216,27 @@ a string:
}
}

.. admonition:: Current limitations
Enums and migrations
^^^^^^^^^^^^^^^^^^^^

As enum tables have a requirement to contain at least 1 row, it is necessary to have a migration which inserts
values into an enum table. Otherwise while applying migrations an error would be thrown while trying to set the
table as an enum.

The migration which inserts values into an enum table needs to be between the migration creating the table
and the migration setting it as an enum.

This can be achieved via the console by performing the following steps while setting up an enum table:

1. Create the enum table
2. Use the ``RawSQL`` tab of the console to insert the enum values into the table and mark the insert as a migration
3. Set the table as an enum

You can also :doc:`manually create migration files <../migrations/advanced/writing-migrations-manually>` to achieve
this.

Current limitations
^^^^^^^^^^^^^^^^^^^

Currently, Hasura does not automatically detect changes to the contents of enum tables, so the GraphQL schema will
only be updated after manually reloading metadata after inserting, updating, or deleting rows from an enum table.
Currently, Hasura does not automatically detect changes to the contents of enum tables, so the GraphQL schema will
only be updated after manually reloading metadata after inserting, updating, or deleting rows from an enum table.
Binary file added docs/img/graphql/manual/schema/enum-set.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.