/home/phd/current/SQLObject/SQLObject/sqlobject/constraints.py

`0001"""
0002Constraints
0003"""
0004
0005class BadValue(ValueError):
0006
0007 def __init__(self, desc, obj, col, value, *args):
0008 self.desc = desc
0009 self.col = col
0010
0011 # I want these objects to be garbage-collectable, so
0012 # I just keep their repr:
0013 self.obj = repr(obj)
0014 self.value = repr(value)
0015 fullDesc = "%s.%s %s (you gave: %s)" % (obj, col.name, desc, value)
0017 ValueError.__init__(self, fullDesc, *args)
0018
0019def isString(obj, col, value):
0020 if not isinstance(value, str):
0021 raise BadValue("only allows strings", obj, col, value)
0022
0023def notNull(obj, col, value):
0024 if value is None:
0025 raise BadValue("is defined NOT NULL", obj, col, value)
0026
0027def isInt(obj, col, value):
0028 if not isinstance(value, (int, long)):
0029 raise BadValue("only allows integers", obj, col, value)
0030
0031def isFloat(obj, col, value):
0032 if not isinstance(value, (int, long, float)):
0033 raise BadValue("only allows floating point numbers", obj, col, value)
0034
0035def isBool(obj, col, value):
0036 if not isinstance(value, bool):
0037 raise BadValue("only allows booleans", obj, col, value)
0038
0039class InList:
0040
0041 def __init__(self, l):
0042 self.list = l
0043
0044 def __call__(self, obj, col, value):
0045 if value not in self.list:
0046 raise BadValue("accepts only values in %s" % repr(self.list),
0047 obj, col, value)
0048
0049class MaxLength:
0050
0051 def __init__(self, length):
0052 self.length = length
0053
0054 def __call__(self, obj, col, value):
0055 try:
0056 length = len(value)
0057 except TypeError:
0058 raise BadValue("object does not have a length",
0059 obj, col, value)
0060 if length > self.length:
0061 raise BadValue("must be shorter in length than %s"
0062 % self.length,
0063 obj, col, value)`