Project description

In some use cases, I’ve found it more natural to generate the requested GraphQL
data using SQL joins rather than resolving values individually. This is a proof
of concept that provides an alternative way of responding to GraphQL queries.

In the reference GraphQL implementation, resolve functions describe how to
fulfil some part of the requested data for each instance of an object.
If implemented naively with a SQL backend, this results in the N+1 problem.
For instance, given the query:

{
books(genre: "comedy") {
title
author {
name
}
}
}

A naive GraphQL implement would issue one SQL query to get the list of all
books in the comedy genre, and then N queries to get the author of each book
(where N is the number of books returned by the first query).

There are various solutions proposed to this problem: GraphJoiner suggests that
using joins is a natural fit for many use cases. For this specific case, we only
need to run two queries: one to find the list of all books in the comedy genre,
and one to get the authors of books in the comedy genre.

Example

Let’s say we have some models defined by SQLAlchemy. A book has an ID, a title,
a genre and an author ID. An author has an ID and a name.

For each object type, we need to define its fields.
The root has only one field, books, a one-to-many relationship,
which we define using many().
The first argument, book_join_type,
is the type we’re defining a relationship to.
The second argument to describes how to create a query representing all of those
related books: in this case all books, potentially filtered by a genre argument.

The author field is defined as a one-to-one mapping from book to author.
As before, we define a function that generates a query for the requested authors.
We also provide a join argument to single() so that GraphJoiner knows
how to join together the results of the author query and the book query:
in this case, the authorId field on books corresponds to the id field
on authors.
(If we leave out the join argument, then GraphJoiner will perform a cross
join i.e. a cartesian product. Since there’s always exactly one root instance,
this is fine for relationships defined on the root.)

The remaining fields define a mapping from the GraphQL field to the database
column. This mapping is handled by fetch_immediates_from_database.
The value of request.selections in
fetch_immediates() is the selections of fields that aren’t defined as relationships
(using single or many) that were either explicitly requested in the
original GraphQL query, or are required as part of the join.