diff --git a/AUTHORS b/AUTHORS index ca943548..1b53504f 100644 --- a/AUTHORS +++ b/AUTHORS @@ -137,6 +137,7 @@ Contributors: * Chris Rose (offbyone/offby1) * Mathieu Dupuy (deronnax) * Chris Novakovic + * Max Smolin (maximsmol) Creator: -------- diff --git a/changelog.rst b/changelog.rst index 8e7a8aed..36b379cc 100644 --- a/changelog.rst +++ b/changelog.rst @@ -5,6 +5,7 @@ Features -------- * Add a `--ping` command line option; allows pgcli to replace `pg_isready` * Changed the packaging metadata from setup.py to pyproject.toml +* The session time zone setting is set to the system time zone by default Bug fixes: ---------- diff --git a/pgcli/main.py b/pgcli/main.py index d4c6dbf6..63a93ce7 100644 --- a/pgcli/main.py +++ b/pgcli/main.py @@ -1,3 +1,4 @@ +from zoneinfo import ZoneInfoNotFoundError from configobj import ConfigObj, ParseError from pgspecial.namedqueries import NamedQueries from .config import skip_initial_comment @@ -23,6 +24,7 @@ from cli_helpers.utils import strip_ansi from .explain_output_formatter import ExplainOutputFormatter import click +import tzlocal try: import setproctitle @@ -1624,6 +1626,30 @@ def cli( else: pgcli.connect(database, host, user, port) + local_tz = None + try: + local_tz = tzlocal.get_localzone_name() + + if local_tz is None: + click.secho( + "No local time zone configuration found", + err=True, + fg="yellow", + ) + except ZoneInfoNotFoundError as e: + # e.args[0] is the pre-formatted message which includes a list + # of conflicting sources + click.secho(e.args[0], err=True, fg="yellow") + + if local_tz is not None: + pgcli.pgexecute.set_timezone(local_tz) + else: + click.secho( + "Continuing with the default server time zone", + err=True, + fg="yellow", + ) + if list_databases: cur, headers, status = pgcli.pgexecute.full_databases() diff --git a/pgcli/pgexecute.py b/pgcli/pgexecute.py index e0917572..a2590250 100644 --- a/pgcli/pgexecute.py +++ b/pgcli/pgexecute.py @@ -881,3 +881,10 @@ def casing(self): def explain_prefix(self): return "EXPLAIN (ANALYZE, COSTS, VERBOSE, BUFFERS, FORMAT JSON) " + + def set_timezone(self, timezone: str): + query = psycopg.sql.SQL("set time zone {}").format( + psycopg.sql.Identifier(timezone) + ) + with self.conn.cursor() as cur: + cur.execute(query) diff --git a/pyproject.toml b/pyproject.toml index 84afc1b3..1e29368a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -40,6 +40,7 @@ dependencies = [ # task manager. Also setproctitle is a hard dependency to install in Windows, # so we'll only install it if we're not in Windows. "setproctitle >= 1.1.9; sys_platform != 'win32' and 'CYGWIN' not in sys_platform", + "tzlocal >= 5.2", ] dynamic = ["version"]