Skip to content

Commit

Permalink
Implement pg.needs_password() specifically for Psycopg 3.1+
Browse files Browse the repository at this point in the history
Psycopg 3 links exceptions to the underlying libpq PGconn object, which
exposes a 'needs_password' property; exactly what we need and much more
robust than parsing the error message.
  • Loading branch information
dlax committed Jul 6, 2023
1 parent bf630d9 commit 4ccefc7
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 10 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@

* Document how to *hack* on pg\_activity in the `README`.
* Add a [pre-commit](https://pre-commit.com/) configuration.
* Require psycopg >= 3.1 (when using the psycopg backend) to get a more robust
detection of connection password need.

## pg\_activity 3.4.2 - 2023-06-01

Expand Down
21 changes: 12 additions & 9 deletions pgactivity/pg.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,10 @@ def decode(value: bytes, pgenc: bytes, *, errors: str) -> str:
pyenc = "utf-8"
return value.decode(pyenc, errors=errors)

def needs_password(exc: OperationalError) -> bool:
assert exc.pgconn is not None
return exc.pgconn.needs_password

except ImportError:
import codecs

Expand Down Expand Up @@ -270,15 +274,14 @@ def decode(value: bytes, pgenc: bytes, *, errors: str) -> str:
pyenc = "utf-8"
return value.decode(pyenc, errors=errors)


def needs_password(exc: OperationalError) -> bool:
if isinstance(exc, InvalidPassword):
return True
msg = str(exc)
return (
msg.startswith("FATAL: password authentication failed for user")
or "fe_sendauth: no password supplied" in msg
)
def needs_password(exc: OperationalError) -> bool:
if isinstance(exc, InvalidPassword):
return True
msg = str(exc)
return (
msg.startswith("FATAL: password authentication failed for user")
or "fe_sendauth: no password supplied" in msg
)


__all__ = [
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ typing = [
"types-setuptools",
]
psycopg = [
"psycopg[binary]",
"psycopg[binary] >= 3.1",
]
psycopg2 = [
"psycopg2-binary >= 2.8",
Expand Down

0 comments on commit 4ccefc7

Please sign in to comment.