roles.py 925 B

1234567891011121314151617181920212223242526272829303132
  1. from __future__ import annotations
  2. import contextlib
  3. import os
  4. import sys
  5. from django.db.transaction import get_connection
  6. from sentry.silo.patches.silo_aware_transaction_patch import determine_using_by_silo_mode
  7. @contextlib.contextmanager
  8. def in_test_psql_role_override(role_name: str, using: str | None = None):
  9. """
  10. During test runs, the role of the current connection will be swapped with role_name, and then swapped
  11. back to its original. Has no effect in production.
  12. """
  13. if "pytest" not in sys.argv[0] or os.environ.get("DB", "postgres") != "postgres":
  14. yield
  15. return
  16. using = determine_using_by_silo_mode(using)
  17. with get_connection(using).cursor() as conn:
  18. conn.execute("SELECT user")
  19. (cur,) = conn.fetchone()
  20. conn.execute("SET ROLE %s", [role_name])
  21. try:
  22. yield
  23. finally:
  24. conn.execute("SET ROLE %s", [cur])