[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
r5165 - trunk/gnue-common/src/schema
From: |
johannes |
Subject: |
r5165 - trunk/gnue-common/src/schema |
Date: |
Thu, 26 Feb 2004 10:55:09 -0600 (CST) |
Author: johannes
Date: 2004-02-26 10:55:08 -0600 (Thu, 26 Feb 2004)
New Revision: 5165
Added:
trunk/gnue-common/src/schema/GSData.py
Log:
Forgotten to add the new file :)
Added: trunk/gnue-common/src/schema/GSData.py
===================================================================
--- trunk/gnue-common/src/schema/GSData.py 2004-02-26 16:23:23 UTC (rev
5164)
+++ trunk/gnue-common/src/schema/GSData.py 2004-02-26 16:55:08 UTC (rev
5165)
@@ -0,0 +1,341 @@
+#
+# This file is part of GNU Enterprise.
+#
+# GNU Enterprise is free software; you can redistribute it
+# and/or modify it under the terms of the GNU General Public
+# License as published by the Free Software Foundation; either
+# version 2, or (at your option) any later version.
+#
+# GNU Enterprise is distributed in the hope that it will be
+# useful, but WITHOUT ANY WARRANTY; without even the implied
+# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+# PURPOSE. See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public
+# License along with program; see the file COPYING. If not,
+# write to the Free Software Foundation, Inc., 59 Temple Place
+# - Suite 330, Boston, MA 02111-1307, USA.
+#
+# Copyright 2001-2004 Free Software Foundation
+#
+# $Id$
+
+import re
+import mx.DateTime.ISO
+from string import join
+
+
+# =============================================================================
+# Constants
+# =============================================================================
+
+_LENGTH_SCALE = re.compile ('^\w+\s*\((\d+)[\.]{0,1}(\d*)\)\s*')
+
+
+# =============================================================================
+# Base Exception class
+# =============================================================================
+
+class EGSData (Exception):
+ """
+ This class is the ancestor of all exceptions used by this module.
+ """
+ def __init__ (self, text):
+ self._text = text
+ Exception.__init__ (self, text)
+
+
+ # ---------------------------------------------------------------------------
+ # Object representation
+ # ---------------------------------------------------------------------------
+
+ def __repr__ (self):
+ return self._text
+
+
+# =============================================================================
+# Invalid or unknown datatype
+# =============================================================================
+
+class EInvalidType (EGSData):
+ """
+ This exception is raised, if a invalid or unknown datatype was found.
+ """
+ def __init__ (self, gsValue, dataType):
+ fName = ""
+ if hasattr (gsValue, "field"):
+ fName = "%s: " % gsValue.field
+
+ msg = _("%sInvalid datatype '%s'.") % (fName, dataType)
+ EGSData.__init__ (self, msg)
+
+
+# =============================================================================
+# Invalid or unknown value
+# =============================================================================
+
+class EInvalidValue (EGSData):
+ """
+ This exception is raised, if a native object has an invalid value/type
+ """
+ def __init__ (self, value, text):
+ EGSData.__init__ (self, "'%s' %s" % (str (value), text))
+
+
+
+# =============================================================================
+# Fieldvalue out of range
+# =============================================================================
+
+class EOutOfRange (EGSData):
+ """
+ This exception is raised if a fieldvalue is out of range, e.g. a string
+ exceeds it's length or a number exceeds it's numeric bounds.
+ """
+ def __init__ (self, gsValue, fieldValue, length, scale = None):
+ fName = ""
+ if hasattr (gsValue, "field"):
+ fName = "%s: " % gsValue.field
+
+ if scale is not None:
+ rDef = "%d.%d" % (length, scale)
+ else:
+ rDef = "%d" % length
+
+ msg = _("%sValue '%s' out of Range (%s)") % (fName, fieldValue, rDef)
+
+ EGSData.__init__ (self, msg)
+
+
+# =============================================================================
+# EInvalidFormat
+# =============================================================================
+
+class EInvalidFormat (EGSData):
+ """
+ This exception is the base class of format errors.
+ """
+ def __init__ (self, gsValue, fieldValue, fmtString):
+ fName = ""
+ if hasattr (gsValue, "field"):
+ fName = "%s: " % gsValue.field
+
+ msg = _("%sValue '%s' %s") % (fName, fieldValue, fmtString)
+ EGSData.__init__ (self, msg)
+
+
+# =============================================================================
+# Field value is not a number
+# =============================================================================
+
+class EInvalidNumber (EInvalidFormat):
+ """
+ This exception is raised if a string cannot be converted to a number.
+ """
+ def __init__ (self, gsValue, value, length, scale):
+ fmt = _("is not a number (%d.%d)") % (length, scale)
+ EInvalidFormat.__init__ (self, gsValue, value, fmt)
+
+
+# =============================================================================
+# Field value is not a valid date
+# =============================================================================
+
+class EInvalidDate (EInvalidFormat):
+ """
+ Exception class for invalid formatted dates
+ """
+ def __init__ (self, gsValue, fieldValue):
+ fmt = _("is not a date (YYYY-MM-DD)")
+ EInvalidFormat.__init__ (self, gsValue, fieldValue, fmt)
+
+
+# =============================================================================
+# Field value is not a valid time
+# =============================================================================
+
+class EInvalidTime (EInvalidFormat):
+ """
+ Exception class for invalid formatted times
+ """
+ def __init__ (self, gsValue, fieldValue):
+ fmt = _("is not a time (HH:MM:SS.ss")
+ EInvalidFormat.__init__ (self, gsValue, fieldValue, fmt)
+
+
+# =============================================================================
+# Field value is not a valid datetime
+# =============================================================================
+
+class EInvalidDateTime (EInvalidFormat):
+ """
+ Exception class for invalid formatted datetimes
+ """
+ def __init__ (self, gsValue, fieldValue):
+ fmt = _("is not a datetime (YYYY-MM-DD HH:MM:SS.ss)")
+ EInvalidFormat.__init__ (self, gsValue, fieldValue, fmt)
+
+
+
+
+# -----------------------------------------------------------------------------
+# Convert a value from a GSValue instance to a native python object
+# -----------------------------------------------------------------------------
+
+def valueToNative (gsValue):
+ """
+ This function takes a GSValue instance and creates a native python object
+ representing it's value according to it's type. If the value is an empty
+ string 'None' is returned. As a side effect, the property 'dataType' of the
+ GSValue instance will be updated to the type used.
+ """
+ fieldValue = unquoteString (gsValue.getChildrenAsContent ())
+
+ # if no gsValue has no value we return None
+ if len (fieldValue) == 0:
+ gsValue.dataType = None
+ return None
+
+ # if gsValue has no type information we assume it to be string
+ if not hasattr (gsValue, "type"):
+ gsValue.dataType = "string"
+ return fieldValue
+
+ else:
+ # extract the datatype first
+ ftm = re.compile ('^(\w+)').match (gsValue.type.lower ())
+ if ftm is None:
+ raise EInvalidType (gsValue, gsValue.type)
+
+ fieldType = ftm.groups () [0]
+
+ # default type is text (if no explicit type attribute is given)
+ if fieldType == "text":
+ fieldType = "string"
+
+ if fieldType == "timestamp":
+ fieldType = "datetime"
+
+ gsValue.dataType = fieldType
+
+ # a string type must stay in it's bounds (if known)
+ if fieldType == "string":
+
+ # if the fieldtype contains a length, we've to check it
+ if _LENGTH_SCALE.match (gsValue.type) is not None:
+ flen = int (_LENGTH_SCALE.match (gsValue.type).groups () [0])
+
+ if len (fieldValue) > flen:
+ raise EOutOfRange (gsValue, fieldValue, flen)
+
+ return fieldValue
+
+
+ # booleans must be 'TRUE' or 'FALSE', otherwise they're "None"
+ elif fieldType == "boolean":
+ bool = fieldValue.upper ().strip ()
+
+ if bool in ["TRUE", "FALSE"]:
+ return bool == "TRUE"
+ else:
+ return None
+
+
+ # create a number according to length and scale
+ elif fieldType == "number":
+ value = fieldValue.strip ()
+
+ if _LENGTH_SCALE.match (gsValue.type) is not None:
+ fmatch = _LENGTH_SCALE.match (gsValue.type)
+ (fml, fms) = fmatch.groups ()
+
+ flength = int (fml)
+ fscale = 0
+ if len (fms):
+ fscale = int (fms)
+
+ vmatch = re.compile ('^([+-]{0,1})(\d+)[\.]{0,1}(\d*)$').match (value)
+ if vmatch is None:
+ raise EInvalidNumber (gsValue, value, flength, fscale)
+
+ sign = vmatch.groups () [0]
+ pre = vmatch.groups () [1]
+ frac = vmatch.groups () [2]
+
+ if len (pre) > (flength-fscale) or len (frac) > fscale:
+ raise EOutOfRange (gsValue, value, flength, fscale)
+
+ if len (frac):
+ return float ("%s%s.%s" % (sign, pre, frac))
+
+ else:
+ return int ("%s%s" % (sign, pre))
+
+ # we know nothing about precision
+ else:
+ if "." in value:
+ return float (value)
+ else:
+ return int (value)
+
+ # Dates must conform with the ISO spec: YYYY-MM-DD
+ elif fieldType == "date":
+ try:
+ return mx.DateTime.ISO.ParseDate (fieldValue.strip ())
+
+ except ValueError:
+ raise EInvalidDate (gsValue, fieldValue)
+
+ except:
+ raise
+
+
+ # Times must conform with the ISO spec: HH:[MM[:SS[.ss]]]
+ elif fieldType == "time":
+ try:
+ return mx.DateTime.ISO.ParseTime (fieldValue.strip ())
+
+ except ValueError:
+ raise EInvalidTime (gsValue, fieldValue)
+
+ except:
+ raise
+
+
+ # DateTime values must conform with the ISO spec: YYYY-MM-DD HH:MM:SS.ss
+ elif fieldType == "datetime":
+ try:
+ return mx.DateTime.ISO.ParseDateTime (fieldValue.strip ())
+
+ except ValueError:
+ raise EInvalidDateTime (gsValue, fieldValue)
+
+ except:
+ raise
+
+
+ # unhandled types
+ else:
+ raise EInvalidType (gsValue, gsValue.type)
+
+
+
+
+
+
+# -----------------------------------------------------------------------------
+# Unquote a string
+# -----------------------------------------------------------------------------
+
+def unquoteString (aString):
+ """
+ This function strips away leading and trailling quotes (single or double)
+ from a string.
+ """
+ if len (aString) and aString [0] in ['"', "'"]:
+ aString = aString [1:]
+
+ if len (aString) and aString [-1] in ['"', "'"]:
+ aString = aString [:-1]
+
+ return aString
Property changes on: trunk/gnue-common/src/schema/GSData.py
___________________________________________________________________
Name: svn:keywords
+ Id
[Prev in Thread] |
Current Thread |
[Next in Thread] |
- r5165 - trunk/gnue-common/src/schema,
johannes <=