Source

sqlalchemy-1753 / test / orm / test_of_type.py

Full commit
  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
from sqlalchemy.orm import Session, aliased, with_polymorphic, \
    contains_eager, joinedload, subqueryload, relationship,\
    subqueryload_all, joinedload_all
from sqlalchemy import and_
from sqlalchemy import testing
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import assert_raises, eq_
from sqlalchemy.testing.schema import Column
from sqlalchemy.engine import default
from sqlalchemy.testing.entities import ComparableEntity
from sqlalchemy import Integer, String, ForeignKey
from .inheritance._poly_fixtures import Company, Person, Engineer, Manager, Boss, \
    Machine, Paperwork, _PolymorphicFixtureBase, _Polymorphic,\
    _PolymorphicPolymorphic, _PolymorphicUnions, _PolymorphicJoins,\
    _PolymorphicAliasedJoins

class _PolymorphicTestBase(object):
    __dialect__ = 'default'

    def test_any_one(self):
        sess = Session()
        any_ = Company.employees.of_type(Engineer).any(
            Engineer.primary_language == 'cobol')
        eq_(sess.query(Company).filter(any_).one(), self.c2)

    def test_any_two(self):
        sess = Session()
        calias = aliased(Company)
        any_ = calias.employees.of_type(Engineer).any(
            Engineer.primary_language == 'cobol')
        eq_(sess.query(calias).filter(any_).one(), self.c2)

    def test_any_three(self):
        sess = Session()
        any_ = Company.employees.of_type(Boss).any(
            Boss.golf_swing == 'fore')
        eq_(sess.query(Company).filter(any_).one(), self.c1)

    def test_any_four(self):
        sess = Session()
        any_ = Company.employees.of_type(Boss).any(
            Manager.manager_name == 'pointy')
        eq_(sess.query(Company).filter(any_).one(), self.c1)

    def test_any_five(self):
        sess = Session()
        any_ = Company.employees.of_type(Engineer).any(
            and_(Engineer.primary_language == 'cobol'))
        eq_(sess.query(Company).filter(any_).one(), self.c2)

    def test_join_to_subclass_one(self):
        sess = Session()
        eq_(sess.query(Company)
                .join(Company.employees.of_type(Engineer))
                .filter(Engineer.primary_language == 'java').all(),
            [self.c1])

    def test_join_to_subclass_two(self):
        sess = Session()
        eq_(sess.query(Company)
                .join(Company.employees.of_type(Engineer), 'machines')
                .filter(Machine.name.ilike("%thinkpad%")).all(),
            [self.c1])

    def test_join_to_subclass_three(self):
        sess = Session()
        eq_(sess.query(Company, Engineer)
                .join(Company.employees.of_type(Engineer))
                .filter(Engineer.primary_language == 'java').count(),
            1)

        # test [ticket:2093]
        eq_(sess.query(Company.company_id, Engineer)
                .join(Company.employees.of_type(Engineer))
                .filter(Engineer.primary_language == 'java').count(),
            1)

        eq_(sess.query(Company)
                .join(Company.employees.of_type(Engineer))
                .filter(Engineer.primary_language == 'java').count(),
            1)

    def test_with_polymorphic_join_compile_one(self):
        sess = Session()

        self.assert_compile(
            sess.query(Company).join(
                    Company.employees.of_type(
                        with_polymorphic(Person, [Engineer, Manager], aliased=True)
                    )
                ),
            "SELECT companies.company_id AS companies_company_id, "
            "companies.name AS companies_name FROM companies "
            "JOIN %s"
             % (
                self._polymorphic_join_target([Engineer, Manager])
            )
        )

    def test_with_polymorphic_join_exec_contains_eager_one(self):
        sess = Session()
        def go():
            wp = with_polymorphic(Person, [Engineer, Manager], aliased=True)
            eq_(
                sess.query(Company).join(
                    Company.employees.of_type(wp)
                ).order_by(Company.company_id, wp.person_id).\
                options(contains_eager(Company.employees.of_type(wp))).all(),
                [self.c1, self.c2]
            )
        self.assert_sql_count(testing.db, go, 1)

    def test_with_polymorphic_join_exec_contains_eager_two(self):
        sess = Session()
        def go():
            wp = with_polymorphic(Person, [Engineer, Manager], aliased=True)
            eq_(
                sess.query(Company).join(
                    Company.employees.of_type(wp)
                ).order_by(Company.company_id, wp.person_id).\
                options(contains_eager(Company.employees, alias=wp)).all(),
                [self.c1, self.c2]
            )
        self.assert_sql_count(testing.db, go, 1)

    def test_with_polymorphic_any(self):
        sess = Session()
        wp = with_polymorphic(Person, [Engineer], aliased=True)
        eq_(
            sess.query(Company.company_id).\
                filter(
                    Company.employees.of_type(wp).any(
                            wp.Engineer.primary_language == 'java')
                ).all(),
            [(1, )]
        )

    def test_subqueryload_implicit_withpoly(self):
        sess = Session()
        def go():
            eq_(
                sess.query(Company).\
                    filter_by(company_id=1).\
                    options(subqueryload(Company.employees.of_type(Engineer))).\
                    all(),
                [self._company_with_emps_fixture()[0]]
            )
        self.assert_sql_count(testing.db, go, 4)

    def test_joinedload_implicit_withpoly(self):
        sess = Session()
        def go():
            eq_(
                sess.query(Company).\
                    filter_by(company_id=1).\
                    options(joinedload(Company.employees.of_type(Engineer))).\
                    all(),
                [self._company_with_emps_fixture()[0]]
            )
        self.assert_sql_count(testing.db, go, 3)

    def test_subqueryload_explicit_withpoly(self):
        sess = Session()
        def go():
            target = with_polymorphic(Person, Engineer, aliased=True)
            eq_(
                sess.query(Company).\
                    filter_by(company_id=1).\
                    options(subqueryload(Company.employees.of_type(target))).\
                    all(),
                [self._company_with_emps_fixture()[0]]
            )
        self.assert_sql_count(testing.db, go, 4)

    def test_joinedload_explicit_withpoly(self):
        sess = Session()
        def go():
            target = with_polymorphic(Person, Engineer, aliased=True)
            eq_(
                sess.query(Company).\
                    filter_by(company_id=1).\
                    options(joinedload(Company.employees.of_type(target))).\
                    all(),
                [self._company_with_emps_fixture()[0]]
            )
        self.assert_sql_count(testing.db, go, 3)

class PolymorphicPolymorphicTest(_PolymorphicTestBase, _PolymorphicPolymorphic):
    def _polymorphic_join_target(self, cls):
        from sqlalchemy.orm import class_mapper

        m, sel = class_mapper(Person)._with_polymorphic_args(cls)
        sel = sel.alias()
        comp_sel = sel.compile(dialect=default.DefaultDialect())

        return \
            comp_sel.process(sel, asfrom=True).replace("\n", "") + \
            " ON companies.company_id = anon_1.people_company_id"

class PolymorphicUnionsTest(_PolymorphicTestBase, _PolymorphicUnions):

    def _polymorphic_join_target(self, cls):
        from sqlalchemy.orm import class_mapper

        sel = class_mapper(Person)._with_polymorphic_selectable.element
        comp_sel = sel.compile(dialect=default.DefaultDialect())

        return \
            comp_sel.process(sel, asfrom=True).replace("\n", "") + \
            " AS anon_1 ON companies.company_id = anon_1.company_id"

class PolymorphicAliasedJoinsTest(_PolymorphicTestBase, _PolymorphicAliasedJoins):
    def _polymorphic_join_target(self, cls):
        from sqlalchemy.orm import class_mapper

        sel = class_mapper(Person)._with_polymorphic_selectable.element
        comp_sel = sel.compile(dialect=default.DefaultDialect())

        return \
            comp_sel.process(sel, asfrom=True).replace("\n", "") + \
            " AS anon_1 ON companies.company_id = anon_1.people_company_id"

class PolymorphicJoinsTest(_PolymorphicTestBase, _PolymorphicJoins):
    def _polymorphic_join_target(self, cls):
        from sqlalchemy.orm import class_mapper

        sel = class_mapper(Person)._with_polymorphic_selectable.alias()
        comp_sel = sel.compile(dialect=default.DefaultDialect())

        return \
            comp_sel.process(sel, asfrom=True).replace("\n", "") + \
            " ON companies.company_id = anon_1.people_company_id"


class SubclassRelationshipTest(testing.AssertsCompiledSQL, fixtures.DeclarativeMappedTest):
    """There's overlap here vs. the ones above."""

    run_setup_classes = 'once'
    run_setup_mappers = 'once'
    run_inserts = 'once'
    run_deletes = None
    __dialect__ = 'default'

    @classmethod
    def setup_classes(cls):
        Base = cls.DeclarativeBasic
        class Job(ComparableEntity, Base):
            __tablename__ = "job"

            id = Column(Integer, primary_key=True,
                                        test_needs_autoincrement=True)
            type = Column(String(10))
            container_id = Column(Integer, ForeignKey('data_container.id'))
            __mapper_args__ = {"polymorphic_on": type}

        class SubJob(Job):
            __tablename__ = 'subjob'
            id = Column(Integer, ForeignKey('job.id'), primary_key=True)
            attr = Column(String(10))
            __mapper_args__ = {"polymorphic_identity": "sub"}

        class ParentThing(ComparableEntity, Base):
            __tablename__ = 'parent'
            id = Column(Integer, primary_key=True,
                                            test_needs_autoincrement=True)
            container_id = Column(Integer, ForeignKey('data_container.id'))
            container = relationship("DataContainer")

        class DataContainer(ComparableEntity, Base):
            __tablename__ = "data_container"

            id = Column(Integer, primary_key=True,
                                            test_needs_autoincrement=True)
            name = Column(String(10))
            jobs = relationship(Job, order_by=Job.id)

    @classmethod
    def insert_data(cls):
        s = Session(testing.db)

        s.add_all(cls._fixture())
        s.commit()

    @classmethod
    def _fixture(cls):
        ParentThing, DataContainer, SubJob = \
            cls.classes.ParentThing,\
            cls.classes.DataContainer,\
            cls.classes.SubJob
        return [
            ParentThing(
                container=DataContainer(name="d1",
                    jobs=[
                        SubJob(attr="s1"),
                        SubJob(attr="s2")
                    ])
            ),
            ParentThing(
                container=DataContainer(name="d2",
                    jobs=[
                        SubJob(attr="s3"),
                        SubJob(attr="s4")
                    ])
            ),
        ]

    @classmethod
    def _dc_fixture(cls):
        return [p.container for p in cls._fixture()]

    def test_contains_eager_wpoly(self):
        ParentThing, DataContainer, Job, SubJob = \
            self.classes.ParentThing,\
            self.classes.DataContainer,\
            self.classes.Job,\
            self.classes.SubJob

        Job_P = with_polymorphic(Job, SubJob, aliased=True)

        s = Session(testing.db)
        q = s.query(DataContainer).\
                    join(DataContainer.jobs.of_type(Job_P)).\
                        options(contains_eager(DataContainer.jobs.of_type(Job_P)))
        def go():
            eq_(
                q.all(),
                self._dc_fixture()
            )
        self.assert_sql_count(testing.db, go, 1)

    def test_joinedload_wpoly(self):
        ParentThing, DataContainer, Job, SubJob = \
            self.classes.ParentThing,\
            self.classes.DataContainer,\
            self.classes.Job,\
            self.classes.SubJob

        Job_P = with_polymorphic(Job, SubJob, aliased=True)

        s = Session(testing.db)
        q = s.query(DataContainer).\
                        options(joinedload(DataContainer.jobs.of_type(Job_P)))
        def go():
            eq_(
                q.all(),
                self._dc_fixture()
            )
        self.assert_sql_count(testing.db, go, 1)

    def test_joinedload_wsubclass(self):
        ParentThing, DataContainer, Job, SubJob = \
            self.classes.ParentThing,\
            self.classes.DataContainer,\
            self.classes.Job,\
            self.classes.SubJob
        s = Session(testing.db)
        q = s.query(DataContainer).\
                        options(joinedload(DataContainer.jobs.of_type(SubJob)))
        def go():
            eq_(
                q.all(),
                self._dc_fixture()
            )
        self.assert_sql_count(testing.db, go, 1)

    def test_lazyload(self):
        DataContainer = self.classes.DataContainer
        s = Session(testing.db)
        q = s.query(DataContainer)
        def go():
            eq_(
                q.all(),
                self._dc_fixture()
            )
        # SELECT data container
        # SELECT job * 2 container rows
        # SELECT subjob * 4 rows
        self.assert_sql_count(testing.db, go, 7)

    def test_subquery_wsubclass(self):
        ParentThing, DataContainer, Job, SubJob = \
            self.classes.ParentThing,\
            self.classes.DataContainer,\
            self.classes.Job,\
            self.classes.SubJob
        s = Session(testing.db)
        q = s.query(DataContainer).\
                        options(subqueryload(DataContainer.jobs.of_type(SubJob)))
        def go():
            eq_(
                q.all(),
                self._dc_fixture()
            )
        self.assert_sql_count(testing.db, go, 2)

    def test_twolevel_subqueryload_wsubclass(self):
        ParentThing, DataContainer, Job, SubJob = \
            self.classes.ParentThing,\
            self.classes.DataContainer,\
            self.classes.Job,\
            self.classes.SubJob
        s = Session(testing.db)
        q = s.query(ParentThing).\
                        options(
                            subqueryload_all(
                                ParentThing.container,
                                DataContainer.jobs.of_type(SubJob)
                        ))
        def go():
            eq_(
                q.all(),
                self._fixture()
            )
        self.assert_sql_count(testing.db, go, 3)

    def test_twolevel_joinedload_wsubclass(self):
        ParentThing, DataContainer, Job, SubJob = \
            self.classes.ParentThing,\
            self.classes.DataContainer,\
            self.classes.Job,\
            self.classes.SubJob
        s = Session(testing.db)
        q = s.query(ParentThing).\
                        options(
                            joinedload_all(
                                ParentThing.container,
                                DataContainer.jobs.of_type(SubJob)
                        ))
        def go():
            eq_(
                q.all(),
                self._fixture()
            )
        self.assert_sql_count(testing.db, go, 1)

    def test_any_wpoly(self):
        ParentThing, DataContainer, Job, SubJob = \
            self.classes.ParentThing,\
            self.classes.DataContainer,\
            self.classes.Job,\
            self.classes.SubJob

        Job_P = with_polymorphic(Job, SubJob, aliased=True)

        s = Session()
        q = s.query(Job).join(DataContainer.jobs).\
                        filter(
                            DataContainer.jobs.of_type(Job_P).\
                                any(Job_P.id < Job.id)
                        )
        self.assert_compile(q,
            "SELECT job.id AS job_id, job.type AS job_type, "
            "job.container_id "
            "AS job_container_id "
            "FROM data_container "
            "JOIN job ON data_container.id = job.container_id "
            "WHERE EXISTS (SELECT 1 "
            "FROM (SELECT job.id AS job_id, job.type AS job_type, "
            "job.container_id AS job_container_id, "
            "subjob.id AS subjob_id, subjob.attr AS subjob_attr "
            "FROM job LEFT OUTER JOIN subjob ON job.id = subjob.id) AS anon_1 "
            "WHERE data_container.id = anon_1.job_container_id AND job.id > anon_1.job_id)"
        )

    def test_any_walias(self):
        ParentThing, DataContainer, Job, SubJob = \
            self.classes.ParentThing,\
            self.classes.DataContainer,\
            self.classes.Job,\
            self.classes.SubJob

        Job_A = aliased(Job)

        s = Session()
        q = s.query(Job).join(DataContainer.jobs).\
                        filter(
                            DataContainer.jobs.of_type(Job_A).\
                                any(and_(Job_A.id < Job.id, Job_A.type=='fred'))
                        )
        self.assert_compile(q,
            "SELECT job.id AS job_id, job.type AS job_type, "
            "job.container_id AS job_container_id "
            "FROM data_container JOIN job ON data_container.id = job.container_id "
            "WHERE EXISTS (SELECT 1 "
            "FROM job AS job_1 "
            "WHERE data_container.id = job_1.container_id "
            "AND job.id > job_1.id AND job_1.type = :type_1)"
        )

    def test_join_wpoly(self):
        ParentThing, DataContainer, Job, SubJob = \
            self.classes.ParentThing,\
            self.classes.DataContainer,\
            self.classes.Job,\
            self.classes.SubJob

        Job_P = with_polymorphic(Job, SubJob, aliased=True)

        s = Session()
        q = s.query(DataContainer).join(DataContainer.jobs.of_type(Job_P))
        self.assert_compile(q,
            "SELECT data_container.id AS data_container_id, "
            "data_container.name AS data_container_name "
            "FROM data_container JOIN (SELECT job.id AS job_id, "
            "job.type AS job_type, job.container_id AS job_container_id, "
            "subjob.id AS subjob_id, subjob.attr AS subjob_attr "
            "FROM job LEFT OUTER JOIN subjob ON job.id = subjob.id) "
            "AS anon_1 ON data_container.id = anon_1.job_container_id")

    def test_join_wsubclass(self):
        ParentThing, DataContainer, Job, SubJob = \
            self.classes.ParentThing,\
            self.classes.DataContainer,\
            self.classes.Job,\
            self.classes.SubJob

        s = Session()
        q = s.query(DataContainer).join(DataContainer.jobs.of_type(SubJob))
        # note the of_type() here renders JOIN for the Job->SubJob.
        # this is because it's using the SubJob mapper directly within
        # query.join().  When we do joinedload() etc., we're instead
        # doing a with_polymorphic(), and there we need the join to be
        # outer by default.
        self.assert_compile(q,
            "SELECT data_container.id AS data_container_id, "
            "data_container.name AS data_container_name "
            "FROM data_container JOIN (SELECT job.id AS job_id, "
            "job.type AS job_type, job.container_id AS job_container_id, "
            "subjob.id AS subjob_id, subjob.attr AS subjob_attr "
            "FROM job JOIN subjob ON job.id = subjob.id) AS anon_1 "
            "ON data_container.id = anon_1.job_container_id"
        )

    def test_join_wpoly_innerjoin(self):
        ParentThing, DataContainer, Job, SubJob = \
            self.classes.ParentThing,\
            self.classes.DataContainer,\
            self.classes.Job,\
            self.classes.SubJob

        Job_P = with_polymorphic(Job, SubJob, aliased=True, innerjoin=True)

        s = Session()
        q = s.query(DataContainer).join(DataContainer.jobs.of_type(Job_P))
        self.assert_compile(q,
            "SELECT data_container.id AS data_container_id, "
            "data_container.name AS data_container_name "
            "FROM data_container JOIN (SELECT job.id AS job_id, "
            "job.type AS job_type, job.container_id AS job_container_id, "
            "subjob.id AS subjob_id, subjob.attr AS subjob_attr "
            "FROM job JOIN subjob ON job.id = subjob.id) "
            "AS anon_1 ON data_container.id = anon_1.job_container_id")

    def test_join_walias(self):
        ParentThing, DataContainer, Job, SubJob = \
            self.classes.ParentThing,\
            self.classes.DataContainer,\
            self.classes.Job,\
            self.classes.SubJob

        Job_A = aliased(Job)

        s = Session()
        q = s.query(DataContainer).join(DataContainer.jobs.of_type(Job_A))
        self.assert_compile(q,
            "SELECT data_container.id AS data_container_id, "
            "data_container.name AS data_container_name "
            "FROM data_container JOIN job AS job_1 "
            "ON data_container.id = job_1.container_id")

    def test_join_explicit_wpoly(self):
        ParentThing, DataContainer, Job, SubJob = \
            self.classes.ParentThing,\
            self.classes.DataContainer,\
            self.classes.Job,\
            self.classes.SubJob

        Job_P = with_polymorphic(Job, SubJob, aliased=True)

        s = Session()
        q = s.query(DataContainer).join(Job_P, DataContainer.jobs)
        self.assert_compile(q,
            "SELECT data_container.id AS data_container_id, "
            "data_container.name AS data_container_name "
            "FROM data_container JOIN (SELECT job.id AS job_id, "
            "job.type AS job_type, job.container_id AS job_container_id, "
            "subjob.id AS subjob_id, subjob.attr AS subjob_attr "
            "FROM job LEFT OUTER JOIN subjob ON job.id = subjob.id) "
            "AS anon_1 ON data_container.id = anon_1.job_container_id")