Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/common/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import random
from functools import lru_cache
from itertools import cycle
from typing import Iterator, Literal, NotRequired, TypedDict, TypeVar
from typing import Iterator, Literal, NotRequired, TypedDict, TypeVar, get_args

from django.conf import settings
from django.contrib.auth import get_user_model
Expand Down Expand Up @@ -130,6 +130,14 @@ def get_file_contents(file_path: str) -> str | None:
return None


@lru_cache()
def is_database_replica_setup() -> bool:
Comment thread
khvn26 marked this conversation as resolved.
"""Checks if any database replica is set up"""
return any(
name for name in connections if name.startswith(get_args(ReplicaNamePrefix))
)


def using_database_replica(
manager: ManagerType,
replica_prefix: ReplicaNamePrefix = "replica_",
Expand Down
32 changes: 32 additions & 0 deletions tests/unit/common/core/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
get_version_info,
get_versions_from_manifest,
has_email_provider,
is_database_replica_setup,
is_enterprise,
is_oss,
is_saas,
Expand Down Expand Up @@ -204,6 +205,37 @@ def test_get_version__invalid_file_contents__returns_unknown(
assert result == "unknown"


@pytest.mark.parametrize(
["database_names", "expected"],
[
({"default"}, False),
({"default", "another_database_with_'replica'_in_its_name"}, False),
({"default", "task_processor"}, False),
({"default", "replica_1"}, True),
({"default", "replica_1", "replica_2"}, True),
({"default", "cross_region_replica_1"}, True),
({"default", "replica_1", "cross_region_replica_1"}, True),
],
)
def test_is_database_replica_setup__tells_whether_any_replica_is_present(
database_names: list[str],
expected: bool,
mocker: MockerFixture,
) -> None:
# Given
is_database_replica_setup.cache_clear()
mocker.patch(
"common.core.utils.connections",
{name: connections["default"] for name in database_names},
)

# When
result = is_database_replica_setup()

# Then
assert result is expected


@pytest.mark.django_db(databases="__all__")
def test_using_database_replica__no_replicas__points_to_default(
django_assert_num_queries: DjangoAssertNumQueries,
Expand Down