In our API, each SQL table is reflected as a set of GraphQL types. At a high level, tables become types and columns/foreign keys become fields on those types.
By default, PostgreSQL table and column names are not inflected when reflecting GraphQL names. For example, an account_holder table has GraphQL type name account_holder. In cases where SQL entities are named using snake_case, enable inflection to match GraphQL/Javascript conventions e.g. account_holder -> AccountHolder.
Individual table, column, and relationship names may also be manually overridden.
Primary Keys (Required)
Every table must have a primary key for it to be exposed in the GraphQL schema. For example, the following Blog table will be available in the GraphQL schema as blogCollection since it has a primary key named id:
The Query type is the entrypoint for all read access into the graph.
Node
The node interface allows for retrieving records that are uniquely identifiable by a globally unique nodeId: ID! field. For more information about nodeId, see nodeId.
"""The root type for querying data"""typeQuery{"""Retrieve a record by its `ID`"""node(nodeId: ID!):Node}
To query the node interface effectively, use inline fragments to specify which fields to return for each type.
Example
1 2 3 4 5 6 7 8 9101112
{node( nodeId: "WyJwdWJsaWMiLCAiYmxvZyIsIDFd"){nodeId# Inline fragment for `Blog` type...onBlog{namedescription}}}
123456789
{"data":{"node":{"name":"Some Blog","nodeId":"WyJwdWJsaWMiLCAiYmxvZyIsIDFd","description":"Description of Some Blog"}}}
Collections
Each table has top level entry in the Query type for selecting records from that table. Collections return a connection type and can be paginated, filtered, and sorted using the available arguments.
"""The root type for querying data"""typeQuery{"""A pagable collection of type `Blog`"""blogCollection("""Query the first `n` records in the collection""" first: Int"""Query the last `n` records in the collection""" last: Int"""Query values in the collection before the provided cursor""" before: Cursor"""Query values in the collection after the provided cursor""" after: Cursor""" Skip n values from the after cursor. Alternative to cursor pagination. Backward pagination not supported. """ offset: Int"""Filters to apply to the results set when querying from the collection""" filter: BlogFilter"""Sort order to apply to the collection""" orderBy: [BlogOrderBy!]):BlogConnection}
Connection types are the primary interface to returning records from a collection.
Connections wrap a result set with some additional metadata.
1 2 3 4 5 6 7 8 9101112
typeBlogConnection{# Count of all records matching the *filter* criteria totalCount: Int!# Pagination metadata pageInfo: PageInfo!# Result set edges: [BlogEdge!]!}
123456789
typeBlogEdge{# Unique identifier of the record within the query cursor: String!# Contents of a record/row in the results set node: Blog}
1 2 3 4 5 6 7 8 91011121314
typePageInfo{# unique identifier of the first record within the query startCursor: String# unique identifier of the last record within the query endCursor: String# is another page of content available hasNextPage: Boolean!# is another page of content available hasPreviousPage: Boolean!}
1 2 3 4 5 6 7 8 910111213141516171819202122
# A record from the `blog` tabletypeBlog{# globally unique identifier nodeId: ID!# Value from `id` column id: Int!# Value from `name` column name: String!# Value from `description` column description: String# Value from `createdAt` column createdAt: Datetime!# Value from `updatedAt` column updatedAt: Datetime!}
The totalCount field is disabled by default because it can be expensive on large tables. To enable it use a comment directive
Pagination
Keyset Pagination
Paginating forwards and backwards through collections is handled using the first, last, before, and after parameters, following the relay spec.
1 2 3 4 5 6 7 8 91011121314151617181920
typeQuery{blogCollection("""Query the first `n` records in the collection""" first: Int"""Query the last `n` records in the collection""" last: Int"""Query values in the collection before the provided cursor""" before: Cursor"""Query values in the collection after the provided cursor""" after: Cursor...truncated...):BlogConnection}
Metadata relating to the current page of a result set is available on the pageInfo field of the connection type returned from a collection.
1 2 3 4 5 6 7 8 91011121314
typePageInfo{# unique identifier of the first record within the query startCursor: String# unique identifier of the last record within the query endCursor: String# is another page of content available hasNextPage: Boolean!# is another page of content available hasPreviousPage: Boolean!}
123456789
typeBlogConnection{# Pagination metadata pageInfo: PageInfo!# Result set edges: [BlogEdge!]!}
To paginate forward in the collection, use the first and after arguments. To retrieve the first page, the after argument should be null or absent.
once the collection has been fully enumerated, data.blogConnection.pageInfo.hasNextPage returns false.
To paginate backwards through a collection, repeat the process substituting first -> last, after -> before, hasNextPage -> hasPreviousPage
Offset Pagination
In addition to keyset pagination, collections may also be paged using first and offset, which operates like SQL's limit and offset to skip offset number of records in the results.
Note
offset based pagination becomes inefficient the offset value increases. For this reason, prefer cursor based pagination where possible.
To filter the result set, use the filter argument.
1 2 3 4 5 6 7 8 91011
typeQuery{blogCollection("""Filters to apply to the results set when querying from the collection""" filter: BlogFilter...truncated...):BlogConnection}
Where the <Table>Filter type enumerates filterable fields and their associated <Type>Filter.
{"data":{"blogCollection":{"edges":[{"node":{"id":1,"name":"A: Blog 1","createdAt":"2023-07-24T04:01:09.882781","tags":["tech","innovation"]},"cursor":"WzFd"},{"node":{"id":2,"name":"A: Blog 2","createdAt":"2023-07-24T04:01:09.882781","tags":["tech","innovation","entrepreneurship"]},"cursor":"WzJd"}]}}}
The contains filter can also accept a single scalar.
{"data":{"blogCollection":{"edges":[{"node":{"id":1,"name":"A: Blog 1","createdAt":"2023-07-24T04:01:09.882781","tags":["tech","innovation"]},"cursor":"WzFd"},{"node":{"id":2,"name":"A: Blog 2","createdAt":"2023-07-24T04:01:09.882781","tags":["tech","innovation","entrepreneurship"]},"cursor":"WzJd"}]}}}
The containedBy filter is used to return results where every element of the array column appears in the input array.
{"data":{"blogCollection":{"edges":[{"node":{"id":1,"name":"A: Blog 1","createdAt":"2023-07-24T04:01:09.882781","tags":["tech","innovation"]},"cursor":"WzFd"},{"node":{"id":3,"name":"A: Blog 3","createdAt":"2023-07-24T04:01:09.882781","tags":["innovation","entrepreneurship"]},"cursor":"WzNd"}]}}}
The containedBy filter can also accept a single scalar. In this case, only results where the only element in the array column is the input scalar are returned.
{"data":{"blogCollection":{"edges":[{"node":{"id":4,"name":"A: Blog 4","createdAt":"2023-07-24T04:01:09.882781","tags":["travel"]},"cursor":"WzPd"}]}}}
The overlaps filter is used to return results where the array column and the input array have at least one element in common.
{"data":{"blogCollection":{"edges":[{"node":{"id":1,"name":"A: Blog 1","createdAt":"2023-07-24T04:01:09.882781","tags":["tech","innovation"]},"cursor":"WzFd"},{"node":{"id":2,"name":"A: Blog 2","createdAt":"2023-07-24T04:01:09.882781","tags":["tech","innovation","entrepreneurship"]},"cursor":"WzJd"},{"node":{"id":4,"name":"A: Blog 4","createdAt":"2023-07-24T04:01:09.882781","tags":["travel"]},"cursor":"WzPd"}]}}}
Example: and/or
Multiple filters can be combined with and, or and not operators. The and and or operators accept a list of <Type>Filter.
{"data":{"blogCollection":{"edges":[{"node":{"id":1,"name":"A: Blog 1","createdAt":"2023-07-24T04:01:09.882781","description":"a desc1"},"cursor":"WzFd"}]}}}
{"data":{"blogCollection":{"edges":[{"node":{"id":1,"name":"A: Blog 1","createdAt":"2023-07-24T04:01:09.882781","description":"a desc1"},"cursor":"WzFd"},{"node":{"id":2,"name":"A: Blog 2","createdAt":"2023-07-24T04:01:09.882781","description":"a desc2"},"cursor":"WzJd"}]}}}
{"data":{"blogCollection":{"edges":[{"node":{"id":2,"name":"A: Blog 2","createdAt":"2023-07-24T04:01:09.882781","description":"a desc2"},"cursor":"WzJd"},{"node":{"id":3,"name":"A: Blog 3","createdAt":"2023-07-24T04:01:09.882781","description":"a desc3"},"cursor":"WzNd"},{"node":{"id":4,"name":"B: Blog 3","createdAt":"2023-07-24T04:01:09.882781","description":"b desc1"},"cursor":"WzRd"}]}}}
Example: nested composition
The and, or and not operators can be arbitrarily nested inside each other.
{"data":{"blogCollection":{"edges":[{"node":{"id":1,"name":"A: Blog 1","createdAt":"2023-07-24T04:01:09.882781","description":"a desc1"},"cursor":"WzFd"},{"node":{"id":2,"name":"A: Blog 2","createdAt":"2023-07-24T04:01:09.882781","description":"a desc2"},"cursor":"WzJd"},{"node":{"id":3,"name":"A: Blog 3","createdAt":"2023-07-24T04:01:09.882781","description":"a desc3"},"cursor":"WzNd"}]}}}
Example: empty
Empty filters are ignored, i.e. they behave as if the operator was not specified at all.
{"data":{"blogCollection":{"edges":[{"node":{"id":1,"name":"A: Blog 1","createdAt":"2023-07-24T04:01:09.882781","description":"a desc1"},"cursor":"WzFd"},{"node":{"id":2,"name":"A: Blog 2","createdAt":"2023-07-24T04:01:09.882781","description":"a desc2"},"cursor":"WzJd"},{"node":{"id":3,"name":"A: Blog 3","createdAt":"2023-07-24T04:01:09.882781","description":"a desc3"},"cursor":"WzNd"},{"node":{"id":4,"name":"B: Blog 3","createdAt":"2023-07-24T04:01:09.882781","description":"b desc1"},"cursor":"WzRd"}]}}}
Example: implicit and
Multiple column filters at the same level will be implicitly combined with boolean and. In the following example the id: {eq: 1} and name: {eq: "A: Blog 1"} will be anded.
1 2 3 4 5 6 7 8 9101112131415161718192021
{blogCollection( filter: {# Equivalent to not: { and: [{id: {eq: 1}}, {name: {eq: "A: Blog 1"}}]} not: { id: {eq: 1} name: {eq: "A: Blog 1"}}}){edges{cursornode{idnamedescriptioncreatedAt}}}}
{"data":{"blogCollection":{"edges":[{"node":{"id":2,"name":"A: Blog 2","createdAt":"2023-07-24T04:01:09.882781","description":"a desc2"},"cursor":"WzJd"},{"node":{"id":3,"name":"A: Blog 3","createdAt":"2023-07-24T04:01:09.882781","description":"a desc3"},"cursor":"WzNd"},{"node":{"id":4,"name":"B: Blog 3","createdAt":"2023-07-24T04:01:09.882781","description":"b desc1"},"cursor":"WzRd"}]}}}
This means that an and filter can be often be simplified. In the following example all queries are equivalent and produce the same result.
{"data":{"blogCollection":{"edges":[{"node":{"id":2,"name":"A: Blog 2","createdAt":"2023-07-24T04:01:09.882781","description":"a desc2"},"cursor":"WzJd"},{"node":{"id":3,"name":"A: Blog 3","createdAt":"2023-07-24T04:01:09.882781","description":"a desc3"},"cursor":"WzNd"},{"node":{"id":4,"name":"B: Blog 3","createdAt":"2023-07-24T04:01:09.882781","description":"b desc1"},"cursor":"WzRd"}]}}}
Be aware that the above simplification only works for the and operator. If you try it with an or operator it will behave like an and.
1 2 3 4 5 6 7 8 9101112131415161718192021
{blogCollection( filter: {# This is really an `and` in `or`'s clothing or: { id: {eq: 1} name: {eq: "A: Blog 2"}}}){edges{cursornode{idnamedescriptioncreatedAt}}}}
1234567
{"data":{"blogCollection":{"edges":[]}}}
This is because according to the rules of GraphQL list input coercion, if a value passed to an input of list type is not a list, then it is coerced to a list of a single item. So in the above example or: {id: {eq: 1}, name: {eq: "A: Blog 2}} will be coerced into or: [{id: {eq: 1}, name: {eq: "A: Blog 2}}] which is equivalent to or: [and: [{id: {eq: 1}}, {name: {eq: "A: Blog 2}}}] due to implicit anding.
Note
Avoid naming your columns and, or or not. If you do, the corresponding filter operator will not be available for use.
The and, or and not operators also work with update and delete mutations.
Ordering
The default order of results is defined by the underlying table's primary key column in ascending order. That default can be overridden by passing an array of <Table>OrderBy to the collection's orderBy argument.
1 2 3 4 5 6 7 8 91011
typeQuery{blogCollection("""Sort order to apply to the collection""" orderBy: [BlogOrderBy!]...truncated...):BlogConnection}
Note, only one key value pair may be provided to each element of the input array. For example, [{name: AscNullsLast}, {id: AscNullFirst}] is valid. Passing multiple key value pairs in a single element of the input array e.g. [{name: AscNullsLast, id: AscNullFirst}], is invalid.
MutationType
The Mutation type is the entrypoint for mutations/edits.
Each table has top level entry in the Mutation type for insertinginsertInto<Table>Collection, updatingupdate<Table>Collection and deletingdeleteFrom<Table>Collection.
"""The root type for creating and mutating data"""typeMutation{"""Adds one or more `BlogInsertResponse` records to the collection"""insertIntoBlogCollection("""Records to add to the Blog collection""" objects: [BlogInsertInput!]!):BlogInsertResponse"""Updates zero or more records in the collection"""updateBlogCollection(""" Fields that are set will be updated for all records matching the `filter` """ set: BlogUpdateInput!"""Restricts the mutation's impact to records matching the critera""" filter: BlogFilter""" The maximum number of records in the collection permitted to be affected """ atMost: Int!=1):BlogUpdateResponse!"""Deletes zero or more records from the collection"""deleteFromBlogCollection("""Restricts the mutation's impact to records matching the critera""" filter: BlogFilter""" The maximum number of records in the collection permitted to be affected """ atMost: Int!=1):BlogDeleteResponse!}
Insert
To add records to a collection, use the insertInto<Table>Collection field on the Mutation type.
"""The root type for creating and mutating data"""typeMutation{"""Adds one or more `BlogInsertResponse` records to the collection"""insertIntoBlogCollection("""Records to add to the Blog collection""" objects: [BlogInsertInput!]!):BlogInsertResponse}
typeBlogInsertResponse{"""Count of the records impacted by the mutation""" affectedCount: Int!"""Array of records impacted by the mutation""" records: [Blog!]!}
Where elements in the objects array are inserted into the underlying table.
"""The root type for creating and mutating data"""typeMutation{"""Updates zero or more records in the collection"""updateBlogCollection(""" Fields that are set will be updated for all records matching the `filter` """ set: BlogUpdateInput!"""Restricts the mutation's impact to records matching the critera""" filter: BlogFilter""" The maximum number of records in the collection permitted to be affected """ atMost: Int!=1):BlogUpdateResponse!}
typeBlogUpdateResponse{"""Count of the records impacted by the mutation""" affectedCount: Int!"""Array of records impacted by the mutation""" records: [Blog!]!}
Where the set argument is a key value pair describing the values to update, filter controls which records should be updated, and atMost restricts the maximum number of records that may be impacted. If the number of records impacted by the mutation exceeds the atMost parameter the operation will return an error.
"""The root type for creating and mutating data"""typeMutation{"""Deletes zero or more records from the collection"""deleteFromBlogCollection("""Restricts the mutation's impact to records matching the critera""" filter: BlogFilter""" The maximum number of records in the collection permitted to be affected """ atMost: Int!=1):BlogDeleteResponse!}
typeBlogDeleteResponse{"""Count of the records impacted by the mutation""" affectedCount: Int!"""Array of records impacted by the mutation""" records: [Blog!]!}
Where filter controls which records should be deleted and atMost restricts the maximum number of records that may be deleted. If the number of records impacted by the mutation exceeds the atMost parameter the operation will return an error.
The base GraphQL type for every table with a primary key is automatically assigned a nodeId: ID! field. That value, can be passed to the node entrypoint of the Query type to retrieve its other fields. nodeId may also be used as a caching key.
relay support
By default relay expects the ID field for types to have the name id. pg_graphql uses nodeId by default to avoid conflicting with user defined id columns. You can configure relay to work with pg_graphql's nodeId field with relay's nodeInterfaceIdField option. More info available here.
typeBlog{#globallyuniqueidentifiernodeId:ID!id:Int!name:String!description:StringblogPostCollection("""Query the first `n` records in the collection"""first:Int"""Query the last `n` records in the collection"""last:Int"""Query values in the collection before the provided cursor"""before:Cursor"""Query values in the collection after the provided cursor"""after:Cursor""" Skip n values from the after cursor. Alternative to cursor pagination. Backward pagination not supported. """offset:Int"""Filters to apply to the results set when querying from the collection"""filter:BlogPostFilter"""Sort order to apply to the collection"""orderBy:[BlogPostOrderBy!]):BlogPostConnection}
Where blogPostCollection exposes the full Query interface to BlogPosts.
{"data":{"blogCollection":{"edges":[{"node":{"name":"pg_graphql blog","blogPostCollection":{"edges":[{"node":{"id":2,"title":"fIr3t p0sT"}},{"node":{"id":3,"title":"graphql with postgres"}}]}}}]}}}
Many-to-One
A foreign key on table A referencing table B defines a many-to-one relationship from table B to table A.
{"data":{"blogPostCollection":{"edges":[{"node":{"blog":{"name":"pg_graphql blog"},"title":"fIr3t p0sT"}},{"node":{"blog":{"name":"pg_graphql blog"},"title":"graphql with postgres"}}]}}}
One-to-One
A one-to-one relationship is defined by a foreign key on table A referencing table B where the columns making up the foreign key on table A are unique.
Due to differences among the types supported by PostgreSQL, JSON, and GraphQL, pg_graphql adds several new Scalar types to handle PostgreSQL builtins that require special handling.
JSON
pg_graphql serializes json and jsonb data types as String under the custom scalar name JSON.
Use serialized JSON strings when updating or inserting JSON fields via the GraphQL API.
JSON does not currently support filtering.
BigInt
PostgreSQL bigint and bigserial types are 64 bit integers. In contrast, JSON supports 32 bit integers.
Since PostgreSQL bigint values may be outside the min/max range allowed by JSON, they are represented in the GraphQL schema as BigInts and values are serialized as strings.
PostgreSQL's numeric type supports arbitrary precision floating point values. JSON's float is limited to 64-bit precision.
Since a PostgreSQL numeric may require more precision than can be handled by JSON, numeric types are represented in the GraphQL schema as BigFloat and values are serialized as strings.
PostgreSQL's type system is extensible and not all types handle all operations e.g. filtering with like. To account for these, pg_graphql introduces a scalar Opaque type. The Opaque type uses PostgreSQL's to_json method to serialize values. That allows complex or unknown types to be included in the schema by delegating handling to the client.
123456
scalarOpaqueinputOpaqueFilter{ eq: Opaque is: FilterIs}