Unique constraints
This tutorial assumes that you have successfully completed the Get started with GraphQL tutorial, and that you still have the Cloud Console open in a browser tab/window, on the GraphQL Playground screen. If your Cloud Console session has expired:
|
This tutorial explores the @unique
directive, which allows you to
add constraints to your GraphQL schema. When you add @unique
to a
field definition, FaunaDB handles the creation of an index that enforces
this constraint.
Let’s define a simple user type, with a uniqueness constraint on the username, and see what happens when the constraint is triggered. The steps:
-
Create the file
schema-unique.gql
with the following content (or download it here):type User { username: String! @unique }
-
Import the new GraphQL schema into FaunaDB
Click the UPDATE SCHEMA button in the GraphQL Playground screen (in your browser), which opens your browser’s file selector. Select the
schema-unique.gql
file, and click the file selector’s Open button.This new schema only updates collections (and associated indexes) with the same name. Any other collections are unaffected. -
Let’s inspect the constraint via Fauna Shell.
Open a terminal and run:
fauna shell graphql
After Fauna Shell starts, run the following query:
Get(Index("unique_User_username"))
You should see output similar to:
{ ref: Index("unique_User_username"), ts: 1559780318060000, active: true, partitions: 1, name: 'unique_User_username', source: Collection("User"), data: { gql: { ts: Time("2019-06-06T00:18:37.979330Z") } }, values: [], terms: [ { field: [ 'data', 'username' ] } ], unique: true }
The
unique
field in the result is set to true, and the terms specify which field(s) need to be unique, i.e.data/username
. -
Copy the following GraphQL query:
mutation CreateAUser { createUser(data: { username: "Alice" }) { username } }
Then click the "new tab"
+
button on the GraphQL Playground screen in your browser (at the top left, just right of the last query tab). Paste the query into the left panel, and click the "Play" button. The query should execute and the response should appear in the right panel:{ "data": { "createUser": { "username": "Alice" } } }
-
Let’s see what happens when a duplicate user is added. Simply click the "Play" button a second time. The query should execute, and an error response should appear in the right panel:
{ "errors": [ { "message": "Document is not unique.", "extensions": { "code": "document not unique" } } ] }
Conclusion
This tutorial has demonstrated that the @unique
directive can be used
to apply a uniqueness constraint to a field in your GraphQL schema.
For more information, see the
@unique
reference.
Was this article helpful?
We're sorry to hear that.
Tell us how we can improve!
documentation@fauna.com
Thank you for your feedback!