Codebase list python-graphene-sqlalchemy / 80d40265-53bf-4fb3-9dcf-59504a2f4e9e/upstream graphene_sqlalchemy / tests / test_batching.py
80d40265-53bf-4fb3-9dcf-59504a2f4e9e/upstream

Tree @80d40265-53bf-4fb3-9dcf-59504a2f4e9e/upstream (Download .tar.gz)

test_batching.py @80d40265-53bf-4fb3-9dcf-59504a2f4e9e/upstreamraw · history · blame

  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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
import contextlib
import logging

import pytest

import graphene
from graphene import relay

from ..fields import (BatchSQLAlchemyConnectionField,
                      default_connection_field_factory)
from ..types import ORMField, SQLAlchemyObjectType
from .models import Article, HairKind, Pet, Reporter
from .utils import is_sqlalchemy_version_less_than, to_std_dicts


class MockLoggingHandler(logging.Handler):
    """Intercept and store log messages in a list."""
    def __init__(self, *args, **kwargs):
        self.messages = []
        logging.Handler.__init__(self, *args, **kwargs)

    def emit(self, record):
        self.messages.append(record.getMessage())


@contextlib.contextmanager
def mock_sqlalchemy_logging_handler():
    logging.basicConfig()
    sql_logger = logging.getLogger('sqlalchemy.engine')
    previous_level = sql_logger.level

    sql_logger.setLevel(logging.INFO)
    mock_logging_handler = MockLoggingHandler()
    mock_logging_handler.setLevel(logging.INFO)
    sql_logger.addHandler(mock_logging_handler)

    yield mock_logging_handler

    sql_logger.setLevel(previous_level)


def get_schema():
    class ReporterType(SQLAlchemyObjectType):
        class Meta:
            model = Reporter
            interfaces = (relay.Node,)
            batching = True

    class ArticleType(SQLAlchemyObjectType):
        class Meta:
            model = Article
            interfaces = (relay.Node,)
            batching = True

    class PetType(SQLAlchemyObjectType):
        class Meta:
            model = Pet
            interfaces = (relay.Node,)
            batching = True

    class Query(graphene.ObjectType):
        articles = graphene.Field(graphene.List(ArticleType))
        reporters = graphene.Field(graphene.List(ReporterType))

        def resolve_articles(self, info):
            return info.context.get('session').query(Article).all()

        def resolve_reporters(self, info):
            return info.context.get('session').query(Reporter).all()

    return graphene.Schema(query=Query)


if is_sqlalchemy_version_less_than('1.2'):
    pytest.skip('SQL batching only works for SQLAlchemy 1.2+', allow_module_level=True)


def test_many_to_one(session_factory):
    session = session_factory()

    reporter_1 = Reporter(
      first_name='Reporter_1',
    )
    session.add(reporter_1)
    reporter_2 = Reporter(
      first_name='Reporter_2',
    )
    session.add(reporter_2)

    article_1 = Article(headline='Article_1')
    article_1.reporter = reporter_1
    session.add(article_1)

    article_2 = Article(headline='Article_2')
    article_2.reporter = reporter_2
    session.add(article_2)

    session.commit()
    session.close()

    schema = get_schema()

    with mock_sqlalchemy_logging_handler() as sqlalchemy_logging_handler:
        # Starts new session to fully reset the engine / connection logging level
        session = session_factory()
        result = schema.execute("""
          query {
            articles {
              headline
              reporter {
                firstName
              }
            }
          }
        """, context_value={"session": session})
        messages = sqlalchemy_logging_handler.messages

    assert len(messages) == 5

    if is_sqlalchemy_version_less_than('1.3'):
        # The batched SQL statement generated is different in 1.2.x
        # SQLAlchemy 1.3+ optimizes out a JOIN statement in `selectin`
        # See https://git.io/JewQu
        sql_statements = [message for message in messages if 'SELECT' in message and 'JOIN reporters' in message]
        assert len(sql_statements) == 1
        return

    assert messages == [
      'BEGIN (implicit)',

      'SELECT articles.id AS articles_id, '
      'articles.headline AS articles_headline, '
      'articles.pub_date AS articles_pub_date, '
      'articles.reporter_id AS articles_reporter_id \n'
      'FROM articles',
      '()',

      'SELECT reporters.id AS reporters_id, '
      '(SELECT CAST(count(reporters.id) AS INTEGER) AS anon_2 \nFROM reporters) AS anon_1, '
      'reporters.first_name AS reporters_first_name, '
      'reporters.last_name AS reporters_last_name, '
      'reporters.email AS reporters_email, '
      'reporters.favorite_pet_kind AS reporters_favorite_pet_kind \n'
      'FROM reporters \n'
      'WHERE reporters.id IN (?, ?)',
      '(1, 2)',
    ]

    assert not result.errors
    result = to_std_dicts(result.data)
    assert result == {
      "articles": [
        {
          "headline": "Article_1",
          "reporter": {
            "firstName": "Reporter_1",
          },
        },
        {
          "headline": "Article_2",
          "reporter": {
            "firstName": "Reporter_2",
          },
        },
      ],
    }


def test_one_to_one(session_factory):
    session = session_factory()

    reporter_1 = Reporter(
      first_name='Reporter_1',
    )
    session.add(reporter_1)
    reporter_2 = Reporter(
      first_name='Reporter_2',
    )
    session.add(reporter_2)

    article_1 = Article(headline='Article_1')
    article_1.reporter = reporter_1
    session.add(article_1)

    article_2 = Article(headline='Article_2')
    article_2.reporter = reporter_2
    session.add(article_2)

    session.commit()
    session.close()

    schema = get_schema()

    with mock_sqlalchemy_logging_handler() as sqlalchemy_logging_handler:
        # Starts new session to fully reset the engine / connection logging level
        session = session_factory()
        result = schema.execute("""
          query {
            reporters {
              firstName
              favoriteArticle {
                headline
              }
            }
          }
        """, context_value={"session": session})
        messages = sqlalchemy_logging_handler.messages

    assert len(messages) == 5

    if is_sqlalchemy_version_less_than('1.3'):
        # The batched SQL statement generated is different in 1.2.x
        # SQLAlchemy 1.3+ optimizes out a JOIN statement in `selectin`
        # See https://git.io/JewQu
        sql_statements = [message for message in messages if 'SELECT' in message and 'JOIN articles' in message]
        assert len(sql_statements) == 1
        return

    assert messages == [
      'BEGIN (implicit)',

      'SELECT (SELECT CAST(count(reporters.id) AS INTEGER) AS anon_2 \nFROM reporters) AS anon_1, '
      'reporters.id AS reporters_id, '
      'reporters.first_name AS reporters_first_name, '
      'reporters.last_name AS reporters_last_name, '
      'reporters.email AS reporters_email, '
      'reporters.favorite_pet_kind AS reporters_favorite_pet_kind \n'
      'FROM reporters',
      '()',

      'SELECT articles.reporter_id AS articles_reporter_id, '
      'articles.id AS articles_id, '
      'articles.headline AS articles_headline, '
      'articles.pub_date AS articles_pub_date \n'
      'FROM articles \n'
      'WHERE articles.reporter_id IN (?, ?)',
      '(1, 2)'
    ]

    assert not result.errors
    result = to_std_dicts(result.data)
    assert result == {
      "reporters": [
        {
          "firstName": "Reporter_1",
          "favoriteArticle": {
            "headline": "Article_1",
          },
        },
        {
          "firstName": "Reporter_2",
          "favoriteArticle": {
            "headline": "Article_2",
          },
        },
      ],
    }


def test_one_to_many(session_factory):
    session = session_factory()

    reporter_1 = Reporter(
      first_name='Reporter_1',
    )
    session.add(reporter_1)
    reporter_2 = Reporter(
      first_name='Reporter_2',
    )
    session.add(reporter_2)

    article_1 = Article(headline='Article_1')
    article_1.reporter = reporter_1
    session.add(article_1)

    article_2 = Article(headline='Article_2')
    article_2.reporter = reporter_1
    session.add(article_2)

    article_3 = Article(headline='Article_3')
    article_3.reporter = reporter_2
    session.add(article_3)

    article_4 = Article(headline='Article_4')
    article_4.reporter = reporter_2
    session.add(article_4)

    session.commit()
    session.close()

    schema = get_schema()

    with mock_sqlalchemy_logging_handler() as sqlalchemy_logging_handler:
        # Starts new session to fully reset the engine / connection logging level
        session = session_factory()
        result = schema.execute("""
          query {
            reporters {
              firstName
              articles(first: 2) {
                edges {
                  node {
                    headline
                  }
                }
              }
            }
          }
        """, context_value={"session": session})
        messages = sqlalchemy_logging_handler.messages

    assert len(messages) == 5

    if is_sqlalchemy_version_less_than('1.3'):
        # The batched SQL statement generated is different in 1.2.x
        # SQLAlchemy 1.3+ optimizes out a JOIN statement in `selectin`
        # See https://git.io/JewQu
        sql_statements = [message for message in messages if 'SELECT' in message and 'JOIN articles' in message]
        assert len(sql_statements) == 1
        return

    assert messages == [
      'BEGIN (implicit)',

      'SELECT (SELECT CAST(count(reporters.id) AS INTEGER) AS anon_2 \nFROM reporters) AS anon_1, '
      'reporters.id AS reporters_id, '
      'reporters.first_name AS reporters_first_name, '
      'reporters.last_name AS reporters_last_name, '
      'reporters.email AS reporters_email, '
      'reporters.favorite_pet_kind AS reporters_favorite_pet_kind \n'
      'FROM reporters',
      '()',

      'SELECT articles.reporter_id AS articles_reporter_id, '
      'articles.id AS articles_id, '
      'articles.headline AS articles_headline, '
      'articles.pub_date AS articles_pub_date \n'
      'FROM articles \n'
      'WHERE articles.reporter_id IN (?, ?)',
      '(1, 2)'
    ]

    assert not result.errors
    result = to_std_dicts(result.data)
    assert result == {
      "reporters": [
        {
          "firstName": "Reporter_1",
          "articles": {
            "edges": [
              {
                "node": {
                  "headline": "Article_1",
                },
              },
              {
                "node": {
                  "headline": "Article_2",
                },
              },
            ],
          },
        },
        {
          "firstName": "Reporter_2",
          "articles": {
            "edges": [
              {
                "node": {
                  "headline": "Article_3",
                },
              },
              {
                "node": {
                  "headline": "Article_4",
                },
              },
            ],
          },
        },
      ],
    }


def test_many_to_many(session_factory):
    session = session_factory()

    reporter_1 = Reporter(
      first_name='Reporter_1',
    )
    session.add(reporter_1)
    reporter_2 = Reporter(
      first_name='Reporter_2',
    )
    session.add(reporter_2)

    pet_1 = Pet(name='Pet_1', pet_kind='cat', hair_kind=HairKind.LONG)
    session.add(pet_1)

    pet_2 = Pet(name='Pet_2', pet_kind='cat', hair_kind=HairKind.LONG)
    session.add(pet_2)

    reporter_1.pets.append(pet_1)
    reporter_1.pets.append(pet_2)

    pet_3 = Pet(name='Pet_3', pet_kind='cat', hair_kind=HairKind.LONG)
    session.add(pet_3)

    pet_4 = Pet(name='Pet_4', pet_kind='cat', hair_kind=HairKind.LONG)
    session.add(pet_4)

    reporter_2.pets.append(pet_3)
    reporter_2.pets.append(pet_4)

    session.commit()
    session.close()

    schema = get_schema()

    with mock_sqlalchemy_logging_handler() as sqlalchemy_logging_handler:
        # Starts new session to fully reset the engine / connection logging level
        session = session_factory()
        result = schema.execute("""
          query {
            reporters {
              firstName
              pets(first: 2) {
                edges {
                  node {
                    name
                  }
                }
              }
            }
          }
        """, context_value={"session": session})
        messages = sqlalchemy_logging_handler.messages

    assert len(messages) == 5

    if is_sqlalchemy_version_less_than('1.3'):
        # The batched SQL statement generated is different in 1.2.x
        # SQLAlchemy 1.3+ optimizes out a JOIN statement in `selectin`
        # See https://git.io/JewQu
        sql_statements = [message for message in messages if 'SELECT' in message and 'JOIN pets' in message]
        assert len(sql_statements) == 1
        return

    assert messages == [
      'BEGIN (implicit)',

      'SELECT (SELECT CAST(count(reporters.id) AS INTEGER) AS anon_2 \nFROM reporters) AS anon_1, '
      'reporters.id AS reporters_id, '
      'reporters.first_name AS reporters_first_name, '
      'reporters.last_name AS reporters_last_name, '
      'reporters.email AS reporters_email, '
      'reporters.favorite_pet_kind AS reporters_favorite_pet_kind \n'
      'FROM reporters',
      '()',

      'SELECT reporters_1.id AS reporters_1_id, '
      'pets.id AS pets_id, '
      'pets.name AS pets_name, '
      'pets.pet_kind AS pets_pet_kind, '
      'pets.hair_kind AS pets_hair_kind, '
      'pets.reporter_id AS pets_reporter_id \n'
      'FROM reporters AS reporters_1 '
      'JOIN association AS association_1 ON reporters_1.id = association_1.reporter_id '
      'JOIN pets ON pets.id = association_1.pet_id \n'
      'WHERE reporters_1.id IN (?, ?) '
      'ORDER BY pets.id',
      '(1, 2)'
    ]

    assert not result.errors
    result = to_std_dicts(result.data)
    assert result == {
      "reporters": [
        {
          "firstName": "Reporter_1",
          "pets": {
            "edges": [
              {
                "node": {
                  "name": "Pet_1",
                },
              },
              {
                "node": {
                  "name": "Pet_2",
                },
              },
            ],
          },
        },
        {
          "firstName": "Reporter_2",
          "pets": {
            "edges": [
              {
                "node": {
                  "name": "Pet_3",
                },
              },
              {
                "node": {
                  "name": "Pet_4",
                },
              },
            ],
          },
        },
      ],
    }


def test_disable_batching_via_ormfield(session_factory):
    session = session_factory()
    reporter_1 = Reporter(first_name='Reporter_1')
    session.add(reporter_1)
    reporter_2 = Reporter(first_name='Reporter_2')
    session.add(reporter_2)
    session.commit()
    session.close()

    class ReporterType(SQLAlchemyObjectType):
        class Meta:
            model = Reporter
            interfaces = (relay.Node,)
            batching = True

        favorite_article = ORMField(batching=False)
        articles = ORMField(batching=False)

    class ArticleType(SQLAlchemyObjectType):
        class Meta:
            model = Article
            interfaces = (relay.Node,)

    class Query(graphene.ObjectType):
        reporters = graphene.Field(graphene.List(ReporterType))

        def resolve_reporters(self, info):
            return info.context.get('session').query(Reporter).all()

    schema = graphene.Schema(query=Query)

    # Test one-to-one and many-to-one relationships
    with mock_sqlalchemy_logging_handler() as sqlalchemy_logging_handler:
        # Starts new session to fully reset the engine / connection logging level
        session = session_factory()
        schema.execute("""
          query {
            reporters {
              favoriteArticle {
                headline
              }
            }
          }
        """, context_value={"session": session})
        messages = sqlalchemy_logging_handler.messages

    select_statements = [message for message in messages if 'SELECT' in message and 'FROM articles' in message]
    assert len(select_statements) == 2

    # Test one-to-many and many-to-many relationships
    with mock_sqlalchemy_logging_handler() as sqlalchemy_logging_handler:
        # Starts new session to fully reset the engine / connection logging level
        session = session_factory()
        schema.execute("""
          query {
            reporters {
              articles {
                edges {
                  node {
                    headline
                  }
                }
              }
            }
          }
        """, context_value={"session": session})
        messages = sqlalchemy_logging_handler.messages

    select_statements = [message for message in messages if 'SELECT' in message and 'FROM articles' in message]
    assert len(select_statements) == 2


def test_connection_factory_field_overrides_batching_is_false(session_factory):
    session = session_factory()
    reporter_1 = Reporter(first_name='Reporter_1')
    session.add(reporter_1)
    reporter_2 = Reporter(first_name='Reporter_2')
    session.add(reporter_2)
    session.commit()
    session.close()

    class ReporterType(SQLAlchemyObjectType):
        class Meta:
            model = Reporter
            interfaces = (relay.Node,)
            batching = False
            connection_field_factory = BatchSQLAlchemyConnectionField.from_relationship

        articles = ORMField(batching=False)

    class ArticleType(SQLAlchemyObjectType):
        class Meta:
            model = Article
            interfaces = (relay.Node,)

    class Query(graphene.ObjectType):
        reporters = graphene.Field(graphene.List(ReporterType))

        def resolve_reporters(self, info):
            return info.context.get('session').query(Reporter).all()

    schema = graphene.Schema(query=Query)

    with mock_sqlalchemy_logging_handler() as sqlalchemy_logging_handler:
        # Starts new session to fully reset the engine / connection logging level
        session = session_factory()
        schema.execute("""
          query {
            reporters {
              articles {
                edges {
                  node {
                    headline
                  }
                }
              }
            }
          }
        """, context_value={"session": session})
        messages = sqlalchemy_logging_handler.messages

    if is_sqlalchemy_version_less_than('1.3'):
        # The batched SQL statement generated is different in 1.2.x
        # SQLAlchemy 1.3+ optimizes out a JOIN statement in `selectin`
        # See https://git.io/JewQu
        select_statements = [message for message in messages if 'SELECT' in message and 'JOIN articles' in message]
    else:
        select_statements = [message for message in messages if 'SELECT' in message and 'FROM articles' in message]
    assert len(select_statements) == 1


def test_connection_factory_field_overrides_batching_is_true(session_factory):
    session = session_factory()
    reporter_1 = Reporter(first_name='Reporter_1')
    session.add(reporter_1)
    reporter_2 = Reporter(first_name='Reporter_2')
    session.add(reporter_2)
    session.commit()
    session.close()

    class ReporterType(SQLAlchemyObjectType):
        class Meta:
            model = Reporter
            interfaces = (relay.Node,)
            batching = True
            connection_field_factory = default_connection_field_factory

        articles = ORMField(batching=True)

    class ArticleType(SQLAlchemyObjectType):
        class Meta:
            model = Article
            interfaces = (relay.Node,)

    class Query(graphene.ObjectType):
        reporters = graphene.Field(graphene.List(ReporterType))

        def resolve_reporters(self, info):
            return info.context.get('session').query(Reporter).all()

    schema = graphene.Schema(query=Query)

    with mock_sqlalchemy_logging_handler() as sqlalchemy_logging_handler:
        # Starts new session to fully reset the engine / connection logging level
        session = session_factory()
        schema.execute("""
          query {
            reporters {
              articles {
                edges {
                  node {
                    headline
                  }
                }
              }
            }
          }
        """, context_value={"session": session})
        messages = sqlalchemy_logging_handler.messages

    select_statements = [message for message in messages if 'SELECT' in message and 'FROM articles' in message]
    assert len(select_statements) == 2