Skip to content

Commit

Permalink
Update count_total_contacts to have a fallback
Browse files Browse the repository at this point in the history
This was added for cases where the table has not yet been analyzed and the
estimate is not available... mainly in unit tests.
  • Loading branch information
robhudson committed Jan 31, 2025
1 parent f7f5409 commit 7a647a6
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions ctms/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,18 @@ def count_total_contacts(db: Session) -> int:
This metadata is refreshed on `VACUUM` or `ANALYSIS` which
is run regularly by default on our database instances.
"""
query = text(
"SELECT reltuples AS estimate "
"FROM pg_class "
f"where relname = '{Email.__tablename__}'"
)
result = db.execute(query).scalar()
result = db.execute(
text(
"SELECT reltuples AS estimate "
"FROM pg_class "
f"where relname = '{Email.__tablename__}'"
)
).scalar()
if result is None or result < 0:
# Fall back to a full count if the estimate is not available.
result = db.execute(
text(f"SELECT COUNT(*) FROM {Email.__tablename__}")
).scalar()
if result is None:
return -1
return int(result)
Expand Down

0 comments on commit 7a647a6

Please sign in to comment.