Views
Using Postgres Views with GraphQL.
Views, materialized views, and foreign tables can be exposed with pg_graphql.
Primary Keys (Required)
A primary key is required for an entity to be reflected in the GraphQL schema. Tables can define primary keys with SQL DDL, but primary keys are not available for views, materialized views, or foreign tables. For those entities, you can set a "fake" primary key with a comment directive.
1{"primary_key_columns": [<column_name_1>, ..., <column_name_n>]}For example:
1create view "Person" as2 select3 id,4 name5 from6 "Account";78comment on view "Person" is e'@graphql({"primary_key_columns": ["id"]})';tells pg_graphql to treat "Person".id as the primary key for the Person entity resulting in the following GraphQL type:
1type Person {2 nodeId: ID!3 id: Int!4 name: String!5}ID! types, sorting, and pagination.Updatable views are reflected in the Query and Mutation types identically to tables. Non-updatable views are read-only and accessible via the Query type only.
Relationships
pg_graphql identifies relationships among entities by inspecting foreign keys. Views, materialized views, and foreign tables do not support foreign keys. For this reason, relationships can also be defined in comment directive using the structure:
1{2 "foreign_keys": [3 {4 "local_name": "foo", // optional5 "local_columns": ["account_id"],6 "foreign_name": "bar", // optional7 "foreign_schema": "public",8 "foreign_table": "account",9 "foreign_columns": ["id"]10 }11 ]12}For example:
1create table "Account"(2 id serial primary key,3 name text not null4);56create table "EmailAddress"(7 id serial primary key,8 "accountId" int not null, -- note: no foreign key9 "isPrimary" bool not null,10 address text not null11);1213comment on table "EmailAddress" is e'14 @graphql({15 "foreign_keys": [16 {17 "local_name": "addresses",18 "local_columns": ["accountId"],19 "foreign_name": "account",20 "foreign_schema": "public",21 "foreign_table": "Account",22 "foreign_columns": ["id"]23 }24 ]25 })';defines a relationship equivalent to the following foreign key
1alter table "EmailAddress"2 add constraint fkey_email_address_to_account3 foreign key ("accountId")4 references "Account" ("id");56comment on constraint fkey_email_address_to_account7 on "EmailAddress"8 is E'@graphql({"foreign_name": "account", "local_name": "addresses"})';yielding the GraphQL types:
1type Account {2 nodeId: ID!3 id: Int!4 name: String!5 addresses(6 after: Cursor,7 before: Cursor,8 filter: EmailAddressFilter,9 first: Int,10 last: Int,11 orderBy: [EmailAddressOrderBy!]12 ): EmailAddressConnection13}1415type EmailAddress {16 nodeId: ID!17 id: Int!18 isPrimary: Boolean!19 address: String!20 accountId: Int!21 account: Account!22}