Files
tryton/trytond/model/fields/date.py
T

201 lines
6.6 KiB
Python
Raw Normal View History

2014-12-02 12:54:01 +01:00
# This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
2013-09-06 22:32:37 +02:00
import datetime
2019-06-26 21:56:16 +02:00
2018-04-30 14:59:01 +02:00
from sql.functions import Function
2009-02-03 18:58:25 +01:00
2019-02-13 10:37:40 +01:00
from trytond.pyson import PYSONEncoder
2018-04-30 14:59:01 +02:00
from ... import backend
from .field import Field
2009-02-03 18:58:25 +01:00
2018-04-30 14:59:01 +02:00
class SQLite_Date(Function):
__slots__ = ()
_function = 'DATE'
class SQLite_DateTime(Function):
__slots__ = ()
_function = 'DATETIME'
class SQLite_Time(Function):
__slots__ = ()
_function = 'TIME'
2009-02-03 18:58:25 +01:00
class Date(Field):
2009-03-01 13:37:31 +01:00
'''
2009-09-13 15:37:11 +02:00
Define a date field (``date``).
2009-03-01 13:37:31 +01:00
'''
2009-02-03 18:58:25 +01:00
_type = 'date'
_sql_type = 'DATE'
2019-06-26 21:56:16 +02:00
_py_type = datetime.date
2009-02-03 18:58:25 +01:00
def sql_format(self, value):
2018-06-26 19:11:19 +02:00
if isinstance(value, str):
year, month, day = list(map(int, value.split("-", 2)))
2019-06-26 21:56:16 +02:00
value = datetime.date(year, month, day)
elif isinstance(value, datetime.datetime):
if value.time() != datetime.time():
raise ValueError("Date field can not have time")
return super().sql_format(value)
2013-09-06 22:32:37 +02:00
2018-04-30 14:59:01 +02:00
def sql_cast(self, expression):
if backend.name() == 'sqlite':
return SQLite_Date(expression)
return super(Date, self).sql_cast(expression)
2009-02-03 18:58:25 +01:00
2019-02-13 10:37:40 +01:00
class FormatMixin(Field):
def definition(self, model, language):
encoder = PYSONEncoder()
definition = super().definition(model, language)
definition['format'] = encoder.encode(self.format)
return definition
class Timestamp(FormatMixin, Field):
2013-09-06 22:32:37 +02:00
'''
Define a timestamp field (``datetime``).
'''
_type = 'timestamp'
_sql_type = 'TIMESTAMP'
2019-06-26 21:56:16 +02:00
_py_type = datetime.datetime
2018-08-01 11:37:09 +02:00
format = '%H:%M:%S.%f'
2013-09-06 22:32:37 +02:00
def sql_format(self, value):
2018-06-26 19:11:19 +02:00
if isinstance(value, str):
2013-09-06 22:32:37 +02:00
datepart, timepart = value.split(" ")
year, month, day = map(int, datepart.split("-", 2))
timepart_full = timepart.split(".", 1)
hours, minutes, seconds = map(int, timepart_full[0].split(":"))
if len(timepart_full) == 2:
microseconds = int(timepart_full[1])
else:
microseconds = 0
2019-06-26 21:56:16 +02:00
value = datetime.datetime(
year, month, day, hours, minutes, seconds, microseconds)
return super().sql_format(value)
2013-09-06 22:32:37 +02:00
def sql_cast(self, expression):
if backend.name() == 'sqlite':
return SQLite_DateTime(expression)
2019-02-13 12:30:05 +01:00
return super().sql_cast(expression)
class DateTime(Timestamp):
'''
Define a datetime field (``datetime``).
'''
_type = 'datetime'
_sql_type = 'DATETIME'
def __init__(self, string='', format='%H:%M:%S', help='', required=False,
readonly=False, domain=None, states=None, select=False,
on_change=None, on_change_with=None, depends=None,
context=None, loading='eager'):
'''
:param format: The validation format as used by strftime.
'''
super(DateTime, self).__init__(string=string, help=help,
required=required, readonly=readonly, domain=domain, states=states,
select=select, on_change=on_change, on_change_with=on_change_with,
depends=depends, context=context, loading=loading)
self.format = format
__init__.__doc__ += Field.__init__.__doc__
def sql_format(self, value):
value = super().sql_format(value)
2019-06-26 21:56:16 +02:00
if isinstance(value, datetime.datetime):
value = value.replace(microsecond=0)
return value
2012-05-16 13:04:36 +02:00
2019-06-26 21:56:16 +02:00
class Time(FormatMixin, Field):
2009-03-01 13:37:31 +01:00
'''
2009-09-13 15:37:11 +02:00
Define a time field (``time``).
2009-03-01 13:37:31 +01:00
'''
2009-02-03 18:58:25 +01:00
_type = 'time'
_sql_type = 'TIME'
2019-06-26 21:56:16 +02:00
_py_type = datetime.time
def __init__(self, string='', format='%H:%M:%S', help='', required=False,
readonly=False, domain=None, states=None, select=False,
on_change=None, on_change_with=None, depends=None,
context=None, loading='eager'):
'''
:param format: The validation format as used by strftime.
'''
super().__init__(string=string, help=help,
required=required, readonly=readonly, domain=domain, states=states,
select=select, on_change=on_change, on_change_with=on_change_with,
depends=depends, context=context, loading=loading)
self.format = format
2013-09-06 22:32:37 +02:00
def sql_format(self, value):
2018-06-26 19:11:19 +02:00
if isinstance(value, str):
2013-09-06 22:32:37 +02:00
hours, minutes, seconds = map(int, value.split(":"))
2019-06-26 21:56:16 +02:00
value = datetime.time(hours, minutes, seconds)
value = super().sql_format(value)
if isinstance(value, datetime.time):
value = value.replace(microsecond=0)
return value
2013-09-06 22:32:37 +02:00
2018-04-30 14:59:01 +02:00
def sql_cast(self, expression):
if backend.name() == 'sqlite':
return SQLite_Time(expression)
return super(Time, self).sql_cast(expression)
2015-02-09 22:58:56 +01:00
class TimeDelta(Field):
'''
Define a timedelta field (``timedelta``).
'''
_type = 'timedelta'
_sql_type = 'INTERVAL'
2019-06-26 21:56:16 +02:00
_py_type = datetime.timedelta
2015-02-09 22:58:56 +01:00
def __init__(self, string='', converter=None, help='', required=False,
readonly=False, domain=None, states=None, select=False,
on_change=None, on_change_with=None, depends=None,
context=None, loading='eager'):
'''
:param converter: The name of the context key containing
the time converter.
'''
super(TimeDelta, self).__init__(string=string, help=help,
required=required, readonly=readonly, domain=domain, states=states,
select=select, on_change=on_change, on_change_with=on_change_with,
depends=depends, context=context, loading=loading)
self.converter = converter
def sql_format(self, value):
2019-06-26 21:56:16 +02:00
if isinstance(value, (int, float)):
raise TypeError("TimeDelta requires a timedelta")
return super().sql_format(value)
2015-02-19 13:45:57 +01:00
@classmethod
def get(cls, ids, model, name, values=None):
result = {}
for row in values:
value = row[name]
if (value is not None
and not isinstance(value, datetime.timedelta)):
if value >= datetime.timedelta.max.total_seconds():
value = datetime.timedelta.max
elif value <= datetime.timedelta.min.total_seconds():
value = datetime.timedelta.min
else:
value = datetime.timedelta(seconds=value)
result[row['id']] = value
else:
result[row['id']] = value
return result
2019-02-13 10:37:40 +01:00
def definition(self, model, language):
definition = super().definition(model, language)
definition['converter'] = self.converter
return definition