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