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
699
700
701
702
703
704
705
706
707
708
709
710
|
import random
import threading
import time
from unittest.mock import Mock
from unittest.mock import patch
from sqlalchemy import create_engine
from sqlalchemy import exc as sa_exc
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import select
from sqlalchemy import String
from sqlalchemy import testing
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.ext.automap import AutomapBase
from sqlalchemy.ext.automap import generate_relationship
from sqlalchemy.orm import configure_mappers
from sqlalchemy.orm import exc as orm_exc
from sqlalchemy.orm import interfaces
from sqlalchemy.orm import relationship
from sqlalchemy.orm import Session
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import AssertsCompiledSQL
from sqlalchemy.testing import config
from sqlalchemy.testing import expect_raises_message
from sqlalchemy.testing import expect_warnings
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import is_
from sqlalchemy.testing.schema import Column
from sqlalchemy.testing.schema import Table
from ..orm._fixtures import FixtureTest
class AutomapTest(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
FixtureTest.define_tables(metadata)
def test_relationship_o2m_default(self):
Base = automap_base(metadata=self.tables_test_metadata)
Base.prepare()
User = Base.classes.users
Address = Base.classes.addresses
a1 = Address(email_address="e1")
u1 = User(name="u1", addresses_collection=[a1])
assert a1.users is u1
def test_relationship_explicit_override_o2m(self):
Base = automap_base(metadata=self.tables_test_metadata)
prop = relationship("addresses", collection_class=set)
class User(Base):
__tablename__ = "users"
addresses_collection = prop
Base.prepare()
assert User.addresses_collection.property is prop
Address = Base.classes.addresses
a1 = Address(email_address="e1")
u1 = User(name="u1", addresses_collection={a1})
assert a1.user is u1
def test_prepare_from_subclass(self):
"""test #9367"""
Base = automap_base()
class User(Base):
__tablename__ = "users"
User.prepare(testing.db)
assert not hasattr(Base.classes, "users")
assert hasattr(Base.classes, "addresses")
def test_prepare_w_only(self):
Base = automap_base()
Base.prepare(
testing.db,
reflection_options={"only": ["users"], "resolve_fks": False},
)
assert hasattr(Base.classes, "users")
assert not hasattr(Base.classes, "addresses")
def test_prepare_call_multiple_times(self):
"""newly added in 2.0 as part of #5145"""
Base = automap_base()
Base.prepare(
testing.db,
reflection_options={"only": ["users"], "resolve_fks": False},
)
assert hasattr(Base.classes, "users")
assert not hasattr(Base.classes, "addresses")
um = Base.classes.users.__mapper__
Base.prepare(
testing.db,
reflection_options={"only": ["users"], "resolve_fks": False},
)
assert hasattr(Base.classes, "users")
assert not hasattr(Base.classes, "addresses")
is_(Base.classes.users.__mapper__, um)
Base.prepare(testing.db)
assert hasattr(Base.classes, "users")
assert hasattr(Base.classes, "addresses")
am = Base.classes.addresses.__mapper__
Base.prepare()
Base.prepare()
is_(Base.classes.users.__mapper__, um)
is_(Base.classes.addresses.__mapper__, am)
def test_prepare_call_dont_rely_on_reflected(self):
"""newly added in 2.0 as part of #5145"""
Base = automap_base()
Base.metadata.reflect(testing.db, only=["users"], resolve_fks=False)
Base.prepare(
testing.db,
reflection_options={"only": ["addresses"]},
)
# check that users was prepared also, even though it wasn't in
# the second reflection call
assert hasattr(Base.classes, "users")
assert hasattr(Base.classes, "addresses")
def test_exception_prepare_not_called(self):
Base = automap_base(metadata=self.tables_test_metadata)
class User(Base):
__tablename__ = "users"
s = Session()
assert_raises_message(
orm_exc.UnmappedClassError,
"Class test.ext.test_automap.User is a subclass of AutomapBase. "
r"Mappings are not produced until the .prepare\(\) method is "
"called on the class hierarchy.",
s.query,
User,
)
def test_relationship_explicit_override_m2o(self):
Base = automap_base(metadata=self.tables_test_metadata)
prop = relationship("users")
class Address(Base):
__tablename__ = "addresses"
users = prop
Base.prepare()
User = Base.classes.users
assert Address.users.property is prop
a1 = Address(email_address="e1")
u1 = User(name="u1", address_collection=[a1])
assert a1.users is u1
def test_relationship_self_referential(self):
Base = automap_base(metadata=self.tables_test_metadata)
Base.prepare()
Node = Base.classes.nodes
n1 = Node()
n2 = Node()
n1.nodes_collection.append(n2)
assert n2.nodes is n1
def test_prepare_accepts_optional_schema_arg(self):
"""
The underlying reflect call accepts an optional schema argument.
This is for determining which database schema to load.
This test verifies that prepare can accept an optional schema
argument and pass it to reflect.
"""
Base = automap_base(metadata=self.tables_test_metadata)
engine_mock = Mock()
with patch.object(Base.metadata, "reflect") as reflect_mock:
Base.prepare(autoload_with=engine_mock, schema="some_schema")
reflect_mock.assert_called_once_with(
engine_mock,
schema="some_schema",
extend_existing=True,
autoload_replace=False,
)
def test_prepare_defaults_to_no_schema(self):
"""
The underlying reflect call accepts an optional schema argument.
This is for determining which database schema to load.
This test verifies that prepare passes a default None if no schema is
provided.
"""
Base = automap_base(metadata=self.tables_test_metadata)
engine_mock = Mock()
with patch.object(Base.metadata, "reflect") as reflect_mock:
Base.prepare(autoload_with=engine_mock)
reflect_mock.assert_called_once_with(
engine_mock,
schema=None,
extend_existing=True,
autoload_replace=False,
)
def test_prepare_w_dialect_kwargs(self):
Base = automap_base(metadata=self.tables_test_metadata)
engine_mock = Mock()
with patch.object(Base.metadata, "reflect") as reflect_mock:
Base.prepare(
autoload_with=engine_mock,
reflection_options={"oracle_resolve_synonyms": True},
)
reflect_mock.assert_called_once_with(
engine_mock,
schema=None,
extend_existing=True,
autoload_replace=False,
oracle_resolve_synonyms=True,
)
def test_naming_schemes(self):
Base = automap_base(metadata=self.tables_test_metadata)
def classname_for_table(base, tablename, table):
return str("cls_" + tablename)
def name_for_scalar_relationship(
base, local_cls, referred_cls, constraint
):
return "scalar_" + referred_cls.__name__
def name_for_collection_relationship(
base, local_cls, referred_cls, constraint
):
return "coll_" + referred_cls.__name__
Base.prepare(
classname_for_table=classname_for_table,
name_for_scalar_relationship=name_for_scalar_relationship,
name_for_collection_relationship=name_for_collection_relationship,
)
User = Base.classes.cls_users
Address = Base.classes.cls_addresses
u1 = User()
a1 = Address()
u1.coll_cls_addresses.append(a1)
assert a1.scalar_cls_users is u1
def test_relationship_m2m(self):
Base = automap_base(metadata=self.tables_test_metadata)
Base.prepare()
Order, Item = Base.classes.orders, Base.classes["items"]
o1 = Order()
i1 = Item()
o1.items_collection.append(i1)
assert o1 in i1.orders_collection
def test_relationship_explicit_override_forwards_m2m(self):
Base = automap_base(metadata=self.tables_test_metadata)
class Order(Base):
__tablename__ = "orders"
items_collection = relationship(
"items", secondary="order_items", collection_class=set
)
Base.prepare()
Item = Base.classes["items"]
o1 = Order()
i1 = Item()
o1.items_collection.add(i1)
# it is 'order_collection' because the class name is
# "Order" !
assert isinstance(i1.order_collection, list)
assert o1 in i1.order_collection
def test_m2m_relationship_also_map_the_secondary(self):
"""test #6679"""
Base = automap_base(metadata=self.tables_test_metadata)
# extend the table to have pk cols
Table(
"order_items",
self.tables_test_metadata,
Column("item_id", None, ForeignKey("items.id"), primary_key=True),
Column(
"order_id", None, ForeignKey("orders.id"), primary_key=True
),
extend_existing=True,
)
# then also map to it
class OrderItem(Base):
__tablename__ = "order_items"
Base.prepare()
Order = Base.classes["orders"]
Item = Base.classes["items"]
o1 = Order()
i1 = Item(description="x")
o1.items_collection.append(i1)
s = fixtures.fixture_session()
s.add(o1)
s.flush()
oi = s.execute(select(OrderItem)).scalars().one()
is_(oi.items, i1)
is_(oi.orders, o1)
def test_relationship_pass_params(self):
Base = automap_base(metadata=self.tables_test_metadata)
mock = Mock()
def _gen_relationship(
base, direction, return_fn, attrname, local_cls, referred_cls, **kw
):
mock(base, direction, attrname)
return generate_relationship(
base,
direction,
return_fn,
attrname,
local_cls,
referred_cls,
**kw,
)
Base.prepare(generate_relationship=_gen_relationship)
assert {tuple(c[1]) for c in mock.mock_calls}.issuperset(
[
(Base, interfaces.MANYTOONE, "nodes"),
(Base, interfaces.MANYTOMANY, "keywords_collection"),
(Base, interfaces.MANYTOMANY, "items_collection"),
(Base, interfaces.MANYTOONE, "users"),
(Base, interfaces.ONETOMANY, "addresses_collection"),
]
)
class MultipleSchemaTest(AssertsCompiledSQL, fixtures.MappedTest):
"""test #5145"""
__requires__ = ("schemas",)
__dialect__ = "default"
@classmethod
def define_tables(cls, metadata):
Table(
"user",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("name", String(30), nullable=False),
)
Table(
"user",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("name", String(30), nullable=False),
schema=config.test_schema,
)
@testing.variation("reflect_method", ["reflect", "prepare"])
def test_by_schema_collection(self, reflect_method):
m2 = MetaData()
Base: AutomapBase = automap_base(metadata=m2)
def mnft(cls, tablename, table):
return table.schema
if reflect_method.reflect:
m2.reflect(testing.db)
m2.reflect(testing.db, schema=config.test_schema)
Base.prepare(modulename_for_table=mnft)
elif reflect_method.prepare:
Base.prepare(autoload_with=testing.db, modulename_for_table=mnft)
Base.prepare(
autoload_with=testing.db,
modulename_for_table=mnft,
schema=config.test_schema,
)
else:
reflect_method.fail()
# only class with None for __module__ gets placed in .classes
is_(Base.classes.user, Base.by_module.sqlalchemy.ext.automap.user)
self.assert_compile(
select(Base.by_module.sqlalchemy.ext.automap.user),
'SELECT "user".id, "user".name FROM "user"',
)
self.assert_compile(
select(Base.by_module[config.test_schema].user),
f'SELECT {config.test_schema}."user".id, '
f'{config.test_schema}."user".name '
f'FROM {config.test_schema}."user"',
)
def test_named_not_in_classes(self):
Base: AutomapBase = automap_base()
def mnft(cls, tablename, table):
assert table.schema is not None
return table.schema
Base.prepare(
autoload_with=testing.db,
schema=config.test_schema,
modulename_for_table=mnft,
)
assert "user" not in Base.classes
assert "user" in Base.by_module[config.test_schema]
Base.prepare(autoload_with=testing.db)
assert "user" in Base.classes
def test_cls_schema_name_conflict(self):
m2 = MetaData()
Base: AutomapBase = automap_base(metadata=m2)
m2.reflect(testing.db)
m2.reflect(testing.db, schema=config.test_schema)
def mnft(cls, tablename, table):
if table.schema is not None:
return "user.user"
else:
return "user"
with expect_raises_message(
sa_exc.InvalidRequestError,
'name "user" matches both a class name and a module name',
):
Base.prepare(modulename_for_table=mnft)
def test_dupe_clsname_warning(self):
Base: AutomapBase = automap_base()
Base.prepare(testing.db)
with expect_warnings(
"Ignoring duplicate class name 'user' received in automap base "
f"for table {config.test_schema}.user "
"without ``__module__`` being set;",
):
Base.prepare(testing.db, schema=config.test_schema)
def test_dupe_tablename_ok_w_explicit_classes(self):
Base = automap_base()
class User1(Base):
__tablename__ = "user"
class User2(Base):
__tablename__ = "user"
__table_args__ = {"schema": config.test_schema}
# currently we have to do the reflection separate since prepare()
# tries to map all the classes at once
Base.metadata.reflect(testing.db, extend_existing=True)
Base.metadata.reflect(
testing.db, schema=config.test_schema, extend_existing=True
)
Base.prepare()
class CascadeTest(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table("a", metadata, Column("id", Integer, primary_key=True))
Table(
"b",
metadata,
Column("id", Integer, primary_key=True),
Column("aid", ForeignKey("a.id"), nullable=True),
)
Table(
"c",
metadata,
Column("id", Integer, primary_key=True),
Column("aid", ForeignKey("a.id"), nullable=False),
)
Table(
"d",
metadata,
Column("id", Integer, primary_key=True),
Column(
"aid", ForeignKey("a.id", ondelete="cascade"), nullable=False
),
)
Table(
"e",
metadata,
Column("id", Integer, primary_key=True),
Column(
"aid", ForeignKey("a.id", ondelete="set null"), nullable=True
),
)
def test_o2m_relationship_cascade(self):
Base = automap_base(metadata=self.tables_test_metadata)
Base.prepare()
configure_mappers()
b_rel = Base.classes.a.b_collection
assert not b_rel.property.cascade.delete
assert not b_rel.property.cascade.delete_orphan
assert not b_rel.property.passive_deletes
assert b_rel.property.cascade.save_update
c_rel = Base.classes.a.c_collection
assert c_rel.property.cascade.delete
assert c_rel.property.cascade.delete_orphan
assert not c_rel.property.passive_deletes
assert c_rel.property.cascade.save_update
d_rel = Base.classes.a.d_collection
assert d_rel.property.cascade.delete
assert d_rel.property.cascade.delete_orphan
assert d_rel.property.passive_deletes
assert d_rel.property.cascade.save_update
e_rel = Base.classes.a.e_collection
assert not e_rel.property.cascade.delete
assert not e_rel.property.cascade.delete_orphan
assert e_rel.property.passive_deletes
assert e_rel.property.cascade.save_update
class AutomapInhTest(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"single",
metadata,
Column("id", Integer, primary_key=True),
Column("type", String(10)),
test_needs_fk=True,
)
Table(
"joined_base",
metadata,
Column("id", Integer, primary_key=True),
Column("type", String(10)),
test_needs_fk=True,
)
Table(
"joined_inh",
metadata,
Column(
"id", Integer, ForeignKey("joined_base.id"), primary_key=True
),
test_needs_fk=True,
)
FixtureTest.define_tables(metadata)
def test_single_inheritance_reflect(self):
Base = automap_base()
class Single(Base):
__tablename__ = "single"
type = Column(String)
__mapper_args__ = {
"polymorphic_identity": "u0",
"polymorphic_on": type,
}
class SubUser1(Single):
__mapper_args__ = {"polymorphic_identity": "u1"}
class SubUser2(Single):
__mapper_args__ = {"polymorphic_identity": "u2"}
Base.prepare(autoload_with=testing.db)
assert SubUser2.__mapper__.inherits is Single.__mapper__
def test_joined_inheritance_reflect(self):
Base = automap_base()
class Joined(Base):
__tablename__ = "joined_base"
type = Column(String)
__mapper_args__ = {
"polymorphic_identity": "u0",
"polymorphic_on": type,
}
class SubJoined(Joined):
__tablename__ = "joined_inh"
__mapper_args__ = {"polymorphic_identity": "u1"}
Base.prepare(autoload_with=testing.db)
assert SubJoined.__mapper__.inherits is Joined.__mapper__
assert not Joined.__mapper__.relationships
assert not SubJoined.__mapper__.relationships
def test_conditional_relationship(self):
Base = automap_base()
def _gen_relationship(*arg, **kw):
return None
Base.prepare(
autoload_with=testing.db,
generate_relationship=_gen_relationship,
)
class ConcurrentAutomapTest(fixtures.TestBase):
__only_on__ = "sqlite+pysqlite"
def _make_tables(self, e):
m = MetaData()
for i in range(15):
Table(
"table_%d" % i,
m,
Column("id", Integer, primary_key=True),
Column("data", String(50)),
Column(
"t_%d_id" % (i - 1), ForeignKey("table_%d.id" % (i - 1))
)
if i > 4
else None,
)
m.drop_all(e)
m.create_all(e)
def _automap(self, e):
Base = automap_base()
Base.prepare(autoload_with=e)
time.sleep(0.01)
configure_mappers()
def _chaos(self):
e = create_engine("sqlite://")
try:
self._make_tables(e)
for i in range(2):
try:
self._automap(e)
except:
self._success = False
raise
time.sleep(random.random())
finally:
e.dispose()
def test_concurrent_automaps_w_configure(self):
self._success = True
threads = [threading.Thread(target=self._chaos) for i in range(30)]
for t in threads:
t.start()
for t in threads:
t.join()
assert self._success, "One or more threads failed"
|