File: test_orm.py

package info (click to toggle)
sqlalchemy 0.9.8%2Bdfsg-0.1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 23,952 kB
  • ctags: 24,534
  • sloc: python: 152,282; ansic: 1,346; makefile: 257; xml: 17
file content (374 lines) | stat: -rw-r--r-- 11,251 bytes parent folder | download
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
from sqlalchemy.testing import eq_, assert_raises, \
    assert_raises_message
from sqlalchemy import exc as sa_exc, util, Integer, String, ForeignKey
from sqlalchemy.orm import exc as orm_exc, mapper, relationship, \
    sessionmaker, Session, defer
from sqlalchemy import testing
from sqlalchemy.testing import profiling
from sqlalchemy.testing import fixtures
from sqlalchemy.testing.schema import Table, Column
import sys

class MergeTest(fixtures.MappedTest):

    @classmethod
    def define_tables(cls, metadata):
        Table('parent', metadata, Column('id', Integer,
                       primary_key=True,
                       test_needs_autoincrement=True), Column('data',
                       String(20)))
        Table('child', metadata, Column('id', Integer,
                      primary_key=True, test_needs_autoincrement=True),
                      Column('data', String(20)), Column('parent_id',
                      Integer, ForeignKey('parent.id'), nullable=False))

    @classmethod
    def setup_classes(cls):
        class Parent(cls.Basic):
            pass

        class Child(cls.Basic):
            pass

    @classmethod
    def setup_mappers(cls):
        Child, Parent, parent, child = (cls.classes.Child,
                                cls.classes.Parent,
                                cls.tables.parent,
                                cls.tables.child)

        mapper(Parent, parent, properties={'children':
                        relationship(Child, backref='parent')})
        mapper(Child, child)

    @classmethod
    def insert_data(cls):
        parent, child = cls.tables.parent, cls.tables.child

        parent.insert().execute({'id': 1, 'data': 'p1'})
        child.insert().execute({'id': 1, 'data': 'p1c1', 'parent_id': 1})

    def test_merge_no_load(self):
        Parent = self.classes.Parent

        sess = sessionmaker()()
        sess2 = sessionmaker()()
        p1 = sess.query(Parent).get(1)
        p1.children

        # down from 185 on this this is a small slice of a usually
        # bigger operation so using a small variance

        @profiling.function_call_count(variance=0.10)
        def go1():
            return sess2.merge(p1, load=False)
        p2 = go1()

        # third call, merge object already present. almost no calls.

        @profiling.function_call_count(variance=0.10)
        def go2():
            return sess2.merge(p2, load=False)
        go2()

    def test_merge_load(self):
        Parent = self.classes.Parent

        sess = sessionmaker()()
        sess2 = sessionmaker()()
        p1 = sess.query(Parent).get(1)
        p1.children

        # preloading of collection took this down from 1728 to 1192
        # using sqlite3 the C extension took it back up to approx. 1257
        # (py2.6)

        @profiling.function_call_count()
        def go():
            p2 = sess2.merge(p1)
        go()

        # one more time, count the SQL

        def go2():
            p2 = sess2.merge(p1)
        sess2 = sessionmaker(testing.db)()
        self.assert_sql_count(testing.db, go2, 2)

class LoadManyToOneFromIdentityTest(fixtures.MappedTest):
    """test overhead associated with many-to-one fetches.

    Prior to the refactor of LoadLazyAttribute and
    query._get(), the load from identity map took 2x
    as many calls (65K calls here instead of around 33K)
    to load 1000 related objects from the identity map.

    """


    @classmethod
    def define_tables(cls, metadata):
        Table('parent', metadata,
                        Column('id', Integer, primary_key=True),
                       Column('data', String(20)),
                       Column('child_id', Integer, ForeignKey('child.id'))
                       )

        Table('child', metadata,
                    Column('id', Integer, primary_key=True),
                  Column('data', String(20))
                 )

    @classmethod
    def setup_classes(cls):
        class Parent(cls.Basic):
            pass

        class Child(cls.Basic):
            pass

    @classmethod
    def setup_mappers(cls):
        Child, Parent, parent, child = (cls.classes.Child,
                                cls.classes.Parent,
                                cls.tables.parent,
                                cls.tables.child)

        mapper(Parent, parent, properties={
            'child': relationship(Child)})
        mapper(Child, child)

    @classmethod
    def insert_data(cls):
        parent, child = cls.tables.parent, cls.tables.child

        child.insert().execute([
            {'id':i, 'data':'c%d' % i}
            for i in range(1, 251)
        ])
        parent.insert().execute([
            {
                'id':i,
                'data':'p%dc%d' % (i, (i % 250) + 1),
                'child_id':(i % 250) + 1
            }
            for i in range(1, 1000)
        ])

    def test_many_to_one_load_no_identity(self):
        Parent = self.classes.Parent

        sess = Session()
        parents = sess.query(Parent).all()


        @profiling.function_call_count(variance=.2)
        def go():
            for p in parents:
                p.child
        go()

    def test_many_to_one_load_identity(self):
        Parent, Child = self.classes.Parent, self.classes.Child

        sess = Session()
        parents = sess.query(Parent).all()
        children = sess.query(Child).all()

        @profiling.function_call_count()
        def go():
            for p in parents:
                p.child
        go()

class MergeBackrefsTest(fixtures.MappedTest):

    @classmethod
    def define_tables(cls, metadata):
        Table('a', metadata,
            Column('id', Integer, primary_key=True),
            Column('c_id', Integer, ForeignKey('c.id'))
        )
        Table('b', metadata,
            Column('id', Integer, primary_key=True),
            Column('a_id', Integer, ForeignKey('a.id'))
        )
        Table('c', metadata,
            Column('id', Integer, primary_key=True),
        )
        Table('d', metadata,
            Column('id', Integer, primary_key=True),
            Column('a_id', Integer, ForeignKey('a.id'))
        )

    @classmethod
    def setup_classes(cls):
        class A(cls.Basic):
            pass
        class B(cls.Basic):
            pass
        class C(cls.Basic):
            pass
        class D(cls.Basic):
            pass

    @classmethod
    def setup_mappers(cls):
        A, B, C, D = cls.classes.A, cls.classes.B, \
                    cls.classes.C, cls.classes.D
        a, b, c, d = cls.tables.a, cls.tables.b, \
                    cls.tables.c, cls.tables.d
        mapper(A, a, properties={
            'bs': relationship(B, backref='a'),
            'c': relationship(C, backref='as'),
            'ds': relationship(D, backref='a'),
        })
        mapper(B, b)
        mapper(C, c)
        mapper(D, d)

    @classmethod
    def insert_data(cls):
        A, B, C, D = cls.classes.A, cls.classes.B, \
                    cls.classes.C, cls.classes.D
        s = Session()
        s.add_all([
            A(id=i,
                bs=[B(id=(i * 5) + j) for j in range(1, 5)],
                c=C(id=i),
                ds=[D(id=(i * 5) + j) for j in range(1, 5)]
            )
            for i in range(1, 5)
        ])
        s.commit()

    @profiling.function_call_count(variance=.10)
    def test_merge_pending_with_all_pks(self):
        A, B, C, D = self.classes.A, self.classes.B, \
                    self.classes.C, self.classes.D
        s = Session()
        for a in [
            A(id=i,
                bs=[B(id=(i * 5) + j) for j in range(1, 5)],
                c=C(id=i),
                ds=[D(id=(i * 5) + j) for j in range(1, 5)]
            )
            for i in range(1, 5)
        ]:
            s.merge(a)

class DeferOptionsTest(fixtures.MappedTest):

    @classmethod
    def define_tables(cls, metadata):
        Table('a', metadata,
            Column('id', Integer, primary_key=True),
            Column('x', String(5)),
            Column('y', String(5)),
            Column('z', String(5)),
            Column('q', String(5)),
            Column('p', String(5)),
            Column('r', String(5)),
        )

    @classmethod
    def setup_classes(cls):
        class A(cls.Basic):
            pass

    @classmethod
    def setup_mappers(cls):
        A = cls.classes.A
        a = cls.tables.a
        mapper(A, a)

    @classmethod
    def insert_data(cls):
        A = cls.classes.A
        s = Session()
        s.add_all([
            A(id=i,
                **dict((letter, "%s%d" % (letter, i)) for letter in
                        ['x', 'y', 'z', 'p', 'q', 'r'])
            ) for i in range(1, 1001)
        ])
        s.commit()

    @profiling.function_call_count(variance=.10)
    def test_baseline(self):
        # as of [ticket:2778], this is at 39025
        A = self.classes.A
        s = Session()
        s.query(A).all()

    @profiling.function_call_count(variance=.10)
    def test_defer_many_cols(self):
        # with [ticket:2778], this goes from 50805 to 32817,
        # as it should be fewer function calls than the baseline
        A = self.classes.A
        s = Session()
        s.query(A).options(
            *[defer(letter) for letter in ['x', 'y', 'z', 'p', 'q', 'r']]).\
            all()


class AttributeOverheadTest(fixtures.MappedTest):

    @classmethod
    def define_tables(cls, metadata):
        Table('parent', metadata, Column('id', Integer,
                       primary_key=True,
                       test_needs_autoincrement=True), Column('data',
                       String(20)))
        Table('child', metadata, Column('id', Integer,
                      primary_key=True, test_needs_autoincrement=True),
                      Column('data', String(20)), Column('parent_id',
                      Integer, ForeignKey('parent.id'), nullable=False))

    @classmethod
    def setup_classes(cls):
        class Parent(cls.Basic):
            pass

        class Child(cls.Basic):
            pass

    @classmethod
    def setup_mappers(cls):
        Child, Parent, parent, child = (cls.classes.Child,
                                cls.classes.Parent,
                                cls.tables.parent,
                                cls.tables.child)

        mapper(Parent, parent, properties={'children':
                        relationship(Child, backref='parent')})
        mapper(Child, child)


    def test_attribute_set(self):
        Parent, Child = self.classes.Parent, self.classes.Child
        p1 = Parent()
        c1 = Child()

        @profiling.function_call_count()
        def go():
            for i in range(30):
                c1.parent = p1
                c1.parent = None
                c1.parent = p1
                del c1.parent
        go()

    def test_collection_append_remove(self):
        Parent, Child = self.classes.Parent, self.classes.Child
        p1 = Parent()
        children = [Child() for i in range(100)]

        @profiling.function_call_count()
        def go():
            for child in children:
                p1.children.append(child)
            for child in children:
                p1.children.remove(child)
        go()