2016-03-05 20:05:47 +08:00
|
|
|
from datetime import datetime
|
|
|
|
|
|
|
|
from django.conf import settings
|
2019-01-09 08:21:31 +08:00
|
|
|
from django.db.models.expressions import Func
|
|
|
|
from django.db.models.fields import (
|
|
|
|
DateField, DateTimeField, DurationField, Field, IntegerField, TimeField,
|
2016-03-05 20:05:47 +08:00
|
|
|
)
|
|
|
|
from django.db.models.lookups import (
|
2019-01-09 08:21:31 +08:00
|
|
|
Transform, YearExact, YearGt, YearGte, YearLt, YearLte,
|
2016-03-05 20:05:47 +08:00
|
|
|
)
|
|
|
|
from django.utils import timezone
|
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class TimezoneMixin:
|
2016-03-05 20:05:47 +08:00
|
|
|
tzinfo = None
|
|
|
|
|
|
|
|
def get_tzname(self):
|
|
|
|
# Timezone conversions must happen to the input datetime *before*
|
|
|
|
# applying a function. 2015-12-31 23:00:00 -02:00 is stored in the
|
|
|
|
# database as 2016-01-01 01:00:00 +00:00. Any results should be
|
|
|
|
# based on the input datetime not the stored datetime.
|
|
|
|
tzname = None
|
|
|
|
if settings.USE_TZ:
|
|
|
|
if self.tzinfo is None:
|
|
|
|
tzname = timezone.get_current_timezone_name()
|
|
|
|
else:
|
|
|
|
tzname = timezone._get_timezone_name(self.tzinfo)
|
|
|
|
return tzname
|
|
|
|
|
|
|
|
|
|
|
|
class Extract(TimezoneMixin, Transform):
|
|
|
|
lookup_name = None
|
2017-08-09 01:31:59 +08:00
|
|
|
output_field = IntegerField()
|
2016-03-05 20:05:47 +08:00
|
|
|
|
|
|
|
def __init__(self, expression, lookup_name=None, tzinfo=None, **extra):
|
|
|
|
if self.lookup_name is None:
|
|
|
|
self.lookup_name = lookup_name
|
|
|
|
if self.lookup_name is None:
|
|
|
|
raise ValueError('lookup_name must be provided')
|
|
|
|
self.tzinfo = tzinfo
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(expression, **extra)
|
2016-03-05 20:05:47 +08:00
|
|
|
|
|
|
|
def as_sql(self, compiler, connection):
|
|
|
|
sql, params = compiler.compile(self.lhs)
|
|
|
|
lhs_output_field = self.lhs.output_field
|
|
|
|
if isinstance(lhs_output_field, DateTimeField):
|
|
|
|
tzname = self.get_tzname()
|
2017-02-01 21:48:04 +08:00
|
|
|
sql = connection.ops.datetime_extract_sql(self.lookup_name, sql, tzname)
|
2020-10-05 23:39:53 +08:00
|
|
|
elif self.tzinfo is not None:
|
|
|
|
raise ValueError('tzinfo can only be used with DateTimeField.')
|
2016-03-05 20:05:47 +08:00
|
|
|
elif isinstance(lhs_output_field, DateField):
|
|
|
|
sql = connection.ops.date_extract_sql(self.lookup_name, sql)
|
|
|
|
elif isinstance(lhs_output_field, TimeField):
|
|
|
|
sql = connection.ops.time_extract_sql(self.lookup_name, sql)
|
2016-11-23 23:36:11 +08:00
|
|
|
elif isinstance(lhs_output_field, DurationField):
|
|
|
|
if not connection.features.has_native_duration_field:
|
|
|
|
raise ValueError('Extract requires native DurationField database support.')
|
|
|
|
sql = connection.ops.time_extract_sql(self.lookup_name, sql)
|
2016-03-05 20:05:47 +08:00
|
|
|
else:
|
|
|
|
# resolve_expression has already validated the output_field so this
|
|
|
|
# assert should never be hit.
|
|
|
|
assert False, "Tried to Extract from an invalid type."
|
|
|
|
return sql, params
|
|
|
|
|
|
|
|
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
|
2017-01-21 21:13:44 +08:00
|
|
|
copy = super().resolve_expression(query, allow_joins, reuse, summarize, for_save)
|
2016-03-05 20:05:47 +08:00
|
|
|
field = copy.lhs.output_field
|
2016-11-23 23:36:11 +08:00
|
|
|
if not isinstance(field, (DateField, DateTimeField, TimeField, DurationField)):
|
|
|
|
raise ValueError(
|
|
|
|
'Extract input expression must be DateField, DateTimeField, '
|
|
|
|
'TimeField, or DurationField.'
|
|
|
|
)
|
2016-03-05 20:05:47 +08:00
|
|
|
# Passing dates to functions expecting datetimes is most likely a mistake.
|
|
|
|
if type(field) == DateField and copy.lookup_name in ('hour', 'minute', 'second'):
|
|
|
|
raise ValueError(
|
2021-03-24 18:44:01 +08:00
|
|
|
"Cannot extract time component '%s' from DateField '%s'." % (copy.lookup_name, field.name)
|
2016-03-05 20:05:47 +08:00
|
|
|
)
|
2019-07-12 03:13:36 +08:00
|
|
|
if (
|
|
|
|
isinstance(field, DurationField) and
|
2019-10-01 06:12:19 +08:00
|
|
|
copy.lookup_name in ('year', 'iso_year', 'month', 'week', 'week_day', 'iso_week_day', 'quarter')
|
2019-07-12 03:13:36 +08:00
|
|
|
):
|
|
|
|
raise ValueError(
|
|
|
|
"Cannot extract component '%s' from DurationField '%s'."
|
|
|
|
% (copy.lookup_name, field.name)
|
|
|
|
)
|
2016-03-05 20:05:47 +08:00
|
|
|
return copy
|
|
|
|
|
|
|
|
|
|
|
|
class ExtractYear(Extract):
|
|
|
|
lookup_name = 'year'
|
|
|
|
|
|
|
|
|
2017-09-29 04:28:48 +08:00
|
|
|
class ExtractIsoYear(Extract):
|
|
|
|
"""Return the ISO-8601 week-numbering year."""
|
|
|
|
lookup_name = 'iso_year'
|
|
|
|
|
|
|
|
|
2016-03-05 20:05:47 +08:00
|
|
|
class ExtractMonth(Extract):
|
|
|
|
lookup_name = 'month'
|
|
|
|
|
|
|
|
|
|
|
|
class ExtractDay(Extract):
|
|
|
|
lookup_name = 'day'
|
|
|
|
|
|
|
|
|
2016-11-11 21:01:40 +08:00
|
|
|
class ExtractWeek(Extract):
|
|
|
|
"""
|
|
|
|
Return 1-52 or 53, based on ISO-8601, i.e., Monday is the first of the
|
|
|
|
week.
|
|
|
|
"""
|
|
|
|
lookup_name = 'week'
|
|
|
|
|
|
|
|
|
2016-03-05 20:05:47 +08:00
|
|
|
class ExtractWeekDay(Extract):
|
|
|
|
"""
|
|
|
|
Return Sunday=1 through Saturday=7.
|
|
|
|
|
|
|
|
To replicate this in Python: (mydatetime.isoweekday() % 7) + 1
|
|
|
|
"""
|
|
|
|
lookup_name = 'week_day'
|
|
|
|
|
|
|
|
|
2019-10-01 06:12:19 +08:00
|
|
|
class ExtractIsoWeekDay(Extract):
|
|
|
|
"""Return Monday=1 through Sunday=7, based on ISO-8601."""
|
|
|
|
lookup_name = 'iso_week_day'
|
|
|
|
|
|
|
|
|
2017-06-09 03:15:29 +08:00
|
|
|
class ExtractQuarter(Extract):
|
|
|
|
lookup_name = 'quarter'
|
|
|
|
|
|
|
|
|
2016-03-05 20:05:47 +08:00
|
|
|
class ExtractHour(Extract):
|
|
|
|
lookup_name = 'hour'
|
|
|
|
|
|
|
|
|
|
|
|
class ExtractMinute(Extract):
|
|
|
|
lookup_name = 'minute'
|
|
|
|
|
|
|
|
|
|
|
|
class ExtractSecond(Extract):
|
|
|
|
lookup_name = 'second'
|
|
|
|
|
|
|
|
|
|
|
|
DateField.register_lookup(ExtractYear)
|
|
|
|
DateField.register_lookup(ExtractMonth)
|
|
|
|
DateField.register_lookup(ExtractDay)
|
|
|
|
DateField.register_lookup(ExtractWeekDay)
|
2019-10-01 06:12:19 +08:00
|
|
|
DateField.register_lookup(ExtractIsoWeekDay)
|
2016-11-11 21:01:40 +08:00
|
|
|
DateField.register_lookup(ExtractWeek)
|
2017-09-29 04:28:48 +08:00
|
|
|
DateField.register_lookup(ExtractIsoYear)
|
2017-06-09 03:15:29 +08:00
|
|
|
DateField.register_lookup(ExtractQuarter)
|
2016-03-05 20:05:47 +08:00
|
|
|
|
|
|
|
TimeField.register_lookup(ExtractHour)
|
|
|
|
TimeField.register_lookup(ExtractMinute)
|
|
|
|
TimeField.register_lookup(ExtractSecond)
|
|
|
|
|
|
|
|
DateTimeField.register_lookup(ExtractHour)
|
|
|
|
DateTimeField.register_lookup(ExtractMinute)
|
|
|
|
DateTimeField.register_lookup(ExtractSecond)
|
|
|
|
|
|
|
|
ExtractYear.register_lookup(YearExact)
|
|
|
|
ExtractYear.register_lookup(YearGt)
|
|
|
|
ExtractYear.register_lookup(YearGte)
|
|
|
|
ExtractYear.register_lookup(YearLt)
|
|
|
|
ExtractYear.register_lookup(YearLte)
|
|
|
|
|
2017-09-29 04:28:48 +08:00
|
|
|
ExtractIsoYear.register_lookup(YearExact)
|
|
|
|
ExtractIsoYear.register_lookup(YearGt)
|
|
|
|
ExtractIsoYear.register_lookup(YearGte)
|
|
|
|
ExtractIsoYear.register_lookup(YearLt)
|
|
|
|
ExtractIsoYear.register_lookup(YearLte)
|
|
|
|
|
2016-03-05 20:05:47 +08:00
|
|
|
|
2017-10-14 03:23:00 +08:00
|
|
|
class Now(Func):
|
|
|
|
template = 'CURRENT_TIMESTAMP'
|
2019-01-09 08:21:31 +08:00
|
|
|
output_field = DateTimeField()
|
2017-10-14 03:23:00 +08:00
|
|
|
|
2018-02-08 15:09:00 +08:00
|
|
|
def as_postgresql(self, compiler, connection, **extra_context):
|
2017-10-14 03:23:00 +08:00
|
|
|
# PostgreSQL's CURRENT_TIMESTAMP means "the time at the start of the
|
|
|
|
# transaction". Use STATEMENT_TIMESTAMP to be cross-compatible with
|
|
|
|
# other databases.
|
2018-02-08 15:09:00 +08:00
|
|
|
return self.as_sql(compiler, connection, template='STATEMENT_TIMESTAMP()', **extra_context)
|
2017-10-14 03:23:00 +08:00
|
|
|
|
|
|
|
|
2016-03-05 20:05:47 +08:00
|
|
|
class TruncBase(TimezoneMixin, Transform):
|
|
|
|
kind = None
|
|
|
|
tzinfo = None
|
|
|
|
|
2019-03-07 23:02:18 +08:00
|
|
|
def __init__(self, expression, output_field=None, tzinfo=None, is_dst=None, **extra):
|
2016-03-05 20:05:47 +08:00
|
|
|
self.tzinfo = tzinfo
|
2019-03-07 23:02:18 +08:00
|
|
|
self.is_dst = is_dst
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(expression, output_field=output_field, **extra)
|
2016-03-05 20:05:47 +08:00
|
|
|
|
|
|
|
def as_sql(self, compiler, connection):
|
|
|
|
inner_sql, inner_params = compiler.compile(self.lhs)
|
2020-10-05 01:28:21 +08:00
|
|
|
tzname = None
|
|
|
|
if isinstance(self.lhs.output_field, DateTimeField):
|
2016-03-05 20:05:47 +08:00
|
|
|
tzname = self.get_tzname()
|
2020-10-05 01:28:21 +08:00
|
|
|
elif self.tzinfo is not None:
|
|
|
|
raise ValueError('tzinfo can only be used with DateTimeField.')
|
|
|
|
if isinstance(self.output_field, DateTimeField):
|
2017-02-01 21:48:04 +08:00
|
|
|
sql = connection.ops.datetime_trunc_sql(self.kind, inner_sql, tzname)
|
2016-03-05 20:05:47 +08:00
|
|
|
elif isinstance(self.output_field, DateField):
|
2020-10-05 01:28:21 +08:00
|
|
|
sql = connection.ops.date_trunc_sql(self.kind, inner_sql, tzname)
|
2016-06-19 11:38:24 +08:00
|
|
|
elif isinstance(self.output_field, TimeField):
|
2020-10-05 01:28:21 +08:00
|
|
|
sql = connection.ops.time_trunc_sql(self.kind, inner_sql, tzname)
|
2016-03-05 20:05:47 +08:00
|
|
|
else:
|
2016-06-19 11:38:24 +08:00
|
|
|
raise ValueError('Trunc only valid on DateField, TimeField, or DateTimeField.')
|
2017-02-01 21:48:04 +08:00
|
|
|
return sql, inner_params
|
2016-03-05 20:05:47 +08:00
|
|
|
|
|
|
|
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
|
2017-01-21 21:13:44 +08:00
|
|
|
copy = super().resolve_expression(query, allow_joins, reuse, summarize, for_save)
|
2016-03-05 20:05:47 +08:00
|
|
|
field = copy.lhs.output_field
|
|
|
|
# DateTimeField is a subclass of DateField so this works for both.
|
2016-06-19 11:38:24 +08:00
|
|
|
assert isinstance(field, (DateField, TimeField)), (
|
|
|
|
"%r isn't a DateField, TimeField, or DateTimeField." % field.name
|
2016-03-05 20:05:47 +08:00
|
|
|
)
|
|
|
|
# If self.output_field was None, then accessing the field will trigger
|
|
|
|
# the resolver to assign it to self.lhs.output_field.
|
2016-06-19 11:38:24 +08:00
|
|
|
if not isinstance(copy.output_field, (DateField, DateTimeField, TimeField)):
|
|
|
|
raise ValueError('output_field must be either DateField, TimeField, or DateTimeField')
|
|
|
|
# Passing dates or times to functions expecting datetimes is most
|
|
|
|
# likely a mistake.
|
2017-08-09 01:31:59 +08:00
|
|
|
class_output_field = self.__class__.output_field if isinstance(self.__class__.output_field, Field) else None
|
|
|
|
output_field = class_output_field or copy.output_field
|
|
|
|
has_explicit_output_field = class_output_field or field.__class__ is not copy.output_field.__class__
|
2016-03-05 20:05:47 +08:00
|
|
|
if type(field) == DateField and (
|
2016-06-19 11:38:24 +08:00
|
|
|
isinstance(output_field, DateTimeField) or copy.kind in ('hour', 'minute', 'second', 'time')):
|
2021-03-24 18:44:01 +08:00
|
|
|
raise ValueError("Cannot truncate DateField '%s' to %s." % (
|
2017-08-09 01:31:59 +08:00
|
|
|
field.name, output_field.__class__.__name__ if has_explicit_output_field else 'DateTimeField'
|
2016-06-19 11:38:24 +08:00
|
|
|
))
|
|
|
|
elif isinstance(field, TimeField) and (
|
2017-09-29 04:39:03 +08:00
|
|
|
isinstance(output_field, DateTimeField) or
|
|
|
|
copy.kind in ('year', 'quarter', 'month', 'week', 'day', 'date')):
|
2021-03-24 18:44:01 +08:00
|
|
|
raise ValueError("Cannot truncate TimeField '%s' to %s." % (
|
2017-08-09 01:31:59 +08:00
|
|
|
field.name, output_field.__class__.__name__ if has_explicit_output_field else 'DateTimeField'
|
2016-06-19 11:38:24 +08:00
|
|
|
))
|
2016-03-05 20:05:47 +08:00
|
|
|
return copy
|
|
|
|
|
2017-07-07 01:18:05 +08:00
|
|
|
def convert_value(self, value, expression, connection):
|
2016-03-05 20:05:47 +08:00
|
|
|
if isinstance(self.output_field, DateTimeField):
|
2018-07-01 04:49:20 +08:00
|
|
|
if not settings.USE_TZ:
|
|
|
|
pass
|
|
|
|
elif value is not None:
|
2016-03-05 20:05:47 +08:00
|
|
|
value = value.replace(tzinfo=None)
|
2019-03-07 23:02:18 +08:00
|
|
|
value = timezone.make_aware(value, self.tzinfo, is_dst=self.is_dst)
|
2018-07-01 04:49:20 +08:00
|
|
|
elif not connection.features.has_zoneinfo_database:
|
|
|
|
raise ValueError(
|
|
|
|
'Database returned an invalid datetime value. Are time '
|
|
|
|
'zone definitions for your database installed?'
|
|
|
|
)
|
2016-03-05 20:05:47 +08:00
|
|
|
elif isinstance(value, datetime):
|
2018-07-01 04:49:20 +08:00
|
|
|
if value is None:
|
|
|
|
pass
|
|
|
|
elif isinstance(self.output_field, DateField):
|
2016-06-19 11:38:24 +08:00
|
|
|
value = value.date()
|
|
|
|
elif isinstance(self.output_field, TimeField):
|
|
|
|
value = value.time()
|
2016-03-05 20:05:47 +08:00
|
|
|
return value
|
|
|
|
|
|
|
|
|
|
|
|
class Trunc(TruncBase):
|
|
|
|
|
2019-03-07 23:02:18 +08:00
|
|
|
def __init__(self, expression, kind, output_field=None, tzinfo=None, is_dst=None, **extra):
|
2016-03-05 20:05:47 +08:00
|
|
|
self.kind = kind
|
2019-03-07 23:02:18 +08:00
|
|
|
super().__init__(
|
|
|
|
expression, output_field=output_field, tzinfo=tzinfo,
|
|
|
|
is_dst=is_dst, **extra
|
|
|
|
)
|
2016-03-05 20:05:47 +08:00
|
|
|
|
|
|
|
|
|
|
|
class TruncYear(TruncBase):
|
|
|
|
kind = 'year'
|
|
|
|
|
|
|
|
|
2017-06-09 03:15:29 +08:00
|
|
|
class TruncQuarter(TruncBase):
|
|
|
|
kind = 'quarter'
|
|
|
|
|
|
|
|
|
2016-03-05 20:05:47 +08:00
|
|
|
class TruncMonth(TruncBase):
|
|
|
|
kind = 'month'
|
|
|
|
|
|
|
|
|
2017-09-29 04:39:03 +08:00
|
|
|
class TruncWeek(TruncBase):
|
|
|
|
"""Truncate to midnight on the Monday of the week."""
|
|
|
|
kind = 'week'
|
|
|
|
|
|
|
|
|
2016-03-05 20:05:47 +08:00
|
|
|
class TruncDay(TruncBase):
|
|
|
|
kind = 'day'
|
|
|
|
|
|
|
|
|
|
|
|
class TruncDate(TruncBase):
|
2016-06-19 11:38:24 +08:00
|
|
|
kind = 'date'
|
2016-03-05 20:05:47 +08:00
|
|
|
lookup_name = 'date'
|
2017-08-09 01:31:59 +08:00
|
|
|
output_field = DateField()
|
2016-03-05 20:05:47 +08:00
|
|
|
|
|
|
|
def as_sql(self, compiler, connection):
|
|
|
|
# Cast to date rather than truncate to date.
|
|
|
|
lhs, lhs_params = compiler.compile(self.lhs)
|
2020-08-30 02:40:54 +08:00
|
|
|
tzname = self.get_tzname()
|
2017-02-01 21:48:04 +08:00
|
|
|
sql = connection.ops.datetime_cast_date_sql(lhs, tzname)
|
2016-03-05 20:05:47 +08:00
|
|
|
return sql, lhs_params
|
|
|
|
|
|
|
|
|
2016-06-19 11:39:26 +08:00
|
|
|
class TruncTime(TruncBase):
|
|
|
|
kind = 'time'
|
|
|
|
lookup_name = 'time'
|
2017-08-09 01:31:59 +08:00
|
|
|
output_field = TimeField()
|
2016-06-19 11:39:26 +08:00
|
|
|
|
|
|
|
def as_sql(self, compiler, connection):
|
2019-01-14 05:58:48 +08:00
|
|
|
# Cast to time rather than truncate to time.
|
2016-06-19 11:39:26 +08:00
|
|
|
lhs, lhs_params = compiler.compile(self.lhs)
|
2020-08-30 02:40:54 +08:00
|
|
|
tzname = self.get_tzname()
|
2017-02-01 21:48:04 +08:00
|
|
|
sql = connection.ops.datetime_cast_time_sql(lhs, tzname)
|
2016-06-19 11:39:26 +08:00
|
|
|
return sql, lhs_params
|
|
|
|
|
|
|
|
|
2016-03-05 20:05:47 +08:00
|
|
|
class TruncHour(TruncBase):
|
|
|
|
kind = 'hour'
|
|
|
|
|
|
|
|
|
|
|
|
class TruncMinute(TruncBase):
|
|
|
|
kind = 'minute'
|
|
|
|
|
|
|
|
|
|
|
|
class TruncSecond(TruncBase):
|
|
|
|
kind = 'second'
|
|
|
|
|
|
|
|
|
|
|
|
DateTimeField.register_lookup(TruncDate)
|
2016-06-19 11:39:26 +08:00
|
|
|
DateTimeField.register_lookup(TruncTime)
|