Skip to content

Commit

Permalink
feat(cli): read connection parameters from environment variables
Browse files Browse the repository at this point in the history
Add missing variables for user and database name.
  • Loading branch information
jonbiemond committed Feb 28, 2024
1 parent 27debb3 commit e322202
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ Create a connection to a PostgreSQL database.

Defaults to the `postgres` database on `localhost` with the `postgres` user.
Pass alternate connection parameters as options.
You can save yourself some typing by setting the environment variables `PGDATABASE`,
`PGHOST`, `PGPORT` and/or `PGUSER` to appropriate values.
It is also convenient to have a [.pgpass](https://www.postgresql.org/docs/current/libpq-pgpass.html) file
to avoid regularly having to type in passwords.

#### Options

Expand Down
9 changes: 8 additions & 1 deletion heave/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,15 @@ def connect(
"--username",
default="",
help="Username to connect to the postgres database.",
envvar="PGUSER",
)
@click.option(
"-d",
"--dbname",
default="postgres",
help="Database name to connect to.",
envvar="PGDATABASE",
)
@click.option("-d", "--dbname", default="postgres", help="Database name to connect to.")
@click.pass_context
def cli(
ctx,
Expand Down
15 changes: 14 additions & 1 deletion tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,23 @@ def test_connection(self, runner, monkeypatch):
mock_connect = Mock()
monkeypatch.setattr("heave.cli.connect", mock_connect)
runner.invoke(cli, ["insert"])
assert mock_connect.called_with(
mock_connect.assert_called_with(
ANY, "postgresql", "postgres", "localhost", "5432", "", "psycopg"
)

def test_connection_envvars(self, runner, monkeypatch):
"""Test the connection parameters from environment variables."""
mock_connect = Mock()
monkeypatch.setattr("heave.cli.connect", mock_connect)
monkeypatch.setenv("PGHOST", "myhost")
monkeypatch.setenv("PGPORT", "1234")
monkeypatch.setenv("PGUSER", "myuser")
monkeypatch.setenv("PGDATABASE", "mydb")
runner.invoke(cli, ["insert"])
mock_connect.assert_called_with(
ANY, "postgresql", "mydb", "myhost", "1234", "myuser", "psycopg"
)

def test_insert(self, runner, monkeypatch):
"""Test the insert command."""
data = Table(
Expand Down

0 comments on commit e322202

Please sign in to comment.