Connecting a database
Put SQLite behind resolvers: open the handle once, pass it via context, use parameterised queries, map columns to fields, and use transactions.
Connecting a database
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Open the database handle once at startup and hand it to resolvers through context, rather than connecting inside each resolver.
- Always pass user input as query parameters, such as `WHERE id = ?`; a GraphQL argument is untrusted input exactly like a request body.
- The schema is the API and the tables are storage. Bridge naming and shape differences, such as `created_at` to `createdAt`, in field resolvers.
- Wrap multi-statement writes in a transaction so a mutation either fully happens or not at all; a thrown error rolls it back.
- A resolver per field means many small queries; that is fine until a list multiplies them, which the next lessons address.
The problem: resolvers need real data
Up to now the examples read from a toy database. A real server has the same shape: some storage, a way to read and write it, and resolvers that map between that storage and the schema. GraphQL is neutral about the store. Anything that can answer a function call works: SQL, a document store, another HTTP service.
This lesson uses SQLite through better-sqlite3 13.2.0 because it needs no server to run and its API is synchronous, which keeps the examples short. Node also ships its own driver, covered in SQLite in Node. The ideas apply unchanged to Postgres with pg, or to an ORM such as Prisma.
The data
Two tables, ten seeded posts. This is the db.mjs helper the previous lesson imported:
import Database from 'better-sqlite3';
export function makeDb() {
const db = new Database(':memory:');
db.exec(`
CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE posts (
id INTEGER PRIMARY KEY,
author_id INTEGER NOT NULL REFERENCES authors(id),
title TEXT NOT NULL,
body TEXT NOT NULL DEFAULT '',
created_at INTEGER NOT NULL
);
`);
const insertAuthor = db.prepare('INSERT INTO authors (name) VALUES (?)');
['Ada', 'Grace', 'Linus', 'Margaret', 'Dennis'].forEach((n) => insertAuthor.run(n));
const insertPost = db.prepare(
'INSERT INTO posts (author_id, title, body, created_at) VALUES (?, ?, ?, ?)');
for (let i = 1; i <= 10; i++) insertPost.run((i % 5) + 1, `Post ${i}`, `Body ${i}`, 1700000000 + i);
return db;
}
Notice the column is created_at and author_id. SQL convention is snake case; GraphQL convention is camel case. The schema is the API clients see, and the tables are storage. They are allowed to differ.
One handle, in context
Open the connection once and pass it through the context factory:
const db = makeDb();
const yoga = createYoga({ schema, context: () => ({ db }) });
Every resolver gets it as { db }. With a networked database you would put a connection pool in the same place, since a pool is built to be shared by concurrent requests. Don’t open a connection inside each resolver: a list of fifty items would try for fifty connections.
Parameterised queries, always
A GraphQL argument is user input, however neatly typed. String! guarantees a string, not a safe one. I ran this:
postsBy: (_, { name }, { db }) =>
db.prepare('SELECT p.* FROM posts p JOIN authors a ON a.id = p.author_id WHERE a.name = ?')
.all(name),
With name: "Ada' OR '1'='1" the result was [], because the whole string was treated as a name that matches nobody. With name: "Ada" it returned posts 5 and 10. The unsafe alternative, building the SQL with a template literal, would have returned every post for the first input. Use ? (or $1 in Postgres) for every value, no exceptions.
Mapping columns to fields
Query the row, return the row, and let the default resolver take what it can. Where the names differ, add a field resolver:
const resolvers = {
Query: {
post: (_, { id }, { db }) =>
db.prepare('SELECT * FROM posts WHERE id = ?').get(id) ?? null,
},
Post: {
createdAt: (post) => post.created_at,
author: (post, _args, { db }) =>
db.prepare('SELECT * FROM authors WHERE id = ?').get(post.author_id),
},
};
{ post(id: "1") { id title createdAt } } returned {"id":"1","title":"Post 1","createdAt":1700000001}. id and title came from the default resolver; createdAt from the one above. The ?? null matters: the driver returns undefined when no row matches, and returning null is the explicit way to say “not found” for a nullable field.
Transactions for multi-step writes
A mutation that touches several rows should be all or nothing. In better-sqlite3, db.transaction(fn) wraps fn in a transaction; a throw rolls it back:
transferAll: (_, { from, to }, { db }) =>
db.transaction(() => {
const n = db.prepare('UPDATE posts SET author_id = ? WHERE author_id = ?').run(to, from).changes;
if (n > 1) throw new Error('too many');
return n;
})(),
Author 1 owns two posts, so transferAll(from: "1", to: "2") updates both rows and then throws. Afterwards I counted: author 1 still had both posts. The update was undone with the error. In Postgres you open a transaction on a connection and pass that connection down, which is one more reason the handle is not a global.
The cost you will meet next
Look at Post.author. It runs one SELECT per post. A query for ten posts with authors runs one query for the list and ten for the authors, eleven in total. Nothing is wrong in any single resolver, and that is exactly the trap. The next lesson counts it.
What the video covers
Eric Tech’s twelve-minute video builds a GraphQL server with Apollo Server, Prisma and SQLite. I could not read its description or a transcript, so this lesson rests on the title. It uses Apollo Server rather than Yoga and Prisma rather than raw SQL, so it shows the ORM route to the same idea: schema, resolvers, a database client in context. The raw-SQL version above shows what the ORM does for you. The video is from 2023 and Prisma’s client setup has changed since, so expect to adapt the details. The notJust.dev course linked below connects a MongoDB database instead.
Where this fits
The server now reads and writes real data. Whether it does so efficiently is a separate matter that does not show up until a list does. Next: the N+1 problem.
Check yourself
Why use `WHERE name = ?` with a bound parameter instead of building the SQL string from the argument?
A bound parameter is treated as data and never as SQL. Pasting an argument into the string lets a client send something like `Ada' OR '1'='1` and change the query.
Where should the database handle live, and why?
Created once at startup and passed through `context`, so resolvers do not import a global and tests can supply a different database.
The `posts` table has a `created_at` column, and the schema field is `createdAt`. How does the data get across?
A field resolver, `Post.createdAt: (post) => post.created_at`. The default resolver reads only the property of the same name.
What does wrapping a mutation's writes in a transaction buy you?
If any statement throws, all earlier writes in it are undone. I made a transfer fail after updating rows and the author still had both posts afterwards.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.