Merge remote-tracking branch 'refs/remotes/rodney757/reprocessing'
[mediagoblin.git] / mediagoblin / db / base.py
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17
18 from sqlalchemy.ext.declarative import declarative_base
19 from sqlalchemy.orm import scoped_session, sessionmaker, object_session
20
21 Session = scoped_session(sessionmaker())
22
23
24 class GMGTableBase(object):
25 query = Session.query_property()
26
27 def get(self, key):
28 return getattr(self, key)
29
30 def setdefault(self, key, defaultvalue):
31 # The key *has* to exist on sql.
32 return getattr(self, key)
33
34 def save(self):
35 sess = object_session(self)
36 if sess is None:
37 sess = Session()
38 sess.add(self)
39 sess.commit()
40
41 def delete(self, commit=True):
42 """Delete the object and commit the change immediately by default"""
43 sess = object_session(self)
44 assert sess is not None, "Not going to delete detached %r" % self
45 sess.delete(self)
46 if commit:
47 sess.commit()
48
49
50 Base = declarative_base(cls=GMGTableBase)
51
52
53 class DictReadAttrProxy(object):
54 """
55 Maps read accesses to obj['key'] to obj.key
56 and hides all the rest of the obj
57 """
58 def __init__(self, proxied_obj):
59 self.proxied_obj = proxied_obj
60
61 def __getitem__(self, key):
62 try:
63 return getattr(self.proxied_obj, key)
64 except AttributeError:
65 raise KeyError("%r is not an attribute on %r"
66 % (key, self.proxied_obj))