DateTimeKey.py 9.46 KB
Newer Older
Ivan Tyagov's avatar
Ivan Tyagov committed
1 2
##############################################################################
#
3 4 5 6
# Copyright (c) 2002-2006 Nexedi SARL and Contributors. All Rights Reserved.
# Copyright (c) 2007-2009 Nexedi SA and Contributors. All Rights Reserved.
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
#                    Vincent Pelletier <vincent@nexedi.com>
Ivan Tyagov's avatar
Ivan Tyagov committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

31
import sys
32
from SearchKey import SearchKey
33 34 35 36
from Products.ZSQLCatalog.Query.SimpleQuery import SimpleQuery
from Products.ZSQLCatalog.Query.ComplexQuery import ComplexQuery
from zLOG import LOG
from DateTime.DateTime import DateTime, DateTimeError, _cache
37
from Products.ZSQLCatalog.interfaces.search_key import ISearchKey
38 39
from Interface.Verify import verifyClass
from Products.ZSQLCatalog.SQLCatalog import profiler_decorator
40
from Products.ZSQLCatalog.SearchText import parse
Ivan Tyagov's avatar
Ivan Tyagov committed
41

42
MARKER = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
43

44 45 46 47 48 49 50 51 52 53 54 55 56
timezone_dict = _cache._zmap

date_completion_format_dict = {
  None: ['01/01/%s', '01/%s'],
  'international': ['%s/01/01', '%s/01']
}

@profiler_decorator
def _DateTime(*args, **kw):
  return DateTime(*args, **kw)

@profiler_decorator
def castDate(value):
57 58
  if value is None:
    return None
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
  date_kw = {'datefmt': 'international'}
  if isinstance(value, dict):
    # Convert value into a DateTime, and guess desired delta from what user
    # input.
    assert value['type'] == 'date'
    format = value.get('format')
    value = value['query']
    if format == '%m/%d/%Y':
      date_kw.pop('datefmt')
  if isinstance(value, DateTime):
    pass
  elif isinstance(value, basestring):
    try:
      value = _DateTime(value, **date_kw)
    except DateTimeError:
      delimiter_count = countDelimiters(value)
      if delimiter_count < 3:
        split_value = value.split()
        if split_value[-1].lower() in timezone_dict:
          value = '%s %s' % (date_completion_format_dict[date_kw.get('datefmt')][delimiter_count] % (' '.join(split_value[:-1]), ), split_value[-1])
        else:
          value = date_completion_format_dict[date_kw.get('datefmt')][delimiter_count] % (value, )
        value = _DateTime(value, **date_kw)
      else:
        raise
  else:
    raise TypeError, 'Unknown date type: %r' % (value)
  return value.toZone('UTC')

# (strongly) inspired from DateTime.DateTime.py
delimiter_list = ' -/.:,+'

def getMonthLen(datetime):
  return datetime._month_len[datetime.isLeapYear()][datetime.month()]

def getYearLen(datetime):
  return 365 + datetime.isLeapYear()

delta_list = [getYearLen, getMonthLen, 1, 1.0 / 24, 1.0 / (24 * 60), 1.0 / (24 * 60 * 60)]

@profiler_decorator
def countDelimiters(value):
  assert isinstance(value, basestring)
  # Detect if timezone was provided, to avoid counting it as in precision computation.
  split_value = value.split()
  if split_value[-1].lower() in timezone_dict:
    value = ' '.join(split_value[:-1])
  # Count delimiters
  delimiter_count = 0
  for char in value:
    if char in delimiter_list:
      delimiter_count += 1
  return delimiter_count

@profiler_decorator
def getPeriodBoundaries(value):
  first_date = castDate(value)
  if isinstance(value, dict):
    value = value['query']
  # Try to guess how much was given in query.
  if isinstance(value, basestring):
    delimiter_count = countDelimiters(value)
  elif isinstance(value, DateTime):
    raise TypeError, 'Impossible to guess a precision from a DateTime type.'
  else:
    raise TypeError, 'Unknown date type: %r' % (value)
  delta = delta_list[delimiter_count]
  if callable(delta):
    delta = delta(first_date)
  return first_date, first_date + delta

@profiler_decorator
def wholePeriod(search_key, group, column, value_list, exclude=False):
  if exclude:
    first_operator = '<'
    second_operator = '>='
    logical_operator = 'or'
  else:
    first_operator = '>='
    second_operator = '<'
    logical_operator = 'and'
  query_list = []
  append = query_list.append
  for value in value_list:
    first_date, second_date = getPeriodBoundaries(value)
144 145
    append(ComplexQuery([SimpleQuery(search_key=search_key, comparison_operator=first_operator, group=group, **{column: first_date}),
                         SimpleQuery(search_key=search_key, comparison_operator=second_operator, group=group, **{column: second_date})],
146 147 148 149 150
                        operator=logical_operator))
  return query_list

def matchWholePeriod(search_key, group, column, value_list, *ignored):
  return wholePeriod(search_key, group, column, value_list)
151

152 153
def matchNotWholePeriod(search_key, group, column, value_list, *ignored):
  return wholePeriod(search_key, group, column, value_list, exclude=True)
154

155 156 157 158 159 160
@profiler_decorator
def matchExact(search_key, group, column, value_list, comparison_operator, logical_operator):
  if comparison_operator is None:
    comparison_operator = '='
  value_list = [castDate(x) for x in value_list]
  if logical_operator == 'or' and comparison_operator == '=':
161
    query_list = [SimpleQuery(search_key=search_key, comparison_operator='in', group=group, **{column: value_list})]
162
  else:
163
    query_list = [SimpleQuery(search_key=search_key, comparison_operator=comparison_operator, group=group, **{column: x}) for x in value_list]
164
  return query_list
165

166 167
def getNextPeriod(value):
  return getPeriodBoundaries(value)[1]
168

169 170 171
@profiler_decorator
def matchBeforeNextPeriod(search_key, group, column, value_list, comparison_operator, logical_operator):
  return matchExact(search_key, group, column, [getNextPeriod(x) for x in value_list], '<', logical_operator)
172

173 174 175
@profiler_decorator
def matchAfterPeriod(search_key, group, column, value_list, comparison_operator, logical_operator):
  return matchExact(search_key, group, column, [getNextPeriod(x) for x in value_list], '>=', logical_operator)
176

177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
operator_matcher_dict = {
  None: matchWholePeriod,
  '=': matchWholePeriod,
  '!=': matchNotWholePeriod,
  '<': matchExact,
  '>=': matchExact,
  '<=': matchBeforeNextPeriod,
  '>': matchAfterPeriod,
}

# Behaviour of date time operators
# Objects:
#   2005/03/14 23:59:59
#   2005/03/15 00:00:00
#   2005/03/15 00:00:01
#   2005/03/15 23:59:59
#   2005/03/16 00:00:00
#   2005/03/16 00:00:01
#
# Searches:
#   "2005/03/15" (operator = None)
#     Implicitely matches the whole period.
#     2005/03/15 00:00:00
#     2005/03/15 00:00:01
#     2005/03/15 23:59:59
#
#   "=2005/03/15" (operator = '=')
#     Behaves the same way as None operator.
#     2005/03/15 00:00:00
#     2005/03/15 00:00:01
#     2005/03/15 23:59:59
#
#   "!=2005/03/15" (operator = '!=')
#     Complementary of '=' operator.
#     2005/03/14 23:59:59
#     2005/03/16 00:00:00
#     2005/03/16 00:00:01
#
#   "<2005/03/15" (operator = '<')
#     Non-ambiguous (no difference wether time is considered as a period or a single point in time).
#     2005/03/14 23:59:59
#
#   ">=2005/03/15" (operator = '>=')
#     Complementary of '<' operator, and also non-ambiguous.
#     2005/03/15 00:00:00
#     2005/03/15 00:00:01
#     2005/03/15 23:59:59
#     2005/03/16 00:00:00
#     2005/03/16 00:00:01
#
#   "<=2005/03/15" (operator = '<=')
#     Union of results from '=' and '<' operators.
#     2005/03/14 23:59:59
#     2005/03/15 00:00:00
#     2005/03/15 00:00:01
#     2005/03/15 23:59:59
#
#   ">2005/03/15" (operator = '>')
#     Complementary of '<=' operator.
#     2005/03/16 00:00:00
#     2005/03/16 00:00:01

class DateTimeKey(SearchKey):
Ivan Tyagov's avatar
Ivan Tyagov committed
240
  """
241 242 243 244 245
    This SearchKey allows generating date ranges from single, user-input dates.
  """

  default_comparison_operator = None
  get_operator_from_value = True
246

247 248 249
  def parseSearchText(self, value, is_column):
    return parse(value, is_column)

250 251 252 253 254 255
  def _renderValueAsSearchText(self, value, operator):
    return '"%s"' % (DateTime(value).ISO(), )

  @profiler_decorator
  def _buildQuery(self, operator_value_dict, logical_operator, parsed, group):
    column = self.getColumn()
Ivan Tyagov's avatar
Ivan Tyagov committed
256
    query_list = []
257 258
    extend = query_list.extend
    for comparison_operator, value_list in operator_value_dict.iteritems():
Ivan Tyagov's avatar
Ivan Tyagov committed
259
      try:
260 261 262 263
        if parsed:
          subquery_list = operator_matcher_dict[comparison_operator](
                   self, group, column, value_list, comparison_operator,
                   logical_operator)
Ivan Tyagov's avatar
Ivan Tyagov committed
264
        else:
265 266 267
          subquery_list = matchExact(self, group, column, value_list, comparison_operator, logical_operator)
      except DateTimeError:
        LOG('DateTimeKey', 100, 'Got an exception while generating a query for %r %r.' % (comparison_operator, value_list), error=sys.exc_info())
Ivan Tyagov's avatar
Ivan Tyagov committed
268
      else:
269 270 271 272 273
        extend(subquery_list)
    return query_list

verifyClass(ISearchKey, DateTimeKey)