Skip to content

Commit 72c5f91

Browse files
ChrisJr404j-bennet
andauthored
Fix alias_dsn detection for --list-dsn and -D (dbcli#1617)
* Fix alias_dsn detection for --list-dsn and -D --list-dsn and -D/--dsn read the config with a bare load_config that skips the packaged default, unlike the rest of pgcli. On a fresh install (config not written yet) --list-dsn hit a KeyError on the missing [alias_dsn] section and printed a misleading "Invalid DSNs found" error, and -D could crash on the missing [main] section when the user config only had an [alias_dsn] block. Load config via get_config instead, which writes the default template if needed and always carries the expected sections. Fixes dbcli#1489 * Make --list-dsn and -D resolve aliases without writing the config --------- Co-authored-by: Chris (ChrisJr404) <[email protected]> Co-authored-by: Irina Truong <[email protected]>
1 parent a6ced25 commit 72c5f91

3 files changed

Lines changed: 106 additions & 3 deletions

File tree

‎changelog.rst‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,12 @@ Internal:
4141

4242
Bug fixes:
4343
----------
44+
* Fix ``--list-dsn`` and ``-D``/``--dsn`` not finding ``[alias_dsn]`` entries.
45+
On a fresh install (no config written yet) ``--list-dsn`` printed a misleading
46+
"Invalid DSNs found" error. ``--list-dsn`` now treats a missing config or
47+
``[alias_dsn]`` section as simply nothing to list, without writing a config
48+
file, and ``-D`` resolves the alias from the config already loaded at startup
49+
instead of reading it again ([issue 1489](https://github.com/dbcli/pgcli/issues/1489)).
4450
* Restore cursor shape behaviour for Emacs mode
4551
* Fix ``TypeError: cannot use a string pattern on a bytes-like object`` when
4652
completion metadata comes back as bytes (e.g. ``SQL_ASCII`` client encoding).

‎pgcli/main.py‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1706,9 +1706,14 @@ def cli(
17061706
config_full_path,
17071707
)
17081708
if list_dsn:
1709+
config_file = get_config_filename(pgclirc)
1710+
if not os.path.exists(config_file):
1711+
# Nothing is configured yet, so there is nothing to list. Don't write
1712+
# out the default config just to read it back for a read-only command.
1713+
sys.exit(0)
17091714
try:
1710-
cfg = load_config(pgclirc, config_full_path)
1711-
for alias in cfg["alias_dsn"]:
1715+
cfg = load_config(config_file)
1716+
for alias in cfg.get("alias_dsn", {}):
17121717
click.secho(alias + " : " + cfg["alias_dsn"][alias])
17131718
sys.exit(0)
17141719
except Exception:
@@ -1777,7 +1782,9 @@ def cli(
17771782
except Exception:
17781783
pass # invalid conninfo: let the connection attempt report it
17791784

1780-
cfg = load_config(pgclirc, config_full_path)
1785+
# PGCli() already loaded (and, if needed, wrote) the config above, so reuse it
1786+
# rather than reading the file a second time to resolve the -D alias.
1787+
cfg = pgcli.config
17811788
if dsn != "":
17821789
try:
17831790
dsn_config = cfg["alias_dsn"][dsn]

‎tests/test_alias_dsn.py‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import pytest
2+
from click.testing import CliRunner
3+
4+
from pgcli.main import cli, PGCli
5+
6+
7+
def write_config(tmp_path, body):
8+
cfg = tmp_path / "config"
9+
cfg.write_text(body)
10+
return cfg
11+
12+
13+
@pytest.fixture
14+
def isolate_config(monkeypatch, tmp_path):
15+
# Keep the real config dir out of the picture. get_config() writes its
16+
# default template under here when a config file does not exist yet.
17+
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
18+
return tmp_path
19+
20+
21+
def test_list_dsn_fresh_config(isolate_config):
22+
# No config file exists yet. --list-dsn used to read the not-yet-written
23+
# config before PGCli() created it, hit a KeyError on the missing
24+
# [alias_dsn] section, and print "Invalid DSNs found" with exit code 1.
25+
# It should just report no aliases and exit cleanly.
26+
cfg = isolate_config / "config"
27+
runner = CliRunner()
28+
result = runner.invoke(cli, ["--pgclirc", str(cfg), "--list-dsn"])
29+
assert result.exit_code == 0
30+
assert "Invalid DSNs" not in result.output
31+
assert result.output.strip() == ""
32+
# A read-only command must not create the config file as a side effect.
33+
assert not cfg.exists()
34+
35+
36+
def test_list_dsn_lists_aliases(isolate_config):
37+
cfg = write_config(
38+
isolate_config,
39+
"[alias_dsn]\nfoo = postgres://u:p@localhost:5432/foo\nbar = postgres://u:p@localhost:5432/bar\n",
40+
)
41+
runner = CliRunner()
42+
result = runner.invoke(cli, ["--pgclirc", str(cfg), "--list-dsn"])
43+
assert result.exit_code == 0
44+
assert "foo : postgres://u:p@localhost:5432/foo" in result.output
45+
assert "bar : postgres://u:p@localhost:5432/bar" in result.output
46+
47+
48+
def test_dsn_alias_resolves(isolate_config, monkeypatch):
49+
cfg = write_config(
50+
isolate_config,
51+
"[alias_dsn]\nfoo = postgres://u:p@localhost:5432/foo\n",
52+
)
53+
captured = {}
54+
55+
def fake_connect(self, *args, **kwargs):
56+
# connect_uri() parses the alias URI and calls connect() with the
57+
# resolved parts, so recording them proves the alias was found.
58+
captured.update(kwargs)
59+
60+
class DummyExec:
61+
def run(self, cmd):
62+
return []
63+
64+
def get_timezone(self):
65+
return "UTC"
66+
67+
def set_timezone(self, *a, **k):
68+
pass
69+
70+
self.pgexecute = DummyExec()
71+
72+
monkeypatch.setattr(PGCli, "connect", fake_connect)
73+
74+
runner = CliRunner()
75+
result = runner.invoke(cli, ["--pgclirc", str(cfg), "-D", "foo", "--ping"])
76+
assert result.exit_code == 0
77+
assert "Could not find a DSN" not in result.output
78+
assert captured.get("database") == "foo"
79+
assert captured.get("host") == "localhost"
80+
81+
82+
def test_dsn_alias_missing(isolate_config):
83+
cfg = write_config(
84+
isolate_config,
85+
"[alias_dsn]\nfoo = postgres://u:p@localhost:5432/foo\n",
86+
)
87+
runner = CliRunner()
88+
result = runner.invoke(cli, ["--pgclirc", str(cfg), "-D", "does-not-exist"])
89+
assert result.exit_code == 1
90+
assert "Could not find a DSN with alias does-not-exist" in result.output

0 commit comments

Comments
 (0)