|
| 1 | +from zoneinfo import ZoneInfoNotFoundError |
1 | 2 | from configobj import ConfigObj, ParseError |
2 | 3 | from pgspecial.namedqueries import NamedQueries |
3 | 4 | from .config import skip_initial_comment |
|
27 | 28 | from cli_helpers.utils import strip_ansi |
28 | 29 | from .explain_output_formatter import ExplainOutputFormatter |
29 | 30 | import click |
| 31 | +import tzlocal |
30 | 32 |
|
31 | 33 | try: |
32 | 34 | import setproctitle |
@@ -1600,9 +1602,9 @@ def cli( |
1600 | 1602 | if list_databases or ping_database: |
1601 | 1603 | database = "postgres" |
1602 | 1604 |
|
| 1605 | + cfg = load_config(pgclirc, config_full_path) |
1603 | 1606 | if dsn != "": |
1604 | 1607 | try: |
1605 | | - cfg = load_config(pgclirc, config_full_path) |
1606 | 1608 | dsn_config = cfg["alias_dsn"][dsn] |
1607 | 1609 | except KeyError: |
1608 | 1610 | click.secho( |
@@ -1631,6 +1633,55 @@ def cli( |
1631 | 1633 | else: |
1632 | 1634 | pgcli.connect(database, host, user, port) |
1633 | 1635 |
|
| 1636 | + if "use_local_timezone" not in cfg["main"] or cfg["main"].as_bool( |
| 1637 | + "use_local_timezone" |
| 1638 | + ): |
| 1639 | + server_tz = pgcli.pgexecute.get_timezone() |
| 1640 | + |
| 1641 | + def echo_error(msg: str): |
| 1642 | + click.secho( |
| 1643 | + "Failed to determine the local time zone", |
| 1644 | + err=True, |
| 1645 | + fg="yellow", |
| 1646 | + ) |
| 1647 | + click.secho( |
| 1648 | + msg, |
| 1649 | + err=True, |
| 1650 | + fg="yellow", |
| 1651 | + ) |
| 1652 | + click.secho( |
| 1653 | + f"Continuing with the default time zone as preset by the server ({server_tz})", |
| 1654 | + err=True, |
| 1655 | + fg="yellow", |
| 1656 | + ) |
| 1657 | + click.secho( |
| 1658 | + "Set `use_local_timezone = False` in the config to avoid trying to override the server time zone\n", |
| 1659 | + err=True, |
| 1660 | + dim=True, |
| 1661 | + ) |
| 1662 | + |
| 1663 | + local_tz = None |
| 1664 | + try: |
| 1665 | + local_tz = tzlocal.get_localzone_name() |
| 1666 | + |
| 1667 | + if local_tz is None: |
| 1668 | + echo_error("No local time zone configuration found\n") |
| 1669 | + else: |
| 1670 | + click.secho( |
| 1671 | + f"Using local time zone {local_tz} (server uses {server_tz})", |
| 1672 | + fg="green", |
| 1673 | + ) |
| 1674 | + click.secho( |
| 1675 | + "Use `set time zone <TZ>` to override, or set `use_local_timezone = False` in the config", |
| 1676 | + dim=True, |
| 1677 | + ) |
| 1678 | + |
| 1679 | + pgcli.pgexecute.set_timezone(local_tz) |
| 1680 | + except ZoneInfoNotFoundError as e: |
| 1681 | + # e.args[0] is the pre-formatted message which includes a list |
| 1682 | + # of conflicting sources |
| 1683 | + echo_error(e.args[0]) |
| 1684 | + |
1634 | 1685 | if list_databases: |
1635 | 1686 | cur, headers, status = pgcli.pgexecute.full_databases() |
1636 | 1687 |
|
|
0 commit comments