juniper-eager-loading 0.5.1

Eliminate N+1 query bugs when using Juniper
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
#![allow(unused_variables, unused_imports, dead_code, unused_mut)]
#![allow(clippy::type_complexity)]

mod helpers;

use assert_json_diff::{assert_json_eq, assert_json_include};
use helpers::{SortedExtension, StatsHash};
use juniper::{Executor, FieldError, FieldResult};
use juniper_eager_loading::{
    prelude::*, EagerLoading, HasMany, HasManyThrough, HasOne, LoadChildrenOutput, LoadFrom,
    OptionHasOne,
};
use juniper_from_schema::graphql_schema;
use serde_json::{json, Value};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::{borrow::Borrow, collections::HashMap, hash::Hash};

graphql_schema! {
    schema {
      query: Query
      mutation: Mutation
    }

    type Query {
      countries: [Country!]! @juniper(ownership: "owned")
    }

    type Mutation {
      noop: Boolean!
    }

    type User {
        id: Int!
        isAdmin: Boolean!
        country: Country!
    }

    type Country {
        id: Int!
        users(onlyAdmins: Boolean!): [User!]!
    }
}

mod models {
    use super::*;
    use either::Either;

    #[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
    pub struct User {
        pub id: i32,
        pub country_id: i32,
        pub admin: bool,
    }

    #[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
    pub struct Country {
        pub id: i32,
    }

    impl juniper_eager_loading::LoadFrom<i32> for Country {
        type Error = Box<dyn std::error::Error>;
        type Context = super::Context;

        fn load(ids: &[i32], _: &(), ctx: &Self::Context) -> Result<Vec<Self>, Self::Error> {
            let mut models = ctx
                .db
                .countries
                .all_values()
                .into_iter()
                .filter(|value| ids.contains(&value.id))
                .cloned()
                .collect::<Vec<_>>();
            models.sort_by_key(|model| model.id);
            Ok(models)
        }
    }

    impl juniper_eager_loading::LoadFrom<i32, CountryUsersArgs<'_>> for User {
        type Error = Box<dyn std::error::Error>;
        type Context = super::Context;

        fn load(
            ids: &[i32],
            field_args: &CountryUsersArgs,
            ctx: &Self::Context,
        ) -> Result<Vec<Self>, Self::Error> {
            let models = ctx
                .db
                .users
                .all_values()
                .into_iter()
                .filter(|value| ids.contains(&value.id));

            let mut models = if field_args.only_admins() {
                Either::Left(models.filter(|user| user.admin))
            } else {
                Either::Right(models)
            }
            .cloned()
            .collect::<Vec<_>>();

            models.sort_by_key(|model| model.id);

            Ok(models)
        }
    }

    impl juniper_eager_loading::LoadFrom<i32> for User {
        type Error = Box<dyn std::error::Error>;
        type Context = super::Context;

        fn load(ids: &[i32], _: &(), ctx: &Self::Context) -> Result<Vec<Self>, Self::Error> {
            let mut models = ctx
                .db
                .users
                .all_values()
                .into_iter()
                .filter(|value| ids.contains(&value.id))
                .cloned()
                .collect::<Vec<_>>();
            models.sort_by_key(|model| model.id);
            Ok(models)
        }
    }

    impl juniper_eager_loading::LoadFrom<Country> for User {
        type Error = Box<dyn std::error::Error>;
        type Context = super::Context;

        fn load(
            countries: &[Country],
            _: &(),
            ctx: &Self::Context,
        ) -> Result<Vec<Self>, Self::Error> {
            let country_ids = countries.iter().map(|c| c.id).collect::<Vec<_>>();
            let mut models = ctx
                .db
                .users
                .all_values()
                .into_iter()
                .filter(|user| country_ids.contains(&user.country_id))
                .cloned()
                .collect::<Vec<_>>();
            models.sort_by_key(|model| model.id);
            Ok(models)
        }
    }

    impl LoadFrom<Country, CountryUsersArgs<'_>> for User {
        type Error = Box<dyn std::error::Error>;
        type Context = super::Context;

        fn load(
            countries: &[Country],
            args: &CountryUsersArgs,
            ctx: &Self::Context,
        ) -> Result<Vec<Self>, Self::Error> {
            let only_admins = args.only_admins();

            let country_ids = countries.iter().map(|c| c.id).collect::<Vec<_>>();

            let models = ctx
                .db
                .users
                .all_values()
                .into_iter()
                .filter(|user| country_ids.contains(&user.country_id));

            let models = if only_admins {
                Either::Left(models.filter(|user| user.admin))
            } else {
                Either::Right(models)
            };

            let mut models = models.cloned().collect::<Vec<_>>();
            models.sort_by_key(|model| model.id);
            Ok(models)
        }
    }
}

pub struct Db {
    users: StatsHash<i32, models::User>,
    countries: StatsHash<i32, models::Country>,
}

pub struct Context {
    db: Db,
}

impl juniper::Context for Context {}

pub struct Query;

impl QueryFields for Query {
    fn field_countries(
        &self,
        executor: &Executor<'_, Context>,
        trail: &QueryTrail<'_, Country, Walked>,
    ) -> FieldResult<Vec<Country>> {
        let ctx = executor.context();

        let mut country_models = ctx
            .db
            .countries
            .all_values()
            .into_iter()
            .cloned()
            .collect::<Vec<_>>();
        country_models.sort_by_key(|country| country.id);

        let mut countries = Country::from_db_models(&country_models);
        Country::eager_load_all_children_for_each(&mut countries, &country_models, ctx, trail)?;

        Ok(countries)
    }
}

pub struct Mutation;

impl MutationFields for Mutation {
    fn field_noop(&self, _executor: &Executor<'_, Context>) -> FieldResult<&bool> {
        Ok(&true)
    }
}

// The default values are commented out
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, EagerLoading)]
#[eager_loading(
    model = models::User,
    id = i32,
    context = Context,
    error = Box<dyn std::error::Error>,
)]
pub struct User {
    user: models::User,

    #[has_one(default)]
    country: HasOne<Country>,
}

impl UserFields for User {
    fn field_id(&self, _executor: &Executor<'_, Context>) -> FieldResult<&i32> {
        Ok(&self.user.id)
    }

    fn field_is_admin(&self, _executor: &Executor<'_, Context>) -> FieldResult<&bool> {
        Ok(&self.user.admin)
    }

    fn field_country(
        &self,
        _executor: &Executor<'_, Context>,
        _trail: &QueryTrail<'_, Country, Walked>,
    ) -> FieldResult<&Country> {
        Ok(self.country.try_unwrap()?)
    }
}

#[derive(Clone, Eq, PartialEq, Debug, Ord, PartialOrd, EagerLoading)]
#[eager_loading(
    model = models::Country,
    id = i32,
    context = Context,
    error = Box<dyn std::error::Error>,
)]
pub struct Country {
    country: models::Country,

    #[has_many(skip)]
    users: HasMany<User>,
}

#[allow(missing_docs, dead_code)]
struct EagerLoadingContextCountryForUsers;

impl<'a> EagerLoadChildrenOfType<'a, User, EagerLoadingContextCountryForUsers, ()> for Country {
    type FieldArguments = CountryUsersArgs<'a>;

    fn load_children(
        models: &[Self::Model],
        field_args: &Self::FieldArguments,
        ctx: &Self::Context,
    ) -> Result<
        LoadChildrenOutput<<User as juniper_eager_loading::GraphqlNodeForModel>::Model, ()>,
        Self::Error,
    > {
        let children = LoadFrom::load(&models, field_args, ctx)?;
        Ok(LoadChildrenOutput::ChildModels(children))
    }

    fn is_child_of(
        node: &Self,
        child: &User,
        _join_model: &(),
        _field_args: &Self::FieldArguments,
        _ctx: &Self::Context,
    ) -> bool {
        node.country.id == child.user.country_id
    }

    fn association(node: &mut Country) -> &mut dyn Association<User> {
        &mut node.users
    }
}

impl CountryFields for Country {
    fn field_users(
        &self,
        executor: &Executor<'_, Context>,
        trail: &QueryTrail<'_, User, Walked>,
        _only_admins: bool,
    ) -> FieldResult<&Vec<User>> {
        Ok(self.users.try_unwrap()?)
    }

    fn field_id(&self, _executor: &Executor<'_, Context>) -> FieldResult<&i32> {
        Ok(&self.country.id)
    }
}

#[test]
fn loading_user() {
    let mut countries = StatsHash::new("countries");
    let mut users = StatsHash::new("users");

    let mut country = models::Country { id: 10 };
    let country_id = country.id;

    countries.insert(country_id, country.clone());

    let bob = models::User {
        id: 1,
        country_id,
        admin: true,
    };
    let alice = models::User {
        id: 2,
        country_id,
        admin: false,
    };
    users.insert(bob.id, bob.clone());
    users.insert(alice.id, alice.clone());

    let db = Db { users, countries };
    let (json, counts) = run_query(
        r#"
        query Test {
            countries {
                id
                users(onlyAdmins: true) {
                    id
                    isAdmin
                    country {
                        id
                    }
                }
            }
        }
    "#,
        db,
    );

    assert_eq!(1, counts.user_reads);
    assert_eq!(2, counts.country_reads);

    assert_json_eq!(
        json!({
            "countries": [
                {
                    "id": country.id,
                    "users": [
                        {
                            "id": bob.id,
                            "isAdmin": true,
                            "country": { "id": country.id }
                        },
                    ]
                }
            ],
        }),
        json,
    );
}

struct DbStats {
    user_reads: usize,
    country_reads: usize,
}

fn run_query(query: &str, db: Db) -> (Value, DbStats) {
    let ctx = Context { db };

    let (result, errors) = juniper::execute(
        query,
        None,
        &Schema::new(Query, Mutation),
        &juniper::Variables::new(),
        &ctx,
    )
    .unwrap();

    if !errors.is_empty() {
        panic!(
            "GraphQL errors\n{}",
            serde_json::to_string_pretty(&errors).unwrap()
        );
    }

    let json: Value = serde_json::from_str(&serde_json::to_string(&result).unwrap()).unwrap();

    println!("{}", serde_json::to_string_pretty(&json).unwrap());

    (
        json,
        DbStats {
            user_reads: ctx.db.users.reads_count(),
            country_reads: ctx.db.countries.reads_count(),
        },
    )
}