diff --git a/synapse/storage/databases/main/user_directory.py b/synapse/storage/databases/main/user_directory.py
index d6cd0774a8..391f0dd638 100644
--- a/synapse/storage/databases/main/user_directory.py
+++ b/synapse/storage/databases/main/user_directory.py
@@ -1037,11 +1037,11 @@ class UserDirectoryStore(UserDirectoryBackgroundUpdateStore):
}
"""
+ join_args: Tuple[str, ...] = (user_id,)
+
if self.hs.config.userdirectory.user_directory_search_all_users:
- join_args = (user_id,)
where_clause = "user_id != ?"
else:
- join_args = (user_id,)
where_clause = """
(
EXISTS (select 1 from users_in_public_rooms WHERE user_id = t.user_id)
@@ -1055,6 +1055,14 @@ class UserDirectoryStore(UserDirectoryBackgroundUpdateStore):
if not show_locked_users:
where_clause += " AND (u.locked IS NULL OR u.locked = FALSE)"
+ # Adjust the JOIN type based on the exclude_remote_users flag (the users
+ # table only contains local users so an inner join is a good way to
+ # to exclude remote users)
+ if self.hs.config.userdirectory.user_directory_exclude_remote_users:
+ join_type = "JOIN"
+ else:
+ join_type = "LEFT JOIN"
+
# We allow manipulating the ranking algorithm by injecting statements
# based on config options.
additional_ordering_statements = []
@@ -1086,7 +1094,7 @@ class UserDirectoryStore(UserDirectoryBackgroundUpdateStore):
SELECT d.user_id AS user_id, display_name, avatar_url
FROM matching_users as t
INNER JOIN user_directory AS d USING (user_id)
- LEFT JOIN users AS u ON t.user_id = u.name
+ %(join_type)s users AS u ON t.user_id = u.name
WHERE
%(where_clause)s
ORDER BY
@@ -1115,6 +1123,7 @@ class UserDirectoryStore(UserDirectoryBackgroundUpdateStore):
""" % {
"where_clause": where_clause,
"order_case_statements": " ".join(additional_ordering_statements),
+ "join_type": join_type,
}
args = (
(full_query,)
@@ -1142,7 +1151,7 @@ class UserDirectoryStore(UserDirectoryBackgroundUpdateStore):
SELECT d.user_id AS user_id, display_name, avatar_url
FROM user_directory_search as t
INNER JOIN user_directory AS d USING (user_id)
- LEFT JOIN users AS u ON t.user_id = u.name
+ %(join_type)s users AS u ON t.user_id = u.name
WHERE
%(where_clause)s
AND value MATCH ?
@@ -1155,6 +1164,7 @@ class UserDirectoryStore(UserDirectoryBackgroundUpdateStore):
""" % {
"where_clause": where_clause,
"order_statements": " ".join(additional_ordering_statements),
+ "join_type": join_type,
}
args = join_args + (search_query,) + ordering_arguments + (limit + 1,)
else:
|