Add a .save method on the sql db objects
authorElrond <elrond+mediagoblin.org@samba-tng.org>
Sun, 25 Dec 2011 18:09:23 +0000 (19:09 +0100)
committerElrond <elrond+mediagoblin.org@samba-tng.org>
Thu, 29 Dec 2011 09:41:50 +0000 (10:41 +0100)
This is a shortcut to adding the object to a session (if
needed) and giving a commit on the session.

In reality, calling code should probably utilize the
session on its own and call commit in an appropiate place.

mediagoblin/db/sql/base.py

index 1249bace0c34c685d0dd67fefa0b37de4705c173..40140327de374b75595bac2768ac0742d8d811c0 100644 (file)
@@ -1,4 +1,4 @@
-from sqlalchemy.orm import scoped_session, sessionmaker
+from sqlalchemy.orm import scoped_session, sessionmaker, object_session
 
 
 Session = scoped_session(sessionmaker())
@@ -28,3 +28,11 @@ class GMGTableBase(object):
 
     def get(self, key):
         return getattr(self, key)
+
+    def save(self, validate = True):
+        assert validate
+        sess = object_session(self)
+        if sess is None:
+            sess = Session()
+        sess.add(self)
+        sess.commit()