Package install :: Package MoSTBioDat :: Package DataBase :: Package Query :: Package SQLBuilder :: Module converters
[hide private]
[frames] | no frames]

Source Code for Module install.MoSTBioDat.DataBase.Query.SQLBuilder.converters

  1  import array 
  2   
  3  try: 
  4      import mx.DateTime.ISO 
  5      origISOStr = mx.DateTime.ISO.strGMT 
  6      from mx.DateTime import DateTimeType, DateTimeDeltaType 
  7  except ImportError: 
  8      try: 
  9          import DateTime.ISO 
 10          origISOStr = DateTime.ISO.strGMT 
 11          from DateTime import DateTimeType, DateTimeDeltaType 
 12      except ImportError: 
 13          origISOStr = None 
 14          DateTimeType = None 
 15          DateTimeDeltaType = None 
 16   
 17  import time 
 18  try: 
 19      import datetime 
 20  except ImportError: 
 21      datetime = None 
 22   
 23  try: 
 24      import Sybase 
 25      NumericType=Sybase.NumericType 
 26  except ImportError: 
 27      NumericType = None 
 28   
 29  if type(1==1) == type(1): 
30 - class BOOL(object):
31 - def __init__(self, value):
32 self.value = not not value
33 - def __nonzero__(self):
34 return self.value
35 - def __repr__(self):
36 if self: 37 return 'TRUE' 38 else: 39 return 'FALSE'
40 TRUE = BOOL(1) 41 FALSE = BOOL(0) 42 else: 43 TRUE = 1==1 44 FALSE = 0==1 45 46 from types import InstanceType, ClassType, TypeType 47 48 try: 49 from decimal import Decimal 50 except ImportError: 51 Decimal = None 52 53 ######################################## 54 ## Quoting 55 ######################################## 56 57 sqlStringReplace = [ 58 ("'", "''"), 59 ('\\', '\\\\'), 60 ('\000', '\\0'), 61 ('\b', '\\b'), 62 ('\n', '\\n'), 63 ('\r', '\\r'), 64 ('\t', '\\t'), 65 ] 66
67 -def isoStr(val):
68 """ 69 Gets rid of time zone information 70 (@@: should we convert to GMT?) 71 """ 72 val = origISOStr(val) 73 if val.find('+') == -1: 74 return val 75 else: 76 return val[:val.find('+')]
77
78 -class ConverterRegistry:
79
80 - def __init__(self):
81 self.basic = {} 82 self.klass = {}
83
84 - def registerConverter(self, typ, func):
85 if type(typ) is ClassType: 86 self.klass[typ] = func 87 else: 88 self.basic[typ] = func
89
90 - def lookupConverter(self, value, default=None):
91 if type(value) == InstanceType: 92 # lookup on klasses dict 93 return self.klass.get(value.__class__, default) 94 return self.basic.get(type(value), default)
95 96 converters = ConverterRegistry() 97 registerConverter = converters.registerConverter 98 lookupConverter = converters.lookupConverter 99 100 array_type = type(array.array('c', '')) # In Python 2.2 array.array and buffer 101 buffer_type = type(buffer('')) # are functions, not classes 102
103 -def StringLikeConverter(value, db):
104 if isinstance(value, array_type): 105 try: 106 value = value.tounicode() 107 except ValueError: 108 value = value.tostring() 109 elif isinstance(value, buffer_type): 110 value = str(value) 111 112 if db in ('mysql', 'postgres'): 113 for orig, repl in sqlStringReplace: 114 value = value.replace(orig, repl) 115 elif db in ('sqlite', 'firebird', 'sybase', 'maxdb', 'mssql'): 116 value = value.replace("'", "''") 117 else: 118 assert 0, "Database %s unknown" % db 119 return "'%s'" % value
120 121 registerConverter(type(""), StringLikeConverter) 122 registerConverter(type(u""), StringLikeConverter) 123 registerConverter(array_type, StringLikeConverter) 124 registerConverter(buffer_type, StringLikeConverter) 125
126 -def IntConverter(value, db):
127 return repr(int(value))
128 129 registerConverter(type(1), IntConverter) 130
131 -def LongConverter(value, db):
132 return str(value)
133 134 registerConverter(type(0L), LongConverter) 135 136 if NumericType: 137 registerConverter(NumericType, IntConverter) 138
139 -def BoolConverter(value, db):
140 if db in ('postgres',): 141 if value: 142 return "'t'" 143 else: 144 return "'f'" 145 else: 146 if value: 147 return '1' 148 else: 149 return '0'
150 151 if type(TRUE) == InstanceType: 152 # Python 2.2 compatibility: 153 registerConverter(BOOL, BoolConverter) 154 else: 155 registerConverter(type(TRUE), BoolConverter) 156
157 -def FloatConverter(value, db):
158 return repr(value)
159 160 registerConverter(type(1.0), FloatConverter) 161 162 if DateTimeType:
163 - def DateTimeConverter(value, db):
164 return "'%s'" % isoStr(value)
165 166 registerConverter(DateTimeType, DateTimeConverter) 167
168 - def TimeConverter(value, db):
169 return "'%s'" % value.strftime("%T")
170 171 registerConverter(DateTimeDeltaType, TimeConverter) 172
173 -def NoneConverter(value, db):
174 return "NULL"
175 176 registerConverter(type(None), NoneConverter) 177
178 -def SequenceConverter(value, db):
179 return "(%s)" % ", ".join([sqlrepr(v, db) for v in value])
180 181 registerConverter(type(()), SequenceConverter) 182 registerConverter(type([]), SequenceConverter) 183 registerConverter(type({}), SequenceConverter) 184 try: 185 set, frozenset 186 except NameError: 187 pass 188 else: 189 registerConverter(set, SequenceConverter) 190 registerConverter(frozenset, SequenceConverter) 191 try: 192 from sets import Set, ImmutableSet 193 except ImportError: 194 pass 195 else: 196 registerConverter(Set, SequenceConverter) 197 registerConverter(ImmutableSet, SequenceConverter) 198 199 if hasattr(time, 'struct_time'):
200 - def StructTimeConverter(value, db):
201 return time.strftime("'%Y-%m-%d %H:%M:%S'", value)
202 203 registerConverter(time.struct_time, StructTimeConverter) 204 205 if datetime:
206 - def DateTimeConverter(value, db):
207 return "'%04d-%02d-%02d %02d:%02d:%02d'" % ( 208 value.year, value.month, value.day, 209 value.hour, value.minute, value.second)
210 211 registerConverter(datetime.datetime, DateTimeConverter) 212
213 - def DateConverter(value, db):
214 return "'%04d-%02d-%02d'" % (value.year, value.month, value.day)
215 216 registerConverter(datetime.date, DateConverter) 217
218 - def TimeConverter(value, db):
219 return "'%02d:%02d:%02d'" % (value.hour, value.minute, value.second)
220 221 registerConverter(datetime.time, TimeConverter) 222 223 if Decimal:
224 - def DecimalConverter(value, db):
225 return value.to_eng_string()
226 227 registerConverter(Decimal, DecimalConverter) 228
229 -def sqlrepr(obj, db=None):
230 try: 231 reprFunc = obj.__sqlrepr__ 232 except AttributeError: 233 converter = lookupConverter(obj) 234 if converter is None: 235 raise ValueError, "Unknown SQL builtin type: %s for %s" % \ 236 (type(obj), repr(obj)) 237 return converter(obj, db) 238 else: 239 return reprFunc(db)
240