Foreign Keys
- The Fuel indexer service supports foreign key constraints and relationships using a combination of GraphQL schema and a database (whether Postgres or SQLite).
- There are two types of uses for foreign keys - implicit and explicit.
IMPORTANT:
Implicit foreign keys do not require a
@joindirective. When using implicit foreign key references, merely add the referenced object as a field type (shown below). A lookup will automagically be done to add a foreign key constraint using this object's'idfield.Note that implicit foreign key relationships only use the
idfield on the referenced table. If you plan to use implicit foreign keys, the object being referenced must have anidfield.In contrast, explicit foreign keys do require a
@joindirective. Explicit foreign key references work similarly to implicit foreign keys; however, when using explicit foreign key references, you must add a@joindirective after your object type. This@joindirective includes the field in your foreign object that you would like to reference (shown below).
- To demonstrate how the indexer uses GraphQL schema to resolve foreign key relationships, let's look at the following schema:
Usage
Implicit foreign keys
schema {
query: QueryRoot
}
type QueryRoot {
book: Book
library: Library
}
type Book {
id: ID!
name: Bytes8!
}
type Library {
id: ID!
book: Book!
}
Implicit foreign key breakdown
- Given the above schema, two entities will be created: a
Bookentity, and aLibraryentity. - As you can see, we add the
Bookentity as an attribute on theLibraryentity, thus conveying that we want a one-to-many or one-to-one relationship betweenLibraryandBook.- This means that for a given
Library, we may also fetch one or manyBookentities. - This also means that the column
library.bookwill be an integer type that referencesbook.id
- This means that for a given
Explicit foreign keys
schema {
query: QueryRoot
}
type QueryRoot {
book: Book
library: Library
}
type Book {
id: ID!
name: Bytes8! @unique
}
type Library {
id: ID!
book: Book! @join(on:name)
}
Explicit foreign key breakdown
- For the most part, this works the same way as implicit foreign key usage
- However, as you can see, instead of implicitly using
book.idas the reference column for ourBookobject, we're instead explicitly specifying that we wantbook.nameto serve as our foreign key.- Also note that since we're using
book.namein our foreign key constraint, that column is required to be unique -- via the@uniquedirective
- Also note that since we're using
Important:
- At the moment, due to some SQLite quirks, the Fuel indexer SQLite support only offers foreign key relationships, not foreign key constraints. We are very much open to changing this in the future.