Utility function for building data loader for loading repeating data in relational. There still many other use case.
DataLoader is a generic utility used to abstract request batching and caching. It use to solve N+1 Problem when using with data loading. BatchLoader taking all of the required keys when preload and postload return the data to the stack where we call.
I have 3 tables, TeamUser
storing team & user data, User
storing user data, Team
storing team data. Usually with data below, we have to run up at least 9 queries. ( Almost all of the ORM do so )
SELECT * FROM Team ( you will have 1, 2 as team id )
SELECT userId FROM TeamUser WHERE id = 1; ( you will have 1, 2, 3 as userId for team id 1
SELECT userId FROM TeamUser WHERE id = 2; ( you will have 1, 2, 3 as userId for tema id 2 )
SELECT * FROM User WHERE id = 1;
SELECT * FROM User WHERE id = 2;
SELECT * FROM User WHERE id = 3;
SELECT * FROM User WHERE id = 1;
SELECT * FROM User WHERE id = 2;
SELECT * FROM User WHERE id = 3;
But if we implementing data loader, its only take 4 queries for completing the requests.
SELECT * FROM Team ( you will have 1, 2 as team id )
SELECT userId FROM TeamUser WHERE id IN 1
SELECT userId FROM TeamUser WHERE id IN 2;
SELECT * FROM User WHERE id IN ( 1, 2, 3 )
Example of response data
teams: {
id: 1,
name: 'Cool Team',
teammates: [
{
user: {
id: 2,
username: 'yuzylam',
display_name: 'Yuzy Lam',
},
},
{
user: {
id: 1,
username: 'wllee',
display_name: 'Lee Wang Lin',
},
},
{
user: {
id: 3,
username: 'oska',
display_name: 'Ng Sze Chen',
},
},
]
},
teams: {
id: 2,
title: 'Another Cool Team',
teammates: [
{
user: {
id: 2,
username: 'yuzylam',
display_name: 'Yuzy Lam',
},
},
{
user: {
id: 1,
username: 'wllee',
display_name: 'Lee Wang Lin',
},
},
{
user: {
id: 3,
username: 'oska',
display_name: 'Ng Sze Chen',
},
},
]
},
Because of when we completing team query & teamuser query to get userId which belongsTo the team, and we pass to loader after done only loader will load. So we able to get the result by the id given, repeating id will not query again will just directly return result that already have.
- dataloader - https://github.com/graph-gophers/dataloader ( DataLoader implementation in GoLang )
- grpool - https://github.com/ivpusic/grpool ( Lightweight Goroutine Pool )
- goloquent - https://github.com/si3nloong/goloquent ( Fantastic ORM inspired by Laravel Eloquent & Google Cloud Datastore )