事务如何影响NDB中下一个非祖先查询的读取一致性

时间:2012-03-23 23:10:38

标签: google-app-engine

apply phase of save may fail和/或仍在异步完成,然后才能进行非强一致性读取 - 非祖先查询。

基于local testing文章,我写了一个应该模拟不一致读取的测试:

import dev_appserver

dev_appserver.fix_sys_path()

import unittest
from google.appengine.ext import ndb
from google.appengine.ext import testbed
from google.appengine.datastore import datastore_stub_util

class SomeModel(ndb.Model):
    pass

class SingleEntityConsistency(unittest.TestCase):
    def setUp(self):
        # Setup AppEngine env
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.policy = datastore_stub_util.PseudoRandomHRConsistencyPolicy(probability=0)
        self.testbed.init_datastore_v3_stub(consistency_policy=self.policy)
        self.testbed.init_memcache_stub()
        # A test key
        self.key = ndb.Key('SomeModel', 'test')

    def tearDown(self):
        self.testbed.deactivate()

    def test_tx_get_or_insert(self):
        p = SomeModel.get_or_insert('test')
        self.assertEqual(0, SomeModel.query().count(1), "Shouldn't be applied yet")
        self.assertEqual(1, SomeModel.query(ancestor=self.key).count(1), "Ancestor query read should be consistent")

    def test_no_tx_insert(self):
        p = SomeModel(id='test')
        p.put()
        self.assertEqual(0, SomeModel.query().count(2), "Shouldn't be applied yet")
        self.assertEqual(1, SomeModel.query(ancestor=self.key).count(1), "Ancestor query read should be consistent")

    def test_with_ancestor(self):
        p = SomeModel(id='test')
        p.put()
        self.assertEqual(p, SomeModel.query(ancestor=self.key).get())

    def test_key(self):
        p = SomeModel(id='test')
        p.put()
        self.assertEqual(p, self.key.get())

if __name__ == '__main__':
    unittest.main()

实际问题......

  1. 在开头描述的事务更改行为中包装put()吗?我是否还需要一个强一致的查询来确保我读到的是在txn中写的? (测试表明,我仍然需要强烈一致的查询)

  2. key.get()被认为是强烈一致的吗? (测试表明,它是)

  3. 更新

    我已经更新了Guido提到的测试代码,现在所有测试通过:

    self.testbed.init_datastore_v3_stub(consistency_policy=self.policy)
    

1 个答案:

答案 0 :(得分:4)

我相信你必须采取措施来激活政策。这可以解释测试失败。此外,我认为只有查询受到影响,单独的看跌实际上是一个交易。最后要注意NDB的缓存。