Package dbf :: Module _io
[hide private]

Source Code for Module dbf._io

  1  """Routines for saving, retrieving, and creating fields""" 
  2   
  3  import struct 
  4  from decimal import Decimal 
  5  from dbf.exceptions import DbfError, DataOverflow 
  6  from dbf.dates import Date, DateTime, Time 
  7  from math import floor 
  8   
  9   
 10  # Constants 
 11  VFPTIME = 1721425 
 12   
13 -def packShortInt(value, bigendian=False):
14 "Returns a two-bye integer from the value, or raises DbfError" 15 # 256 / 65,536 16 if value > 65535: 17 raise DateOverflow("Maximum Integer size exceeded. Possible: 65535. Attempted: %d" % value) 18 if bigendian: 19 return struct.pack('>H', value) 20 else: 21 return struct.pack('<H', value)
22 -def packLongInt(value, bigendian=False):
23 "Returns a four-bye integer from the value, or raises DbfError" 24 # 256 / 65,536 / 16,777,216 25 if value > 4294967295: 26 raise DateOverflow("Maximum Integer size exceeded. Possible: 4294967295. Attempted: %d" % value) 27 if bigendian: 28 return struct.pack('>L', value) 29 else: 30 return struct.pack('<L', value)
31 -def packDate(date):
32 "Returns a group of three bytes, in integer form, of the date" 33 return "%c%c%c" % (date.year-1900, date.month, date.day)
34 -def packStr(string):
35 "Returns an 11 byte, upper-cased, null padded string suitable for field names; raises DbfError if the string is bigger than 10 bytes" 36 if len(string) > 10: 37 raise DbfError("Maximum string size is ten characters -- %s has %d characters" % (string, len(string))) 38 return struct.pack('11s', string.upper())
39 -def unpackShortInt(bytes, bigendian=False):
40 "Returns the value in the two-byte integer passed in" 41 if bigendian: 42 return struct.unpack('>H', bytes)[0] 43 else: 44 return struct.unpack('<H', bytes)[0]
45 -def unpackLongInt(bytes, bigendian=False):
46 "Returns the value in the four-byte integer passed in" 47 if bigendian: 48 return int(struct.unpack('>L', bytes)[0]) 49 else: 50 return int(struct.unpack('<L', bytes)[0])
51 -def unpackDate(bytestr):
52 "Returns a Date() of the packed three-byte date passed in" 53 year, month, day = struct.unpack('<BBB', bytestr) 54 year += 1900 55 return Date(year, month, day)
56 -def unpackStr(chars):
57 "Returns a normal, lower-cased string from a null-padded byte string" 58 return struct.unpack('%ds' % len(chars), chars)[0].replace('\x00','').lower()
59 -def convertToBool(value):
60 """Returns boolean true or false; normal rules apply to non-string values; string values 61 must be 'y','t', 'yes', or 'true' (case insensitive) to be True""" 62 if type(value) == str: 63 return bool(value.lower() in ['t', 'y', 'true', 'yes']) 64 else: 65 return bool(value)
66 -def unsupportedType(something, field, memo=None, typ=str):
67 "called if a data type is not supported for that style of table" 68 raise DbfError('field type is not supported.')
69 -def retrieveCharacter(bytes, fielddef={}, memo=None, typ=str):
70 "Returns the string in bytes with trailing white space removed" 71 return typ(bytes.tostring().rstrip())
72 -def updateCharacter(string, fielddef, memo=None):
73 "returns the string, truncating if string is longer than it's field" 74 string = str(string) 75 return string.rstrip()
76 -def retrieveCurrency(bytes, fielddef={}, memo=None, typ=Decimal):
77 value = struct.unpack('<q', bytes)[0] 78 return typ("%de-4" % value)
79 -def updateCurrency(value, fielddef={}, memo=None):
80 currency = int(value * 10000) 81 if not -9223372036854775808 < currency < 9223372036854775808: 82 raise DataOverflow("value %s is out of bounds" % value) 83 return struct.pack('<q', currency)
84 -def retrieveDate(bytes, fielddef={}, memo=None):
85 "Returns the ascii coded date as a Date object" 86 return Date.fromymd(bytes.tostring())
87 -def updateDate(moment, fielddef={}, memo=None):
88 "returns the Date or datetime.date object ascii-encoded (yyyymmdd)" 89 if moment: 90 return "%04d%02d%02d" % moment.timetuple()[:3] 91 return ' '
92 -def retrieveDouble(bytes, fielddef={}, memo=None, typ=float):
93 return float(struct.unpack('<d', bytes)[0])
94 -def updateDouble(value, fielddef={}, memo=None):
95 return struct.pack('<d', float(value))
96 -def retrieveInteger(bytes, fielddef={}, memo=None, typ=int):
97 "Returns the binary number stored in bytes in little-endian format" 98 return typ(struct.unpack('<i', bytes)[0])
99 -def updateInteger(value, fielddef={}, memo=None):
100 "returns value in little-endian binary format" 101 try: 102 value = int(value) 103 except Exception: 104 raise DbfError("incompatible type: %s(%s)" % (type(value), value)) 105 if not -2147483648 < value < 2147483647: 106 raise DataOverflow("Integer size exceeded. Possible: -2,147,483,648..+2,147,483,647. Attempted: %d" % value) 107 return struct.pack('<i', int(value))
108 -def retrieveLogical(bytes, fielddef={}, memo=None):
109 "Returns True if bytes is 't', 'T', 'y', or 'Y', None if '?', and False otherwise" 110 bytes = bytes.tostring() 111 if bytes == '?': 112 return None 113 return bytes in ['t','T','y','Y']
114 -def updateLogical(logical, fielddef={}, memo=None):
115 "Returs 'T' if logical is True, 'F' otherwise" 116 if type(logical) != bool: 117 logical = convertToBool(logical) 118 if type(logical) <> bool: 119 raise DbfError('Value %s is not logical.' % logical) 120 return logical and 'T' or 'F'
121 -def retrieveMemo(bytes, fielddef, memo):
122 "Returns the block of data from a memo file" 123 stringval = bytes.tostring() 124 if stringval.strip(): 125 block = int(stringval.strip()) 126 else: 127 block = 0 128 return memo.get_memo(block, fielddef)
129 -def updateMemo(string, fielddef, memo):
130 "Writes string as a memo, returns the block number it was saved into" 131 block = memo.put_memo(string) 132 if block == 0: 133 block = '' 134 return "%*s" % (fielddef['length'], block)
135 -def retrieveNumeric(bytes, fielddef, memo=None, typ='default'):
136 "Returns the number stored in bytes as integer if field spec for decimals is 0, float otherwise" 137 string = bytes.tostring() 138 if string[0:1] == '*': # value too big to store (Visual FoxPro idiocy) 139 return None 140 if not string.strip(): 141 string = '0' 142 if typ == 'default': 143 if fielddef['decimals'] == 0: 144 return int(string) 145 else: 146 return float(string) 147 else: 148 return typ(string)
149 -def updateNumeric(value, fielddef, memo=None):
150 "returns value as ascii representation, rounding decimal portion as necessary" 151 try: 152 value = float(value) 153 except Exception: 154 raise DbfError("incompatible type: %s(%s)" % (type(value), value)) 155 decimalsize = fielddef['decimals'] 156 if decimalsize: 157 decimalsize += 1 158 maxintegersize = fielddef['length']-decimalsize 159 integersize = len("%.0f" % floor(value)) 160 if integersize > maxintegersize: 161 raise DataOverflow('Integer portion too big') 162 return "%*.*f" % (fielddef['length'], fielddef['decimals'], value)
163 -def retrieveVfpDateTime(bytes, fielddef={}, memo=None):
164 """returns the date/time stored in bytes; dates <= 01/01/1981 00:00:00 165 may not be accurate; BC dates are nulled.""" 166 # two four-byte integers store the date and time. 167 # millesecords are discarded from time 168 time = retrieveInteger(bytes[4:]) 169 microseconds = (time % 1000) * 1000 170 time = time // 1000 # int(round(time, -3)) // 1000 discard milliseconds 171 hours = time // 3600 172 mins = time % 3600 // 60 173 secs = time % 3600 % 60 174 time = Time(hours, mins, secs, microseconds) 175 possible = retrieveInteger(bytes[:4]) 176 possible -= VFPTIME 177 possible = max(0, possible) 178 date = Date.fromordinal(possible) 179 return DateTime.combine(date, time)
180 -def updateVfpDateTime(moment, fielddef={}, memo=None):
181 """sets the date/time stored in moment 182 moment must have fields year, month, day, hour, minute, second, microsecond""" 183 bytes = [0] * 8 184 hour = moment.hour 185 minute = moment.minute 186 second = moment.second 187 millisecond = moment.microsecond // 1000 # convert from millionths to thousandths 188 time = ((hour * 3600) + (minute * 60) + second) * 1000 + millisecond 189 bytes[4:] = updateInteger(time) 190 bytes[:4] = updateInteger(moment.toordinal() + VFPTIME) 191 return ''.join(bytes)
192 -def retrieveVfpMemo(bytes, fielddef, memo):
193 "Returns the block of data from a memo file" 194 block = struct.unpack('<i', bytes)[0] 195 return memo.get_memo(block, fielddef)
196 -def updateVfpMemo(string, fielddef, memo):
197 "Writes string as a memo, returns the block number it was saved into" 198 block = memo.put_memo(string) 199 return struct.pack('<i', block)
200 -def addCharacter(format):
201 if format[1] != '(' or format[-1] != ')': 202 raise DbfError("Format for Character field creation is C(n), not %s" % format) 203 length = int(format[2:-1]) 204 if not 0 < length < 255: 205 raise ValueError 206 decimals = 0 207 return length, decimals
208 -def addDate(format):
209 length = 8 210 decimals = 0 211 return length, decimals
212 -def addLogical(format):
213 length = 1 214 decimals = 0 215 return length, decimals
216 -def addMemo(format):
217 length = 10 218 decimals = 0 219 return length, decimals
220 -def addNumeric(format):
221 if format[1] != '(' or format[-1] != ')': 222 raise DbfError("Format for Numeric field creation is N(n,n), not %s" % format) 223 length, decimals = format[2:-1].split(',') 224 length = int(length) 225 decimals = int(decimals) 226 if not 0 < length < 18: 227 raise ValueError 228 if decimals and not 0 < decimals <= length - 2: 229 raise ValueError 230 return length, decimals
231 -def addVfpCurrency(format):
232 length = 8 233 decimals = 0 234 return length, decimals
235 -def addVfpDateTime(format):
236 length = 8 237 decimals = 8 238 return length, decimals
239 -def addVfpDouble(format):
240 length = 8 241 decimals = 0 242 return length, decimals
243 -def addVfpInteger(format):
244 length = 4 245 decimals = 0 246 return length, decimals
247 -def addVfpMemo(format):
248 length = 4 249 decimals = 0 250 return length, decimals
251 -def addVfpNumeric(format):
252 if format[1] != '(' or format[-1] != ')': 253 raise DbfError("Format for Numeric field creation is N(n,n), not %s" % format) 254 length, decimals = format[2:-1].split(',') 255 length = int(length) 256 decimals = int(decimals) 257 if not 0 < length < 21: 258 raise ValueError 259 if decimals and not 0 < decimals <= length - 2: 260 raise ValueError 261 return length, decimals
262