-
Notifications
You must be signed in to change notification settings - Fork 11
/
datatypes.py
322 lines (228 loc) · 6.99 KB
/
datatypes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# For reference, the bultin types
# Courtesty libpqtypes http://libpqtypes.esilo.com/browse_source.html?file=libpqtypes-int.h
# Numerics types
# INT2OID 21 Y
# INT4OID 23 Y
# INT8OID 20 Y
# FLOAT4OID 700 Y
# FLOAT8OID 701 Y
# NUMERICOID 1700 Needs doing
# Geo types
# POINTOID 600 N
# LSEGOID 601 N
# PATHOID 602 N
# BOXOID 603 N
# POLYGONOID 604 N
# LINEOID 628 N
# CIRCLEOID 718 N
# Network types
# INETOID 869 ?
# CIDROID 650 ?
# MACADDROID 829 ?
# Variable length types
# BPCHAROID 1042
# VARCHAROID 1043 Y
# NAMEOID 19 ?
# TEXTOID 25 Y
# ZPBITOID 1560 /* not supported yet */
# VARBITOID 1562 /* not supported yet */
# BYTEAOID 17 ?
# Date and time types
# DATEOID 1082 Y
# TIMEOID 1083 Y
# TIMETZOID 1266 ?
# TIMESTAMPOID 1114 Y
# TIMESTAMPTZOID 1184 Y
# INTERVALOID 1186 Y
# Misc types
# CHAROID 18 Needs doing!
# BOOLOID 16 Y
# OIDOID 26 ?
# CASHOID 790 ?
# RECORDOID 2249 ?
# UUIDOID 2950 ?
import datetime
import abc
import ctypes
import collections
try:
import pytz
except ImportError:
pytz = None
import errors
TYPE_MAP = {}
OID_MAP = {}
class AutoRegisteringPQType(abc.ABCMeta):
def __new__(mcs, name, bases, dict):
cls = super(AutoRegisteringPQType, mcs).__new__(mcs, name, bases, dict)
if cls.auto_register:
for c in cls.python_types:
register_adapter(c, cls.to_postgres)
register_type(cls)
return cls
def register_adapter(cls, adapter):
TYPE_MAP[cls] = adapter
def new_type(oids, name, adapter):
return type(name, (_PyPQDataType,), {'to_python': adapter, 'oids': oids})
def register_type(cls):
for oid in cls.oids:
OID_MAP[oid] = cls
class _PyPQDataType(object):
oids = ()
python_types = ()
@classmethod
def to_python(cls, value):
return value
@classmethod
def to_postgres(cls, value):
return str(value), cls._get_oid(value)
@classmethod
def _get_oid(cls, value):
if cls.oids:
return cls.oids[0]
else:
return 0
class PyPQDataType(_PyPQDataType):
__metaclass__ = AutoRegisteringPQType
auto_register = True
class Integer(PyPQDataType):
oids = (20, 21, 23)
python_types = (int, )
@classmethod
def _get_oid(cls, value):
return 0
@classmethod
def to_python(cls, value):
return int(value)
class ROWID(Integer):
oids = (26, )
python_types = ()
class Float(PyPQDataType):
oids = (700, 701)
python_types = (float, )
@classmethod
def to_python(cls, value):
return float(value)
class String(PyPQDataType):
oids = (25, 1043)
python_types = (str, )
@classmethod
def _get_oid(cls, value):
return 0
class Unicode(String):
python_types = (unicode, )
@classmethod
def to_postgres(cls, value):
if isinstance(value, unicode):
value = value.encode('utf-8')
return value, 25
class AutoUnicode(Unicode):
auto_register = False
@classmethod
def to_python(cls, value):
return value.decode('utf-8')
class Date(PyPQDataType):
oids = (1082,)
python_types = (datetime.date, )
@classmethod
def to_python(cls, value):
return datetime.datetime.strptime(value, '%Y-%m-%d').date()
class DateTime(PyPQDataType):
oids = (1114, )
python_types = (datetime.datetime, )
@classmethod
def to_python(cls, value):
format = '%Y-%m-%d %H:%M:%S'
if '.' in value:
format += '.%f'
return datetime.datetime.strptime(value, format)
class DateTimeTz(PyPQDataType):
oids = (1184,)
@classmethod
def to_python(cls, value):
# TODO: Implement timezone handling
value = value.split('+')[0]
return DateTime.to_python(value)
class Time(PyPQDataType):
oids = (1083,)
python_types = (datetime.time,)
@classmethod
def to_python(cls, value):
h,m,s,ms = 0,0,0,0
if '.' in value:
value, ms = value.split('.')
ms = int(ms)
if ':' in value:
h,m,s = map(int, value.split(':'))
return datetime.time(h,m,s,ms)
class PgInterval(datetime.timedelta):
def __init__(self, *args, **kwargs):
super(PgInterval, self).__init__(*args, **kwargs)
self.original_interval = None
# Converting into python Timedelta destroys some information
# so we use PgInterval instead, which saves the original info
class Interval(PyPQDataType):
oids = (1186,)
python_types = (datetime.timedelta, PgInterval)
@classmethod
def to_postgres(cls, value):
if isinstance(value, PgInterval):
return value.original_interval, 1186
return '%s days %s seconds %s microseconds' % \
(value.days, value.seconds, value.microseconds), 1186
@classmethod
def to_python(cls, value):
years, months, days = 0,0,0
# This will be stored in the resulting PgInterval object
original_value = value
# example value: '10 years 10 mons 15 days 10:10:10'
if 'year' in value:
years, value = value.split(' year')
years = int(years)
try:
value = value.split(' ', 1)[1]
except IndexError:
value = ''
if 'mon' in value:
months, value = value.split(' mon')
months = int(months)
try:
value = value.split(' ', 1)[1]
except IndexError:
value = ''
if 'day' in value:
days, value = value.split(' day')
days = int(days)
try:
value = value.split(' ', 1)[1]
except IndexError:
value = ''
time = Time.to_python(value)
interval = PgInterval(365 * years + 31 * months + days, hours=time.hour,
minutes=time.minute, seconds=time.second,
microseconds=time.microsecond)
interval.original_interval = original_value
return interval
class Boolean(PyPQDataType):
python_types = (bool, )
oids = (16,)
@classmethod
def to_python(cls, value):
value = value.lower()
if value == 't':
return True
elif value == 'f':
return False
raise errors.Error('Cannot convert "%s" to bool' % value)
def to_postgres(value):
try:
adapter = TYPE_MAP[type(value)]
except KeyError:
raise errors.NotSupportedError('Cannot cast %s to postgres type' % type(value))
return adapter(value)
adapt = to_postgres
def to_python(value, oid=None):
cls = get_type_by_oid(oid)
return cls.to_python(value)
def get_type_by_oid(oid, default=String):
return OID_MAP.get(oid, default)