SQLCatalog.py 28.7 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL. All Rights Reserved.
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################

from Persistence import Persistent
import Acquisition
import ExtensionClass
from string import lower, split, join
19
from thread import get_ident
Jean-Paul Smets's avatar
Jean-Paul Smets committed
20

21
from DateTime import DateTime
Jean-Paul Smets's avatar
Jean-Paul Smets committed
22 23
from Products.PluginIndexes.common.randid import randid
from Products.CMFCore.Expression import Expression
24
from Products.CMFCore.utils import getToolByName
Jean-Paul Smets's avatar
Jean-Paul Smets committed
25 26 27 28
from Acquisition import aq_parent, aq_inner, aq_base, aq_self
from zLOG import LOG

import time
Jean-Paul Smets's avatar
Jean-Paul Smets committed
29
import sys
Jean-Paul Smets's avatar
Jean-Paul Smets committed
30

Jean-Paul Smets's avatar
Jean-Paul Smets committed
31
UID_BUFFER_SIZE = 900
32 33
MAX_UID_BUFFER_SIZE = 20000

Jean-Paul Smets's avatar
Jean-Paul Smets committed
34 35 36 37 38
class Catalog(Persistent, Acquisition.Implicit, ExtensionClass.Base):
  """ An Object Catalog

  An Object Catalog maintains a table of object metadata, and a
  series of manageable indexes to quickly search for objects
39
  (references in the metadata) that satisfy a search where_expression.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

  This class is not Zope specific, and can be used in any python
  program to build catalogs of objects.  Note that it does require
  the objects to be Persistent, and thus must be used with ZODB3.

  uid -> the (local) universal ID of objects
  path -> the (local) path of objects


  bgrain defined in meyhods...

  TODO:

    - optmization: indexing objects should be deferred
      until timeout value or end of transaction
  """
56
  _after_clear_reserved = 0
Jean-Paul Smets's avatar
Jean-Paul Smets committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

  def __init__(self):
    self.schema = {}  # mapping from attribute name to column
    self.names = {}   # mapping from column to attribute name
    self.indexes = {}   # empty mapping

  def clear(self):
    """
    Clears the catalog by calling a list of methods
    """
    methods = self.sql_clear_catalog
    for method_name in methods:
      method = getattr(self,method_name)
      try:
        method()
      except:
        pass
74
    self._after_clear_reserved = 1
Jean-Paul Smets's avatar
Jean-Paul Smets committed
75

76 77 78 79 80 81 82 83 84
  def clearReserved(self):
    """
    Clears reserved uids
    """
    method_id = self.sql_catalog_clear_reserved
    method = getattr(self, method_id)
    method()
    self._after_clear_reserved = 1

Jean-Paul Smets's avatar
Jean-Paul Smets committed
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
  def __getitem__(self, uid):
    """
    Get an object by UID
    Note: brain is defined in Z SQL Method object
    """
    method = getattr(self,  self.sql_getitem_by_uid)
    search_result = method(uid = uid)
    if len(search_result) > 0:
      return search_result[0]
    else:
      return None

  def editSchema(self, names_list):
    """
    Builds a schema from a list of strings
    Splits each string to build a list of attribute names
    Columns on the database should not change during this operations
    """
    i = 0
    schema = {}
    names = {}
    for cid in self.getColumnIds():
      name_list = []
      for name in names_list[i].split():
        schema[name] = cid
        name_list += [name,]
      names[cid] = tuple(name_list)
      i += 1
    self.schema = schema
    self.names = names

  def getColumnIds(self):
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
118 119
    Calls the show column method and returns dictionnary of
    Field Ids
120

121
    XXX This should be cached
Jean-Paul Smets's avatar
Jean-Paul Smets committed
122 123 124 125 126 127 128 129 130
    """
    method_name = self.sql_catalog_schema
    keys = {}
    for table in self.getCatalogSearchTableIds():
      try:
        method = getattr(self,  method_name)
        search_result = method(table=table)
        for c in search_result:
          keys[c.Field] = 1
131
          keys['%s.%s' % (table, c.Field)] = 1  # Is this inconsistent ?
Jean-Paul Smets's avatar
Jean-Paul Smets committed
132 133 134 135 136 137
      except:
        pass
    keys = keys.keys()
    keys.sort()
    return keys

138 139 140 141
  def getColumnMap(self):
    """
    Calls the show column method and returns dictionnary of
    Field Ids
142

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
    XXX This should be cached
    """
    method_name = self.sql_catalog_schema
    keys = {}
    for table in self.getCatalogSearchTableIds():
      try:
        method = getattr(self,  method_name)
        search_result = method(table=table)
        for c in search_result:
          key = c.Field
          if not keys.has_key(key): keys[c.Field] = []
          keys[key].append(table)
          key = '%s.%s' % (table, c.Field)
          if not keys.has_key(key): keys[key] = []
          keys[key].append(table) # Is this inconsistent ?
      except:
        pass
160
    return keys
161

Jean-Paul Smets's avatar
Jean-Paul Smets committed
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
  def getResultColumnIds(self):
    """
    Calls the show column method and returns dictionnary of
    Field Ids
    """
    method_name = self.sql_catalog_schema
    keys = {}
    for table in self.getCatalogSearchTableIds():
      try:
        method = getattr(self,  method_name)
        search_result = method(table=table)
        for c in search_result:
          keys['%s.%s' % (table, c.Field)] = 1
      except:
        pass
    keys = keys.keys()
    keys.sort()
    return keys

  def getTableIds(self):
    """
    Calls the show table method and returns dictionnary of
Jean-Paul Smets's avatar
Jean-Paul Smets committed
184 185 186
    Field Ids
    """
    keys = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
187 188
    method_name = self.sql_catalog_tables
    try:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
189 190 191
      method = getattr(self,  method_name)
      search_result = method()
      for c in search_result:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
192 193 194
        keys.append(c[0])
    except:
      pass
Jean-Paul Smets's avatar
Jean-Paul Smets committed
195 196 197
    return keys

  # the cataloging API
198 199 200
  def produceUid(self):
    """
      Produces reserved uids in advance
201
    """
202 203 204 205 206 207 208 209 210 211 212 213
    method_id = self.sql_catalog_produce_reserved
    method = getattr(self, method_id)
    thread_id = get_ident()
    uid_list = getattr(self, '_v_uid_buffer', [])
    if self._after_clear_reserved:
      # Reset uid list after clear reserved
      self._after_clear_reserved = 0
      uid_list = []
    if len(uid_list) < UID_BUFFER_SIZE:
      date = DateTime()
      new_uid_list = method(count = UID_BUFFER_SIZE, thread_id=thread_id, date=date)
      uid_list.extend( filter(lambda x: x != 0, map(lambda x: x.uid, new_uid_list )))
214 215
    self._v_uid_buffer = uid_list

216 217 218
  def newUid(self):
    """
      This is where uid generation takes place. We should consider a multi-threaded environment
219 220
      with multiple ZEO clients on a single ZEO server.

221
      The main risk is the following:
222

223
      - objects a/b/c/d/e/f are created (a is parent of b which is parent of ... of f)
224

225
      - one reindexing node N1 starts reindexing f
226

227
      - another reindexing node N2 starts reindexing e
228

229 230 231
      - there is a strong risk that N1 and N2 start reindexing at the same time
        and provide different uid values for a/b/c/d/e

232
      Similar problems may happen with relations and acquisition of uid values (ex. order_uid)
233
      with the risk of graph loops
234
    """
235 236 237 238 239 240
    self.produceUid()
    uid_list = getattr(self, '_v_uid_buffer', [])
    if len(uid_list) > 0:
      return uid_list.pop()
    else:
      raise CatalogError("Could not retrieve new uid")
241

Jean-Paul Smets's avatar
Jean-Paul Smets committed
242
  def catalogObject(self, object, path, is_object_moved=0):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
243 244 245 246 247 248 249 250 251
    """
    Adds an object to the Catalog by calling
    all SQL methods and providing needed arguments.

    'object' is the object to be cataloged

    'uid' is the unique Catalog identifier for this object

    """
252
    #LOG('Catalog object:',0,str(path))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
253 254 255 256 257

    # Prepare the dictionnary of values
    kw = {}

    # Check if already Catalogued
258
    if hasattr(aq_base(object), 'uid'):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
259 260 261 262
      # Try to use existing uid
      # WARNING COPY PASTE....
      uid = object.uid
    else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
263
      # Look up in (previous) path
Jean-Paul Smets's avatar
Jean-Paul Smets committed
264
      uid = 0
Jean-Paul Smets's avatar
Jean-Paul Smets committed
265 266 267 268
    if is_object_moved:
      index = uid # We trust the current uid
    else:
      index = self.getUidForPath(path)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
269
    if index:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
270
      if (uid != index):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
271 272
        # Update uid attribute of object
        uid = int(index)
273
        #LOG("Write Uid",0, "uid %s index %s" % (uid, index))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
274 275 276 277 278 279 280 281 282
        object.uid = uid
      # We will check if there is an filter on this
      # method, if so we may not call this zsqlMethod
      # for this object
      for method_name in self.sql_update_object:
        if self.isMethodFiltered(method_name):
          if self.filter_dict.has_key(method_name):
            portal_type = object.getPortalType()
            if portal_type not in (self.filter_dict[method_name]['type']):
283
              #LOG('catalog_object',0,'XX1 this method is broken because not in types: %s' % method_name)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
284 285 286 287 288 289 290 291 292
              continue
            else:
              expression = self.filter_dict[method_name]['expression_instance']
              if expression is not None:
                econtext = self.getExpressionContext(object)
                result = expression(econtext)
                if not result:
                  #LOG('catalog_object',0,'XX2 this method is broken because expression: %s' % method_name)
                  continue
293
        #LOG('catalog_object',0,'this method is not broken: %s' % method_name)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
        # Get the appropriate SQL Method
        # Lookup by path is required because of OFS Semantics
        method = getattr(self, method_name)
        if method.meta_type == "Z SQL Method":
          # Build the dictionnary of values
          arguments = method.arguments_src
          for arg in split(arguments):
            try:
              value = getattr(object, arg)
              if callable(value):
                value = value()
              kw[arg] = value
            except:
              #LOG("SQLCatalog Warning: Callable value could not be called",0,str((path, arg, method_name)))
              kw[arg] = None
        method = aq_base(method).__of__(object.__of__(self)) # Use method in the context of object
        # Generate UID
        kw['path'] = path
        kw['uid'] = int(index)
313
        kw['insert_catalog_line'] = 0
314
        #LOG("SQLCatalog Warning: insert_catalog_line, case1 value",0,0)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
315 316 317
        # LOG
        # LOG("Call SQL Method %s with args:" % method_name,0, str(kw))
        # Alter row
318
        #LOG("Call SQL Method %s with args:" % method_name,0, str(kw))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
319 320 321 322 323
        method(**kw)
    else:
      # Get the appropriate SQL Method
      # Lookup by path is required because of OFS Semantics
      if uid:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
324 325 326
        # Make sure no duplicates - ie. if an object with different path has same uid, we need a new uid
        # This can be very dangerous with relations stored in a category table (CMFCategory)
        # This is why we recommend completely reindexing subobjects after any change of id
327 328 329 330
        catalog_path = self.getPathForUid(uid)
        if catalog_path == "reserved":
          # Reserved line in catalog table
          insert_catalog_line = 0
331
          #LOG("SQLCatalog Warning: insert_catalog_line, case2",0,insert_catalog_line)
332 333 334
        elif catalog_path is None:
          # No line in catalog table
          insert_catalog_line = 1
335
          #LOG("SQLCatalog Warning: insert_catalog_line, case3",0,insert_catalog_line)
336
        else:
337
          #LOG('SQLCatalog WARNING',0,'assigning new uid to already catalogued object %s' % path)
338
          uid = 0
339
          insert_catalog_line = 0
340
          #LOG("SQLCatalog Warning: insert_catalog_line, case4",0,insert_catalog_line)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
341 342
      if not uid:
        # Generate UID
343
        index = self.newUid()
344
        object.uid = index
345
        insert_catalog_line = 0
346
        #LOG("SQLCatalog Warning: insert_catalog_line, case5",0,insert_catalog_line)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
347 348 349 350 351 352 353 354 355 356
      else:
        index = uid
      for method_name in self.sql_catalog_object:
        # We will check if there is an filter on this
        # method, if so we may not call this zsqlMethod
        # for this object
        if self.isMethodFiltered(method_name):
          if self.filter_dict.has_key(method_name):
            portal_type = object.getPortalType()
            if portal_type not in (self.filter_dict[method_name]['type']):
357
              #LOG('catalog_object',0,'XX1 this method is broken because not in types: %s' % method_name)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
358 359 360 361 362 363 364
              continue
            else:
              expression = self.filter_dict[method_name]['expression_instance']
              if expression is not None:
                econtext = self.getExpressionContext(object)
                result = expression(econtext)
                if not result:
365
                  #LOG('catalog_object',0,'XX2 this method is broken because expression: %s' % method_name)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
366
                  continue
367
        #LOG('catalog_object',0,'this method is not broken: %s' % method_name)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
368 369 370 371 372 373 374 375 376 377 378 379

        method = getattr(self, method_name)
        if method.meta_type == "Z SQL Method":
          # Build the dictionnary of values
          arguments = method.arguments_src
          for arg in split(arguments):
            try:
              value = getattr(object, arg)
              if callable(value):
                value = value()
              kw[arg] = value
            except:
380
              #LOG("SQLCatalog Warning: Callable value could not be called",0,str((path, arg, method_name)))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
381 382 383 384 385
              kw[arg] = None
        method = aq_base(method).__of__(object.__of__(self)) # Use method in the context of object
        # Generate UID
        kw['path'] = path
        kw['uid'] = index
386
        kw['insert_catalog_line'] = insert_catalog_line
387
        # Alter/Create row       
388
        try:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
389
          zope_root = getToolByName(self, 'portal_url').getPortalObject().aq_parent
390 391
          root_indexable = int(getattr(zope_root,'isIndexable',1))
          if root_indexable:
392
            #LOG("Call SQL Method %s with args:" % method_name,0, str(kw))
393 394 395 396 397 398 399 400 401
            method(**kw)
        except:
          LOG("SQLCatalog Warning: could not catalog object with method %s" % method_name,100, str(path))
          raise
        #except:
        #  #  # This is a real LOG message
        #  #  # which is required in order to be able to import .zexp files
        #  LOG("SQLCatalog Warning: could not catalog object with method %s" % method_name,
        #                                                                   100,str(path))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
402 403 404 405 406 407 408 409 410 411 412 413 414 415

  def uncatalogObject(self, path):
    """
    Uncatalog and object from the Catalog.

    Note, the uid must be the same as when the object was
    catalogued, otherwise it will not get removed from the catalog

    This method should not raise an exception if the uid cannot
    be found in the catalog.

    XXX Add filter of methods

    """
416
    #LOG('Uncatalog object:',0,str(path))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
417

Jean-Paul Smets's avatar
Jean-Paul Smets committed
418 419 420 421 422
    uid = self.getUidForPath(path)
    methods = self.sql_uncatalog_object
    for method_name in methods:
      method = getattr(self, method_name)
      try:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
423
        #if 1:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
        method(uid = uid)
      except:
        # This is a real LOG message
        # which is required in order to be able to import .zexp files
        LOG("SQLCatalog Warning: could not uncatalog object uid %s with method %s" %
                                               (uid, method_name),0,str(path))

  def uniqueValuesFor(self, name):
    """ return unique values for FieldIndex name """
    method = getattr(self, self.sql_unique_values)
    return method()

  def getPaths(self):
    """ Returns all object paths stored inside catalog """
    method = getattr(self, self.sql_catalog_paths)
    return method()

  def getUidForPath(self, path):
    """ Looks up into catalog table to convert path into uid """
    try:
      if path is None:
        return None
      # Get the appropriate SQL Method
      method = getattr(self, self.sql_getitem_by_path)
      search_result = method(path = path)
      # If not emptyn return first record
      if len(search_result) > 0:
        return search_result[0].uid
      else:
        return None
    except:
      # This is a real LOG message
      # which is required in order to be able to import .zexp files
      LOG("Warning: could not find uid from path",0,str(path))
      return None

  def hasPath(self, path):
    """ Checks if path is catalogued """
    return self.getUidForPath(path) is not None

  def getPathForUid(self, uid):
    """ Looks up into catalog table to convert uid into path """
    try:
      if uid is None:
        return None
      # Get the appropriate SQL Method
      method = getattr(self, self.sql_getitem_by_uid)
      search_result = method(uid = uid)
      # If not empty return first record
      if len(search_result) > 0:
        return search_result[0].path
      else:
        return None
    except:
      # This is a real LOG message
      # which is required in order to be able to import .zexp files
      LOG("Warning: could not find path from uid",0,str(uid))
      return None

  def getMetadataForUid(self, uid):
    """ Accesses a single record for a given uid """
    if uid is None:
      return None
    # Get the appropriate SQL Method
    method = getattr(self, self.sql_getitem_by_uid)
    brain = method(uid = uid)[0]
    result = {}
    for k in brain.__record_schema__.keys():
      result[k] = getattr(brain,k)
    return result

  def getIndexDataForUid(self, uid):
    """ Accesses a single record for a given uid """
    return self.getMetadataForUid(uid)

  def getMetadataForPath(self, path):
    """ Accesses a single record for a given path """
    try:
      if uid is None:
        return None
      # Get the appropriate SQL Method
      method = getattr(self, self.sql_getitem_by_path)
      brain = method(path = path)[0]
      result = {}
      for k in brain.__record_schema__.keys():
        result[k] = getattr(brain,k)
      return result
    except:
      # This is a real LOG message
      # which is required in order to be able to import .zexp files
      LOG("Warning: could not find uid from path",0,str(path))
      return None

  def getIndexDataForPath(self, path):
    """ Accesses a single record for a given path """
    return self.getMetadataForPath(path)

521 522
  def buildSQLQuery(self, query_table='catalog', REQUEST=None, **kw):
    """ Builds a complex SQL query to simulate ZCalatog behaviour """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
523 524 525 526 527 528 529 530 531 532 533
    # Get search arguments:
    if REQUEST is None and (kw is None or kw == {}):
      # We try to get the REQUEST parameter
      # since we have nothing handy
      try: REQUEST=self.REQUEST
      except AttributeError: pass

    # If kw is not set, then use REQUEST instead
    if kw is None or kw == {}:
      kw = REQUEST

534
    acceptable_key_map = self.getColumnMap()
535 536 537
    acceptable_keys = acceptable_key_map.keys()
    full_text_search_keys = self.sql_catalog_full_text_search_keys
    keyword_search_keys = self.sql_catalog_keyword_search_keys
538
    topic_search_keys = self.sql_catalog_topic_search_keys
Jean-Paul Smets's avatar
Jean-Paul Smets committed
539
    multivalue_keys = self.sql_catalog_multivalue_keys
540

Jean-Paul Smets's avatar
Jean-Paul Smets committed
541 542
    # We take additional parameters from the REQUEST
    # and give priority to the REQUEST
543
    if REQUEST is not None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
544 545 546 547 548 549
      for key in acceptable_keys:
        if REQUEST.has_key(key):
          # Only copy a few keys from the REQUEST
          if key in self.sql_catalog_request_keys:
            kw[key] = REQUEST[key]

550
    # Let us start building the where_expression
Jean-Paul Smets's avatar
Jean-Paul Smets committed
551
    if kw:
552 553
      where_expression = []
      from_table_dict = {'catalog': 1} # Always include catalog table
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
      # Rebuild keywords to behave as new style query (_usage='toto:titi' becomes {'toto':'titi'})
      new_kw = {}
      usage_len = len('_usage')
      for k, v in kw.items():
        if k.endswith('_usage'):
          new_k = k[0:-usage_len]
          if not new_kw.has_key(new_k): new_kw[new_k] = {}  
          if type(new_kw[new_k]) is not type({}): new_kw[new_k] = {'query': new_kw[new_k]}
          split_v = v.split(':') 
          new_kw[new_k] = {split_v[0]: split_v[1]}
        else:
          if not new_kw.has_key(k):
            new_kw[k] = v
          else:            
            new_kw[k]['query'] = v
      kw = new_kw
      #LOG('new kw', 0, str(kw))
      # We can now consider that old style query is changed into new style
572 573
      for key in kw.keys(): # Do not use kw.items() because this consumes much more memory
        value = kw[key]
574
        if key not in ('where_expression', 'sort-on', 'sort_on', 'sort-order', 'sort_order'):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
575 576
          # Make sure key belongs to schema
          if key in acceptable_keys:
577 578 579 580 581 582 583 584 585 586
            if key.find('.') < 0:
              # if the key is only used by one table, just append its name
              if len(acceptable_key_map[key]) == 1 :
                key = acceptable_key_map[key][0] + '.' + key
              # query_table specifies what table name should be used
              elif query_table:
                key = query_table + '.' + key
              elif key == 'uid':
                # uid is always ambiguous so we can only change it here
                key = 'catalog.uid'
587 588
            # Add table to table dict
            from_table_dict[acceptable_key_map[key][0]] = 1 # We use catalog by default
Jean-Paul Smets's avatar
Jean-Paul Smets committed
589 590 591 592 593 594 595 596
            # Default case: variable equality
            if type(value) is type(''):
              if value != '':
                # we consider empty string as Non Significant
                if value == '=':
                  # But we consider the sign = as empty string
                  value=''
                if '%' in value:
597
                  where_expression += ["%s LIKE '%s'" % (key, value)]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
598
                elif value[0] == '>':
599
                  where_expression += ["%s > '%s'" % (key, value[1:])]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
600
                elif value[0] == '<':
601
                  where_expression += ["%s < '%s'" % (key, value[1:])]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
602 603
                elif key in keyword_search_keys:
                  # We must add % in the request to simulate the catalog
604
                  where_expression += ["%s LIKE '%%%s%%'" % (key, value)]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
605 606
                elif key in full_text_search_keys:
                  # We must add % in the request to simulate the catalog
607
                  where_expression += ["MATCH %s AGAINST ('%s')" % (key, value)]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
608
                else:
609
                  where_expression += ["%s = '%s'" % (key, value)]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
            elif type(value) is type([]) or type(value) is type(()):
              # We have to create an OR from tuple or list
              query_item = []
              for value_item in value:
                if value_item != '':
                  # we consider empty string as Non Significant
                  # also for lists
                  if type(value_item) in (type(1), type(1.0)):
                    query_item += ["%s = %s" % (key, value_item)]
                  else:
                    if '%' in value_item:
                      query_item += ["%s LIKE '%s'" % (key, str(value_item))]
                    elif key in keyword_search_keys:
                      # We must add % in the request to simulate the catalog
                      query_item += ["%s LIKE '%%%s%%'" % (key, str(value_item))]
                    elif key in full_text_search_keys:
                      # We must add % in the request to simulate the catalog
                      query_item +=  ["MATCH %s AGAINST ('%s')" % (key, value)]
                    else:
                      query_item += ["%s = '%s'" % (key, str(value_item))]
              if len(query_item) > 0:
631
                where_expression += ['(%s)' % join(query_item, ' OR ')]
632 633 634 635 636 637 638 639 640 641
            elif type(value) is type({}):
              # We are in the case of a complex query
              query_value = value['query']
              if value.has_key('range'):
                # This is a range
                range_value = value['range']            
                if range_value == 'min':
                  where_expression += ["%s >= '%s'" % (key, query_value)]
                elif range_value == 'max':
                  where_expression += ["%s < '%s'" % (key, query_value)]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
642
            else:
643
              where_expression += ["%s = %s" % (key, value)]
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
          elif key in topic_search_keys: 
            # ERP5 CPS compatibility           
            topic_operator = 'or'
            if type(value) is type({}):          
              topic_operator = value.get('operator', 'or')            
              value = value['query']
            if type(value) is type(''):
              topic_value = [value]
            else:
              topic_value = value # list or tuple
            query_item = []
            for topic_key in topic_value:
              if topic_key in acceptable_keys:
                if topic_key.find('.') < 0:
                  # if the key is only used by one table, just append its name
                  if len(acceptable_key_map[topic_key]) == 1 :
                    topic_key = acceptable_key_map[topic_key][0] + '.' + topic_key
                  # query_table specifies what table name should be used
                  elif query_table:
                    topic_key = query_table + '.' + topic_key
                # Add table to table dict
                from_table_dict[acceptable_key_map[topic_key][0]] = 1 # We use catalog by default              
                query_item += ["%s = 1" % topic_key]
            # Join                              
            if len(query_item) > 0:
              where_expression += ['(%s)' % join(query_item, ' %s ' % topic_operator)]
670
      if kw.get('where_expression'):
671
        if len(where_expression) > 0:
672
          where_expression = "(%s) AND (%s)" % (kw['where_expression'], join(where_expression, ' AND ') )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
673
      else:
674
        where_expression = join(where_expression, ' AND ')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706

    # Compute "sort_index", which is a sort index, or none:
    if kw.has_key('sort-on'):
      sort_index=kw['sort-on']
    elif hasattr(self, 'sort-on'):
      sort_index=getattr(self, 'sort-on')
    elif kw.has_key('sort_on'):
      sort_index=kw['sort_on']
    else: sort_index=None

    # Compute the sort order
    if kw.has_key('sort-order'):
      so=kw['sort-order']
    elif hasattr(self, 'sort-order'):
      so=getattr(self, 'sort-order')
    elif kw.has_key('sort_order'):
      so=kw['sort_order']
    else: so=None

    # We must now turn so into a string
    if type(so) is not type('a'):
      so = 'ascending'

    # We must now turn sort_index into
    # a dict with keys as sort keys and values as sort order
    if type(sort_index) is type('a'):
      sort_index = [(sort_index, so)]
    elif type(sort_index) is not type(()) and type(sort_index) is not type([]):
      sort_index = None

    # If sort_index is a dictionnary
    # then parse it and change it
707
    sort_on = None
Jean-Paul Smets's avatar
Jean-Paul Smets committed
708 709 710 711
    if sort_index is not None:
      try:
        new_sort_index = []
        for (k , v) in sort_index:
Alexandre Boeglin's avatar
Alexandre Boeglin committed
712 713
          if len(acceptable_key_map[k]) == 1 :
            k = acceptable_key_map[k][0] + '.' + k
714 715
          elif query_table:
            k = query_table + '.' + k
Jean-Paul Smets's avatar
Jean-Paul Smets committed
716
          if v == 'descending' or v == 'reverse':
717
            from_table_dict[acceptable_key_map[k][0]] = 1 # We need this table to sort on it
Jean-Paul Smets's avatar
Jean-Paul Smets committed
718 719
            new_sort_index += ['%s DESC' % k]
          else:
720
            from_table_dict[acceptable_key_map[k][0]] = 1 # We need this table to sort on it
Jean-Paul Smets's avatar
Jean-Paul Smets committed
721 722
            new_sort_index += ['%s' % k]
        sort_index = join(new_sort_index,',')
723
        sort_on = str(sort_index)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
724 725 726
      except:
        pass

727 728 729 730 731 732 733 734 735 736 737
    # Use a dictionary at the moment.
    return { 'from_table_list' : from_table_dict.keys(),
             'order_by_expression' : sort_on,
             'where_expression' : where_expression }

  def queryResults(self, sql_method, REQUEST=None, used=None, **kw):
    """ Returns a list of brains from a set of constraints on variables """
    query = self.buildSQLQuery(REQUEST=REQUEST, **kw)
    kw['where_expression'] = query['where_expression']
    kw['sort_on'] = query['order_by_expression']
    kw['from_table_list'] = query['from_table_list']
Jean-Paul Smets's avatar
Jean-Paul Smets committed
738
    # Return the result
739

740 741 742 743
    #LOG('acceptable_keys',0,'acceptable_keys: %s' % str(acceptable_keys))
    #LOG('acceptable_key_map',0,'acceptable_key_map: %s' % str(acceptable_key_map))
    #LOG('queryResults',0,'kw: %s' % str(kw))
    #LOG('queryResults',0,'from_table_list: %s' % str(from_table_dict.keys()))
744
    return sql_method(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
745

746
  def searchResults(self, REQUEST=None, used=None, **kw):
747
    """ Builds a complex SQL where_expression to simulate ZCalatog behaviour """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
748
    """ Returns a list of brains from a set of constraints on variables """
749
    # The used argument is deprecated and is ignored
Jean-Paul Smets's avatar
Jean-Paul Smets committed
750 751
    try:
      # Get the search method
752
      #LOG("searchResults: kw:",0,str(kw))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
753 754 755 756 757 758 759
      method = getattr(self, self.sql_search_results)

      # Return the result
      kw['used'] = used
      kw['REQUEST'] = REQUEST
      return self.queryResults(method, **kw)
    except:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
760
      LOG("Warning: could not search catalog",0,'', error=sys.exc_info())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
761 762 763 764 765
      return []

  __call__ = searchResults

  def countResults(self, REQUEST=None, used=None, **kw):
766 767
    """ Builds a complex SQL where_expression to simulate ZCalatog behaviour """
    """ Returns the number of items which satisfy the where_expression """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
768 769 770 771 772 773 774 775 776 777 778 779
    try:
      # Get the search method
      #LOG("countResults: scr:",0,str(self.sql_count_results))
      #LOG("countResults: used:",0,str(used))
      #LOG("countResults: kw:",0,str(kw))
      method = getattr(self, self.sql_count_results)

      # Return the result
      kw['used'] = used
      kw['REQUEST'] = REQUEST
      return self.queryResults(method, **kw)
    except:
780
      LOG("Warning: could not count catalog",0,str(self.sql_count_results), error=sys.exc_info())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
781 782 783
      return [[0]]

class CatalogError(Exception): pass