/
testConnection.py
1398 lines (1113 loc) · 42.6 KB
/
testConnection.py
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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Unit tests for the Connection class."""
from __future__ import print_function
import doctest
import re
import six
import sys
import unittest
import transaction
from transaction import Transaction
import ZODB.tests.util
from ZODB.config import databaseFromString
from ZODB.utils import p64, u64, z64
from persistent import Persistent
from zope.interface.verify import verifyObject
from zope.testing import loggingsupport, renormalizing
from .. import mvccadapter
checker = renormalizing.RENormalizing([
# Python 3 bytes add a "b".
(re.compile("b('.*?')"), r"\1"),
# Python 3 removes empty list representation.
(re.compile(r"set\(\[\]\)"), r"set()"),
# Python 3 adds module name to exceptions.
(re.compile("ZODB.POSException.POSKeyError"), r"POSKeyError"),
(re.compile("ZODB.POSException.ReadConflictError"), r"ReadConflictError"),
(re.compile("ZODB.POSException.ConflictError"), r"ConflictError"),
(re.compile("ZODB.POSException.ConnectionStateError"),
r"ConnectionStateError"),
])
class ConnectionDotAdd(ZODB.tests.util.TestCase):
def setUp(self):
ZODB.tests.util.TestCase.setUp(self)
from ZODB.Connection import Connection
self.db = StubDatabase()
self.datamgr = Connection(self.db)
self.datamgr.open()
self.transaction = Transaction()
def test_add(self):
from ZODB.POSException import InvalidObjectReference
obj = StubObject()
self.assertTrue(obj._p_oid is None)
self.assertTrue(obj._p_jar is None)
self.datamgr.add(obj)
self.assertTrue(obj._p_oid is not None)
self.assertTrue(obj._p_jar is self.datamgr)
self.assertTrue(self.datamgr.get(obj._p_oid) is obj)
# Only first-class persistent objects may be added.
self.assertRaises(TypeError, self.datamgr.add, object())
# Adding to the same connection does not fail. Object keeps the
# same oid.
oid = obj._p_oid
self.datamgr.add(obj)
self.assertEqual(obj._p_oid, oid)
# Cannot add an object from a different connection.
obj2 = StubObject()
obj2._p_jar = object()
self.assertRaises(InvalidObjectReference, self.datamgr.add, obj2)
def testResetOnAbort(self):
# Check that _p_oid and _p_jar are reset when a transaction is
# aborted.
obj = StubObject()
self.datamgr.add(obj)
oid = obj._p_oid
self.datamgr.abort(self.transaction)
self.assertTrue(obj._p_oid is None)
self.assertTrue(obj._p_jar is None)
self.assertRaises(KeyError, self.datamgr.get, oid)
def testResetOnTpcAbort(self):
obj = StubObject()
self.datamgr.add(obj)
oid = obj._p_oid
# Simulate an error while committing some other object.
self.datamgr.tpc_begin(self.transaction)
# Let's pretend something bad happens here.
# Call tpc_abort, clearing everything.
self.datamgr.tpc_abort(self.transaction)
self.assertTrue(obj._p_oid is None)
self.assertTrue(obj._p_jar is None)
self.assertRaises(KeyError, self.datamgr.get, oid)
def testTpcAbortAfterCommit(self):
obj = StubObject()
self.datamgr.add(obj)
oid = obj._p_oid
self.datamgr.tpc_begin(self.transaction)
self.datamgr.commit(self.transaction)
# Let's pretend something bad happened here.
self.datamgr.tpc_abort(self.transaction)
self.assertTrue(obj._p_oid is None)
self.assertTrue(obj._p_jar is None)
self.assertRaises(KeyError, self.datamgr.get, oid)
self.assertEqual(self.db.storage._stored, [oid])
def testCommit(self):
obj = StubObject()
self.datamgr.add(obj)
oid = obj._p_oid
self.datamgr.tpc_begin(self.transaction)
self.datamgr.commit(self.transaction)
self.datamgr.tpc_finish(self.transaction)
self.assertTrue(obj._p_oid is oid)
self.assertTrue(obj._p_jar is self.datamgr)
# This next assertTrue is covered by an assert in tpc_finish.
##self.assertTrue(not self.datamgr._added)
self.assertEqual(self.db.storage._stored, [oid])
self.assertEqual(self.db.storage._finished, [oid])
def testModifyOnGetstate(self):
member = StubObject()
subobj = StubObject()
subobj.member = member
obj = ModifyOnGetStateObject(subobj)
self.datamgr.add(obj)
self.datamgr.tpc_begin(self.transaction)
self.datamgr.commit(self.transaction)
self.datamgr.tpc_finish(self.transaction)
storage = self.db.storage
self.assertTrue(obj._p_oid in storage._stored, "object was not stored")
self.assertTrue(subobj._p_oid in storage._stored,
"subobject was not stored")
self.assertTrue(member._p_oid in storage._stored,
"member was not stored")
self.assertTrue(self.datamgr._added_during_commit is None)
def testUnusedAddWorks(self):
# When an object is added, but not committed, it shouldn't be stored,
# but also it should be an error.
obj = StubObject()
self.datamgr.add(obj)
self.datamgr.tpc_begin(self.transaction)
self.datamgr.tpc_finish(self.transaction)
self.assertTrue(obj._p_oid not in
self.datamgr._storage._storage._stored)
def test__resetCacheResetsReader(self):
# https://bugs.launchpad.net/zodb/+bug/142667
old_cache = self.datamgr._cache
self.datamgr._resetCache()
new_cache = self.datamgr._cache
self.assertFalse(new_cache is old_cache)
self.assertTrue(self.datamgr._reader._cache is new_cache)
class SetstateErrorLoggingTests(ZODB.tests.util.TestCase):
def setUp(self):
ZODB.tests.util.TestCase.setUp(self)
from ZODB.Connection import Connection
self.db = db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
self.datamgr = self.db.open()
self.object = StubObject()
self.datamgr.add(self.object)
transaction.commit()
self.handler = loggingsupport.InstalledHandler("ZODB")
def tearDown(self):
self.handler.uninstall()
def test_closed_connection_wont_setstate(self):
oid = self.object._p_oid
self.object._p_deactivate()
self.datamgr.close()
self.assertRaises(
ZODB.POSException.ConnectionStateError,
self.datamgr.setstate, self.object)
record, = self.handler.records
self.assertEqual(
record.msg,
"Shouldn't load state for ZODB.tests.testConnection.StubObject"
" 0x01 when the connection is closed")
self.assertTrue(record.exc_info)
class UserMethodTests(unittest.TestCase):
# add isn't tested here, because there are a bunch of traditional
# unit tests for it.
def doctest_root(self):
r"""doctest of root() method
The root() method is simple, and the tests are pretty minimal.
Ensure that a new database has a root and that it is a
PersistentMapping.
>>> db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
>>> cn = db.open()
>>> root = cn.root()
>>> type(root).__name__
'PersistentMapping'
>>> root._p_oid
'\x00\x00\x00\x00\x00\x00\x00\x00'
>>> root._p_jar is cn
True
>>> db.close()
"""
def doctest_get(self):
r"""doctest of get() method
The get() method return the persistent object corresponding to
an oid.
>>> db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
>>> cn = db.open()
>>> cn.cacheMinimize() # See fix84.rst
>>> obj = cn.get(p64(0))
>>> obj._p_oid
'\x00\x00\x00\x00\x00\x00\x00\x00'
The object is a ghost.
>>> obj._p_state
-1
And multiple calls with the same oid, return the same object.
>>> obj2 = cn.get(p64(0))
>>> obj is obj2
True
If all references to the object are released, then a new
object will be returned. The cache doesn't keep unreferenced
ghosts alive, although on some implementations like PyPy we
need to run a garbage collection to be sure they go away. (The
next object returned may still have the same id, because Python
may re-use the same memory.)
>>> del obj, obj2
>>> import gc
>>> _ = gc.collect()
>>> cn._cache.get(p64(0), None)
If the object is unghosted, then it will stay in the cache
after the last reference is released. (This is true only if
there is room in the cache and the object is recently used.)
>>> obj = cn.get(p64(0))
>>> obj._p_activate()
>>> y = id(obj)
>>> del obj
>>> obj = cn.get(p64(0))
>>> id(obj) == y
True
>>> obj._p_state
0
A request for an object that doesn't exist will raise a POSKeyError.
>>> cn.get(p64(1))
Traceback (most recent call last):
...
POSKeyError: 0x01
"""
def doctest_close(self):
r"""doctest of close() method
This is a minimal test, because most of the interesting
effects on closing a connection involve its interaction with the
database and the transaction.
>>> db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
>>> cn = db.open()
It's safe to close a connection multiple times.
>>> cn.close()
>>> cn.close()
>>> cn.close()
It's not possible to load or store objects once the storage is closed.
>>> cn.get(p64(0))
Traceback (most recent call last):
...
ConnectionStateError: The database connection is closed
>>> p = Persistent()
>>> cn.add(p)
Traceback (most recent call last):
...
ConnectionStateError: The database connection is closed
"""
def doctest_close_with_pending_changes(self):
r"""doctest to ensure close() w/ pending changes complains
>>> import transaction
Just opening and closing is fine.
>>> db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
>>> cn = db.open()
>>> cn.close()
Opening, making a change, committing, and closing is fine.
>>> cn = db.open()
>>> cn.root()['a'] = 1
>>> transaction.commit()
>>> cn.close()
Opening, making a change, and aborting is fine.
>>> cn = db.open()
>>> cn.root()['a'] = 1
>>> transaction.abort()
>>> cn.close()
But trying to close with a change pending complains.
>>> cn = db.open()
>>> cn.root()['a'] = 10
>>> cn.close()
Traceback (most recent call last):
...
ConnectionStateError: Cannot close a connection joined to a transaction
This leaves the connection as it was, so we can still commit
the change.
>>> transaction.commit()
>>> cn2 = db.open()
>>> cn2.root()['a']
10
>>> cn.close(); cn2.close()
>>> db.close()
"""
def doctest_onCloseCallbacks(self):
r"""doctest of onCloseCallback() method
>>> db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
>>> cn = db.open()
Every function registered is called, even if it raises an
exception. They are only called once.
>>> L = []
>>> def f():
... L.append("f")
>>> def g():
... L.append("g")
... return 1 / 0
>>> cn.onCloseCallback(g)
>>> cn.onCloseCallback(f)
>>> cn.close()
>>> L
['g', 'f']
>>> del L[:]
>>> cn.close()
>>> L
[]
The implementation keeps a list of callbacks that is reset
to a class variable (which is bound to None) after the connection
is closed.
>>> cn._Connection__onCloseCallbacks
"""
def doctest_close_dispatches_to_activity_monitors(self):
r"""doctest that connection close updates activity monitors
Set up a multi-database:
>>> db1 = ZODB.DB(None)
>>> db2 = ZODB.DB(None, databases=db1.databases, database_name='2',
... cache_size=10)
>>> conn1 = db1.open()
>>> conn2 = conn1.get_connection('2')
Add activity monitors to both dbs:
>>> from ZODB.ActivityMonitor import ActivityMonitor
>>> db1.setActivityMonitor(ActivityMonitor())
>>> db2.setActivityMonitor(ActivityMonitor())
Commit a transaction that affects both connections:
>>> conn1.root()[0] = conn1.root().__class__()
>>> conn2.root()[0] = conn2.root().__class__()
>>> transaction.commit()
After closing the primary connection, both monitors should be up to
date:
>>> conn1.close()
>>> len(db1.getActivityMonitor().log)
1
>>> len(db2.getActivityMonitor().log)
1
"""
def doctest_db(self):
r"""doctest of db() method
>>> db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
>>> cn = db.open()
>>> cn.db() is db
True
>>> cn.close()
>>> cn.db() is db
True
"""
def doctest_isReadOnly(self):
r"""doctest of isReadOnly() method
>>> db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
>>> cn = db.open()
>>> cn.isReadOnly()
False
>>> cn.close()
>>> cn.isReadOnly()
Traceback (most recent call last):
...
ConnectionStateError: The database connection is closed
>>> db.close()
An expedient way to create a read-only storage:
>>> db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
>>> db.storage.isReadOnly = lambda: True
>>> cn = db.open()
>>> cn.isReadOnly()
True
"""
def doctest_cache(self):
r"""doctest of cacheMinimize().
Thus test us minimal, just verifying that the method can be called
and has some effect. We need other tests that verify the cache works
as intended.
>>> db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
>>> cn = db.open()
>>> r = cn.root()
>>> cn.cacheMinimize()
>>> r._p_state
-1
>>> r._p_activate()
>>> r._p_state # up to date
0
>>> cn.cacheMinimize()
>>> r._p_state # ghost again
-1
"""
def doctest_transaction_retry_convenience():
"""
Simple test to verify integration with the transaction retry
helper my verifying that we can raise ConflictError and have it
handled properly.
This is an adaptation of the convenience tests in transaction.
>>> db = ZODB.tests.util.DB()
>>> conn = db.open()
>>> dm = conn.root()
>>> ntry = 0
>>> with transaction.manager:
... dm['ntry'] = 0
>>> import ZODB.POSException
>>> for attempt in transaction.manager.attempts():
... with attempt as t:
... t.note(u'test')
... six.print_(dm['ntry'], ntry)
... ntry += 1
... dm['ntry'] = ntry
... if ntry % 3:
... raise ZODB.POSException.ConflictError()
0 0
0 1
0 2
"""
class InvalidationTests(unittest.TestCase):
# It's harder to write serious tests, because some of the critical
# correctness issues relate to concurrency. We'll have to depend
# on the various concurrent updates and NZODBThreads tests to
# handle these.
def doctest_invalidate(self):
r"""
This test initializes the database with several persistent
objects, then manually delivers invalidations and verifies that
they have the expected effect.
>>> db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
>>> mvcc_storage = db._mvcc_storage
>>> cn = db.open()
>>> mvcc_instance = cn._storage
>>> p1 = Persistent()
>>> p2 = Persistent()
>>> p3 = Persistent()
>>> r = cn.root()
>>> r.update(dict(p1=p1, p2=p2, p3=p3))
>>> transaction.commit()
Transaction ids are 8-byte strings, just like oids; p64() will
create one from an int.
>>> mvcc_storage.invalidate(p64(1), {p1._p_oid: 1})
Transaction start times are based on storage's last
transaction. (Previousely, they were based on the first
invalidation seen in a transaction.)
>>> mvcc_instance.poll_invalidations() == [p1._p_oid]
True
>>> mvcc_instance._start == p64(u64(db.storage.lastTransaction()) + 1)
True
>>> mvcc_storage.invalidate(p64(10), {p2._p_oid: 1, p64(76): 1})
Calling invalidate() doesn't affect the object state until
a transaction boundary.
>>> p1._p_state
0
>>> p2._p_state
0
>>> p3._p_state
0
The sync() method will abort the current transaction and
process any pending invalidations.
>>> cn.sync()
>>> p1._p_state
0
>>> p2._p_state
-1
>>> p3._p_state
0
>>> db.close()
"""
def doctest_invalidateCache():
"""The invalidateCache method invalidates a connection's cache.
It also prevents reads until the end of a transaction::
>>> from ZODB.tests.util import DB
>>> import transaction
>>> db = DB()
>>> mvcc_storage = db._mvcc_storage
>>> tm = transaction.TransactionManager()
>>> connection = db.open(transaction_manager=tm)
>>> connection.root()['a'] = StubObject()
>>> connection.root()['a'].x = 1
>>> connection.root()['b'] = StubObject()
>>> connection.root()['b'].x = 1
>>> connection.root()['c'] = StubObject()
>>> connection.root()['c'].x = 1
>>> tm.commit()
>>> connection.root()['b']._p_deactivate()
>>> connection.root()['c'].x = 2
So we have a connection and an active transaction with some modifications.
Lets call invalidateCache:
>>> mvcc_storage.invalidateCache()
This won't have any effect until the next transaction:
>>> connection.root()['a']._p_changed
0
>>> connection.root()['b']._p_changed
>>> connection.root()['c']._p_changed
1
But if we sync():
>>> connection.sync()
All of our data was invalidated:
>>> connection.root()['a']._p_changed
>>> connection.root()['b']._p_changed
>>> connection.root()['c']._p_changed
But we can load data as usual:
Now, if we try to load an object, we'll get a read conflict:
>>> connection.root()['b'].x
1
>>> db.close()
"""
def doctest_connection_root_convenience():
"""Connection root attributes can now be used as objects with attributes
>>> db = ZODB.tests.util.DB()
>>> conn = db.open()
>>> conn.root.x
Traceback (most recent call last):
...
AttributeError: x
>>> del conn.root.x
Traceback (most recent call last):
...
AttributeError: x
>>> conn.root()['x'] = 1
>>> conn.root.x
1
>>> conn.root.y = 2
>>> sorted(conn.root().items())
[('x', 1), ('y', 2)]
>>> conn.root
<root: x y>
>>> del conn.root.x
>>> sorted(conn.root().items())
[('y', 2)]
>>> conn.root.rather_long_name = 1
>>> conn.root.rather_long_name2 = 1
>>> conn.root.rather_long_name4 = 1
>>> conn.root.rather_long_name5 = 1
>>> conn.root
<root: rather_long_name rather_long_name2 rather_long_name4 ...>
"""
class proper_ghost_initialization_with_empty__p_deactivate_class(Persistent):
def _p_deactivate(self):
pass
def doctest_proper_ghost_initialization_with_empty__p_deactivate():
"""
See https://bugs.launchpad.net/zodb/+bug/185066
>>> db = ZODB.tests.util.DB()
>>> conn = db.open()
>>> C = proper_ghost_initialization_with_empty__p_deactivate_class
>>> conn.root.x = x = C()
>>> conn.root.x.y = 1
>>> transaction.commit()
>>> conn2 = db.open()
>>> bool(conn2.root.x._p_changed)
False
>>> conn2.root.x.y
1
"""
def doctest_readCurrent():
r"""
The connection's readCurrent method is called to provide a higher
level of consistency in cases where an object is read to compute an
update to a separate object. When this is used, the
checkCurrentSerialInTransaction method on the storage is called in
2-phase commit.
To demonstrate this, we'll create a storage and give it a test
implementation of checkCurrentSerialInTransaction.
>>> import ZODB.MappingStorage
>>> store = ZODB.MappingStorage.MappingStorage()
>>> from ZODB.POSException import ReadConflictError
>>> bad = set()
>>> def checkCurrentSerialInTransaction(oid, serial, trans):
... six.print_('checkCurrentSerialInTransaction', repr(oid))
... if oid in bad:
... raise ReadConflictError(oid=oid)
>>> store.checkCurrentSerialInTransaction = checkCurrentSerialInTransaction
Now, we'll use the storage as usual. checkCurrentSerialInTransaction
won't normally be called:
>>> db = ZODB.DB(store)
>>> conn = db.open()
>>> conn.root.a = ZODB.tests.util.P('a')
>>> transaction.commit()
>>> conn.root.b = ZODB.tests.util.P('b')
>>> transaction.commit()
>>> conn.root.a._p_oid
b'\x00\x00\x00\x00\x00\x00\x00\x01'
>>> conn.root.b._p_oid
b'\x00\x00\x00\x00\x00\x00\x00\x02'
If we call readCurrent for an object and we modify another object,
then checkCurrentSerialInTransaction will be called for the object
readCurrent was called on.
>>> conn.readCurrent(conn.root.a)
>>> conn.root.b.x = 0
>>> transaction.commit()
checkCurrentSerialInTransaction '\x00\x00\x00\x00\x00\x00\x00\x01'
It doesn't matter how often we call readCurrent,
checkCurrentSerialInTransaction will be called only once:
>>> conn.readCurrent(conn.root.a)
>>> conn.readCurrent(conn.root.a)
>>> conn.readCurrent(conn.root.a)
>>> conn.readCurrent(conn.root.a)
>>> conn.root.b.x += 1
>>> transaction.commit()
checkCurrentSerialInTransaction '\x00\x00\x00\x00\x00\x00\x00\x01'
checkCurrentSerialInTransaction won't be called if another object
isn't modified:
>>> conn.readCurrent(conn.root.a)
>>> transaction.commit()
Or if the object it was called on is modified:
>>> conn.readCurrent(conn.root.a)
>>> conn.root.a.x = 0
>>> conn.root.b.x += 1
>>> transaction.commit()
If the storage raises a conflict error, it'll be propagated:
>>> _ = str(conn.root.a) # do read
>>> bad.add(conn.root.a._p_oid)
>>> conn.readCurrent(conn.root.a)
>>> conn.root.b.x += 1
>>> transaction.commit()
Traceback (most recent call last):
...
ReadConflictError: database read conflict error (oid 0x01)
>>> transaction.abort()
The conflict error will cause the affected object to be invalidated:
>>> conn.root.a._p_changed
The storage may raise it later:
>>> def checkCurrentSerialInTransaction(oid, serial, trans):
... if not trans == transaction.get(): print('oops')
... six.print_('checkCurrentSerialInTransaction', repr(oid))
... store.badness = ReadConflictError(oid=oid)
>>> def tpc_vote(t):
... if store.badness:
... badness = store.badness
... store.badness = None
... raise badness
>>> store.checkCurrentSerialInTransaction = checkCurrentSerialInTransaction
>>> store.badness = None
>>> store.tpc_vote = tpc_vote
It will still be propagated:
>>> _ = str(conn.root.a) # do read
>>> conn.readCurrent(conn.root.a)
>>> conn.root.b.x = +1
>>> transaction.commit()
Traceback (most recent call last):
...
ReadConflictError: database read conflict error (oid 0x01)
>>> transaction.abort()
The conflict error will cause the affected object to be invalidated:
>>> conn.root.a._p_changed
Read checks don't leak across transactions:
>>> conn.readCurrent(conn.root.a)
>>> transaction.commit()
>>> conn.root.b.x = +1
>>> transaction.commit()
Read checks to work across savepoints.
>>> conn.readCurrent(conn.root.a)
>>> conn.root.b.x = +1
>>> _ = transaction.savepoint()
>>> transaction.commit()
Traceback (most recent call last):
...
ReadConflictError: database read conflict error (oid 0x01)
>>> transaction.abort()
>>> conn.readCurrent(conn.root.a)
>>> _ = transaction.savepoint()
>>> conn.root.b.x = +1
>>> transaction.commit()
Traceback (most recent call last):
...
ReadConflictError: database read conflict error (oid 0x01)
>>> transaction.abort()
"""
def doctest_cache_management_of_subconnections():
"""Make that cache management works for subconnections.
When we use multi-databases, we open a connection in one database and
access connections to other databases through it. This test verifies
that cache management is applied to all of the connections.
Set up a multi-database:
>>> db1 = ZODB.DB(None)
>>> db2 = ZODB.DB(None, databases=db1.databases, database_name='2',
... cache_size=10)
>>> conn1 = db1.open()
>>> conn2 = conn1.get_connection('2')
Populate it with some data, more than will fit in the cache:
>>> for i in range(100):
... conn2.root()[i] = conn2.root().__class__()
Upon commit, the cache is reduced to the cache size:
>>> transaction.commit()
>>> conn2._cache.cache_non_ghost_count
10
Fill it back up:
>>> for i in range(100):
... _ = str(conn2.root()[i])
>>> conn2._cache.cache_non_ghost_count
101
Doing cache GC on the primary also does it on the secondary:
>>> conn1.cacheGC()
>>> conn2._cache.cache_non_ghost_count
10
Ditto for cache minimize:
>>> conn1.cacheMinimize()
>>> conn2._cache.cache_non_ghost_count
0
Fill it back up:
>>> for i in range(100):
... _ = str(conn2.root()[i])
>>> conn2._cache.cache_non_ghost_count
101
GC is done on reopen:
>>> conn1.close()
>>> db1.open() is conn1
True
>>> conn2 is conn1.get_connection('2')
True
>>> conn2._cache.cache_non_ghost_count
10
"""
class C_invalidations_of_new_objects_work_after_savepoint(Persistent):
def __init__(self):
self.settings = 1
def _p_invalidate(self):
print('INVALIDATE', self.settings)
Persistent._p_invalidate(self)
print(self.settings) # POSKeyError here
def doctest_abort_of_savepoint_creating_new_objects_w_exotic_invalidate_doesnt_break():
r"""
Before, the following would fail with a POSKeyError, which was
somewhat surprising, in a very edgy sort of way. :)
Really, when an object add is aborted, the object should be "removed" from
the db and its invalidation method shouldn't even be called:
>>> conn = ZODB.connection(None)
>>> conn.root.x = x = C_invalidations_of_new_objects_work_after_savepoint()
>>> _ = transaction.savepoint()
>>> x._p_oid
'\x00\x00\x00\x00\x00\x00\x00\x01'
>>> x._p_jar is conn
True
>>> transaction.abort()
After the abort, the oid and jar are None:
>>> x._p_oid
>>> x._p_jar
"""
class Clp9460655(Persistent):
def __init__(self, word, id):
super(Clp9460655, self).__init__()
self.id = id
self._word = word
def doctest_lp9460655():
r"""
>>> conn = ZODB.connection(None)
>>> root = conn.root()
>>> Word = Clp9460655
>>> from BTrees.OOBTree import OOBTree
>>> data = root['data'] = OOBTree()
>>> commonWords = []
>>> count = "0"
>>> for x in ('hello', 'world', 'how', 'are', 'you'):
... commonWords.append(Word(x, count))
... count = str(int(count) + 1)
>>> sv = transaction.savepoint()
>>> for word in commonWords:
... sv2 = transaction.savepoint()
... data[word.id] = word
>>> sv.rollback()
>>> print(commonWords[1].id) # raises POSKeyError
1
"""
def doctest_lp615758_transaction_abort_Incomplete_cleanup_for_new_objects():
r"""
As the following doctest demonstrates, "abort" forgets to
reset "_p_changed" for new (i.e. "added") objects.
>>> class P(Persistent): pass
...
>>> c = ZODB.connection(None)
>>> obj = P()
>>> c.add(obj)
>>> obj.x = 1
>>> obj._p_changed
True
>>> transaction.abort()
>>> obj._p_changed
False
>>> c.close()
"""
class Clp485456_setattr_in_getstate_doesnt_cause_multiple_stores(Persistent):
def __getstate__(self):
self.got = 1
return self.__dict__.copy()
def doctest_lp485456_setattr_in_setstate_doesnt_cause_multiple_stores():