from google.appengine.ext import db
import md5
import base64
class UniqueConstraint(db.Model):
@classmethod
def check(cls, model, **values):
# Build a list of key names to test.
key_names = []
concat = ""
for key in values:
pair_str = '%s:%s' % (key, values[key])
key_names.append(pair_str)
concat += pair_str
# "sharded" version now added - it creates a hash for each one of the
# possible key combinations
concat_hash = base64.b64encode(md5.new(concat).digest())
# Create a pseudo-key for use as an entity group.
parent = db.Key.from_path(model.kind(), 'unique-values' + concat_hash[0:2])
def txn():
result = cls.get_by_key_name(key_names, parent)
for test in result:
if test: return False
for key_name in key_names:
uc = cls(key_name=key_name, parent=parent)
uc.put()
return True
return db.run_in_transaction(txn)