]> git.ipfire.org Git - people/jschlag/pbs.git/blame - src/buildservice/base.py
Add DataObject type
[people/jschlag/pbs.git] / src / buildservice / base.py
CommitLineData
9137135a
MT
1#!/usr/bin/python
2
2e1b81e0
MT
3from .decorators import *
4
9137135a
MT
5class Object(object):
6 """
7 Main object where all other objects inherit from.
8
9 This is used to access the global instance of Pakfire
10 and hold the database connection.
11 """
5e432e87 12 def __init__(self, pakfire, *args, **kwargs):
9137135a
MT
13 self.pakfire = pakfire
14
15 # Shortcut to the database.
16 self.db = self.pakfire.db
17
18 # Shortcut to settings.
19 if hasattr(self.pakfire, "settings"):
20 self.settings = self.pakfire.settings
f6e6ff79 21
771320fe
MT
22 # Private cache.
23 self._cache = None
24
5e432e87
MT
25 # Call custom constructor
26 self.init(*args, **kwargs)
27
28 def init(self, *args, **kwargs):
29 """
30 Custom constructor to be overwritten by inheriting class
31 """
32 pass
33
f6e6ff79
MT
34 @property
35 def cache(self):
36 """
37 Shortcut to the cache.
38 """
771320fe
MT
39 if self._cache:
40 return self._cache
41
f6e6ff79
MT
42 return self.pakfire.cache
43
44 @property
45 def geoip(self):
46 return self.pakfire.geoip
2e1b81e0
MT
47
48
49class DataObject(Object):
50 # Table name
51 table = None
52
53 def init(self, id, data=None):
54 self.id = id
55
56 if data:
57 self.data = data
58
59 @lazy_property
60 def data(self):
61 assert self.table, "Table name is not set"
62 assert self.id
63
64 return self.db.get("SELECT * FROM %s \
65 WHERE id = %%s" % self.table, self.id)
66
67 def _set_attribute(self, key, val):
68 # Detect if an update is needed
69 if self.data[key] == val:
70 return
71
72 self.db.execute("UPDATE %s SET %s = %%s \
73 WHERE id = %%s" % (self.table, key), val, self.id)
74
75 # Update the cached attribute
76 self.data[key] = val