[Mpuls-commits] r1958 - wasko/branches/2.0/jmdweb/lib

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


Author: torsten
Date: 2010-03-16 10:10:43 +0100 (Tue, 16 Mar 2010)
New Revision: 1958

Modified:
   wasko/branches/2.0/jmdweb/lib/search.py
Log:
* jmdweb/lib/search.py (__get_where): Overwrite function from
mpulsbase 


Modified: wasko/branches/2.0/jmdweb/lib/search.py
===================================================================
--- wasko/branches/2.0/jmdweb/lib/search.py	2010-03-16 09:06:52 UTC (rev 1957)
+++ wasko/branches/2.0/jmdweb/lib/search.py	2010-03-16 09:10:43 UTC (rev 1958)
@@ -26,39 +26,13 @@
 #
 # Authors:
 # Torsten Irländer <torsten.irlaender at intevation.de>
-#
 
 import logging
-import sys
-import re
 from datetime import datetime
 
-import psycopg2.extras
-
-from mpulsweb.lib.db import db
 from mpulsweb.lib.security import hasRole
+from mpulsweb.lib.search import CaseSearch as CaseBaseSearch 
 
-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_WHERE = """
       %s
       AND st.status IN (%s)
@@ -75,91 +49,15 @@
       AND %s
 """
 
-SEARCH_ORDER = """ORDER BY %s %s"""
-
 # FIXME: This should be better a config var
 INCONSISTENCY_CHECK_AFTER = '2008-08-31'
 
 log = logging.getLogger(__name__)
 
-class Search:
+class CaseSearch(CaseBaseSearch):
 
-    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):
-        fields = {'needle': ""}
-        ee = "TRUE"
-
+        # Ansicht eigene Fallakten / Vertretung
         which_user = 0
         allowed_viewer = "FALSE"
         if options.has_key('own'):
@@ -172,12 +70,40 @@
             allowed_viewer = "m.bearbeiter_id = %s" % options.get('own')
         if which_user == 3:
             allowed_viewer = "TRUE"
-        gender = (options.get('gender')
-                  and "m.geschlecht = %s" % options.get('gender') or "TRUE")
         allowed_viewer = (hasRole(['admin_ka', 'pb_ka'])
                           and "TRUE" or allowed_viewer)
+        # Bearbeiter
         editor = (options.has_key('editor')
                   and "m.bearbeiter_id = %s" % options.get('editor') or "TRUE")
+
+        #Phases
+        phases = 'TRUE' #default
+        if phaseslist:
+            phases = ('m.id in'
+                      ' (SELECT id from master_tbl_view WHERE phase in (%s))'
+                      % ','.join([str(p) for p in phaseslist]))
+
+        fields = {'needle': ""}
+        fields['needle'] = " ".join(search)
+        needle_expr = ("((%s) OR (%s))"
+                       % (" OR ".join("m.%s ~* '%%(needle)s'"
+                                      % field
+                                      for field in self.match_fields),
+                          " AND ".join("m.%s IS NULL"
+                                       % field
+                                       for field in self.match_fields)))
+
+        needle_expr = needle_expr % fields
+        ee = "TRUE"
+
+        #
+        # WASKOSPECIFIC or at least depending on concrete naming of fields.
+        #
+
+        # Geschlecht
+        gender = (options.get('gender')
+                  and "m.geschlecht = %s" % options.get('gender') or "TRUE")
+
         branch = (options.get('branch')
                   and "b.filiale = '%s'" % options.get('branch') or "TRUE")
         fkz = (options.get('fkz')
@@ -228,13 +154,6 @@
                                 " AND (coalesce(%(end_field)s, now())"
                                        " >= '%(start_date)s'::date))" % fields)
 
-        #Phases
-        phases = 'TRUE' #default
-        if phaseslist:
-            phases = ('m.id in'
-                      ' (SELECT id from master_tbl_view WHERE phase in (%s))'
-                      % ','.join([str(p) for p in phaseslist]))
-
         #Migration
         migration = "TRUE"
         if options.get('migration'):
@@ -262,39 +181,8 @@
                 migration = ("(nat_staat = 2"
                              " and (vater_staat != 2 or mutter_staat != 2))")
 
-        fields['needle'] = " ".join(search)
-        needle_expr = ("((%s) OR (%s))"
-                       % (" OR ".join("m.%s ~* '%%(needle)s'"
-                                      % field
-                                      for field in self.match_fields),
-                          " AND ".join("m.%s IS NULL"
-                                       % field
-                                       for field in self.match_fields)))
-
-        needle_expr = needle_expr % fields
         return SEARCH_WHERE % (needle_expr, ",".join([str(x) for x in allowed_states]),
                                ee, allowed_viewer, editor, gender, time_interval,
                                phases, branch, fkz, bad, only_cases_after, migration) 
 
-
-
-    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