DateTimeKey.py 10.4 KB
Newer Older
1
from __future__ import absolute_import
Ivan Tyagov's avatar
Ivan Tyagov committed
2 3
##############################################################################
#
4 5 6 7
# 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
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#
# 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.
#
##############################################################################

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
from zope.interface.verify import verifyClass
39
from Products.ZSQLCatalog.SearchText import parse
Ivan Tyagov's avatar
Ivan Tyagov committed
40

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

43 44 45 46 47 48 49 50 51 52
timezone_dict = _cache._zmap

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

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

53
def castDate(value, change_timezone=True):
54 55
  if value is None:
    return None
56 57 58 59 60 61 62 63 64 65 66 67 68
  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:
69 70 71 72 73 74 75 76 77 78 79
      # This is needed because DateTime(2012) ignores timezone.
      # >>> DateTime()
      # DateTime('2012/01/30 19:06:34.216686 GMT+9')
      # >>> DateTime('2012')
      # DateTime('2012/01/01 00:00:00 GMT+0')
      # Timezone changed from GMT+9 to GMT+0!
      # Then document at "2012/01/01 00:00:00 GMT+9" cannot be found by
      # query of '2012'.
      # Because "2012/01/01 00:00:00 GMT+9" < "2012/01/01 00:00:00 GMT+0".
      if value.isdigit():
        raise DateTimeError
80 81 82
      value = _DateTime(value, **date_kw)
    except DateTimeError:
      delimiter_count = countDelimiters(value)
83
      if delimiter_count is not None and delimiter_count < 2:
84 85 86 87 88 89 90 91 92
        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:
93
    raise TypeError('Unknown date type: %r' % (value,))
94 95 96 97 98 99 100 101
  if change_timezone:
    return value.toZone('UTC')
  else:
    # This is needed. Because if you call toZone('UTC'),
    # 2012/12/01 can become 2012/11/30 and then month
    # is changed! Month must not be changed. Otherwise
    # getMonthLen returns wrong value.
    return value
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117

# (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)]

def countDelimiters(value):
  assert isinstance(value, basestring)
  # Detect if timezone was provided, to avoid counting it as in precision computation.
  split_value = value.split()
118 119
  if not split_value:
    return None
120 121 122 123
  if split_value[-1].lower() in timezone_dict:
    value = ' '.join(split_value[:-1])
  # Count delimiters
  delimiter_count = 0
124
  last_delimiter = None
125 126
  for char in value:
    if char in delimiter_list:
127 128 129 130 131
      if char != last_delimiter:
        delimiter_count += 1
        last_delimiter = char
    else:
      last_delimiter = None
132 133 134
  return delimiter_count

def getPeriodBoundaries(value):
135
  first_date = castDate(value, change_timezone=False)
136 137 138 139 140 141
  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):
142
    raise TypeError('Impossible to guess a precision from a DateTime type.')
143
  else:
144
    raise TypeError('Unknown date type: %r' % (value,))
145 146 147
  delta = delta_list[delimiter_count]
  if callable(delta):
    delta = delta(first_date)
148
  return first_date.toZone('UTC'), (first_date + delta).toZone('UTC')
149 150 151 152 153 154 155 156 157 158 159 160 161 162

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)
163 164
    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})],
165
                        logical_operator=logical_operator))
166 167 168 169
  return query_list

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

171 172
def matchNotWholePeriod(search_key, group, column, value_list, *ignored):
  return wholePeriod(search_key, group, column, value_list, exclude=True)
173

174 175 176 177 178
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 == '=':
179
    query_list = [SimpleQuery(search_key=search_key, comparison_operator='in', group=group, **{column: value_list})]
180
  else:
181
    query_list = [SimpleQuery(search_key=search_key, comparison_operator=comparison_operator, group=group, **{column: x}) for x in value_list]
182
  return query_list
183

184 185
def getNextPeriod(value):
  return getPeriodBoundaries(value)[1]
186

187 188
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)
189

190 191
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)
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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
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
256
  """
257 258 259 260 261
    This SearchKey allows generating date ranges from single, user-input dates.
  """

  default_comparison_operator = None
  get_operator_from_value = True
262

263 264 265
  def parseSearchText(self, value, is_column):
    return parse(value, is_column)

266 267 268 269 270
  def _renderValueAsSearchText(self, value, operator):
    return '"%s"' % (DateTime(value).ISO(), )

  def _buildQuery(self, operator_value_dict, logical_operator, parsed, group):
    column = self.getColumn()
Ivan Tyagov's avatar
Ivan Tyagov committed
271
    query_list = []
272 273
    extend = query_list.extend
    for comparison_operator, value_list in operator_value_dict.iteritems():
274 275 276
      reference_value = value_list[0]
      if isinstance(reference_value, dict):
        reference_value = reference_value['query']
Ivan Tyagov's avatar
Ivan Tyagov committed
277
      try:
278
        if isinstance(reference_value, basestring):
279 280 281
          subquery_list = operator_matcher_dict[comparison_operator](
                   self, group, column, value_list, comparison_operator,
                   logical_operator)
Ivan Tyagov's avatar
Ivan Tyagov committed
282
        else:
283 284
          subquery_list = matchExact(self, group, column, value_list, comparison_operator, logical_operator)
      except DateTimeError:
285
        LOG('DateTimeKey', 100, 'Got an exception while generating a query for %r %r.' % (comparison_operator, value_list), error=True)
Ivan Tyagov's avatar
Ivan Tyagov committed
286
      else:
287 288 289 290 291
        extend(subquery_list)
    return query_list

verifyClass(ISearchKey, DateTimeKey)