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 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
|
# Copyright (c) 2006,2007,2008 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from boto.sdb.db.key import Key
from boto.sdb.db.model import Model
import psycopg2
import psycopg2.extensions
import uuid
import os
import string
from boto.exception import SDBPersistenceError
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
class PGConverter:
def __init__(self, manager):
self.manager = manager
self.type_map = {Key : (self.encode_reference, self.decode_reference),
Model : (self.encode_reference, self.decode_reference)}
def encode(self, type, value):
if type in self.type_map:
encode = self.type_map[type][0]
return encode(value)
return value
def decode(self, type, value):
if type in self.type_map:
decode = self.type_map[type][1]
return decode(value)
return value
def encode_prop(self, prop, value):
if isinstance(value, list):
if hasattr(prop, 'item_type'):
s = "{"
new_value = []
for v in value:
item_type = getattr(prop, 'item_type')
if Model in item_type.mro():
item_type = Model
new_value.append('%s' % self.encode(item_type, v))
s += ','.join(new_value)
s += "}"
return s
else:
return value
return self.encode(prop.data_type, value)
def decode_prop(self, prop, value):
if prop.data_type == list:
if value != None:
if not isinstance(value, list):
value = [value]
if hasattr(prop, 'item_type'):
item_type = getattr(prop, "item_type")
if Model in item_type.mro():
if item_type != self.manager.cls:
return item_type._manager.decode_value(prop, value)
else:
item_type = Model
return [self.decode(item_type, v) for v in value]
return value
elif hasattr(prop, 'reference_class'):
ref_class = getattr(prop, 'reference_class')
if ref_class != self.manager.cls:
return ref_class._manager.decode_value(prop, value)
else:
return self.decode(prop.data_type, value)
elif hasattr(prop, 'calculated_type'):
calc_type = getattr(prop, 'calculated_type')
return self.decode(calc_type, value)
else:
return self.decode(prop.data_type, value)
def encode_reference(self, value):
if isinstance(value, str) or isinstance(value, unicode):
return value
if value == None:
return ''
else:
return value.id
def decode_reference(self, value):
if not value:
return None
try:
return self.manager.get_object_from_id(value)
except:
raise ValueError, 'Unable to convert %s to Object' % value
class PGManager(object):
def __init__(self, cls, db_name, db_user, db_passwd,
db_host, db_port, db_table, sql_dir, enable_ssl):
self.cls = cls
self.db_name = db_name
self.db_user = db_user
self.db_passwd = db_passwd
self.db_host = db_host
self.db_port = db_port
self.db_table = db_table
self.sql_dir = sql_dir
self.in_transaction = False
self.converter = PGConverter(self)
self._connect()
def _build_connect_string(self):
cs = 'dbname=%s user=%s password=%s host=%s port=%d'
return cs % (self.db_name, self.db_user, self.db_passwd,
self.db_host, self.db_port)
def _connect(self):
self.connection = psycopg2.connect(self._build_connect_string())
self.connection.set_client_encoding('UTF8')
self.cursor = self.connection.cursor()
def _object_lister(self, cursor):
try:
for row in cursor:
yield self._object_from_row(row, cursor.description)
except StopIteration:
cursor.close()
raise StopIteration
def _dict_from_row(self, row, description):
d = {}
for i in range(0, len(row)):
d[description[i][0]] = row[i]
return d
def _object_from_row(self, row, description=None):
if not description:
description = self.cursor.description
d = self._dict_from_row(row, description)
obj = self.cls(d['id'])
obj._manager = self
obj._auto_update = False
for prop in obj.properties(hidden=False):
if prop.data_type != Key:
v = self.decode_value(prop, d[prop.name])
v = prop.make_value_from_datastore(v)
if hasattr(prop, 'calculated_type'):
prop._set_direct(obj, v)
elif not prop.empty(v):
setattr(obj, prop.name, v)
else:
setattr(obj, prop.name, prop.default_value())
return obj
def _build_insert_qs(self, obj, calculated):
fields = []
values = []
templs = []
id_calculated = [p for p in calculated if p.name == 'id']
for prop in obj.properties(hidden=False):
if prop not in calculated:
value = prop.get_value_for_datastore(obj)
if value != prop.default_value() or prop.required:
value = self.encode_value(prop, value)
values.append(value)
fields.append('"%s"' % prop.name)
templs.append('%s')
qs = 'INSERT INTO "%s" (' % self.db_table
if len(id_calculated) == 0:
qs += '"id",'
qs += ','.join(fields)
qs += ") VALUES ("
if len(id_calculated) == 0:
qs += "'%s'," % obj.id
qs += ','.join(templs)
qs += ')'
if calculated:
qs += ' RETURNING '
calc_values = ['"%s"' % p.name for p in calculated]
qs += ','.join(calc_values)
qs += ';'
return qs, values
def _build_update_qs(self, obj, calculated):
fields = []
values = []
for prop in obj.properties(hidden=False):
if prop not in calculated:
value = prop.get_value_for_datastore(obj)
if value != prop.default_value() or prop.required:
value = self.encode_value(prop, value)
values.append(value)
field = '"%s"=' % prop.name
field += '%s'
fields.append(field)
qs = 'UPDATE "%s" SET ' % self.db_table
qs += ','.join(fields)
qs += """ WHERE "id" = '%s'""" % obj.id
if calculated:
qs += ' RETURNING '
calc_values = ['"%s"' % p.name for p in calculated]
qs += ','.join(calc_values)
qs += ';'
return qs, values
def _get_sql(self, mapping=None):
print '_get_sql'
sql = None
if self.sql_dir:
path = os.path.join(self.sql_dir, self.cls.__name__ + '.sql')
print path
if os.path.isfile(path):
fp = open(path)
sql = fp.read()
fp.close()
t = string.Template(sql)
sql = t.safe_substitute(mapping)
return sql
def start_transaction(self):
print 'start_transaction'
self.in_transaction = True
def end_transaction(self):
print 'end_transaction'
self.in_transaction = False
self.commit()
def commit(self):
if not self.in_transaction:
print '!!commit on %s' % self.db_table
try:
self.connection.commit()
except psycopg2.ProgrammingError, err:
self.connection.rollback()
raise err
def rollback(self):
print '!!rollback on %s' % self.db_table
self.connection.rollback()
def delete_table(self):
self.cursor.execute('DROP TABLE "%s";' % self.db_table)
self.commit()
def create_table(self, mapping=None):
self.cursor.execute(self._get_sql(mapping))
self.commit()
def encode_value(self, prop, value):
return self.converter.encode_prop(prop, value)
def decode_value(self, prop, value):
return self.converter.decode_prop(prop, value)
def execute_sql(self, query):
self.cursor.execute(query, None)
self.commit()
def query_sql(self, query, vars=None):
self.cursor.execute(query, vars)
return self.cursor.fetchall()
def lookup(self, cls, name, value):
values = []
qs = 'SELECT * FROM "%s" WHERE ' % self.db_table
found = False
for property in cls.properties(hidden=False):
if property.name == name:
found = True
value = self.encode_value(property, value)
values.append(value)
qs += "%s=" % name
qs += "%s"
if not found:
raise SDBPersistenceError('%s is not a valid field' % name)
qs += ';'
print qs
self.cursor.execute(qs, values)
if self.cursor.rowcount == 1:
row = self.cursor.fetchone()
return self._object_from_row(row, self.cursor.description)
elif self.cursor.rowcount == 0:
raise KeyError, 'Object not found'
else:
raise LookupError, 'Multiple Objects Found'
def query(self, cls, filters, limit=None, order_by=None):
parts = []
qs = 'SELECT * FROM "%s"' % self.db_table
if filters:
qs += ' WHERE '
properties = cls.properties(hidden=False)
for filter, value in filters:
name, op = filter.strip().split()
found = False
for property in properties:
if property.name == name:
found = True
value = self.encode_value(property, value)
parts.append(""""%s"%s'%s'""" % (name, op, value))
if not found:
raise SDBPersistenceError('%s is not a valid field' % name)
qs += ','.join(parts)
qs += ';'
print qs
cursor = self.connection.cursor()
cursor.execute(qs)
return self._object_lister(cursor)
def get_property(self, prop, obj, name):
qs = """SELECT "%s" FROM "%s" WHERE id='%s';""" % (name, self.db_table, obj.id)
print qs
self.cursor.execute(qs, None)
if self.cursor.rowcount == 1:
rs = self.cursor.fetchone()
for prop in obj.properties(hidden=False):
if prop.name == name:
v = self.decode_value(prop, rs[0])
return v
raise AttributeError, '%s not found' % name
def set_property(self, prop, obj, name, value):
pass
value = self.encode_value(prop, value)
qs = 'UPDATE "%s" SET ' % self.db_table
qs += "%s='%s'" % (name, self.encode_value(prop, value))
qs += " WHERE id='%s'" % obj.id
qs += ';'
print qs
self.cursor.execute(qs)
self.commit()
def get_object(self, cls, id):
qs = """SELECT * FROM "%s" WHERE id='%s';""" % (self.db_table, id)
self.cursor.execute(qs, None)
if self.cursor.rowcount == 1:
row = self.cursor.fetchone()
return self._object_from_row(row, self.cursor.description)
else:
raise SDBPersistenceError('%s object with id=%s does not exist' % (cls.__name__, id))
def get_object_from_id(self, id):
return self.get_object(self.cls, id)
def _find_calculated_props(self, obj):
return [p for p in obj.properties() if hasattr(p, 'calculated_type')]
def save_object(self, obj, expected_value=None):
obj._auto_update = False
calculated = self._find_calculated_props(obj)
if not obj.id:
obj.id = str(uuid.uuid4())
qs, values = self._build_insert_qs(obj, calculated)
else:
qs, values = self._build_update_qs(obj, calculated)
print qs
self.cursor.execute(qs, values)
if calculated:
calc_values = self.cursor.fetchone()
print calculated
print calc_values
for i in range(0, len(calculated)):
prop = calculated[i]
prop._set_direct(obj, calc_values[i])
self.commit()
def delete_object(self, obj):
qs = """DELETE FROM "%s" WHERE id='%s';""" % (self.db_table, obj.id)
print qs
self.cursor.execute(qs)
self.commit()
|