File: test_poly_linked_list.py

package info (click to toggle)
sqlalchemy 2.0.40%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 26,404 kB
  • sloc: python: 410,002; makefile: 230; sh: 7
file content (259 lines) | stat: -rw-r--r-- 7,461 bytes parent folder | download | duplicates (3)
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
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy.orm import backref
from sqlalchemy.orm import configure_mappers
from sqlalchemy.orm import relationship
from sqlalchemy.testing import fixtures
from sqlalchemy.testing.fixtures import fixture_session
from sqlalchemy.testing.schema import Column
from sqlalchemy.testing.schema import Table


class PolymorphicCircularTest(fixtures.MappedTest):
    run_setup_mappers = "once"

    @classmethod
    def define_tables(cls, metadata):
        Table(
            "table1",
            metadata,
            Column(
                "id", Integer, primary_key=True, test_needs_autoincrement=True
            ),
            Column(
                "related_id", Integer, ForeignKey("table1.id"), nullable=True
            ),
            Column("type", String(30)),
            Column("name", String(30)),
        )

        Table(
            "table2",
            metadata,
            Column("id", Integer, ForeignKey("table1.id"), primary_key=True),
        )

        Table(
            "table3",
            metadata,
            Column("id", Integer, ForeignKey("table1.id"), primary_key=True),
        )

        Table(
            "data",
            metadata,
            Column(
                "id", Integer, primary_key=True, test_needs_autoincrement=True
            ),
            Column("node_id", Integer, ForeignKey("table1.id")),
            Column("data", String(30)),
        )

    @classmethod
    def setup_mappers(cls):
        table1, table2, table3, data = cls.tables(
            "table1", "table2", "table3", "data"
        )

        Base = cls.Basic

        class Table1(Base):
            def __init__(self, name, data=None):
                self.name = name
                if data is not None:
                    self.data = data

            def __repr__(self):
                return "%s(%s, %s, %s)" % (
                    self.__class__.__name__,
                    self.id,
                    repr(str(self.name)),
                    repr(self.data),
                )

        class Table1B(Table1):
            pass

        class Table2(Table1):
            pass

        class Table3(Table1):
            pass

        class Data(Base):
            def __init__(self, data):
                self.data = data

            def __repr__(self):
                return "%s(%s, %s)" % (
                    self.__class__.__name__,
                    self.id,
                    repr(str(self.data)),
                )

        # currently, the "eager" relationships degrade to lazy relationships
        # due to the polymorphic load.
        # the "nxt" relationship used to have a "lazy='joined'" on it, but the
        # EagerLoader raises the "self-referential"
        # exception now.  since eager loading would never work for that
        # relationship anyway, its better that the user
        # gets an exception instead of it silently not eager loading.
        # NOTE: using "nxt" instead of "next" to avoid 2to3 turning it into
        # __next__() for some reason.
        table1_mapper = cls.mapper_registry.map_imperatively(
            Table1,
            table1,
            # select_table=join,
            polymorphic_on=table1.c.type,
            polymorphic_identity="table1",
            properties={
                "nxt": relationship(
                    Table1,
                    backref=backref(
                        "prev", remote_side=table1.c.id, uselist=False
                    ),
                    uselist=False,
                    primaryjoin=table1.c.id == table1.c.related_id,
                ),
                "data": relationship(
                    cls.mapper_registry.map_imperatively(Data, data),
                    lazy="joined",
                    order_by=data.c.id,
                ),
            },
        )

        cls.mapper_registry.map_imperatively(
            Table1B, inherits=table1_mapper, polymorphic_identity="table1b"
        )

        cls.mapper_registry.map_imperatively(
            Table2,
            table2,
            inherits=table1_mapper,
            polymorphic_identity="table2",
        )

        cls.mapper_registry.map_imperatively(
            Table3,
            table3,
            inherits=table1_mapper,
            polymorphic_identity="table3",
        )

        configure_mappers()
        assert table1_mapper.primary_key == (
            table1.c.id,
        ), table1_mapper.primary_key

    def test_one(self):
        Table1, Table2 = self.classes("Table1", "Table2")
        self._testlist([Table1, Table2, Table1, Table2])

    def test_two(self):
        Table3 = self.classes.Table3
        self._testlist([Table3])

    def test_three(self):
        Table1, Table1B, Table2, Table3 = self.classes(
            "Table1", "Table1B", "Table2", "Table3"
        )
        self._testlist(
            [
                Table2,
                Table1,
                Table1B,
                Table3,
                Table3,
                Table1B,
                Table1B,
                Table2,
                Table1,
            ]
        )

    def test_four(self):
        Table1, Table1B, Table2, Table3, Data = self.classes(
            "Table1", "Table1B", "Table2", "Table3", "Data"
        )
        self._testlist(
            [
                Table2("t2", [Data("data1"), Data("data2")]),
                Table1("t1", []),
                Table3("t3", [Data("data3")]),
                Table1B("t1b", [Data("data4"), Data("data5")]),
            ]
        )

    def _testlist(self, classes):
        Table1 = self.classes.Table1

        sess = fixture_session()

        # create objects in a linked list
        count = 1
        obj = None
        for c in classes:
            if isinstance(c, type):
                newobj = c("item %d" % count)
                count += 1
            else:
                newobj = c
            if obj is not None:
                obj.nxt = newobj
            else:
                t = newobj
            obj = newobj

        # save to DB
        sess.add(t)
        sess.flush()

        # string version of the saved list
        assertlist = []
        node = t
        while node:
            assertlist.append(node)
            n = node.nxt
            if n is not None:
                assert n.prev is node
            node = n
        original = repr(assertlist)

        # clear and query forwards
        sess.expunge_all()
        node = (
            sess.query(Table1)
            .order_by(Table1.id)
            .filter(Table1.id == t.id)
            .first()
        )
        assertlist = []
        while node:
            assertlist.append(node)
            n = node.nxt
            if n is not None:
                assert n.prev is node
            node = n
        forwards = repr(assertlist)

        # clear and query backwards
        sess.expunge_all()
        node = (
            sess.query(Table1)
            .order_by(Table1.id)
            .filter(Table1.id == obj.id)
            .first()
        )
        assertlist = []
        while node:
            assertlist.insert(0, node)
            n = node.prev
            if n is not None:
                assert n.nxt is node
            node = n
        backwards = repr(assertlist)

        # everything should match !
        assert original == forwards == backwards