[Mpuls-commits] r1962 - wasko/branches/2.0/mpulsweb/lib

scm-commit@wald.intevation.org scm-commit at wald.intevation.org
Tue Mar 16 10:17:59 CET 2010


Author: torsten
Date: 2010-03-16 10:17:56 +0100 (Tue, 16 Mar 2010)
New Revision: 1962

Added:
   wasko/branches/2.0/mpulsweb/lib/search.py
Log:
* mpulsweb/lib/search.py: New.


Added: wasko/branches/2.0/mpulsweb/lib/search.py
===================================================================
--- wasko/branches/2.0/mpulsweb/lib/search.py	2010-03-16 09:14:42 UTC (rev 1961)
+++ wasko/branches/2.0/mpulsweb/lib/search.py	2010-03-16 09:17:56 UTC (rev 1962)
@@ -0,0 +1,127 @@
+# -*- coding: utf-8 -*-
+import logging
+import sys
+import re
+from datetime import datetime
+
+import psycopg2.extras
+
+from mpulsweb.lib.db import db
+
+SAVE_SEARCH = re.compile(r'[^\w:;\-\. ]', re.UNICODE)
+VALID_OPTIONS = ['editor', 'migration', 'own', 'standin', 'state',
+                 'sort_field', 'sort_order', 'interval_start_date',
+                 'interval_end_date', 'interval_start_field',
+                 'interval_end_field', 'gender', 'phase', 'branch', 'fkz',
+                 'inconsistency', 'only_cases_after', 'bad', 'field']
+SEARCH_QUERY = """
+    SELECT %(fields)s
+    FROM master_tbl_view m
+    JOIN ka_status_tbl_view st ON
+    m.id = st.master_id
+    JOIN ka_benutzer_tbl b ON
+    m.bearbeiter_id = b.id
+    WHERE %(where)s
+    %(order)s
+"""
+SEARCH_FIELDS = """m.id, %s, st.status, st.zugriff, st.id as s_id """
+SEARCH_ORDER = """ORDER BY %s %s"""
+
+log = logging.getLogger(__name__)
+
+class Search(object):
+
+    def __init__(self):
+        pass
+
+    def _parse_search_str(self, s):
+        # TODO This is a very very simple approach. We should defentiley
+        # implement some searchengine here
+        search = []
+        allowed_states = [-1]
+        bad_types = []
+        phases = []
+        fields = {}
+        options = {}
+
+        if s:
+            s = SAVE_SEARCH.sub(u'', s)
+            option_list = [o.strip() for o in s.split(';')]
+            for option in option_list:
+                if option.find(":") > 0:
+                    try:
+                        key, value = [x.strip() for x in option.split(":")]
+                        if key in VALID_OPTIONS:
+                            if key == 'state':
+                                allowed_states.append(int(value))
+                            if key == 'phase':
+                                phases.append(int(value))
+                            else:
+                                options[key] = value
+                    except ValueError, err:
+                        print >> sys.stderr, \
+                              "Found invalid search syntax in options: %s" % err
+                else:
+                    search.append(option)
+        return search, options, allowed_states, bad_types, phases, fields
+
+    def _build_sql(self, search, options, allowed_states, bad_types, phases,
+                   fieldsdic):
+        pass
+
+    def queryDB(self, sql):
+        '''Does the search on the DB and returns the result of the search'''
+        rows = []
+        con, cur = None, None
+        try:
+            con = db.getConnection()
+            cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
+            cur.execute(sql)
+            rows = cur.fetchall()
+        finally:
+            db.recycleConnection(con, cur)
+        return rows
+
+    def perform(self, search_str):
+        '''Returns the result set of a search based on the search string'''
+        search, options, states, bad_types, phases, fields = \
+                self._parse_search_str(search_str)
+        sql = self._build_sql(search, options, states, bad_types,
+                                      phases, fields)
+        result = self.queryDB(sql)
+        return result
+
+class CaseSearch(Search):
+
+    def __init__(self, retrieve_fields, match_fields):
+        Search.__init__(self)
+        self.retrieve_fields = retrieve_fields
+        self.match_fields = match_fields
+
+    def __get_fields(self, options):
+        retrieve = ", ".join("m." + field for field in self.retrieve_fields)
+        return SEARCH_FIELDS % retrieve
+
+    def __get_where(self, search, options, allowed_states, bad_types, phaseslist, fieldsdic):
+        return "TRUE" 
+
+    def __get_order(self, options):
+        sort_field = options.get('sort_field', "name")
+        sort_order = options.get('sort_order', "desc")
+        return SEARCH_ORDER % (sort_field, sort_order)
+
+    def _build_sql(self, search, options, allowed_states, bad_types, phaseslist,
+                   fieldsdic):
+
+        sql_fields = {}
+        sql_fields['fields'] = self.__get_fields(options)
+        sql_fields['where'] =  self.__get_where(search, options, allowed_states, 
+                                                bad_types, phaseslist, fieldsdic) 
+        sql_fields['order'] =  self.__get_order(options) 
+
+        log.debug(sql_fields)
+        SQL = SEARCH_QUERY % sql_fields
+        log.debug(SQL)
+        return (SQL)
+
+# vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:



More information about the Mpuls-commits mailing list