Commits

Guido Draheim  committed 3b33bee

switch tuning.py to sql orm

  • Participants
  • Parent commits 6d21447

Comments (0)

Files changed (6)

File src/GNUmakefile

 	$(RPMBUILD) -ba $(RPMROOT)/SPECS/$(SPECNAME).spec
 
 update:
-	@ version=`cat $(SPECNAME).spec | sed -e '/define _version/!d' -e 's/.*_version *//'` \
-	; package=`cat $(SPECNAME).spec | sed -e '/Name:/!d' -e 's/Name: *//'` \
-	; echo rpm -U --force $(RPMROOT)/RPMS/noarch/$$package-$$version*.noarch.rpm \
-	;      rpm -U --force $(RPMROOT)/RPMS/noarch/$$package-$$version*.noarch.rpm
+	@ spec="$(RPMROOT)/SPECS/$(SPECNAME).spec" \
+	; version=`cat "$$spec" | sed -e '/define _version/!d' -e 's/.*_version *//'` \
+	; package=`cat "$$spec" | sed -e '/Name:/!d' -e 's/Name: *//'` \
+	; rev=`cat "$$spec" | sed -e '/define revision/!d' -e 's/.*revision *//' -e 's/ .*//'` \
+	; echo rpm -U --force $(RPMROOT)/RPMS/noarch/$$package-$$version.$$rev*.noarch.rpm \
+	;      rpm -U --force $(RPMROOT)/RPMS/noarch/$$package-$$version.$$rev*.noarch.rpm
 	   
 trac restart:
 	sudo /sbin/service tracd restart

File src/dvbcronrecording/channels.py

       Returns list of the adapter settings
     """
     def _adapter_list(self, cursor, req, defaults = [ 0 ]):
-        return tuning_adapter_list(cursor, defaults)
+        return tuning_adapter_list(self.env, defaults)
     
 
     def _newchannel_list(self, cursor, req):

File src/dvbcronrecording/channelsconf.py

       Returns list of the adapter settings
     """
     def _adapter_list(self, cursor, req, defaults = [ 0 ]):
-        return tuning_adapter_list(cursor, defaults)
+        return tuning_adapter_list(self.env, defaults)
     
     """
       Returns list of the channels.conf

File src/dvbcronrecording/db/schema.py

 metadata = db4.metadata
 tables = metadata.sorted_tables # support old aff() detection
 
+RecordingTuning = db4.RecordingTuning

File src/dvbcronrecording/db/session.py

 from tsab import engine
-from schema import metadata
 from sqlalchemy.orm import create_session
 
 _session = None
         _session = create_session(bind=engine(env))
     return _session
 
-def cnx(env): return context(env)
+def db_cnx(env): return context(env)
 
 def commit():
     global _session

File src/dvbcronrecording/tuning.py

 from trac.web import IRequestHandler
 from trac.perm import IPermissionRequestor
 from trac.web.chrome import  ITemplateProvider # INavigationContributor,
-from db import schema
+from db.session import db_cnx
+from db.schema import RecordingTuning
+import sqlalchemy as _as
 
 from translate import Translate #@UnresolvedImport
 
 
-def affinity(table_name, column_name):
-    for table in schema.tables:
-        if table.name == table_name:
-            for column in table.columns:
-                if column.name == column_name:
-                    return column.type
-    return None
-def aff(value, table_name, column_name):
-    if value is None: return None
-    typed = affinity(table_name, column_name)
-    if typed in [ "int", "INT", "integer", "INTEGER"]:
-        return intnull(value)
-    return ustr(value)
 def intnull(value, default = None):
     if value is None: return default
     try: return int(value)
         req.perm.assert_permission(TUNING_VIEW)
 
         # getting cursor
-        db = self.env.get_db_cnx()
-        cursor = db.cursor()
+        #db = self.env.get_db_cnx()
+        session = db_cnx(self.env)
         page = req.args['page']
         if not page: page = "list"
         
         if page in [ None, '', 'list' ]:
             pass
         if page in [ 'newentry', 'append' ]:
-            message = self._tuning_append(cursor, req)
+            message = self._tuning_append(session, req)
         if page in [ 'update' ]:
-            message = self._tuning_update(cursor, req)
+            message = self._tuning_update(session, req)
         if page in [ 'delete' ]:
-            message = self._tuning_delete(cursor, req)
+            message = self._tuning_delete(session, req)
         
         # database commit and return page content
-        db.commit()
+        session.flush()
 
         add_stylesheet(req, 'common/css/wiki.css')
         add_stylesheet(req, PACKAGE+'/css/tuninglist.css')
         data = {}
         data['message'] = message
         data['title'] = translate('Tuning List')
-        data['newtunings'] = self._newtuning_list(cursor, req)
-        data['tunings'] = self._tuning_list(cursor, req)
+        data['newtunings'] = self._newtuning_list(session, req)
+        data['tunings'] = self._tuning_list(session)
         data['appends'] = req.perm.has_permission(TUNING_VIEW);
         data['author'] = req.authname or ""
         data['_'] = translate
     """
       Returns list of the tuning settings settings
     """
-    def _adapter_list(self, cursor, req, defaults = [ 0 ]):
-        return tuning_adapter_list(cursor, defaults)
+    def _adapter_list(self, session, req, defaults = [ 0 ]):
+        return tuning_adapter_list(session, defaults)
 
-    def _newtuning_list(self, cursor, req):
+    def _newtuning_list(self, session, req):
         _ = ['adapter', 'satellite', 'transponder', 'scansettings', 'scansourcefile', 'channelsconf']
         defs = {}
         defs["adapter"] = "0"
         defs["transponder"] = "Astra 19.2E SDT info service transponder"
         defs["scansettings"] = "S 12551500 V 22000000 5/6"
         defs["scansourcefile"] = "/usr/share/dvb/dvb-s/Astra-19.2E"
-        defs["channelsconf"] = self.channelsconf_from_adapter(cursor, "0")
+        defs["channelsconf"] = self.channelsconf_from_adapter(session, "0")
         return [ defs ]
 
     """
       Returns list of the tuning settings
     """
-    def _tuning_list(self, cursor, req):
-        view = []
+    def _tuning_list(self, session, req = None):
+        q = session.query(RecordingTuning)
         cols = ['id', 'adapter', 'satellite', 'transponder', 'scansettings', 'scansourcefile', 'channelsconf']
+        for col in cols:
+            if req and req.args.has_key(col):
+                q = q.filter_by(**{col : req.args.get(col) })
         order = ["adapter", "satellite", "transponder"]
-        sql = "SELECT %s FROM recording_tuning" % (",".join(cols))
-        order_sql = " ORDER BY %s" % (",".join(order))
-        view_vals = []
-        view_cols = []
-        for col in view:
-            if req.args.has_key(col):
-                view_vals += [ aff(req.args[col], "recording_tuning", col) ]
-                view_cols += [ col ]
-        if view_cols:
-            view_sql = " WHERE " + (" AND ".join([" %s = %%s" % col for col in view_cols ]))
-            cursor.execute(sql + view_sql + order_sql, view_vals)
-        else:
-            cursor.execute(sql)
-        entries = []
-        for entry in cursor:
-            entry = dict(zip(cols, entry))
-            entries.append(entry)
-        return entries
+        for col in order:
+            q = q.order_by(col)
+        return q.all()
 
     """
       Appends a new entry into tuning settings list
     """
-    def _tuning_append(self, cursor, req):
-        cols = ['adapter', 'satellite', 'transponder', 'scansettings', 'scansourcefile','channelsconf']
-        vals = [] 
-        for col in cols:
-            if req.args.has_key(col):
-                vals += [ aff(req.args[col], "recording_tuning", col) ]
-            else:
-                vals += [ None ]
-        sql = "INSERT INTO recording_tuning (%s)" % ",".join(cols)
-        sql += " VALUES (%s)" % (",".join(["%s"] * len(cols)))
-        cursor.execute(sql, vals)
+    def _tuning_append(self, session, req):
+        item = RecordingTuning()
+        item.adapter = req.args.get("adapter", None)
+        item.satellite = req.args.get("satellite", None)
+        item.transponder = req.args.get("transponder", None)
+        item.scansettings = req.args.get("scansettings", None)
+        item.scansourcefile = req.args.get("scansourcefile", None)
+        item.channelsconf = req.args.get("channelsconf", None)
+        session.add(item)
+        session.flush()
         return "OK"
 
     """
       Updates an entry in the tuning settings list
     """
-    def _tuning_update(self, cursor, req):
-        keys = ['id']
-        cols = ['adapter', 'satellite', 'transponder', 'scansettings', 'scansourcefile','channelsconf']
-        vals = [] 
-        for col in cols:
-            if req.args.has_key(col):
-                vals += [ aff(req.args[col], "recording_tuning", col) ]
-            else:
-                vals += [ None ] 
-        where = []
-        for col in keys:
-            if req.args.has_key(col):
-                where += [ aff(req.args[col], "recording_tuning", col) ]
-            else:
-                where += [ None ]
-        sqlX = ""
+    def _tuning_update(self, session, req):
+        q = session.query(RecordingTuning)
         try:
-            sql = "UPDATE recording_tuning " 
-            sql += " SET "+(",".join([" %s = %%s" % col for col in cols]))
-            sql += " WHERE " + (" AND ".join([" %s = %%s" % col for col in keys ]))
-            sqlX = sql + " | " + str( vals + where )
-            cursor.execute(sql, vals + where)
+            q = q.filter_by(id = req.args["id"])
+            for item in q.all():
+                item.adapter = req.args.get("adapter", None)
+                item.satellite = req.args.get("satellite", None)
+                item.transponder = req.args.get("transponder", None)
+                item.scansettings = req.args.get("scansettings", None)
+                item.scansourcefile = req.args.get("scansourcefile", None)
+                item.channelsconf = req.args.get("channelsconf", None)
+                session.flush()
         except Exception, e:
-            return "ERROR: %s\n%s" % (str(e), sqlX)
+            return "ERROR: %s\n%s" % (str(e), q)
         return "OK"
 
     """
       Deletes entry from tuning settings
     """
-    def _tuning_delete(self, cursor, req):
-        keys = ['id']
-        key_vals = []
-        for col in keys:
-            if req.args.has_key(col):
-                key_vals += [ aff(req.args[col], "recording_tuning", col) ]
-            else:
-                key_vals += [ None ]
-        key_sql = " WHERE " + (" AND ".join([" %s = %%s" % col for col in keys ]))
-        cursor.execute("DELETE FROM recording_tuning "+key_sql, key_vals)
+    def _tuning_delete(self, session, req):
+        q = session.query(RecordingTuning).filter_by(id = req.args["id"])
+        q.delete()
 
-    def channelsconf_from_adapter(self, cursor, adapter):
-        cols = ['channelsconf','adapter']
-        sql = "SELECT DISTINCT %s FROM recording_tuning" % (",".join(cols))
-        sql += " WHERE adapter = %s" % adapter
-        cursor.execute(sql)
-        for entry in cursor:
+    def channelsconf_from_adapter(self, session, adapter):
+        q = session.query(_as.distinct(RecordingTuning.channelsconf))
+        q = q.filter_by(adapter = adapter)
+        for entry in q.all():
             value = entry[0]
             if value:
                 return value
 """
   Returns list of the adapter settings
 """
-def tuning_adapter_list(cursor, defaults = [ 0 ]):
-    cols = ['adapter']
-    sql = "SELECT DISTINCT %s FROM recording_tuning" % (",".join(cols))
-    sql += " ORDER BY adapter"
-    cursor.execute(sql)
+def tuning_adapter_list(env, defaults = [ 0 ]):
+    session = db_cnx(env)
+    q = session.query(_as.distinct(RecordingTuning.adapter))
+    q = q.order_by(RecordingTuning.adapter)
     entries = []
-    for entry in cursor:
+    for entry in q.all():
         entries.append(entry[0])
     if not entries:
         return defaults