-
Notifications
You must be signed in to change notification settings - Fork 6
/
mapper.py
57 lines (41 loc) · 1.95 KB
/
mapper.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
"""
Python data layer generator
Author: Juan MAnuel Garcia <jmg.utn@gmail.com>
"""
class ObjectMapper(object):
SQL_PARAM_SYMBOL = "?"
def __init__(self, entity):
self.entity = entity
def _get_pairs(self):
return [(k,str(v)) for k,v in self.entity.__dict__.iteritems() if not k.startswith("_") and not k.startswith("__")]
def _get_names(self):
return [pair[0] for pair in self._get_pairs()]
def _get_values(self):
return [pair[1] for pair in self._get_pairs()]
def _get_names_values(self):
return self._get_names(), self._get_values()
def insert(self):
names, values = self._get_names_values()
names = "%s" % ",".join(names)
params = ",".join(["'?'" for x in values])
return ("INSERT INTO %s(%s) VALUES (%s)" % (self.get_table(), names, params), ) + tuple(values)
def update(self, id):
pairs = self._get_pairs()
fields = ", ".join(["%s = '%s'" % (k, self.SQL_PARAM_SYMBOL) for k,v in pairs])
values = self._get_values()
return ("UPDATE %s SET %s WHERE %s = %s" % (self.get_table(), fields, self.get_id(), self.SQL_PARAM_SYMBOL), ) + tuple(values) + (id, )
def delete(self, id):
return ("DELETE FROM %s WHERE %s = %s" % (self.get_table(), self.get_id(), self.SQL_PARAM_SYMBOL), id)
def get_all(self):
names = ", ".join(self._get_names())
return "SELECT %s FROM %s" % (names, self.get_table())
def get_by_id(self, id):
names = ", ".join(self._get_names())
return ("SELECT %s FROM %s WHERE %s = %s" % (names, self.get_table(), self.get_id(), self.SQL_PARAM_SYMBOL), id)
#Overridables
#You can Extend from this class and override the following methods in order to configurate
#the table name and the id_name
def get_table(self):
return self.entity.__class__.__name__.lower()
def get_id(self):
return "id_%s" % self.entity.__class__.__name__.lower()