rename all 'check_exist' related things to 'if_not_exists'

This commit is contained in:
mission.liao
2014-07-02 12:53:22 +08:00
parent bac0673eaf
commit b4f8e3ac8f
4 changed files with 56 additions and 56 deletions

View File

@@ -116,19 +116,19 @@ class TimestampDescriptor(object):
def __call__(self, *args, **kwargs):
raise NotImplementedError
class CheckExistDescriptor(object):
class IfNotExistsDescriptor(object):
"""
return a query set descriptor with a check-exist flag specified
return a query set descriptor with a if_not_exists flag specified
"""
def __get__(self, instance, model):
if instance:
# instance method
def checkexist_setter(ce):
instance._check_exist = ce
def ifnotexists_setter(ife):
instance._if_not_exists = ife
return instance
return checkexist_setter
return ifnotexists_setter
return model.objects.check_exist
return model.objects.if_not_exists
def __call__(self, *args, **kwargs):
raise NotImplementedError
@@ -243,7 +243,7 @@ class BaseModel(object):
# custom timestamps, see USING TIMESTAMP X
timestamp = TimestampDescriptor()
check_exist = CheckExistDescriptor()
if_not_exists = IfNotExistsDescriptor()
# _len is lazily created by __len__
@@ -295,7 +295,7 @@ class BaseModel(object):
_timestamp = None # optional timestamp to include with the operation (USING TIMESTAMP)
_check_exist = False # optional check_exist flag to check existence before insertion
_if_not_exists = False # optional if_not_exists flag to check existence before insertion
def __init__(self, **values):
self._values = {}
@@ -550,7 +550,7 @@ class BaseModel(object):
ttl=self._ttl,
timestamp=self._timestamp,
consistency=self.__consistency__,
check_exist=self._check_exist).save()
if_not_exists=self._if_not_exists).save()
#reset the value managers
for v in self._values.values():

View File

@@ -220,7 +220,7 @@ class AbstractQuerySet(object):
self._ttl = getattr(model, '__default_ttl__', None)
self._consistency = None
self._timestamp = None
self._check_exist = False
self._if_not_exists = False
@property
def column_family_name(self):
@@ -570,7 +570,7 @@ class AbstractQuerySet(object):
def create(self, **kwargs):
return self.model(**kwargs).batch(self._batch).ttl(self._ttl).\
consistency(self._consistency).check_exist(self._check_exist).\
consistency(self._consistency).if_not_exists(self._if_not_exists).\
timestamp(self._timestamp).save()
def delete(self):
@@ -709,9 +709,9 @@ class ModelQuerySet(AbstractQuerySet):
clone._timestamp = timestamp
return clone
def check_exist(self, check_exist):
def if_not_exists(self, if_not_exists):
clone = copy.deepcopy(self)
clone._check_exist = check_exist
clone._if_not_exists = if_not_exists
return clone
def update(self, **values):
@@ -773,9 +773,9 @@ class DMLQuery(object):
_ttl = None
_consistency = None
_timestamp = None
_check_exist = False
_if_not_exists = False
def __init__(self, model, instance=None, batch=None, ttl=None, consistency=None, timestamp=None, check_exist=False):
def __init__(self, model, instance=None, batch=None, ttl=None, consistency=None, timestamp=None, if_not_exists=False):
self.model = model
self.column_family_name = self.model.column_family_name()
self.instance = instance
@@ -783,7 +783,7 @@ class DMLQuery(object):
self._ttl = ttl
self._consistency = consistency
self._timestamp = timestamp
self._check_exist = check_exist
self._if_not_exists = if_not_exists
def _execute(self, q):
if self._batch:
@@ -898,7 +898,7 @@ class DMLQuery(object):
if self.instance._has_counter or self.instance._can_update():
return self.update()
else:
insert = InsertStatement(self.column_family_name, ttl=self._ttl, timestamp=self._timestamp, check_exist=self._check_exist)
insert = InsertStatement(self.column_family_name, ttl=self._ttl, timestamp=self._timestamp, if_not_exists=self._if_not_exists)
for name, col in self.instance._columns.items():
val = getattr(self.instance, name, None)
if col._val_is_null(val):

View File

@@ -626,7 +626,7 @@ class InsertStatement(AssignmentStatement):
where=None,
ttl=None,
timestamp=None,
check_exist=False):
if_not_exists=False):
super(InsertStatement, self).__init__(
table,
assignments=assignments,
@@ -635,7 +635,7 @@ class InsertStatement(AssignmentStatement):
ttl=ttl,
timestamp=timestamp)
self.check_exist = check_exist
self.if_not_exists = if_not_exists
def add_where_clause(self, clause):
raise StatementException("Cannot add where clauses to insert statements")
@@ -651,7 +651,7 @@ class InsertStatement(AssignmentStatement):
qs += ['VALUES']
qs += ["({})".format(', '.join(['%({})s'.format(v) for v in values]))]
if self.check_exist:
if self.if_not_exists:
qs += ["IF NOT EXISTS"]
if self.ttl:

View File

@@ -7,60 +7,60 @@ import mock
from cqlengine.connection import get_session
class TestChechExistModel(Model):
class TestIfNotExistsModel(Model):
__keyspace__ = 'cqlengine_test_checkexist'
__keyspace__ = 'cqlengine_test_ifnotexists'
id = columns.UUID(primary_key=True, default=lambda:uuid4())
count = columns.Integer()
text = columns.Text(required=False)
class BaseCheckExistTest(BaseCassEngTestCase):
class BaseIfNotExistsTest(BaseCassEngTestCase):
@classmethod
def setUpClass(cls):
super(BaseCheckExistTest, cls).setUpClass()
super(BaseIfNotExistsTest, cls).setUpClass()
"""
when receiving an insert statement with 'if not exist', cassandra would
perform a read with QUORUM level. Unittest would be failed if replica_factor
is 3 and one node only. Therefore I have create a new keyspace with
replica_factor:1.
"""
create_keyspace(TestChechExistModel.__keyspace__, replication_factor=1)
sync_table(TestChechExistModel)
create_keyspace(TestIfNotExistsModel.__keyspace__, replication_factor=1)
sync_table(TestIfNotExistsModel)
@classmethod
def tearDownClass(cls):
super(BaseCassEngTestCase, cls).tearDownClass()
drop_table(TestChechExistModel)
delete_keyspace(TestChechExistModel.__keyspace__)
drop_table(TestIfNotExistsModel)
delete_keyspace(TestIfNotExistsModel.__keyspace__)
class CheckExistInsertTests(BaseCheckExistTest):
class IfNotExistsInsertTests(BaseIfNotExistsTest):
def test_insert_check_exist_success(self):
""" tests that insertion with check_exist work as expected """
def test_insert_if_not_exists_success(self):
""" tests that insertion with if_not_exists work as expected """
id = uuid4()
TestChechExistModel.create(id=id, count=8, text='123456789')
TestChechExistModel.check_exist(True).create(id=id, count=9, text='111111111111')
TestIfNotExistsModel.create(id=id, count=8, text='123456789')
TestIfNotExistsModel.if_not_exists(True).create(id=id, count=9, text='111111111111')
q = TestChechExistModel.objects(id=id)
q = TestIfNotExistsModel.objects(id=id)
self.assertEqual(len(q), 1)
tm = q.first()
self.assertEquals(tm.count, 8)
self.assertEquals(tm.text, '123456789')
def test_insert_check_exist_failure(self):
""" tests that insertion with check_exist failure """
def test_insert_if_not_exists_failure(self):
""" tests that insertion with if_not_exists failure """
id = uuid4()
TestChechExistModel.create(id=id, count=8, text='123456789')
TestChechExistModel.check_exist(False).create(id=id, count=9, text='111111111111')
TestIfNotExistsModel.create(id=id, count=8, text='123456789')
TestIfNotExistsModel.if_not_exists(False).create(id=id, count=9, text='111111111111')
q = TestChechExistModel.objects(id=id)
q = TestIfNotExistsModel.objects(id=id)
self.assertEquals(len(q), 1)
tm = q.first()
@@ -68,57 +68,57 @@ class CheckExistInsertTests(BaseCheckExistTest):
self.assertEquals(tm.text, '111111111111')
class CheckExistModelTest(BaseCheckExistTest):
class IfNotExistsModelTest(BaseIfNotExistsTest):
def test_check_exist_included_on_create(self):
""" tests that check_exist on models works as expected """
def test_if_not_exists_included_on_create(self):
""" tests that if_not_exists on models works as expected """
session = get_session()
with mock.patch.object(session, 'execute') as m:
TestChechExistModel.check_exist(True).create(count=8)
TestIfNotExistsModel.if_not_exists(True).create(count=8)
query = m.call_args[0][0].query_string
self.assertIn("IF NOT EXISTS", query)
def test_check_exist_included_on_save(self):
def test_if_not_exists_included_on_save(self):
session = get_session()
with mock.patch.object(session, 'execute') as m:
tm = TestChechExistModel(count=8)
tm.check_exist(True).save()
tm = TestIfNotExistsModel(count=8)
tm.if_not_exists(True).save()
query = m.call_args[0][0].query_string
self.assertIn("IF NOT EXISTS", query)
def test_queryset_is_returned_on_class(self):
""" ensure we get a queryset description back """
qs = TestChechExistModel.check_exist(True)
self.assertTrue(isinstance(qs, TestChechExistModel.__queryset__), type(qs))
qs = TestIfNotExistsModel.if_not_exists(True)
self.assertTrue(isinstance(qs, TestIfNotExistsModel.__queryset__), type(qs))
class CheckExistInstanceTest(BaseCheckExistTest):
class IfNotExistsInstanceTest(BaseIfNotExistsTest):
def test_instance_is_returned(self):
"""
ensures that we properly handle the instance.check_exist(True).save()
ensures that we properly handle the instance.if_not_exists(True).save()
scenario
"""
o = TestChechExistModel.create(text="whatever")
o = TestIfNotExistsModel.create(text="whatever")
o.text = "new stuff"
o = o.check_exist(True)
self.assertEqual(True, o._check_exist)
o = o.if_not_exists(True)
self.assertEqual(True, o._if_not_exists)
def test_check_exist_is_not_include_with_query_on_update(self):
def test_if_not_exists_is_not_include_with_query_on_update(self):
"""
make sure we don't put 'IF NOT EXIST' in update statements
"""
session = get_session()
o = TestChechExistModel.create(text="whatever")
o = TestIfNotExistsModel.create(text="whatever")
o.text = "new stuff"
o = o.check_exist(True)
o = o.if_not_exists(True)
with mock.patch.object(session, 'execute') as m:
o.save()