From: Daniele Varrazzo Date: Fri, 14 May 2021 16:19:32 +0000 (+0200) Subject: Warn only once about unknown zoneinfo X-Git-Tag: 3.0.dev0~42^2~14 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=e070e46046a1f0092578c2c0d37dbf2649411284;p=thirdparty%2Fpsycopg.git Warn only once about unknown zoneinfo --- diff --git a/psycopg3/psycopg3/connection.py b/psycopg3/psycopg3/connection.py index 7ba7595da..c4bd0a9c2 100644 --- a/psycopg3/psycopg3/connection.py +++ b/psycopg3/psycopg3/connection.py @@ -9,7 +9,7 @@ import logging import warnings import threading from types import TracebackType -from typing import Any, AsyncIterator, Callable, Generic, Iterator, List +from typing import Any, AsyncIterator, Dict, Callable, Generic, Iterator, List from typing import NamedTuple, Optional, Type, TypeVar, Union from typing import overload, TYPE_CHECKING from weakref import ref, ReferenceType @@ -59,7 +59,7 @@ else: connect = generators.connect execute = generators.execute -_UTC = ZoneInfo("UTC") +_timezones: Dict[Union[None, bytes], ZoneInfo] = {} class Notify(NamedTuple): @@ -225,17 +225,20 @@ class BaseConnection(AdaptContext, Generic[Row]): def timezone(self) -> ZoneInfo: """The Python timezone info of the connection's timezone.""" tzname = self.pgconn.parameter_status(b"TimeZone") - if tzname: + try: + return _timezones[tzname] + except KeyError: + sname = tzname.decode("utf8") if tzname else "UTC" try: - return ZoneInfo(tzname.decode("utf8")) + zi = ZoneInfo(sname) except KeyError: logger.warning( - "unknown PostgreSQL timezone: %r will use UTC", - tzname.decode("utf8"), + "unknown PostgreSQL timezone: %r will use UTC", sname ) - return _UTC - else: - return _UTC + zi = ZoneInfo("UTC") + + _timezones[tzname] = zi + return zi @property def info(self) -> ConnectionInfo: diff --git a/psycopg3/psycopg3/types/date.py b/psycopg3/psycopg3/types/date.py index 892a14227..844a8bef9 100644 --- a/psycopg3/psycopg3/types/date.py +++ b/psycopg3/psycopg3/types/date.py @@ -41,8 +41,6 @@ _pg_datetime_epoch = datetime(2000, 1, 1) _pg_datetimetz_epoch = datetime(2000, 1, 1, tzinfo=timezone.utc) _py_date_min_days = date.min.toordinal() -_UTC = ZoneInfo("UTC") - class DateDumper(Dumper): @@ -522,7 +520,9 @@ class TimestampTzLoader(TimestampLoader): def __init__(self, oid: int, context: Optional[AdaptContext] = None): super().__init__(oid, context) - self._timezone = self.connection.timezone if self.connection else _UTC + self._timezone = ( + self.connection.timezone if self.connection else ZoneInfo("UTC") + ) def _format_from_context(self) -> str: ds = self._get_datestyle() @@ -607,7 +607,9 @@ class TimestampTzBinaryLoader(Loader): def __init__(self, oid: int, context: Optional[AdaptContext] = None): super().__init__(oid, context) - self._timezone = self.connection.timezone if self.connection else _UTC + self._timezone = ( + self.connection.timezone if self.connection else ZoneInfo("UTC") + ) def load(self, data: Buffer) -> datetime: micros = _unpack_int8(data)[0]