-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuorm.py
131 lines (105 loc) · 3.07 KB
/
uorm.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
import sqlite3
class DB:
Error = sqlite3.Error
def __init__(self, name):
self.name = name
def connect(self):
self.conn = sqlite3.connect(self.name)
def close(self):
self.conn.close()
class ResultSet:
def __init__(self, c):
self.c = c
def __iter__(self):
return self
def __next__(self):
row = self.c.fetchone()
if row is None:
self.c.close()
raise StopIteration
return row
def close(self):
self.c.close()
class Model:
__pkey__ = "id"
@classmethod
def create_table(cls, fail_silently=False):
c = cls.__db__.conn.cursor()
try:
c.execute(cls.__schema__)
except DB.Error as e:
if fail_silently:
print(e)
else:
raise
c.close()
@classmethod
def execute(cls, sql, args=()):
c = cls.__db__.conn.cursor()
print(sql, args)
c.execute(sql, args)
return ResultSet(c)
@staticmethod
def render_where(where):
if where is None:
return ("1", ())
if isinstance(where, int):
return ("id=%s", (where,))
if isinstance(where, dict):
keys = []
vals = []
for k, v in where.items():
keys.append("%s=?" % k)
vals.append(v)
return (" AND ".join(keys), vals)
return (where, ())
@classmethod
def create(cls, **fields):
s = "INSERT INTO %s(%s) VALUES(%s)" % (
cls.__table__, ", ".join(fields.keys()),
", ".join(["?"] * len(fields))
)
c = cls.__db__.conn.cursor()
c.execute(s, tuple(fields.values()))
c.close()
if cls.__pkey__ == "id":
return c.lastrowid
return list(cls.execute("SELECT %s FROM %s WHERE rowid=?" % (cls.__pkey__, cls.__table__), (c.lastrowid,)))[0][0]
@classmethod
def update(cls, where, **fields):
keys = []
vals = []
for k, v in fields.items():
keys.append("%s=?" % k)
vals.append(v)
wh_sql, wh_vals = cls.render_where(where)
s = "UPDATE %s SET %s WHERE %s" % (
cls.__table__, ", ".join(keys),
wh_sql
)
c = cls.__db__.conn.cursor()
c.execute(s, vals + wh_vals)
c.close()
@classmethod
def delete(cls, where):
wh_sql, wh_vals = cls.render_where(where)
s = "DELETE FROM %s WHERE %s" % (
cls.__table__,
wh_sql
)
c = cls.__db__.conn.cursor()
c.execute(s, wh_vals)
c.close()
@classmethod
def select(cls, where=None):
wh_sql, wh_vals = cls.render_where(where)
s = "SELECT * FROM %s WHERE %s" % (
cls.__table__,
wh_sql
)
c = cls.__db__.conn.cursor()
c.execute(s, wh_vals)
return ResultSet(c)
@classmethod
def get_id(cls, id):
return cls.execute("SELECT * FROM %s WHERE %s=?" % (cls.__table__, cls.__pkey__), (id,))