blob: 14747c666e7be239afaf959e57920495972da5ba (
plain)
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
|
# "orm" is used very loosely
# this is not very good, probably
from .db import get_db
class DBObj:
def __init_subclass__(cls, *, table, **kwargs):
# DO NOT pass anything with sql special characters in as the table name
super().__init_subclass__(**kwargs)
cls.table_name = table
@classmethod
def fetch(cls, *, id):
"""fetch an object from the database, looked up by id."""
db = get_db()
# XXX this could be sped up by caching this query maybe instead of
# string formatting every time
row = db.execute(f"select * from {cls.table_name} where id = ?",(id,)).fetchone()
if row is None:
return None
item = cls.from_row(row)
return item
@classmethod
def from_row(cls, row):
# doesn't handle the ability to set fields yet
# we will use something like properties instead
# so this is somewhat bleh for now
self = cls()
for fieldname in cls.fields:
setattr(self,fieldname,row[fieldname])
return self
@classmethod
def from_row_list(cls, row_list):
"""takes a list of database rows and returns a list of item objects"""
return [cls.from_row(r) for r in row_list]
|