Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
narrow: Rewrite message-fetch query using Django ORM.
Anders Kaseorgc286f39d46da
diff --git a/tools/linter_lib/custom_check.py b/tools/linter_lib/custom_check.pyindex bca60e9fd1b..0497644cff0 100644--- a/tools/linter_lib/custom_check.py+++ b/tools/linter_lib/custom_check.py@@ -11,7 +11,6 @@ from zulint.custom_rules import Rule, RuleListFILES_WITH_LEGACY_SUBJECT = {# This basically requires a big DB migration:"zerver/lib/topic.py",- "zerver/lib/topic_sqlalchemy.py",# This is tied to legacy events."zerver/lib/event_types.py",# This is for backward compatibility.diff --git a/zerver/lib/narrow.py b/zerver/lib/narrow.pyindex 94cc1c99fcd..f534875a512 100644--- a/zerver/lib/narrow.py+++ b/zerver/lib/narrow.py@@ -8,29 +8,11 @@ from django.conf import settingsfrom django.contrib.auth.models import AnonymousUserfrom django.core.exceptions import ValidationErrorfrom django.db import connection+from django.db.models import Exists, F, Func, OuterRef, Q, QuerySet, TextField+from django.db.models.expressions import RawSQLfrom django.utils.translation import gettext as _+from psycopg2.sql import SQL, Composable, Identifierfrom pydantic import BaseModel, model_validator-from sqlalchemy.dialects import postgresql-from sqlalchemy.engine import Connection, Row-from sqlalchemy.sql import (- ClauseElement,- ColumnElement,- Select,- and_,- column,- false,- func,- literal,- literal_column,- not_,- or_,- select,- table,- true,- union_all,-)-from sqlalchemy.sql.selectable import SelectBase-from sqlalchemy.types import ARRAY, Boolean, Integer, Textfrom typing_extensions import overridefrom zerver.lib.addressee import get_user_profiles, get_user_profiles_by_ids@@ -42,7 +24,6 @@ from zerver.lib.message import ()from zerver.lib.narrow_predicate import channel_operators, channels_operatorsfrom zerver.lib.recipient_users import recipient_for_user_profiles-from zerver.lib.sqlalchemy_utils import get_sqlalchemy_connectionfrom zerver.lib.streams import (access_stream_common,can_access_stream_history_by_id,@@ -52,12 +33,12 @@ from zerver.lib.streams import (get_stream_by_narrow_operand_access_unchecked,get_web_public_streams_queryset,)-from zerver.lib.topic import maybe_rename_general_chat_to_empty_topic-from zerver.lib.topic_sqlalchemy import (- get_followed_topic_condition_sa,- get_resolved_topic_condition_sa,- topic_column_sa,- topic_match_sa,+from zerver.lib.topic import (+ DB_TOPIC_NAME,+ get_followed_topic_condition_q,+ get_resolved_topic_condition_q,+ maybe_rename_general_chat_to_empty_topic,+ topic_match_q,)from zerver.lib.types import Validatorfrom zerver.lib.user_groups import get_recursive_membership_groups@@ -73,6 +54,7 @@ from zerver.lib.validator import (from zerver.models import (DirectMessageGroup,Message,+ Reaction,Realm,Recipient,Stream,@@ -227,35 +209,35 @@ class InvalidOperatorCombinationError(JsonableError):return _("Invalid narrow operator combination: {desc}")-ConditionTransform: TypeAlias = Callable[[ClauseElement], ClauseElement]+ConditionTransform: TypeAlias = Callable[[Q], Q]+++def not_(cond: Q) -> Q:+ return ~cond+# These delimiters will not appear in rendered messages or HTML-escaped topics.TS_START = "<ts-match>"TS_STOP = "</ts-match>"-def ts_locs_array(- config: ColumnElement[Text],- text: ColumnElement[Text],- tsquery: ColumnElement[Any],-) -> ColumnElement[ARRAY[Integer]]:+def ts_locs_array(config: str, text: Composable, operand: str) -> RawSQL:options = f"HighlightAll = TRUE, StartSel = {TS_START}, StopSel = {TS_STOP}"- delimited = func.ts_headline(config, text, tsquery, options, type_=Text)- part = func.unnest(- func.string_to_array(delimited, TS_START, type_=ARRAY(Text)), type_=Text- ).column_valued()- part_len = func.length(part, type_=Integer) - len(TS_STOP)- match_pos = func.sum(part_len, type_=Integer).over(rows=(None, -1)) + len(TS_STOP)- match_len = func.strpos(part, TS_STOP, type_=Integer) - 1- return func.array(- select(postgresql.array([match_pos, match_len])).offset(1).scalar_subquery(),- type_=ARRAY(Integer),- )+ composed = SQL(+ "array(SELECT ARRAY["+ "sum(length(p) - %s) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) + %s, "+ "strpos(p, %s) - 1] "+ "FROM unnest(string_to_array("+ "ts_headline(%s, {text}, plainto_tsquery(%s, %s), %s), "+ "%s)) AS p OFFSET 1)"+ ).format(text=text)+ params = [len(TS_STOP), len(TS_STOP), TS_STOP, config, config, operand, options, TS_START]+ return RawSQL(composed.as_string(connection.connection), params) # noqa: S611class NarrowBuilder:"""- Build up a SQLAlchemy query to find messages matching a narrow.+ Build up a Django ORM query to find messages matching a narrow."""# This class has an important security invariant:@@ -263,13 +245,12 @@ class NarrowBuilder:# None of these methods ever *add* messages to a query's result.## That is, the `add_term` method, and its helpers the `by_*` methods,- # are passed a Select object representing a query for messages; they may- # call some methods on it, and then they return a resulting Select+ # are passed a `QuerySet[Message]` object; they may call some+ # methods on it, and then they return a resulting `QuerySet[Message]`# object. Things these methods may do to the queries they handle# include- # * add conditions to filter out rows (i.e., messages), with `query.where`- # * add columns for more information on the same message, with `query.column`- # * add a join for more information on the same message+ # * add conditions to filter out rows (i.e., messages), with `query.filter`+ # * add columns for more information on the same message, with `query.annotate`## Things they may not do include# * anything that would pull in additional rows, or information on@@ -278,12 +259,11 @@ class NarrowBuilder:def __init__(self,user_profile: UserProfile | None,- msg_id_column: ColumnElement[Integer],realm: Realm,+ *,is_web_public_query: bool = False,) -> None:self.user_profile = user_profile- self.msg_id_column = msg_id_columnself.realm = realmself.is_web_public_query = is_web_public_queryself.by_method_map = {@@ -336,7 +316,7 @@ class NarrowBuilder:"No message can be both a channel message and direct message")- def add_term(self, query: Select, term: NarrowParameter) -> Select:+ def add_term(self, query: QuerySet[Message], term: NarrowParameter) -> QuerySet[Message]:"""Extend the given query to one narrowed by the given term, and return the result.@@ -366,30 +346,23 @@ class NarrowBuilder:return method(query, operand, maybe_negate)- def by_has(self, query: Select, operand: str, maybe_negate: ConditionTransform) -> Select:+ def by_has(+ self, query: QuerySet[Message], operand: str, maybe_negate: ConditionTransform+ ) -> QuerySet[Message]:if operand not in ["attachment", "image", "link", "reaction"]:raise BadNarrowOperatorError("unknown 'has' operand " + operand)if operand == "reaction":- if self.msg_id_column.name == "message_id":- # If the initial query uses `zerver_usermessage`- check_col = literal_column("zerver_usermessage.message_id", Integer)- else:- # If the initial query doesn't use `zerver_usermessage`- check_col = literal_column("zerver_message.id", Integer)- exists_cond = (- select(1)- .select_from(table("zerver_reaction"))- .where(check_col == literal_column("zerver_reaction.message_id", Integer))- .exists()- )- return query.where(maybe_negate(exists_cond))+ exists_cond = Q(Exists(Reaction.objects.filter(message_id=OuterRef("id"))))+ return query.filter(maybe_negate(exists_cond))col_name = "has_" + operand- cond = column(col_name, Boolean)- return query.where(maybe_negate(cond))+ cond = Q(**{col_name: True})+ return query.filter(maybe_negate(cond))- def by_in(self, query: Select, operand: str, maybe_negate: ConditionTransform) -> Select:+ def by_in(+ self, query: QuerySet[Message], operand: str, maybe_negate: ConditionTransform+ ) -> QuerySet[Message]:# This operator does not support is_web_public_query.assert not self.is_web_public_queryassert self.user_profile is not None@@ -398,19 +371,19 @@ class NarrowBuilder:conditions = exclude_muting_conditions(self.user_profile, [NarrowParameter(operator="in", operand="home")])- if conditions:- return query.where(maybe_negate(and_(*conditions)))- return query.where(maybe_negate(true()))+ return query.filter(maybe_negate(conditions))elif operand == "all":return queryraise BadNarrowOperatorError("unknown 'in' operand " + operand)- def by_is(self, query: Select, operand: str, maybe_negate: ConditionTransform) -> Select:+ def by_is(+ self, query: QuerySet[Message], operand: str, maybe_negate: ConditionTransform+ ) -> QuerySet[Message]:# Only `resolved` operand of this class supports is_web_public_query.if operand == "resolved":- cond = get_resolved_topic_condition_sa()- return query.where(maybe_negate(cond))+ cond = get_resolved_topic_condition_q()+ return query.filter(maybe_negate(cond))assert not self.is_web_public_queryassert self.user_profile is not None@@ -423,14 +396,13 @@ class NarrowBuilder:)else:self.check_not_both_channel_and_dm_narrow(maybe_negate, is_dm_narrow=True)- cond = column("flags", Integer).op("&")(UserMessage.flags.is_private.mask) != 0- return query.where(maybe_negate(cond))+ return query.filter(+ maybe_negate(Q(user_flags__andnz=UserMessage.flags.is_private.mask))+ )elif operand == "starred":- cond = column("flags", Integer).op("&")(UserMessage.flags.starred.mask) != 0- return query.where(maybe_negate(cond))+ return query.filter(maybe_negate(Q(user_flags__andnz=UserMessage.flags.starred.mask)))elif operand == "unread":- cond = column("flags", Integer).op("&")(UserMessage.flags.read.mask) == 0- return query.where(maybe_negate(cond))+ return query.filter(maybe_negate(Q(user_flags__andz=UserMessage.flags.read.mask)))elif operand == "mentioned":mention_flags_mask = (UserMessage.flags.mentioned.mask@@ -438,14 +410,14 @@ class NarrowBuilder:| UserMessage.flags.topic_wildcard_mentioned.mask| UserMessage.flags.group_mentioned.mask)- cond = column("flags", Integer).op("&")(mention_flags_mask) != 0- return query.where(maybe_negate(cond))+ return query.filter(maybe_negate(Q(user_flags__andnz=mention_flags_mask)))elif operand == "alerted":- cond = column("flags", Integer).op("&")(UserMessage.flags.has_alert_word.mask) != 0- return query.where(maybe_negate(cond))+ return query.filter(+ maybe_negate(Q(user_flags__andnz=UserMessage.flags.has_alert_word.mask))+ )elif operand == "followed":- cond = get_followed_topic_condition_sa(self.user_profile.id)- return query.where(maybe_negate(cond))+ cond = get_followed_topic_condition_q(self.user_profile.id)+ return query.filter(maybe_negate(cond))elif operand == "muted":# TODO: If we also have a channel operator, this could be# a lot more efficient if limited to only those muting@@ -453,19 +425,15 @@ class NarrowBuilder:conditions = exclude_muting_conditions(self.user_profile, [NarrowParameter(operator="is", operand="muted")])- if conditions:- return query.where(maybe_negate(not_(and_(*conditions))))-- # This is the case where no channels or topics were muted.- return query.where(maybe_negate(false()))+ return query.filter(maybe_negate(~conditions))raise BadNarrowOperatorError("unknown 'is' operand " + operand)_alphanum = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")def by_channel(- self, query: Select, operand: str | int, maybe_negate: ConditionTransform- ) -> Select:+ self, query: QuerySet[Message], operand: str | int, maybe_negate: ConditionTransform+ ) -> QuerySet[Message]:self.check_not_both_channel_and_dm_narrow(maybe_negate, is_channel_narrow=True)try:@@ -481,10 +449,12 @@ class NarrowBuilder:recipient_id = channel.recipient_idassert recipient_id is not None- cond = column("recipient_id", Integer) == recipient_id- return query.where(maybe_negate(cond))+ cond = Q(recipient_id=recipient_id)+ return query.filter(maybe_negate(cond))- def by_channels(self, query: Select, operand: str, maybe_negate: ConditionTransform) -> Select:+ def by_channels(+ self, query: QuerySet[Message], operand: str, maybe_negate: ConditionTransform+ ) -> QuerySet[Message]:self.check_not_both_channel_and_dm_narrow(maybe_negate, is_channel_narrow=True)if operand == "public":@@ -499,18 +469,19 @@ class NarrowBuilder:raise BadNarrowOperatorError("unknown channels operand " + operand)recipient_ids = recipient_queryset.values_list("recipient_id", flat=True).order_by("id")- cond = column("recipient_id", Integer).in_(recipient_ids)- return query.where(maybe_negate(cond))+ cond = Q(recipient_id__in=list(recipient_ids))+ return query.filter(maybe_negate(cond))- def by_topic(self, query: Select, operand: str, maybe_negate: ConditionTransform) -> Select:+ def by_topic(+ self, query: QuerySet[Message], operand: str, maybe_negate: ConditionTransform+ ) -> QuerySet[Message]:self.check_not_both_channel_and_dm_narrow(maybe_negate, is_channel_narrow=True)-- cond = topic_match_sa(operand)- return query.where(maybe_negate(cond))+ cond = topic_match_q(operand)+ return query.filter(maybe_negate(cond))def by_sender(- self, query: Select, operand: str | int, maybe_negate: ConditionTransform- ) -> Select:+ self, query: QuerySet[Message], operand: str | int, maybe_negate: ConditionTransform+ ) -> QuerySet[Message]:try:if isinstance(operand, str):sender = get_user_including_cross_realm(operand, self.realm)@@ -519,21 +490,28 @@ class NarrowBuilder:except UserProfile.DoesNotExist:raise BadNarrowOperatorError("unknown user " + str(operand))- cond = column("sender_id", Integer) == literal(sender.id)- return query.where(maybe_negate(cond))+ cond = Q(sender_id=sender.id)+ return query.filter(maybe_negate(cond))- def by_near(self, query: Select, operand: str, maybe_negate: ConditionTransform) -> Select:+ def by_near(+ self, query: QuerySet[Message], operand: str, maybe_negate: ConditionTransform+ ) -> QuerySet[Message]:return query- def by_id(self, query: Select, operand: int | str, maybe_negate: ConditionTransform) -> Select:+ def by_id(+ self, query: QuerySet[Message], operand: int | str, maybe_negate: ConditionTransform+ ) -> QuerySet[Message]:if not str(operand).isdigit() or int(operand) > Message.MAX_POSSIBLE_MESSAGE_ID:raise BadNarrowOperatorError("Invalid message ID")- cond = self.msg_id_column == literal(operand)- return query.where(maybe_negate(cond))+ cond = Q(id=int(operand))+ return query.filter(maybe_negate(cond))def by_dm(- self, query: Select, operand: str | Iterable[int], maybe_negate: ConditionTransform- ) -> Select:+ self,+ query: QuerySet[Message],+ operand: str | Iterable[int],+ maybe_negate: ConditionTransform,+ ) -> QuerySet[Message]:# This operator does not support is_web_public_query.assert not self.is_web_public_queryassert self.user_profile is not None@@ -558,7 +536,8 @@ class NarrowBuilder:)if user_profiles == []:- return query.where(maybe_negate(false()))+ cond = Q(pk__in=[]) # Always false.+ return query.filter(maybe_negate(cond))recipient = recipient_for_user_profiles(user_profiles=user_profiles,@@ -572,10 +551,11 @@ class NarrowBuilder:raise BadNarrowOperatorError("unknown user in " + str(operand))except DirectMessageGroup.DoesNotExist:# DM group doesn't exist, so no messages can exist.- return query.where(maybe_negate(false()))+ cond = Q(pk__in=[]) # Always false.+ return query.filter(maybe_negate(cond))- cond = column("recipient_id", Integer) == recipient.id- return query.where(maybe_negate(cond))+ cond = Q(recipient_id=recipient.id)+ return query.filter(maybe_negate(cond))def _get_direct_message_group_recipients(self, other_user: UserProfile) -> set[int]:return set(@@ -593,8 +573,8 @@ class NarrowBuilder:)def by_dm_including(- self, query: Select, operand: str | int, maybe_negate: ConditionTransform- ) -> Select:+ self, query: QuerySet[Message], operand: str | int, maybe_negate: ConditionTransform+ ) -> QuerySet[Message]:# This operator does not support is_web_public_query.assert not self.is_web_public_queryassert self.user_profile is not None@@ -615,26 +595,24 @@ class NarrowBuilder:# should return all group and 1:1 direct messages (including direct messages# with self), so the simplest query to get these messages is the same as "is:dm".if narrow_user_profile.id == self.user_profile.id:- cond = column("flags", Integer).op("&")(UserMessage.flags.is_private.mask) != 0- return query.where(maybe_negate(cond))+ cond = Q(user_flags__andnz=UserMessage.flags.is_private.mask)+ return query.filter(maybe_negate(cond))# all direct messages including another person (group and 1:1)direct_message_group_recipient_ids = self._get_direct_message_group_recipients(narrow_user_profile)- private_flag = column("flags", Integer).op("&")(UserMessage.flags.is_private.mask) != 0- realm_match = column("realm_id", Integer) == self.realm.id- direct_message_group_cond = column("recipient_id", Integer).in_(- direct_message_group_recipient_ids+ cond = Q(+ user_flags__andnz=UserMessage.flags.is_private.mask,+ realm_id=self.realm.id,+ recipient_id__in=direct_message_group_recipient_ids,)-- cond = and_(private_flag, realm_match, direct_message_group_cond)- return query.where(maybe_negate(cond))+ return query.filter(maybe_negate(cond))def by_mention(- self, query: Select, operand: str | int, maybe_negate: ConditionTransform- ) -> Select:+ self, query: QuerySet[Message], operand: str | int, maybe_negate: ConditionTransform+ ) -> QuerySet[Message]:assert self.user_profile is not Nonetry:@@ -658,23 +636,21 @@ class NarrowBuilder:# We correlate via zerver_message.id (present in both base# query variants) to avoid ambiguity with the outer query's# zerver_usermessage table.- cond = (- select(1)- .select_from(table("zerver_usermessage"))- .where(- column("message_id", Integer) == literal_column("zerver_message.id", Integer),- column("user_profile_id", Integer) == literal(target_user.id),- column("flags", Integer).op("&")(literal(UserMessage.flags.mentioned.mask)) != 0,+ cond = Q(+ Exists(+ UserMessage.objects.filter(+ message_id=OuterRef("id"),+ user_profile_id=target_user.id,+ flags__andnz=UserMessage.flags.mentioned.mask,+ ))- .exists())- return query.where(maybe_negate(cond))+ return query.filter(maybe_negate(cond))def by_group_pm_with(- self, query: Select, operand: str | int, maybe_negate: ConditionTransform- ) -> Select:- # This operator does not support is_web_public_query.+ self, query: QuerySet[Message], operand: str | int, maybe_negate: ConditionTransform+ ) -> QuerySet[Message]:assert not self.is_web_public_queryassert self.user_profile is not None@@ -689,51 +665,69 @@ class NarrowBuilder:raise BadNarrowOperatorError("unknown user " + str(operand))recipient_ids = self._get_direct_message_group_recipients(narrow_profile)- cond = and_(- column("flags", Integer).op("&")(UserMessage.flags.is_private.mask) != 0,- column("realm_id", Integer) == self.realm.id,- column("recipient_id", Integer).in_(recipient_ids),+ cond = Q(+ user_flags__andnz=UserMessage.flags.is_private.mask,+ realm_id=self.realm.id,+ recipient_id__in=recipient_ids,)- return query.where(maybe_negate(cond))+ return query.filter(maybe_negate(cond))- def by_search(self, query: Select, operand: str, maybe_negate: ConditionTransform) -> Select:+ def by_search(+ self, query: QuerySet[Message], operand: str, maybe_negate: ConditionTransform+ ) -> QuerySet[Message]:if settings.USING_PGROONGA:return self._by_search_pgroonga(query, operand, maybe_negate)else:return self._by_search_tsearch(query, operand, maybe_negate)def _by_search_pgroonga(- self, query: Select, operand: str, maybe_negate: ConditionTransform- ) -> Select:- match_positions_character = func.pgroonga_match_positions_character- query_extract_keywords = func.pgroonga_query_extract_keywords- operand_escaped = func.escape_html(operand, type_=Text)- keywords = query_extract_keywords(operand_escaped)- query = query.add_columns(- match_positions_character(column("rendered_content", Text), keywords).label(- "content_matches"+ self, query: QuerySet[Message], operand: str, maybe_negate: ConditionTransform+ ) -> QuerySet[Message]:+ keywords = SQL("pgroonga_query_extract_keywords(escape_html(%s))")++ query = query.annotate(+ content_matches=RawSQL( # noqa: S611+ SQL("pgroonga_match_positions_character({text}, {keywords})")+ .format(+ text=Identifier("zerver_message", "rendered_content"),+ keywords=keywords,+ )+ .as_string(connection.connection),+ [operand],),- match_positions_character(- func.escape_html(topic_column_sa(), type_=Text), keywords- ).label("topic_matches"),+ topic_matches=RawSQL( # noqa: S611+ SQL("pgroonga_match_positions_character({text}, {keywords})")+ .format(+ text=SQL("escape_html({})").format(Identifier("zerver_message", DB_TOPIC_NAME)),+ keywords=keywords,+ )+ .as_string(connection.connection),+ [operand],+ ),+ ).alias(+ _pgroonga_match=RawSQL( # noqa: S611+ SQL("{col} &@~ escape_html(%s)")+ .format(col=Identifier("zerver_message", "search_pgroonga"))+ .as_string(connection.connection),+ [operand],+ ))- condition = column("search_pgroonga", Text).op("&@~")(operand_escaped)- return query.where(maybe_negate(condition))+ condition = Q(_pgroonga_match=True)+ return query.filter(maybe_negate(condition))def _by_search_tsearch(- self, query: Select, operand: str, maybe_negate: ConditionTransform- ) -> Select:- tsquery = func.plainto_tsquery(literal("zulip.english_us_search"), literal(operand))- query = query.add_columns(- ts_locs_array(- literal("zulip.english_us_search", Text), column("rendered_content", Text), tsquery- ).label("content_matches"),+ self, query: QuerySet[Message], operand: str, maybe_negate: ConditionTransform+ ) -> QuerySet[Message]:+ query = query.annotate(+ content_matches=ts_locs_array(+ "zulip.english_us_search", Identifier("zerver_message", "rendered_content"), operand+ ),# We HTML-escape the topic in PostgreSQL to avoid doing a server round-trip- ts_locs_array(- literal("zulip.english_us_search", Text),- func.escape_html(topic_column_sa(), type_=Text),- tsquery,- ).label("topic_matches"),+ topic_matches=ts_locs_array(+ "zulip.english_us_search",+ SQL("escape_html({})").format(Identifier("zerver_message", DB_TOPIC_NAME)),+ operand,+ ),)# Do quoted string matching. We really want phrase@@ -743,18 +737,21 @@ class NarrowBuilder:for term in re.findall(r'"[^"]+"|\S+', operand):if term[0] == '"' and term[-1] == '"':term = term[1:-1]- term = "%" + connection.ops.prep_for_like_query(term) + "%"- cond: ClauseElement = or_(- column("content", Text).ilike(term),- and_(- topic_column_sa().ilike(term),- column("is_channel_message", Boolean),- ),+ cond = Q(content__icontains=term) | Q(+ **{f"{DB_TOPIC_NAME}__icontains": term}, is_channel_message=True)- query = query.where(maybe_negate(cond))-- cond = column("search_tsvector", postgresql.TSVECTOR).op("@@")(tsquery)- return query.where(maybe_negate(cond))+ query = query.filter(maybe_negate(cond))++ query = query.alias(+ _tsvector_match=RawSQL( # noqa: S611+ SQL("{tsvector} @@ plainto_tsquery(%s, %s)")+ .format(tsvector=Identifier("zerver_message", "search_tsvector"))+ .as_string(connection.connection),+ ["zulip.english_us_search", operand],+ )+ )+ cond = Q(_tsvector_match=True)+ return query.filter(maybe_negate(cond))def ok_to_include_history(@@ -940,10 +937,7 @@ def update_narrow_terms_containing_with_operator(raise AssertionError("Invalid recipient type")-def exclude_muting_conditions(- user_profile: UserProfile, narrow: list[NarrowParameter] | None-) -> list[ClauseElement]:- conditions: list[ClauseElement] = []+def exclude_muting_conditions(user_profile: UserProfile, narrow: list[NarrowParameter] | None) -> Q:channel_id = Nonetry:# Note: It is okay here to not check access to channel@@ -955,7 +949,7 @@ def exclude_muting_conditions(except Stream.DoesNotExist:pass- conditions = exclude_stream_and_topic_mutes(conditions, user_profile, channel_id)+ conditions = exclude_stream_and_topic_mutes(user_profile, channel_id)# Muted user logic for hiding messages is implemented entirely# client-side. This is by design, as it allows UI to hint that@@ -970,18 +964,11 @@ def exclude_muting_conditions(def get_base_query_for_search(- realm_id: int, user_profile: UserProfile | None, need_user_message: bool-) -> tuple[Select, ColumnElement[Integer]]:+ realm_id: int, user_profile: UserProfile | None, *, need_user_message: bool+) -> QuerySet[Message]:# Handle the simple case where user_message isn't involved first.if not need_user_message:- query = (- select(column("id", Integer).label("message_id"))- .select_from(table("zerver_message"))- .where(column("realm_id", Integer) == literal(realm_id))- )-- inner_msg_id_col = literal_column("zerver_message.id", Integer)- return (query, inner_msg_id_col)+ return Message.objects.filter(realm_id=realm_id)assert user_profile is not Noneuser_recursive_group_ids = []@@ -992,90 +979,67 @@ def get_base_query_for_search(get_recursive_membership_groups(user_profile).values_list("id", flat=True))- query = (- select(column("message_id", Integer))+ query = Message.objects.annotate(+ # Annotate these to prevent Django from joining the UserMessage table+ # more than once when we later filter on these fields.+ user_profile_id=F("usermessage__user_profile_id"),+ user_flags=F("usermessage__flags"),+ ).filter(# We don't limit by realm_id despite the join to# zerver_messages, since the user_profile_id limit in# usermessage is more selective, and the query planner# can't know about that cross-table correlation.- .where(column("user_profile_id", Integer) == literal(user_profile.id))- .select_from(table("zerver_usermessage"))- .join(- table("zerver_message"),- literal_column("zerver_usermessage.message_id", Integer)- == literal_column("zerver_message.id", Integer),+ user_profile_id=user_profile.id+ )++ # Mirror the restrictions in bulk_access_stream_messages_query, in order+ # to prevent leftover UserMessage rows from granting access to messages+ # the user was previously allowed to access but no longer is.+ stream_access_filters = Q(pk__in=[]) # Always false.+ if user_profile.can_access_public_streams():+ stream_access_filters |= Q(invite_only=False)+ if user_recursive_group_ids:+ stream_access_filters |= Q(can_subscribe_group_id__in=user_recursive_group_ids) | Q(+ can_add_subscribers_group_id__in=user_recursive_group_ids)- .join(- table("zerver_recipient"),- literal_column("zerver_message.recipient_id", Integer)- == literal_column("zerver_recipient.id", Integer),+ return query.filter(+ # Include direct messages.+ ~Q(recipient__type=Recipient.STREAM)+ # Include messages where the recipient is a public stream and+ # the user can access public streams, or the user is a non-guest+ # belonging to a group granting access to the stream.+ | Exists(+ Stream.objects.filter(recipient=OuterRef("recipient")).filter(stream_access_filters))- # Mirror the restrictions in bulk_access_stream_messages_query, in order- # to prevent leftover UserMessage rows from granting access to messages- # the user was previously allowed to access but no longer is.- .where(- or_(- # Include direct messages.- literal_column("zerver_recipient.type", Integer) != Recipient.STREAM,- # Include messages where the recipient is a public stream and- # the user can access public streams, or the user is a non-guest- # belonging to a group granting access to the stream.- select()- .select_from(table("zerver_stream"))- .where(- literal_column("zerver_stream.recipient_id", Integer)- == literal_column("zerver_recipient.id", Integer)- )- .where(- or_(- and_(- not_(literal_column("zerver_stream.invite_only", Boolean)),- user_profile.can_access_public_streams(),- ),- literal_column("zerver_stream.can_subscribe_group_id").in_(- user_recursive_group_ids- ),- literal_column("zerver_stream.can_add_subscribers_group_id").in_(- user_recursive_group_ids- ),- )- )- .exists(),- # Include messages where the user has an active subscription to- # the stream.- select()- .select_from(table("zerver_subscription"))- .where(- literal_column("zerver_subscription.user_profile_id", Integer)- == user_profile.id,- literal_column("zerver_subscription.recipient_id", Integer)- == literal_column("zerver_recipient.id", Integer),- literal_column("zerver_subscription.active", Boolean),- )- .exists(),+ # Include messages where the user has an active subscription to+ # the stream.+ | Exists(+ Subscription.objects.filter(+ user_profile=user_profile, recipient=OuterRef("recipient"), active=True)))- inner_msg_id_col = column("message_id", Integer)- return (query, inner_msg_id_col)-def add_narrow_conditions(+ *,user_profile: UserProfile | None,- inner_msg_id_col: ColumnElement[Integer],- query: Select,+ query: QuerySet[Message],narrow: list[NarrowParameter] | None,is_web_public_query: bool,realm: Realm,-) -> tuple[Select, bool, bool]:+) -> tuple[QuerySet[Message], bool, bool]:is_search = False # for nowif narrow is None:return (query, is_search, False)# Build the query for the narrow- builder = NarrowBuilder(user_profile, inner_msg_id_col, realm, is_web_public_query)+ builder = NarrowBuilder(+ user_profile,+ realm,+ is_web_public_query=is_web_public_query,+ )search_operands = []# As we loop through terms, builder does most of the work to extend@@ -1092,7 +1056,7 @@ def add_narrow_conditions(# the system, ensuring accuracy in string highlighting and avoiding any discrepancies.## When a topic name is fetched from the database, it goes through this logic.- # The `func.escape_html()` function is used to escape the topic name, ensuring that+ # The `escape_html` function is used to escape the topic name, ensuring that# special characters are properly escaped. This helps to avoid the need to apply other# escaping logic to the topic name for string highlighting purposes. As a result, the# highlighted string will accurately match the actual topic name displayed in the UI.@@ -1106,9 +1070,10 @@ def add_narrow_conditions(# is no need for any special handling in `process_fts_updates` to align with this# escaping logic.is_search = True- query = query.add_columns(- func.escape_html(topic_column_sa(), type_=Text).label("escaped_topic_name"),- column("rendered_content", Text),+ query = query.annotate(+ escaped_topic_name=Func(+ F(DB_TOPIC_NAME), function="escape_html", output_field=TextField()+ ),)search_term = NarrowParameter(operator="search",@@ -1119,13 +1084,15 @@ def add_narrow_conditions(return (query, is_search, builder.is_dm_narrow)+def capture_find_first_unread_anchor_query_for_testing(query: QuerySet[Any]) -> None:+ pass++def find_first_unread_anchor(- sa_conn: Connection,user_profile: UserProfile | None,narrow: list[NarrowParameter] | None,- query: Select,+ query: QuerySet[Message],is_dm_narrow: bool,- inner_msg_id_col: ColumnElement[Integer],need_user_message: bool,) -> int:# For anonymous web users, all messages are treated as read, and so@@ -1141,23 +1108,21 @@ def find_first_unread_anchor(if not need_user_message:# We always need UserMessage in our query, because it has the unread# flag for the user.- query, inner_msg_id_col = get_base_query_for_search(+ query = get_base_query_for_search(realm_id=user_profile.realm_id,user_profile=user_profile,need_user_message=True,)- query = query.add_columns(column("flags", Integer))query, _is_search, is_dm_narrow = add_narrow_conditions(user_profile=user_profile,- inner_msg_id_col=inner_msg_id_col,query=query,narrow=narrow,is_web_public_query=False,realm=user_profile.realm,)- condition = column("flags", Integer).op("&")(UserMessage.flags.read.mask) == 0+ query = query.filter(user_flags__andz=UserMessage.flags.read.mask) # type: ignore[misc] # get_base_query_for_search adds the user_flags annotation# We exclude messages on muted topics when finding the first unread# message in this narrow@@ -1167,45 +1132,33 @@ def find_first_unread_anchor(# verbose for PostgreSQL to parse, we skip this for searches# which we know they cannot apply do -- DMs.muting_conditions = exclude_muting_conditions(user_profile, narrow)- if muting_conditions:- condition = and_(condition, *muting_conditions)-- first_unread_query = query.where(condition)- first_unread_query = first_unread_query.order_by(inner_msg_id_col.asc()).limit(1)- first_unread_result = list(sa_conn.execute(first_unread_query).fetchall())- if len(first_unread_result) > 0:- anchor = first_unread_result[0][0]- else:- anchor = LARGER_THAN_MAX_MESSAGE_ID+ query = query.filter(muting_conditions)+ values_query = query.order_by("id").values_list("id", flat=True)+ capture_find_first_unread_anchor_query_for_testing(values_query)+ anchor = values_query.first()+ if anchor is None:+ return LARGER_THAN_MAX_MESSAGE_IDreturn anchordef find_date_anchor(*,- sa_conn: Connection,anchor_date: datetime,- query: Select,- inner_msg_id_col: ColumnElement[Integer],+ query: QuerySet[Message],) -> int | None:- date_sent_col = literal_column("zerver_message.date_sent")-- first_row_after_date_anchor = sa_conn.execute(- query.where(date_sent_col >= anchor_date)- .order_by(date_sent_col.asc(), inner_msg_id_col.asc())- .limit(1)- ).fetchone()- if first_row_after_date_anchor is not None:- return first_row_after_date_anchor[0]+ first_after = (+ query.filter(date_sent__gte=anchor_date)+ .order_by("date_sent", "id")+ .values_list("id", flat=True)+ .first()+ )+ if first_after is not None:+ return first_after# If nothing is on/after the anchor date, fall back to the newest message.- last_row_before_date_anchor = sa_conn.execute(- query.order_by(date_sent_col.desc(), inner_msg_id_col.desc()).limit(1)- ).fetchone()- if last_row_before_date_anchor is not None:- return last_row_before_date_anchor[0]-- return None+ newest = query.order_by("-date_sent", "-id").values_list("id", flat=True).first()+ return newestdef parse_anchor_value(@@ -1268,16 +1221,15 @@ def parse_anchor_value(def limit_query_to_range(- query: Select,+ query: QuerySet[Message],num_before: int,num_after: int,anchor: int,include_anchor: bool,anchored_to_left: bool,anchored_to_right: bool,- id_col: ColumnElement[Integer],first_visible_message_id: int,-) -> SelectBase:+) -> QuerySet[Message]:"""This code is actually generic enough that we could move it to alibrary, but our only caller for now is message search.@@ -1313,29 +1265,30 @@ def limit_query_to_range(after_anchor = max(anchor + (not include_anchor), first_visible_message_id)after_limit = num_after + include_anchor+ before_query = None+ after_query = None+if need_before_query:before_query = queryif not anchored_to_right:- before_query = before_query.where(id_col <= before_anchor)+ before_query = before_query.filter(id__lte=before_anchor)- before_query = before_query.order_by(id_col.desc())- before_query = before_query.limit(before_limit)+ before_query = before_query.order_by("-id")[:before_limit]if need_after_query:after_query = queryif not anchored_to_left:- after_query = after_query.where(id_col >= after_anchor)+ after_query = after_query.filter(id__gte=after_anchor)- after_query = after_query.order_by(id_col.asc())- after_query = after_query.limit(after_limit)+ after_query = after_query.order_by("id")[:after_limit]- if need_both_sides:- return union_all(before_query.self_group(), after_query.self_group())- elif need_before_query:+ if before_query is not None and after_query is not None:+ return before_query.union(after_query, all=True)+ elif before_query is not None:return before_query- elif need_after_query:+ elif after_query is not None:return after_queryelse:# If we don't have either a before_query or after_query, it's because@@ -1346,7 +1299,7 @@ def limit_query_to_range(# for something like `message_id = 42` is exactly what we want. In other# cases, which could possibly be buggy API clients, at least we will# return at most one row here.- return query.where(id_col == anchor)+ return query.filter(id=anchor)MessageRowT = TypeVar("MessageRowT", bound=Sequence[Any])@@ -1439,12 +1392,16 @@ def clean_narrow_for_message_fetch(@dataclass-class FetchedMessages(LimitedMessages[Row]):+class FetchedMessages(LimitedMessages[tuple[Any, ...]]):anchor: int | Noneinclude_history: boolis_search: bool+def capture_message_fetch_query_for_testing(query: QuerySet[Any]) -> None:+ pass++def fetch_messages(*,narrow: list[NarrowParameter] | None,@@ -1488,18 +1445,14 @@ def fetch_messages(# get_base_query_for_search and ok_to_include_history are responsible for ensuring# that we only include messages the user has access to.- query: SelectBase- query, inner_msg_id_col = get_base_query_for_search(+ query = get_base_query_for_search(realm_id=realm.id,user_profile=user_profile,need_user_message=need_user_message,)- if need_user_message:- query = query.add_columns(column("flags", Integer))query, is_search, is_dm_narrow = add_narrow_conditions(user_profile=user_profile,- inner_msg_id_col=inner_msg_id_col,query=query,narrow=narrow,realm=realm,@@ -1513,78 +1466,76 @@ def fetch_messages(anchor_type = anchor_info["type"]anchor_value = anchor_info["value"]first_visible_message_id = get_first_visible_message_id(realm)- with get_sqlalchemy_connection() as sa_conn:- if client_requested_message_ids is not None:- query = query.filter(inner_msg_id_col.in_(client_requested_message_ids))- else:- if anchor_type == "date":- assert isinstance(anchor_value, datetime)- anchor_value = find_date_anchor(- sa_conn=sa_conn,- anchor_date=anchor_value,- query=query,- inner_msg_id_col=inner_msg_id_col,- )- # We did not find any message before or after the given timestamp,- # which means there are no messages in this narrow.- if anchor_value is None:- return FetchedMessages(- rows=[],- found_anchor=False,- found_newest=False,- found_oldest=False,- history_limited=False,- # We first tried to find a message that was sent after our- # anchor_date. When we did not find that, we went and looked- # for the newest message i.e LARGER_THAN_MAX_MESSAGE_ID.- anchor=LARGER_THAN_MAX_MESSAGE_ID,- include_history=include_history,- is_search=is_search,- )-- if anchor_type == "first_unread":- anchor_value = find_first_unread_anchor(- sa_conn,- user_profile,- narrow,- query,- is_dm_narrow,- inner_msg_id_col,- need_user_message,++ if client_requested_message_ids is not None:+ query = query.filter(id__in=client_requested_message_ids)+ else:+ if anchor_type == "date":+ assert isinstance(anchor_value, datetime)+ anchor_value = find_date_anchor(+ anchor_date=anchor_value,+ query=query,+ )+ # We did not find any message before or after the given timestamp,+ # which means there are no messages in this narrow.+ if anchor_value is None:+ return FetchedMessages(+ rows=[],+ found_anchor=False,+ found_newest=False,+ found_oldest=False,+ history_limited=False,+ # We first tried to find a message that was sent after our+ # anchor_date. When we did not find that, we went and looked+ # for the newest message i.e LARGER_THAN_MAX_MESSAGE_ID.+ anchor=LARGER_THAN_MAX_MESSAGE_ID,+ include_history=include_history,+ is_search=is_search,)- assert isinstance(anchor_value, int)+ if anchor_type == "first_unread":+ anchor_value = find_first_unread_anchor(+ user_profile,+ narrow,+ query,+ is_dm_narrow,+ need_user_message,+ )- anchored_to_left = anchor_value == 0+ assert isinstance(anchor_value, int)- # Set value that will be used to short circuit the after_query- # altogether and avoid needless conditions in the before_query.- anchored_to_right = anchor_value >= LARGER_THAN_MAX_MESSAGE_ID- if anchored_to_right:- num_after = 0+ anchored_to_left = anchor_value == 0- query = limit_query_to_range(- query=query,- num_before=num_before,- num_after=num_after,- anchor=anchor_value,- include_anchor=include_anchor,- anchored_to_left=anchored_to_left,- anchored_to_right=anchored_to_right,- id_col=inner_msg_id_col,- first_visible_message_id=first_visible_message_id,- )+ # Set value that will be used to short circuit the after_query+ # altogether and avoid needless conditions in the before_query.+ anchored_to_right = anchor_value >= LARGER_THAN_MAX_MESSAGE_ID+ if anchored_to_right:+ num_after = 0- main_query = query.subquery()- query = (- select(*main_query.c)- .select_from(main_query)- .order_by(column("message_id", Integer).asc())- )+ query = limit_query_to_range(+ query=query,+ num_before=num_before,+ num_after=num_after,+ anchor=anchor_value,+ include_anchor=include_anchor,+ anchored_to_left=anchored_to_left,+ anchored_to_right=anchored_to_right,+ first_visible_message_id=first_visible_message_id,+ )++ values_query = query.values_list(+ "id",+ *["user_flags"] if need_user_message else [],+ *["escaped_topic_name", "rendered_content", "content_matches", "topic_matches"]+ if is_search+ else [],+ )+ capture_message_fetch_query_for_testing(values_query)- # This is a hack to tag the query we use for testing- query = query.prefix_with("/* get_messages */")- rows = list(sa_conn.execute(query).fetchall())+ # limit_query_to_range may apply a DESC ordering or union disjoint+ # ranges; sort the rows by message_id in Python to match the API+ # contract.+ rows = sorted(values_query, key=lambda r: r[0])if client_requested_message_ids is not None:# We don't need to do any post-processing in this case.diff --git a/zerver/lib/sqlalchemy_utils.py b/zerver/lib/sqlalchemy_utils.pydeleted file mode 100644index ace89e353c8..00000000000--- a/zerver/lib/sqlalchemy_utils.py+++ /dev/null@@ -1,42 +0,0 @@-from collections.abc import Iterator-from contextlib import contextmanager--import sqlalchemy-from django.db import connection-from sqlalchemy.engine import Connection, Engine-from typing_extensions import override--from zerver.lib.db import TimeTrackingConnection---# This is a Pool that doesn't close connections. Therefore it can be used with-# existing Django database connections.-class NonClosingPool(sqlalchemy.pool.NullPool):- @override- def status(self) -> str:- return "NonClosingPool"-- def _do_return_conn(self, conn: sqlalchemy.engine.base.Connection) -> None:- pass---sqlalchemy_engine: Engine | None = None---@contextmanager-def get_sqlalchemy_connection() -> Iterator[Connection]:- global sqlalchemy_engine- if sqlalchemy_engine is None:-- def get_dj_conn() -> TimeTrackingConnection:- connection.ensure_connection()- return connection.connection-- sqlalchemy_engine = sqlalchemy.create_engine(- "postgresql://",- creator=get_dj_conn,- poolclass=NonClosingPool,- pool_reset_on_return=None,- )- with sqlalchemy_engine.connect().execution_options(autocommit=False) as sa_connection:- yield sa_connectiondiff --git a/zerver/lib/test_runner.py b/zerver/lib/test_runner.pyindex 6fdc282f660..5221828feb3 100644--- a/zerver/lib/test_runner.py+++ b/zerver/lib/test_runner.py@@ -24,7 +24,6 @@ from scripts.lib.zulip_tools import ()from zerver.lib import test_helpers, uploadfrom zerver.lib.partial import partial-from zerver.lib.sqlalchemy_utils import get_sqlalchemy_connectionfrom zerver.lib.test_fixtures import BACKEND_DATABASE_TEMPLATEfrom zerver.lib.test_helpers import append_instrumentation_data, write_instrumentation_reports@@ -391,12 +390,8 @@ class Runner(DiscoverRunner):destroy_test_databases(_worker_id)create_test_databases(_worker_id)- # We have to do the next line to avoid flaky scenarios where we- # run a single test and getting an SA connection causes data from- # a Django connection to be rolled back mid-test.- with get_sqlalchemy_connection():- result = self.run_suite(suite)- assert isinstance(result, TextTestResult)+ result = self.run_suite(suite)+ assert isinstance(result, TextTestResult)self.teardown_test_environment()failed = self.suite_result(suite, result)if not failed:diff --git a/zerver/lib/topic.py b/zerver/lib/topic.pyindex 182bbff83f0..bef8ab0c28b 100644--- a/zerver/lib/topic.py+++ b/zerver/lib/topic.py@@ -4,14 +4,25 @@ from typing import Anyimport orjsonfrom django.db import connection-from django.db.models import F, Func, JSONField, Q, QuerySet, Subquery, TextField, Value+from django.db.models import (+ Exists,+ F,+ Func,+ JSONField,+ OuterRef,+ Q,+ QuerySet,+ Subquery,+ TextField,+ Value,+)from django.db.models.functions import Castfrom django.utils.translation import gettext as _from django.utils.translation import override as override_languagefrom zerver.lib.types import EditHistoryEvent, StreamMessageEditRequestfrom zerver.lib.utils import assert_is_not_none-from zerver.models import Message, Reaction, UserMessage, UserProfile+from zerver.models import Message, Reaction, UserMessage, UserProfile, UserTopic# Only use these constants for events.ORIG_TOPIC = "orig_subject"@@ -393,3 +404,24 @@ def get_topic_display_name(topic_name: str, language: str) -> str:with override_language(language):return _(Message.EMPTY_TOPIC_FALLBACK_NAME)return topic_name+++def topic_match_q(topic_name: str) -> Q:+ return Q(subject__iexact=topic_name, is_channel_message=True)+++def get_resolved_topic_condition_q() -> Q:+ return Q(subject__startswith=RESOLVED_TOPIC_PREFIX, is_channel_message=True)+++def get_followed_topic_condition_q(user_id: int) -> Q:+ return Q(+ Exists(+ UserTopic.objects.filter(+ user_profile_id=user_id,+ visibility_policy=UserTopic.VisibilityPolicy.FOLLOWED,+ topic_name__iexact=OuterRef("subject"),+ recipient=OuterRef("recipient"),+ )+ )+ )diff --git a/zerver/lib/topic_sqlalchemy.py b/zerver/lib/topic_sqlalchemy.pydeleted file mode 100644index a796c0c5cee..00000000000--- a/zerver/lib/topic_sqlalchemy.py+++ /dev/null@@ -1,47 +0,0 @@-from sqlalchemy.sql import ColumnElement, and_, column, func, literal, literal_column, select, table-from sqlalchemy.types import Boolean, Text--from zerver.lib.topic import RESOLVED_TOPIC_PREFIX-from zerver.models import UserTopic---def topic_match_sa(topic_name: str) -> ColumnElement[Boolean]:- # _sa is short for SQLAlchemy, which we use mostly for- # queries that search messages- topic_cond = and_(- func.upper(column("subject", Text)) == func.upper(literal(topic_name)),- column("is_channel_message", Boolean),- )- return topic_cond---def get_resolved_topic_condition_sa() -> ColumnElement[Boolean]:- resolved_topic_cond = and_(- column("subject", Text).startswith(RESOLVED_TOPIC_PREFIX),- column("is_channel_message", Boolean),- )- return resolved_topic_cond---def topic_column_sa() -> ColumnElement[Text]:- return column("subject", Text)---def get_followed_topic_condition_sa(user_id: int) -> ColumnElement[Boolean]:- follow_topic_cond = (- select(1)- .select_from(table("zerver_usertopic"))- .where(- and_(- literal_column("zerver_usertopic.user_profile_id") == literal(user_id),- literal_column("zerver_usertopic.visibility_policy")- == literal(UserTopic.VisibilityPolicy.FOLLOWED),- func.upper(literal_column("zerver_usertopic.topic_name"))- == func.upper(literal_column("zerver_message.subject")),- literal_column("zerver_message.is_channel_message", Boolean),- literal_column("zerver_usertopic.recipient_id")- == literal_column("zerver_message.recipient_id"),- )- )- ).exists()- return follow_topic_conddiff --git a/zerver/lib/user_topics.py b/zerver/lib/user_topics.pyindex db5e089ab5c..cf733a4f8a2 100644--- a/zerver/lib/user_topics.py+++ b/zerver/lib/user_topics.py@@ -5,14 +5,12 @@ from datetime import datetimefrom typing import TypedDictfrom django.db import connection, transaction-from django.db.models import QuerySet+from django.db.models import Q, QuerySetfrom django.utils.timezone import now as timezone_nowfrom psycopg2.sql import SQL, Literal-from sqlalchemy.sql import ClauseElement, and_, column, not_, or_-from sqlalchemy.types import Integerfrom zerver.lib.timestamp import datetime_to_timestamp-from zerver.lib.topic_sqlalchemy import topic_match_sa+from zerver.lib.topic import topic_match_qfrom zerver.lib.types import UserTopicDictfrom zerver.models import Recipient, Subscription, UserProfile, UserTopicfrom zerver.models.streams import get_stream@@ -228,9 +226,7 @@ def topic_has_visibility_policy(return has_visibility_policy-def exclude_stream_and_topic_mutes(- conditions: list[ClauseElement], user_profile: UserProfile, stream_id: int | None-) -> list[ClauseElement]:+def exclude_stream_and_topic_mutes(user_profile: UserProfile, stream_id: int | None) -> Q:# Note: Unlike get_topic_mutes, here we always want to# consider topics in deactivated streams, so they are# never filtered from the query in this method.@@ -244,26 +240,31 @@ def exclude_stream_and_topic_mutes(# by not considering topic mutes outside the stream.query = query.filter(stream_id=stream_id)- excluded_topic_rows = query.values(- "recipient_id",- "topic_name",+ excluded_topic_rows = list(+ query.values(+ "recipient_id",+ "topic_name",+ ))+ conditions = ~Q(pk__in=[]) # Always true.+class RecipientTopicDict(TypedDict):recipient_id: inttopic_name: str- def topic_cond(row: RecipientTopicDict) -> ClauseElement:+ def topic_cond(row: RecipientTopicDict) -> Q:recipient_id = row["recipient_id"]topic_name = row["topic_name"]- stream_cond = column("recipient_id", Integer) == recipient_id- topic_cond = topic_match_sa(topic_name)- return and_(stream_cond, topic_cond)+ assert isinstance(topic_name, str)+ return Q(recipient_id=recipient_id) & topic_match_q(topic_name)# Add this query later to reduce the number of messages it has to run on.if excluded_topic_rows:- exclude_muted_topics_condition = not_(or_(*map(topic_cond, excluded_topic_rows)))- conditions = [*conditions, exclude_muted_topics_condition]+ muted_topics_q = topic_cond(excluded_topic_rows[0])+ for row in excluded_topic_rows[1:]:+ muted_topics_q |= topic_cond(row)+ conditions &= ~muted_topics_q# Channel-level muting only applies when looking at views that# include multiple channels, since we do want users to be able to@@ -296,24 +297,21 @@ def exclude_stream_and_topic_mutes()# Exclude muted_recipient_ids unless they match include_followed_or_unmuted_topics_condition- muted_stream_condition = column("recipient_id", Integer).in_(muted_recipient_ids)+ muted_stream_condition = Q(recipient_id__in=muted_recipient_ids)if included_topic_rows:- include_followed_or_unmuted_topics_condition = or_(- *map(topic_cond, included_topic_rows)- )+ include_followed_or_unmuted_topics_condition = topic_cond(included_topic_rows[0])+ for row in included_topic_rows[1:]: # nocoverage+ include_followed_or_unmuted_topics_condition |= topic_cond(row)- exclude_muted_streams_condition = not_(- and_(- muted_stream_condition,- not_(include_followed_or_unmuted_topics_condition),- )+ exclude_muted_streams_condition = ~(+ muted_stream_condition & ~include_followed_or_unmuted_topics_condition)else:# If no included topics, exclude all muted streams- exclude_muted_streams_condition = not_(muted_stream_condition)+ exclude_muted_streams_condition = ~muted_stream_condition- conditions = [*conditions, exclude_muted_streams_condition]+ conditions &= exclude_muted_streams_conditionreturn conditionsdiff --git a/zerver/tests/test_message_fetch.py b/zerver/tests/test_message_fetch.pyindex bc6d3f0fb62..c73b63213be 100644--- a/zerver/tests/test_message_fetch.py+++ b/zerver/tests/test_message_fetch.py@@ -5,11 +5,11 @@ from typing import TYPE_CHECKING, Anyfrom unittest import mockimport orjson+from django.core.exceptions import EmptyResultSetfrom django.db import connection+from django.db.models import F, Q, QuerySetfrom django.test import override_settingsfrom django.utils.timezone import now as timezone_now-from sqlalchemy.sql import ClauseElement, Select, and_, column, select, table-from sqlalchemy.types import Integerfrom typing_extensions import overridefrom analytics.lib.counts import COUNT_STATS@@ -47,7 +47,6 @@ from zerver.lib.narrow import ()from zerver.lib.narrow_helpers import NeverNegatedNarrowTermfrom zerver.lib.narrow_predicate import build_narrow_predicate-from zerver.lib.sqlalchemy_utils import get_sqlalchemy_connectionfrom zerver.lib.streams import StreamDict, create_streams_if_needed, get_public_streams_querysetfrom zerver.lib.test_classes import ZulipTestCasefrom zerver.lib.test_helpers import (@@ -87,18 +86,10 @@ class InvalidParam:expected_error: str-def get_sqlalchemy_sql(query: ClauseElement) -> str:- with get_sqlalchemy_connection() as conn:- dialect = conn.dialect- comp = query.compile(dialect=dialect)- return str(comp)---def get_sqlalchemy_query_params(query: ClauseElement) -> dict[str, object]:- with get_sqlalchemy_connection() as conn:- dialect = conn.dialect- comp = query.compile(dialect=dialect)- return comp.params+def get_django_sql(query: QuerySet[Any]) -> str:+ sql, params = query.query.sql_with_params()+ with connection.cursor() as cursor:+ return cursor.mogrify(sql, params).decode()def get_recipient_id_for_channel_name(realm: Realm, channel_name: str) -> int | None:@@ -127,8 +118,8 @@ class NarrowBuilderTest(ZulipTestCase):super().setUp()self.realm = get_realm("zulip")self.user_profile = self.example_user("hamlet")- self.builder = NarrowBuilder(self.user_profile, column("id", Integer), self.realm)- self.raw_query = select(column("id", Integer)).select_from(table("zerver_message"))+ self.builder = NarrowBuilder(self.user_profile, self.realm)+ self.raw_query = Message.objects.all().annotate(user_flags=F("usermessage__flags"))self.hamlet_email = self.example_user("hamlet").emailself.othello_email = self.example_user("othello").email@@ -138,11 +129,11 @@ class NarrowBuilderTest(ZulipTestCase):def test_add_term_using_channel_operator(self) -> None:term = NarrowParameter(operator="channel", operand="Scotland")- self._do_add_term_test(term, "WHERE recipient_id = %(recipient_id_1)s")+ self._do_add_term_test(term, 'WHERE "zerver_message"."recipient_id" = %s')def test_add_term_using_channel_operator_and_negated(self) -> None: # NEGATEDterm = NarrowParameter(operator="channel", operand="Scotland", negated=True)- self._do_add_term_test(term, "WHERE recipient_id != %(recipient_id_1)s")+ self._do_add_term_test(term, 'WHERE NOT ("zerver_message"."recipient_id" = %s)')def test_add_term_using_channel_operator_and_non_existing_operand_should_raise_error(self,@@ -160,7 +151,7 @@ class NarrowBuilderTest(ZulipTestCase):term = NarrowParameter(operator="channels", operand="public")self._do_add_term_test(term,- "WHERE recipient_id IN (__[POSTCOMPILE_recipient_id_1])",+ 'WHERE "zerver_message"."recipient_id" IN (%s, %s, %s, %s, %s, %s, %s)',)# Add new channels@@ -189,14 +180,14 @@ class NarrowBuilderTest(ZulipTestCase):# Number of recipient ids will increase by 1 and not 3self._do_add_term_test(term,- "WHERE recipient_id IN (__[POSTCOMPILE_recipient_id_1])",+ 'WHERE "zerver_message"."recipient_id" IN (%s, %s, %s, %s, %s, %s, %s, %s)',)def test_add_term_using_channels_operator_and_public_operand_negated(self) -> None:term = NarrowParameter(operator="channels", operand="public", negated=True)self._do_add_term_test(term,- "WHERE (recipient_id NOT IN (__[POSTCOMPILE_recipient_id_1]))",+ 'WHERE NOT ("zerver_message"."recipient_id" IN (%s, %s, %s, %s, %s, %s, %s))',)# Add new channels@@ -225,110 +216,109 @@ class NarrowBuilderTest(ZulipTestCase):# Number of recipient ids will increase by 1 and not 3self._do_add_term_test(term,- "WHERE (recipient_id NOT IN (__[POSTCOMPILE_recipient_id_1]))",+ 'WHERE NOT ("zerver_message"."recipient_id" IN (%s, %s, %s, %s, %s, %s, %s, %s))',)def test_add_term_using_channels_operator_and_archived_operand(self) -> None:+ stream = get_stream("Verona", self.realm)+ do_deactivate_stream(stream, acting_user=self.user_profile)term = NarrowParameter(operator="channels", operand="archived")self._do_add_term_test(term,- "WHERE recipient_id IN (__[POSTCOMPILE_recipient_id_1])",+ 'WHERE "zerver_message"."recipient_id" IN (%s)',+ (stream.recipient_id,),)def test_add_term_using_channels_operator_and_archived_operand_negated(self) -> None:+ stream = get_stream("Verona", self.realm)+ do_deactivate_stream(stream, acting_user=self.user_profile)term = NarrowParameter(operator="channels", operand="archived", negated=True)self._do_add_term_test(term,- "WHERE (recipient_id NOT IN (__[POSTCOMPILE_recipient_id_1]))",+ 'WHERE NOT ("zerver_message"."recipient_id" IN (%s))',+ (stream.recipient_id,),)def test_add_term_using_is_operator_and_dm_operand(self) -> None:term = NarrowParameter(operator="is", operand="dm")- self._do_add_term_test(term, "WHERE (flags & %(flags_1)s) != %(param_1)s")+ self._do_add_term_test(term, 'WHERE "zerver_usermessage"."flags" & %s != 0')def test_add_term_using_is_operator_dm_operand_and_negated(self) -> None: # NEGATEDterm = NarrowParameter(operator="is", operand="dm", negated=True)- self._do_add_term_test(term, "WHERE (flags & %(flags_1)s) = %(param_1)s")+ self._do_add_term_test(term, 'WHERE NOT ("zerver_usermessage"."flags" & %s != 0)')def test_add_term_using_is_operator_and_non_dm_operand(self) -> None:for operand in ["starred", "mentioned", "alerted"]:term = NarrowParameter(operator="is", operand=operand)- self._do_add_term_test(term, "WHERE (flags & %(flags_1)s) != %(param_1)s")+ self._do_add_term_test(term, 'WHERE "zerver_usermessage"."flags" & %s != 0')def test_add_term_using_is_operator_and_unread_operand(self) -> None:term = NarrowParameter(operator="is", operand="unread")- self._do_add_term_test(term, "WHERE (flags & %(flags_1)s) = %(param_1)s")+ self._do_add_term_test(term, 'WHERE "zerver_usermessage"."flags" & %s = 0')def test_add_term_using_is_operator_and_unread_operand_and_negated(self) -> None: # NEGATEDterm = NarrowParameter(operator="is", operand="unread", negated=True)- self._do_add_term_test(term, "WHERE (flags & %(flags_1)s) != %(param_1)s")+ self._do_add_term_test(term, 'WHERE NOT ("zerver_usermessage"."flags" & %s = 0)')def test_add_term_using_is_operator_non_dm_operand_and_negated(self) -> None: # NEGATEDterm = NarrowParameter(operator="is", operand="starred", negated=True)- where_clause = "WHERE (flags & %(flags_1)s) = %(param_1)s"- params = dict(- flags_1=UserMessage.flags.starred.mask,- param_1=0,- )+ where_clause = 'WHERE NOT ("zerver_usermessage"."flags" & %s != 0)'+ params = (UserMessage.flags.starred.mask,)self._do_add_term_test(term, where_clause, params)term = NarrowParameter(operator="is", operand="alerted", negated=True)- where_clause = "WHERE (flags & %(flags_1)s) = %(param_1)s"- params = dict(- flags_1=UserMessage.flags.has_alert_word.mask,- param_1=0,- )+ where_clause = 'WHERE NOT ("zerver_usermessage"."flags" & %s != 0)'+ params = (UserMessage.flags.has_alert_word.mask,)self._do_add_term_test(term, where_clause, params)term = NarrowParameter(operator="is", operand="mentioned", negated=True)- where_clause = "WHERE (flags & %(flags_1)s) = %(param_1)s"+ where_clause = 'WHERE NOT ("zerver_usermessage"."flags" & %s != 0)'mention_flags_mask = (UserMessage.flags.mentioned.mask| UserMessage.flags.stream_wildcard_mentioned.mask| UserMessage.flags.topic_wildcard_mentioned.mask| UserMessage.flags.group_mentioned.mask)- params = dict(- flags_1=mention_flags_mask,- param_1=0,- )+ params = (mention_flags_mask,)self._do_add_term_test(term, where_clause, params)def test_add_term_using_is_operator_for_resolved_topics(self) -> None:term = NarrowParameter(operator="is", operand="resolved")self._do_add_term_test(- term, "WHERE (subject LIKE %(subject_1)s || '%%') AND is_channel_message"+ term,+ 'WHERE ("zerver_message"."is_channel_message" AND "zerver_message"."subject"::text LIKE %s)',)def test_add_term_using_is_operator_for_negated_resolved_topics(self) -> None:term = NarrowParameter(operator="is", operand="resolved", negated=True)self._do_add_term_test(- term, "WHERE NOT ((subject LIKE %(subject_1)s || '%%') AND is_channel_message)"+ term,+ 'WHERE NOT ("zerver_message"."is_channel_message" AND "zerver_message"."subject"::text LIKE %s)',)def test_add_term_using_is_operator_for_followed_topics(self) -> None:term = NarrowParameter(operator="is", operand="followed", negated=False)self._do_add_term_test(term,- "EXISTS (SELECT 1 \nFROM zerver_usertopic \nWHERE zerver_usertopic.user_profile_id = %(param_1)s AND zerver_usertopic.visibility_policy = %(param_2)s AND upper(zerver_usertopic.topic_name) = upper(zerver_message.subject) AND zerver_message.is_channel_message AND zerver_usertopic.recipient_id = zerver_message.recipient_id)",+ 'WHERE EXISTS(SELECT %s AS "a" FROM "zerver_usertopic" U0 WHERE (U0."recipient_id" = ("zerver_message"."recipient_id") AND UPPER(U0."topic_name"::text) = UPPER(("zerver_message"."subject")) AND U0."user_profile_id" = %s AND U0."visibility_policy" = %s) LIMIT 1)',)def test_add_term_using_is_operator_for_negated_followed_topics(self) -> None:term = NarrowParameter(operator="is", operand="followed", negated=True)self._do_add_term_test(term,- "NOT (EXISTS (SELECT 1 \nFROM zerver_usertopic \nWHERE zerver_usertopic.user_profile_id = %(param_1)s AND zerver_usertopic.visibility_policy = %(param_2)s AND upper(zerver_usertopic.topic_name) = upper(zerver_message.subject) AND zerver_message.is_channel_message AND zerver_usertopic.recipient_id = zerver_message.recipient_id))",+ 'WHERE NOT (EXISTS(SELECT %s AS "a" FROM "zerver_usertopic" U0 WHERE (U0."recipient_id" = ("zerver_message"."recipient_id") AND UPPER(U0."topic_name"::text) = UPPER(("zerver_message"."subject")) AND U0."user_profile_id" = %s AND U0."visibility_policy" = %s) LIMIT 1))',)def test_add_term_using_is_operator_for_muted_topics(self) -> None:mute_channel(self.realm, self.user_profile, "Verona")term = NarrowParameter(operator="is", operand="muted", negated=False)- self._do_add_term_test(term, "WHERE recipient_id IN (__[POSTCOMPILE_recipient_id_1])")+ self._do_add_term_test(term, 'WHERE NOT (NOT ("zerver_message"."recipient_id" IN (%s)))')def test_add_term_using_is_operator_for_negated_muted_topics(self) -> None:mute_channel(self.realm, self.user_profile, "Verona")term = NarrowParameter(operator="is", operand="muted", negated=True)- self._do_add_term_test(term, "WHERE (recipient_id NOT IN (__[POSTCOMPILE_recipient_id_1]))")+ self._do_add_term_test(term, 'WHERE NOT ("zerver_message"."recipient_id" IN (%s))')def test_add_term_using_non_supported_operator_should_raise_error(self) -> None:term = NarrowParameter(operator="is", operand="non_supported")@@ -337,34 +327,38 @@ class NarrowBuilderTest(ZulipTestCase):def test_add_term_using_topic_operator_and_lunch_operand(self) -> None:term = NarrowParameter(operator="topic", operand="lunch")self._do_add_term_test(- term, "WHERE upper(subject) = upper(%(param_1)s) AND is_channel_message"+ term,+ 'WHERE ("zerver_message"."is_channel_message" AND UPPER("zerver_message"."subject"::text) = UPPER(%s))',)def test_add_term_using_topic_operator_lunch_operand_and_negated(self) -> None: # NEGATEDterm = NarrowParameter(operator="topic", operand="lunch", negated=True)self._do_add_term_test(- term, "WHERE NOT (upper(subject) = upper(%(param_1)s) AND is_channel_message)"+ term,+ 'WHERE NOT ("zerver_message"."is_channel_message" AND UPPER("zerver_message"."subject"::text) = UPPER(%s))',)def test_add_term_using_topic_operator_and_personal_operand(self) -> None:term = NarrowParameter(operator="topic", operand="personal")self._do_add_term_test(- term, "WHERE upper(subject) = upper(%(param_1)s) AND is_channel_message"+ term,+ 'WHERE ("zerver_message"."is_channel_message" AND UPPER("zerver_message"."subject"::text) = UPPER(%s))',)def test_add_term_using_topic_operator_personal_operand_and_negated(self) -> None: # NEGATEDterm = NarrowParameter(operator="topic", operand="personal", negated=True)self._do_add_term_test(- term, "WHERE NOT (upper(subject) = upper(%(param_1)s) AND is_channel_message)"+ term,+ 'WHERE NOT ("zerver_message"."is_channel_message" AND UPPER("zerver_message"."subject"::text) = UPPER(%s))',)def test_add_term_using_sender_operator(self) -> None:term = NarrowParameter(operator="sender", operand=self.othello_email)- self._do_add_term_test(term, "WHERE sender_id = %(param_1)s")+ self._do_add_term_test(term, 'WHERE "zerver_message"."sender_id" = %s')def test_add_term_using_sender_operator_and_negated(self) -> None: # NEGATEDterm = NarrowParameter(operator="sender", operand=self.othello_email, negated=True)- self._do_add_term_test(term, "WHERE sender_id != %(param_1)s")+ self._do_add_term_test(term, 'WHERE NOT ("zerver_message"."sender_id" = %s)')def test_add_term_using_sender_operator_with_non_existing_user_as_operand(self,@@ -377,10 +371,8 @@ class NarrowBuilderTest(ZulipTestCase):) -> None:# Without a DM group, no messages are possibleterm = NarrowParameter(operator="dm", operand=self.othello_email)- self._do_add_term_test(- term,- "WHERE false",- )+ with self.assertRaises(EmptyResultSet):+ self._do_add_term_test(term, "")def test_add_term_using_dm_operator_and_not_the_same_user_as_operand(self) -> None:# Create a direct message group between users@@ -394,7 +386,7 @@ class NarrowBuilderTest(ZulipTestCase):# Query uses DM group recipientself._do_add_term_test(term,- "WHERE recipient_id = %(recipient_id_1)s",+ 'WHERE "zerver_message"."recipient_id" = %s',)def test_negated_is_dm_with_dm_operator(self) -> None:@@ -445,10 +437,7 @@ class NarrowBuilderTest(ZulipTestCase):) -> None: # NEGATED# Without a DM group, negated false() becomes trueterm = NarrowParameter(operator="dm", operand=self.othello_email, negated=True)- self._do_add_term_test(- term,- "WHERE true",- )+ self._do_add_term_test_always_true(term)def test_add_term_using_dm_operator_not_the_same_user_as_operand_and_negated(self,@@ -464,7 +453,7 @@ class NarrowBuilderTest(ZulipTestCase):# Query uses DM group recipient (negated)self._do_add_term_test(term,- "WHERE recipient_id != %(recipient_id_1)s",+ 'WHERE NOT ("zerver_message"."recipient_id" = %s)',)def test_add_term_using_dm_operator_the_same_user_as_operand_no_direct_message_group(@@ -472,10 +461,8 @@ class NarrowBuilderTest(ZulipTestCase):) -> None:# Without a DM group, no messages are possibleterm = NarrowParameter(operator="dm", operand=self.hamlet_email)- self._do_add_term_test(- term,- "WHERE false",- )+ with self.assertRaises(EmptyResultSet):+ self._do_add_term_test(term, "")def test_add_term_using_dm_operator_the_same_user_as_operand(self) -> None:# Create a direct message group with the user@@ -488,7 +475,7 @@ class NarrowBuilderTest(ZulipTestCase):# Query uses DM group recipient for self-DMself._do_add_term_test(term,- "WHERE recipient_id = %(recipient_id_1)s",+ 'WHERE "zerver_message"."recipient_id" = %s',)def test_add_term_using_dm_operator_the_same_user_as_operand_no_direct_message_group_and_negated(@@ -496,10 +483,7 @@ class NarrowBuilderTest(ZulipTestCase):) -> None: # NEGATED# Without a DM group, negated false() becomes trueterm = NarrowParameter(operator="dm", operand=self.hamlet_email, negated=True)- self._do_add_term_test(- term,- "WHERE true",- )+ self._do_add_term_test_always_true(term)def test_add_term_using_dm_operator_the_same_user_as_operand_and_negated(self,@@ -514,7 +498,7 @@ class NarrowBuilderTest(ZulipTestCase):# Query uses DM group recipient (negated)self._do_add_term_test(term,- "WHERE recipient_id != %(recipient_id_1)s",+ 'WHERE NOT ("zerver_message"."recipient_id" = %s)',)def test_add_term_using_dm_operator_and_self_and_user_as_operand_no_direct_message_group(@@ -525,10 +509,8 @@ class NarrowBuilderTest(ZulipTestCase):)term = NarrowParameter(operator="dm", operand=myself_and_other)# Without a DM group, no messages are possible- self._do_add_term_test(- term,- "WHERE false",- )+ with self.assertRaises(EmptyResultSet):+ self._do_add_term_test(term, "")def test_add_term_using_dm_operator_and_self_and_user_as_operand(self) -> None:# Make the direct message group first@@ -545,7 +527,7 @@ class NarrowBuilderTest(ZulipTestCase):# Query uses DM group recipientself._do_add_term_test(term,- "WHERE recipient_id = %(recipient_id_1)s",+ 'WHERE "zerver_message"."recipient_id" = %s',)def test_add_term_using_dm_operator_more_than_one_user_as_operand_no_direct_message_group(@@ -554,7 +536,8 @@ class NarrowBuilderTest(ZulipTestCase):# If the group doesn't exist, it's a flat falsetwo_others = f"{self.example_user('cordelia').email},{self.example_user('othello').email}"term = NarrowParameter(operator="dm", operand=two_others)- self._do_add_term_test(term, "WHERE false")+ with self.assertRaises(EmptyResultSet):+ self._do_add_term_test(term, "")def test_add_term_using_dm_operator_more_than_one_user_as_operand(self) -> None:# Make the direct message group first@@ -570,7 +553,7 @@ class NarrowBuilderTest(ZulipTestCase):# 3+ person group DM uses simple recipient_id matchself._do_add_term_test(term,- "WHERE recipient_id = %(recipient_id_1)s",+ 'WHERE "zerver_message"."recipient_id" = %s',)def test_add_term_using_dm_operator_self_and_user_as_operand_no_group_direct_message_and_negated(@@ -581,10 +564,7 @@ class NarrowBuilderTest(ZulipTestCase):)term = NarrowParameter(operator="dm", operand=myself_and_other, negated=True)# Without a DM group, negated false() becomes true- self._do_add_term_test(- term,- "WHERE true",- )+ self._do_add_term_test_always_true(term)def test_add_term_using_dm_operator_self_and_user_as_operand_and_negated(self,@@ -603,7 +583,7 @@ class NarrowBuilderTest(ZulipTestCase):# Query uses DM group recipient (negated)self._do_add_term_test(term,- "WHERE recipient_id != %(recipient_id_1)s",+ 'WHERE NOT ("zerver_message"."recipient_id" = %s)',)def test_add_term_using_dm_operator_more_than_one_user_as_operand_no_direct_message_group_and_negated(@@ -612,7 +592,7 @@ class NarrowBuilderTest(ZulipTestCase):# If the group doesn't exist, it's a flat truetwo_others = f"{self.example_user('cordelia').email},{self.example_user('othello').email}"term = NarrowParameter(operator="dm", operand=two_others, negated=True)- self._do_add_term_test(term, "WHERE true")+ self._do_add_term_test_always_true(term)def test_add_term_using_dm_operator_more_than_one_user_as_operand_and_negated(self,@@ -630,7 +610,7 @@ class NarrowBuilderTest(ZulipTestCase):# 3+ person group DM uses simple recipient_id match (negated)self._do_add_term_test(term,- "WHERE recipient_id != %(recipient_id_1)s",+ 'WHERE NOT ("zerver_message"."recipient_id" = %s)',)def test_add_term_using_dm_operator_with_comma_noise(self) -> None:@@ -647,15 +627,13 @@ class NarrowBuilderTest(ZulipTestCase):def test_add_term_using_dm_including_operator_with_logged_in_user_email(self) -> None:term = NarrowParameter(operator="dm-including", operand=self.hamlet_email)- self._do_add_term_test(term, "WHERE (flags & %(flags_1)s) != %(param_1)s")+ self._do_add_term_test(term, 'WHERE "zerver_usermessage"."flags" & %s != 0')def test_add_term_using_dm_including_operator_with_different_user_email(self) -> None:# Test without any such group direct messages existingterm = NarrowParameter(operator="dm-including", operand=self.othello_email)- self._do_add_term_test(- term,- "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND recipient_id IN (__[POSTCOMPILE_recipient_id_1])",- )+ with self.assertRaises(EmptyResultSet):+ self._do_add_term_test(term, "")# Test with at least one such group direct messages existingself.send_group_direct_message(@@ -665,25 +643,26 @@ class NarrowBuilderTest(ZulipTestCase):term = NarrowParameter(operator="dm-including", operand=self.othello_email)self._do_add_term_test(term,- "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND recipient_id IN (__[POSTCOMPILE_recipient_id_1])",+ 'WHERE ("zerver_message"."realm_id" = %s AND "zerver_message"."recipient_id" IN (%s) AND "zerver_usermessage"."flags" & %s != 0)',)def test_add_term_using_dm_including_operator_with_different_user_email_and_negated(self,) -> None: # NEGATED+ self.send_group_direct_message(self.user_profile, [self.example_user("othello")])term = NarrowParameter(operator="dm-including", operand=self.othello_email, negated=True)self._do_add_term_test(term,- "WHERE NOT ((flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND recipient_id IN (__[POSTCOMPILE_recipient_id_1]))",+ 'WHERE NOT ("zerver_message"."realm_id" = %s AND "zerver_message"."recipient_id" IN (%s) AND "zerver_usermessage"."flags" & %s != 0)',)def test_add_term_using_id_operator_integer(self) -> None:term = NarrowParameter(operator="id", operand=555)- self._do_add_term_test(term, "WHERE id = %(param_1)s")+ self._do_add_term_test(term, 'WHERE "zerver_message"."id" = %s')def test_add_term_using_id_operator_string(self) -> None:term = NarrowParameter(operator="id", operand="555")- self._do_add_term_test(term, "WHERE id = %(param_1)s")+ self._do_add_term_test(term, 'WHERE "zerver_message"."id" = %s')def test_add_term_using_id_operator_invalid(self) -> None:term = NarrowParameter(operator="id", operand="")@@ -697,14 +676,14 @@ class NarrowBuilderTest(ZulipTestCase):def test_add_term_using_id_operator_and_negated(self) -> None: # NEGATEDterm = NarrowParameter(operator="id", operand=555, negated=True)- self._do_add_term_test(term, "WHERE id != %(param_1)s")+ self._do_add_term_test(term, 'WHERE NOT ("zerver_message"."id" = %s)')@override_settings(USING_PGROONGA=False)def test_add_term_using_search_operator(self) -> None:term = NarrowParameter(operator="search", operand='"french fries"')self._do_add_term_test(term,- "WHERE (content ILIKE %(content_1)s OR subject ILIKE %(subject_1)s AND is_channel_message) AND (search_tsvector @@ plainto_tsquery(%(param_4)s, %(param_5)s))",+ """WHERE ((UPPER("zerver_message"."content"::text) LIKE UPPER(%s) OR ("zerver_message"."is_channel_message" AND UPPER("zerver_message"."subject"::text) LIKE UPPER(%s))) AND ("zerver_message"."search_tsvector" @@ plainto_tsquery(%s, %s)) = %s)""",)@override_settings(USING_PGROONGA=False)@@ -712,57 +691,59 @@ class NarrowBuilderTest(ZulipTestCase):term = NarrowParameter(operator="search", operand='"french fries"', negated=True)self._do_add_term_test(term,- "WHERE NOT (content ILIKE %(content_1)s OR subject ILIKE %(subject_1)s AND is_channel_message) AND NOT (search_tsvector @@ plainto_tsquery(%(param_4)s, %(param_5)s))",+ """WHERE (NOT (UPPER("zerver_message"."content"::text) LIKE UPPER(%s) OR ("zerver_message"."is_channel_message" AND UPPER("zerver_message"."subject"::text) LIKE UPPER(%s))) AND NOT (("zerver_message"."search_tsvector" @@ plainto_tsquery(%s, %s)) = %s))""",)@override_settings(USING_PGROONGA=True)def test_add_term_using_search_operator_pgroonga(self) -> None:term = NarrowParameter(operator="search", operand='"french fries"')- self._do_add_term_test(term, "WHERE search_pgroonga &@~ escape_html(%(escape_html_1)s)")+ self._do_add_term_test(+ term, 'WHERE ("zerver_message"."search_pgroonga" &@~ escape_html(%s)) = %s'+ )@override_settings(USING_PGROONGA=True)def test_add_term_using_search_operator_and_negated_pgroonga(self) -> None: # NEGATEDterm = NarrowParameter(operator="search", operand='"french fries"', negated=True)self._do_add_term_test(- term, "WHERE NOT (search_pgroonga &@~ escape_html(%(escape_html_1)s))"+ term, 'WHERE NOT (("zerver_message"."search_pgroonga" &@~ escape_html(%s)) = %s)')def test_add_term_using_has_operator_and_attachment_operand(self) -> None:term = NarrowParameter(operator="has", operand="attachment")- self._do_add_term_test(term, "WHERE has_attachment")+ self._do_add_term_test(term, 'WHERE "zerver_message"."has_attachment"')def test_add_term_using_has_operator_attachment_operand_and_negated(self) -> None: # NEGATEDterm = NarrowParameter(operator="has", operand="attachment", negated=True)- self._do_add_term_test(term, "WHERE NOT has_attachment")+ self._do_add_term_test(term, 'WHERE NOT ("zerver_message"."has_attachment")')def test_add_term_using_has_operator_and_image_operand(self) -> None:term = NarrowParameter(operator="has", operand="image")- self._do_add_term_test(term, "WHERE has_image")+ self._do_add_term_test(term, 'WHERE "zerver_message"."has_image"')def test_add_term_using_has_operator_image_operand_and_negated(self) -> None: # NEGATEDterm = NarrowParameter(operator="has", operand="image", negated=True)- self._do_add_term_test(term, "WHERE NOT has_image")+ self._do_add_term_test(term, 'WHERE NOT ("zerver_message"."has_image")')def test_add_term_using_has_operator_and_link_operand(self) -> None:term = NarrowParameter(operator="has", operand="link")- self._do_add_term_test(term, "WHERE has_link")+ self._do_add_term_test(term, 'WHERE "zerver_message"."has_link"')def test_add_term_using_has_operator_link_operand_and_negated(self) -> None: # NEGATEDterm = NarrowParameter(operator="has", operand="link", negated=True)- self._do_add_term_test(term, "WHERE NOT has_link")+ self._do_add_term_test(term, 'WHERE NOT ("zerver_message"."has_link")')def test_add_term_using_has_operator_and_reaction_operand(self) -> None:term = NarrowParameter(operator="has", operand="reaction")self._do_add_term_test(term,- "EXISTS (SELECT 1 \nFROM zerver_reaction \nWHERE zerver_message.id = zerver_reaction.message_id)",+ 'WHERE EXISTS(SELECT %s AS "a" FROM "zerver_reaction" U0 WHERE U0."message_id" = ("zerver_message"."id") LIMIT 1)',)def test_add_term_using_has_operator_and_reaction_operand_and_negated(self) -> None:term = NarrowParameter(operator="has", operand="reaction", negated=True)self._do_add_term_test(term,- "NOT (EXISTS (SELECT 1 \nFROM zerver_reaction \nWHERE zerver_message.id = zerver_reaction.message_id))",+ 'WHERE NOT (EXISTS(SELECT %s AS "a" FROM "zerver_reaction" U0 WHERE U0."message_id" = ("zerver_message"."id") LIMIT 1))',)def test_add_term_using_has_operator_non_supported_operand_should_raise_error(self) -> None:@@ -772,25 +753,23 @@ class NarrowBuilderTest(ZulipTestCase):def test_add_term_using_in_operator(self) -> None:mute_channel(self.realm, self.user_profile, "Verona")term = NarrowParameter(operator="in", operand="home")- self._do_add_term_test(term, "WHERE (recipient_id NOT IN (__[POSTCOMPILE_recipient_id_1]))")+ self._do_add_term_test(term, 'WHERE NOT ("zerver_message"."recipient_id" IN (%s))')def test_add_term_using_in_operator_and_negated(self) -> None:mute_channel(self.realm, self.user_profile, "Verona")term = NarrowParameter(operator="in", operand="home", negated=True)- self._do_add_term_test(term, "WHERE recipient_id IN (__[POSTCOMPILE_recipient_id_1])")+ self._do_add_term_test(term, 'WHERE NOT (NOT ("zerver_message"."recipient_id" IN (%s)))')def test_add_term_using_in_operator_and_all_operand(self) -> None:mute_channel(self.realm, self.user_profile, "Verona")term = NarrowParameter(operator="in", operand="all")- query = self._build_query(term)- self.assertEqual(get_sqlalchemy_sql(query), "SELECT id \nFROM zerver_message")+ self._do_add_term_test_always_true(term)def test_add_term_using_in_operator_all_operand_and_negated(self) -> None:# negated = True should not change anythingmute_channel(self.realm, self.user_profile, "Verona")term = NarrowParameter(operator="in", operand="all", negated=True)- query = self._build_query(term)- self.assertEqual(get_sqlalchemy_sql(query), "SELECT id \nFROM zerver_message")+ self._do_add_term_test_always_true(term)def test_add_term_using_in_operator_and_not_defined_operand(self) -> None:term = NarrowParameter(operator="in", operand="not_defined")@@ -798,15 +777,14 @@ class NarrowBuilderTest(ZulipTestCase):def test_add_term_using_near_operator(self) -> None:term = NarrowParameter(operator="near", operand="operand")- query = self._build_query(term)- self.assertEqual(get_sqlalchemy_sql(query), "SELECT id \nFROM zerver_message")+ self._do_add_term_test_always_true(term)def test_add_term_non_web_public_channel_in_web_public_query(self) -> None:self.make_stream("non-web-public-channel", realm=self.realm)term = NarrowParameter(operator="channel", operand="non-web-public-channel")- builder = NarrowBuilder(self.user_profile, column("id", Integer), self.realm, True)+ builder = NarrowBuilder(self.user_profile, self.realm, is_web_public_query=True)- def _build_query(term: NarrowParameter) -> Select:+ def _build_query(term: NarrowParameter) -> QuerySet[Message]:return builder.add_term(self.raw_query, term)self.assertRaises(BadNarrowOperatorError, _build_query, term)@@ -814,19 +792,17 @@ class NarrowBuilderTest(ZulipTestCase):# Test "is:private" (legacy alias for "is:dm")def test_add_term_using_is_operator_and_private_operand(self) -> None:term = NarrowParameter(operator="is", operand="private")- self._do_add_term_test(term, "WHERE (flags & %(flags_1)s) != %(param_1)s")+ self._do_add_term_test(term, 'WHERE "zerver_usermessage"."flags" & %s != 0')def test_add_term_using_is_operator_private_operand_and_negated(self) -> None: # NEGATEDterm = NarrowParameter(operator="is", operand="private", negated=True)- self._do_add_term_test(term, "WHERE (flags & %(flags_1)s) = %(param_1)s")+ self._do_add_term_test(term, 'WHERE NOT ("zerver_usermessage"."flags" & %s != 0)')# Test that "pm-with" (legacy alias for "dm") works.def test_add_term_using_pm_with_operator_no_direct_message_group(self) -> None:term = NarrowParameter(operator="pm-with", operand=self.hamlet_email)- self._do_add_term_test(- term,- "WHERE false",- )+ with self.assertRaises(EmptyResultSet):+ self._do_add_term_test(term, "")# Test that "pm-with" (legacy alias for "dm") works.def test_add_term_using_pm_with_operator(self) -> None:@@ -836,7 +812,7 @@ class NarrowBuilderTest(ZulipTestCase):# Query uses DM group recipient for self-DMself._do_add_term_test(term,- "WHERE recipient_id = %(recipient_id_1)s",+ 'WHERE "zerver_message"."recipient_id" = %s',)# Test that the underscore version of "pm-with" works.@@ -847,7 +823,7 @@ class NarrowBuilderTest(ZulipTestCase):# Query uses DM group recipient for self-DMself._do_add_term_test(term,- "WHERE recipient_id = %(recipient_id_1)s",+ 'WHERE "zerver_message"."recipient_id" = %s',)# Test that deprecated "group-pm-with" (replaced by "dm-including" ) works.@@ -856,19 +832,21 @@ class NarrowBuilderTest(ZulipTestCase):self.assertRaises(BadNarrowOperatorError, self._build_query, term)def test_add_term_using_group_pm_operator_and_not_the_same_user_as_operand(self) -> None:+ self.send_group_direct_message(self.user_profile, [self.example_user("othello")])term = NarrowParameter(operator="group-pm-with", operand=self.othello_email)self._do_add_term_test(term,- "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND recipient_id IN (__[POSTCOMPILE_recipient_id_1])",+ 'WHERE ("zerver_message"."realm_id" = %s AND "zerver_message"."recipient_id" IN (%s) AND "zerver_usermessage"."flags" & %s != 0)',)def test_add_term_using_group_pm_operator_not_the_same_user_as_operand_and_negated(self,) -> None: # NEGATED+ self.send_group_direct_message(self.user_profile, [self.example_user("othello")])term = NarrowParameter(operator="group-pm-with", operand=self.othello_email, negated=True)self._do_add_term_test(term,- "WHERE NOT ((flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND recipient_id IN (__[POSTCOMPILE_recipient_id_1]))",+ 'WHERE NOT ("zerver_message"."realm_id" = %s AND "zerver_message"."recipient_id" IN (%s) AND "zerver_usermessage"."flags" & %s != 0)',)def test_add_term_using_group_pm_operator_with_non_existing_user_as_operand(self) -> None:@@ -881,20 +859,21 @@ class NarrowBuilderTest(ZulipTestCase):# Test that the underscore version of "group-pm-with" works.def test_add_term_using_underscore_version_of_group_pm_with_operator(self) -> None:+ self.send_group_direct_message(self.user_profile, [self.example_user("othello")])term = NarrowParameter(operator="group_pm_with", operand=self.othello_email)self._do_add_term_test(term,- "WHERE (flags & %(flags_1)s) != %(param_1)s AND realm_id = %(realm_id_1)s AND recipient_id IN (__[POSTCOMPILE_recipient_id_1])",+ 'WHERE ("zerver_message"."realm_id" = %s AND "zerver_message"."recipient_id" IN (%s) AND "zerver_usermessage"."flags" & %s != 0)',)# Test that "stream" (legacy alias for "channel" operator) works.def test_add_term_using_stream_operator(self) -> None:term = NarrowParameter(operator="stream", operand="Scotland")- self._do_add_term_test(term, "WHERE recipient_id = %(recipient_id_1)s")+ self._do_add_term_test(term, 'WHERE "zerver_message"."recipient_id" = %s')def test_add_term_using_stream_operator_and_negated(self) -> None: # NEGATEDterm = NarrowParameter(operator="stream", operand="Scotland", negated=True)- self._do_add_term_test(term, "WHERE recipient_id != %(recipient_id_1)s")+ self._do_add_term_test(term, 'WHERE NOT ("zerver_message"."recipient_id" = %s)')def test_add_term_using_stream_operator_and_non_existing_operand_should_raise_error(self,@@ -913,33 +892,38 @@ class NarrowBuilderTest(ZulipTestCase):term = NarrowParameter(operator="streams", operand="public")self._do_add_term_test(term,- "WHERE recipient_id IN (__[POSTCOMPILE_recipient_id_1])",+ 'WHERE "zerver_message"."recipient_id" IN (%s, %s, %s, %s, %s, %s, %s)',)def test_add_term_using_streams_operator_and_public_operand_negated(self) -> None:term = NarrowParameter(operator="streams", operand="public", negated=True)self._do_add_term_test(term,- "WHERE (recipient_id NOT IN (__[POSTCOMPILE_recipient_id_1]))",+ 'WHERE NOT ("zerver_message"."recipient_id" IN (%s, %s, %s, %s, %s, %s, %s))',)def _do_add_term_test(- self, term: NarrowParameter, where_clause: str, params: dict[str, Any] | None = None+ self, term: NarrowParameter, where_clause: str, params: tuple[object, ...] | None = None) -> None:query = self._build_query(term)+ sql, actual_params = query.query.sql_with_params()+ self.assertIn("WHERE ", sql)+ self.assertEqual(sql[sql.index("WHERE ") :], where_clause)if params is not None:- actual_params = get_sqlalchemy_query_params(query)self.assertEqual(actual_params, params)- self.assertIn(where_clause, get_sqlalchemy_sql(query))- def _build_query(self, term: NarrowParameter) -> Select:+ def _do_add_term_test_always_true(self, term: NarrowParameter) -> None:+ query = self._build_query(term)+ self.assertEqual(query.query.sql_with_params(), self.raw_query.query.sql_with_params())++ def _build_query(self, term: NarrowParameter) -> QuerySet[Message]:return self.builder.add_term(self.raw_query, term)def test_add_term_using_mentions_operator_with_logged_in_user_email(self) -> None:term = NarrowParameter(operator="mentions", operand=self.user_profile.id)self._do_add_term_test(term,- "WHERE EXISTS (SELECT 1 \nFROM zerver_usermessage \nWHERE message_id = zerver_message.id AND user_profile_id = %(param_1)s AND (flags & %(param_2)s) != %(param_3)s)",+ 'WHERE EXISTS(SELECT %s AS "a" FROM "zerver_usermessage" U0 WHERE (U0."flags" & %s != 0 AND U0."message_id" = ("zerver_message"."id") AND U0."user_profile_id" = %s) LIMIT 1)',)def test_add_term_using_mentions_operator_with_different_user_email(self) -> None:@@ -948,7 +932,7 @@ class NarrowBuilderTest(ZulipTestCase):self._do_add_term_test(term,- "WHERE EXISTS (SELECT 1 \nFROM zerver_usermessage \nWHERE message_id = zerver_message.id AND user_profile_id = %(param_1)s AND (flags & %(param_2)s) != %(param_3)s)",+ 'WHERE EXISTS(SELECT %s AS "a" FROM "zerver_usermessage" U0 WHERE (U0."flags" & %s != 0 AND U0."message_id" = ("zerver_message"."id") AND U0."user_profile_id" = %s) LIMIT 1)',)self.send_stream_message(@@ -959,7 +943,7 @@ class NarrowBuilderTest(ZulipTestCase):self._do_add_term_test(term,- "WHERE EXISTS (SELECT 1 \nFROM zerver_usermessage \nWHERE message_id = zerver_message.id AND user_profile_id = %(param_1)s AND (flags & %(param_2)s) != %(param_3)s)",+ 'WHERE EXISTS(SELECT %s AS "a" FROM "zerver_usermessage" U0 WHERE (U0."flags" & %s != 0 AND U0."message_id" = ("zerver_message"."id") AND U0."user_profile_id" = %s) LIMIT 1)',)@@ -4399,7 +4383,7 @@ class GetOldMessagesTest(ZulipTestCase):def common_check_get_messages_query(self, query_params: dict[str, Any], expected: str) -> None:user_profile = self.example_user("hamlet")request = HostRequestMock(query_params, user_profile)- with queries_captured() as queries:+ with mock.patch("zerver.lib.narrow.capture_message_fetch_query_for_testing") as capture:get_messages_backend(request,user_profile,@@ -4407,13 +4391,9 @@ class GetOldMessagesTest(ZulipTestCase):num_after=query_params["num_after"],)- for query in queries:- sql = str(query.sql)- if "/* get_messages */" in sql:- sql = sql.replace(" /* get_messages */", "")- self.assertEqual(sql, expected)- return- raise AssertionError("get_messages query not found")+ capture.assert_called_once()+ matched = get_django_sql(capture.call_args.args[0])+ self.assertEqual(matched, expected)def test_find_first_unread_anchor(self) -> None:hamlet = self.example_user("hamlet")@@ -4449,29 +4429,25 @@ class GetOldMessagesTest(ZulipTestCase):def test_find_first_unread_anchor(narrow: list[NarrowParameter], need_user_message: bool) -> tuple[int, list[Any]]:- query, inner_msg_id_col = get_base_query_for_search(+ query = get_base_query_for_search(realm_id=user_profile.realm_id,user_profile=user_profile,need_user_message=need_user_message,)- query = query.add_columns(column("flags", Integer))query, _is_search, is_dm_narrow = add_narrow_conditions(user_profile=user_profile,- inner_msg_id_col=inner_msg_id_col,query=query,narrow=narrow,realm=user_profile.realm,is_web_public_query=False,)- with queries_captured() as queries, get_sqlalchemy_connection() as sa_conn:+ with queries_captured() as queries:anchor = find_first_unread_anchor(- sa_conn=sa_conn,user_profile=user_profile,narrow=narrow,query=query,is_dm_narrow=is_dm_narrow,- inner_msg_id_col=inner_msg_id_col,need_user_message=need_user_message,)return anchor, queries@@ -4828,7 +4804,7 @@ class GetOldMessagesTest(ZulipTestCase):)request = HostRequestMock(query_params, user_profile)- with queries_captured() as all_queries:+ with mock.patch("zerver.lib.narrow.capture_message_fetch_query_for_testing") as capture:get_messages_backend(request,user_profile,@@ -4837,16 +4813,14 @@ class GetOldMessagesTest(ZulipTestCase):)# Verify the query for old messages looks correct.- queries = [q for q in all_queries if "/* get_messages */" in q.sql]- self.assert_length(queries, 1)- sql = queries[0].sql- self.assertNotIn(f"AND message_id = {LARGER_THAN_MAX_MESSAGE_ID}", sql)- self.assertIn("ORDER BY message_id ASC", sql)-- self.assertIn(f"\nWHERE user_profile_id = {user_profile.id} ", sql)- self.assertIn(f" AND message_id >= {first_unread_message_id} ", sql)- self.assertIn(f"\nWHERE user_profile_id = {user_profile.id} ", sql)- self.assertIn(f" AND message_id <= {first_unread_message_id - 1} ", sql)+ capture.assert_called_once()+ sql = get_django_sql(capture.call_args.args[0])+ self.assertNotIn(f"message_id = {LARGER_THAN_MAX_MESSAGE_ID}", sql)+ self.assertIn("ORDER BY 1 ASC", sql)++ self.assertIn(f' WHERE ("zerver_usermessage"."user_profile_id" = {user_profile.id} ', sql)+ self.assertIn(f' AND "zerver_message"."id" >= {first_unread_message_id})', sql)+ self.assertIn(f' AND "zerver_message"."id" <= {first_unread_message_id - 1})', sql)self.assertIn("UNION", sql)def test_visible_messages_use_first_unread_anchor_with_some_unread_messages(self) -> None:@@ -4877,7 +4851,10 @@ class GetOldMessagesTest(ZulipTestCase):request = HostRequestMock(query_params, user_profile)first_visible_message_id = first_unread_message_id + 2- with first_visible_id_as(first_visible_message_id), queries_captured() as all_queries:+ with (+ first_visible_id_as(first_visible_message_id),+ mock.patch("zerver.lib.narrow.capture_message_fetch_query_for_testing") as capture,+ ):get_messages_backend(request,user_profile,@@ -4885,15 +4862,13 @@ class GetOldMessagesTest(ZulipTestCase):num_after=10,)- queries = [q for q in all_queries if "/* get_messages */" in q.sql]- self.assert_length(queries, 1)- sql = queries[0].sql- self.assertNotIn(f"AND message_id = {LARGER_THAN_MAX_MESSAGE_ID}", sql)- self.assertIn("ORDER BY message_id ASC", sql)- self.assertIn(f"\nWHERE user_profile_id = {user_profile.id} ", sql)- self.assertIn(f" AND message_id <= {first_unread_message_id - 1} ", sql)- self.assertIn(f"\nWHERE user_profile_id = {user_profile.id} ", sql)- self.assertIn(f" AND message_id >= {first_visible_message_id} ", sql)+ capture.assert_called_once()+ sql = get_django_sql(capture.call_args.args[0])+ self.assertNotIn(f"message_id = {LARGER_THAN_MAX_MESSAGE_ID}", sql)+ self.assertIn("ORDER BY 1 ASC", sql)+ self.assertIn(f' WHERE ("zerver_usermessage"."user_profile_id" = {user_profile.id} ', sql)+ self.assertIn(f' AND "zerver_message"."id" <= {first_unread_message_id - 1})', sql)+ self.assertIn(f' AND "zerver_message"."id" >= {first_visible_message_id})', sql)def test_use_first_unread_anchor_with_no_unread_messages(self) -> None:user_profile = self.example_user("hamlet")@@ -4906,7 +4881,7 @@ class GetOldMessagesTest(ZulipTestCase):)request = HostRequestMock(query_params, user_profile)- with queries_captured() as all_queries:+ with mock.patch("zerver.lib.narrow.capture_message_fetch_query_for_testing") as capture:get_messages_backend(request,user_profile,@@ -4914,10 +4889,8 @@ class GetOldMessagesTest(ZulipTestCase):num_after=10,)- queries = [q for q in all_queries if "/* get_messages */" in q.sql]- self.assert_length(queries, 1)-- sql = queries[0].sql+ capture.assert_called_once()+ sql = get_django_sql(capture.call_args.args[0])self.assertNotIn("AND message_id <=", sql)self.assertNotIn("AND message_id >=", sql)@@ -4925,15 +4898,15 @@ class GetOldMessagesTest(ZulipTestCase):request = HostRequestMock(query_params, user_profile)first_visible_message_id = 5with first_visible_id_as(first_visible_message_id):- with queries_captured() as all_queries:+ with mock.patch("zerver.lib.narrow.capture_message_fetch_query_for_testing") as capture:get_messages_backend(request,user_profile,num_before=10,num_after=10,)- queries = [q for q in all_queries if "/* get_messages */" in q.sql]- sql = queries[0].sql+ capture.assert_called_once()+ sql = get_django_sql(capture.call_args.args[0])self.assertNotIn("AND message_id <=", sql)self.assertNotIn("AND message_id >=", sql)@@ -4941,7 +4914,7 @@ class GetOldMessagesTest(ZulipTestCase):"""Test that our logic related to `use_first_unread_anchor`invokes the `message_id = LARGER_THAN_MAX_MESSAGE_ID` hack for- the `/* get_messages */` query when relevant muting+ the `fetch_messages` query when relevant mutingis in effect.This is a very arcane test on arcane, but very heavily@@ -4969,7 +4942,14 @@ class GetOldMessagesTest(ZulipTestCase):)request = HostRequestMock(query_params, user_profile)- with queries_captured() as all_queries:+ with (+ mock.patch(+ "zerver.lib.narrow.capture_find_first_unread_anchor_query_for_testing"+ ) as capture_anchor,+ mock.patch(+ "zerver.lib.narrow.capture_message_fetch_query_for_testing"+ ) as capture_fetch,+ ):get_messages_backend(request,user_profile,@@ -4979,20 +4959,22 @@ class GetOldMessagesTest(ZulipTestCase):# Do some tests on the main query, to verify the muting logic# runs on this code path.- queries = [q for q in all_queries if q.sql.startswith("SELECT message_id, flags")]- self.assert_length(queries, 1)+ capture_anchor.assert_called_once()+ sql = get_django_sql(capture_anchor.call_args.args[0])channel = get_stream("Scotland", realm)assert channel.recipient is not Nonerecipient_id = channel.recipient.id- cond = f"AND NOT (recipient_id = {recipient_id} AND upper(subject) = upper('golf') AND is_channel_message)"- self.assertIn(cond, queries[0].sql)+ cond = f"""AND NOT ("zerver_message"."recipient_id" = {recipient_id} AND "zerver_message"."is_channel_message" AND UPPER("zerver_message"."subject"::text) = UPPER('golf'))"""+ self.assertIn(cond, sql)# Next, verify the use_first_unread_anchor setting invokes# the `message_id = LARGER_THAN_MAX_MESSAGE_ID` hack.- queries = [q for q in all_queries if "/* get_messages */" in q.sql]- self.assert_length(queries, 1)- self.assertIn(f"AND zerver_message.id = {LARGER_THAN_MAX_MESSAGE_ID}", queries[0].sql)+ # Django recognizes that as out of range and optimizes away+ # the query.+ capture_fetch.assert_called_once()+ with self.assertRaises(EmptyResultSet):+ capture_fetch.call_args.args[0].query.sql_with_params()def test_get_visible_messages_with_mentions_narrow(self) -> None:iago = self.example_user("iago")@@ -5090,7 +5072,7 @@ class GetOldMessagesTest(ZulipTestCase):NarrowParameter(operator="channel", operand="Scotland"),]muting_conditions = exclude_muting_conditions(user_profile, narrow)- self.assertEqual(muting_conditions, [])+ self.assertEqual(muting_conditions, ~Q(pk__in=[]))# Also test that passing channel ID workschannel_id = get_stream("Scotland", realm).id@@ -5098,7 +5080,7 @@ class GetOldMessagesTest(ZulipTestCase):NarrowParameter(operator="channel", operand=channel_id),]muting_conditions = exclude_muting_conditions(user_profile, narrow)- self.assertEqual(muting_conditions, [])+ self.assertEqual(muting_conditions, ~Q(pk__in=[]))# Ok, now set up our muted topics to include a topic relevant to our narrow.muted_topics = [@@ -5113,23 +5095,23 @@ class GetOldMessagesTest(ZulipTestCase):]muting_conditions = exclude_muting_conditions(user_profile, narrow)- query = select(column("id", Integer).label("message_id")).select_from(- table("zerver_message")- )- query = query.where(*muting_conditions)+ query = Message.objects.all().filter(muting_conditions).values("id").queryexpected_query = """\-SELECT id AS message_id \n\-FROM zerver_message \n\-WHERE NOT (recipient_id = %(recipient_id_1)s AND upper(subject) = upper(%(param_1)s) AND is_channel_message)\+SELECT "zerver_message"."id" AS "id" \+FROM "zerver_message" \+WHERE NOT ("zerver_message"."recipient_id" = %s AND "zerver_message"."is_channel_message" AND UPPER("zerver_message"."subject"::text) = UPPER(%s))\"""- self.assertEqual(get_sqlalchemy_sql(query), expected_query)- params = get_sqlalchemy_query_params(query)+ sql, params = query.sql_with_params()+ self.assertEqual(sql, expected_query)self.assertEqual(- params["recipient_id_1"], get_recipient_id_for_channel_name(realm, "Scotland")+ params,+ (+ get_recipient_id_for_channel_name(realm, "Scotland"),+ "golf",+ ),)- self.assertEqual(params["param_1"], "golf")mute_channel(realm, user_profile, "Verona")channel_verona_id = get_recipient_id_for_channel_name(realm, "Verona")@@ -5141,27 +5123,27 @@ WHERE NOT (recipient_id = %(recipient_id_1)s AND upper(subject) = upper(%(param_]muting_conditions = exclude_muting_conditions(user_profile, narrow)- query = select(column("id", Integer)).select_from(table("zerver_message"))- query = query.where(and_(*muting_conditions))+ query = Message.objects.all().filter(muting_conditions).values("id").queryexpected_query = """\-SELECT id \n\-FROM zerver_message \n\-WHERE NOT (recipient_id = %(recipient_id_1)s AND upper(subject) = upper(%(param_1)s) AND is_channel_message \-OR recipient_id = %(recipient_id_2)s AND upper(subject) = upper(%(param_2)s) AND is_channel_message) \-AND (recipient_id NOT IN (__[POSTCOMPILE_recipient_id_3]))\+SELECT "zerver_message"."id" AS "id" \+FROM "zerver_message" \+WHERE (NOT (("zerver_message"."recipient_id" = %s AND "zerver_message"."is_channel_message" AND UPPER("zerver_message"."subject"::text) = UPPER(%s)) \+OR ("zerver_message"."recipient_id" = %s AND "zerver_message"."is_channel_message" AND UPPER("zerver_message"."subject"::text) = UPPER(%s))) \+AND NOT ("zerver_message"."recipient_id" IN (%s)))\"""- self.assertEqual(get_sqlalchemy_sql(query), expected_query)- params = get_sqlalchemy_query_params(query)- self.assertEqual(params["recipient_id_3"], [channel_verona_id])- self.assertEqual(- params["recipient_id_1"], get_recipient_id_for_channel_name(realm, "Scotland")- )- self.assertEqual(params["param_1"], "golf")+ sql, params = query.sql_with_params()+ self.assertEqual(sql, expected_query)self.assertEqual(- params["recipient_id_2"], get_recipient_id_for_channel_name(realm, "web stuff")+ params,+ (+ get_recipient_id_for_channel_name(realm, "Scotland"),+ "golf",+ get_recipient_id_for_channel_name(realm, "web stuff"),+ "css",+ channel_verona_id,+ ),)- self.assertEqual(params["param_2"], "css")# check that followed topic is included in the query.followed_topics = [@@ -5172,119 +5154,113 @@ AND (recipient_id NOT IN (__[POSTCOMPILE_recipient_id_3]))\)muting_conditions = exclude_muting_conditions(user_profile, narrow)- query = select(column("id", Integer)).select_from(table("zerver_message"))- query = query.where(and_(*muting_conditions))+ query = Message.objects.all().filter(muting_conditions).values("id").queryexpected_query = """\-SELECT id \n\-FROM zerver_message \n\-WHERE NOT (recipient_id = %(recipient_id_1)s AND upper(subject) = upper(%(param_1)s) AND is_channel_message \-OR recipient_id = %(recipient_id_2)s AND upper(subject) = upper(%(param_2)s) AND is_channel_message) \-AND NOT (recipient_id IN (__[POSTCOMPILE_recipient_id_3]) \-AND NOT (recipient_id = %(recipient_id_4)s AND upper(subject) = upper(%(param_3)s) AND is_channel_message))\+SELECT "zerver_message"."id" AS "id" \+FROM "zerver_message" \+WHERE (NOT (("zerver_message"."recipient_id" = %s AND "zerver_message"."is_channel_message" AND UPPER("zerver_message"."subject"::text) = UPPER(%s)) \+OR ("zerver_message"."recipient_id" = %s AND "zerver_message"."is_channel_message" AND UPPER("zerver_message"."subject"::text) = UPPER(%s))) \+AND NOT ("zerver_message"."recipient_id" IN (%s) \+AND NOT ("zerver_message"."recipient_id" = %s AND "zerver_message"."is_channel_message" AND UPPER("zerver_message"."subject"::text) = UPPER(%s))))\"""- self.assertEqual(get_sqlalchemy_sql(query), expected_query)- params = get_sqlalchemy_query_params(query)- self.assertEqual(params["recipient_id_3"], [channel_verona_id])+ sql, params = query.sql_with_params()+ self.assertEqual(sql, expected_query)self.assertEqual(- params["recipient_id_1"], get_recipient_id_for_channel_name(realm, "Scotland")- )- self.assertEqual(params["param_1"], "golf")- self.assertEqual(- params["recipient_id_2"], get_recipient_id_for_channel_name(realm, "web stuff")+ params,+ (+ get_recipient_id_for_channel_name(realm, "Scotland"),+ "golf",+ get_recipient_id_for_channel_name(realm, "web stuff"),+ "css",+ channel_verona_id,+ channel_verona_id,+ "Hi",+ ),)- self.assertEqual(params["param_2"], "css")- self.assertEqual(params["recipient_id_4"], channel_verona_id)- self.assertEqual(params["param_3"], "Hi")def test_get_messages_queries(self) -> None:query_ids = self.get_query_ids()sql_template = """\-SELECT anon_1.message_id, anon_1.flags \n\-FROM (SELECT message_id, flags \n\-FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\-WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\-FROM zerver_stream \n\-WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\-FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND message_id = 0) AS anon_1 ORDER BY message_id ASC\+SELECT "zerver_message"."id" AS "id", "zerver_usermessage"."flags" AS "user_flags" \+FROM "zerver_message" LEFT OUTER JOIN "zerver_usermessage" ON ("zerver_message"."id" = "zerver_usermessage"."message_id") INNER JOIN "zerver_recipient" ON ("zerver_message"."recipient_id" = "zerver_recipient"."id") \+WHERE ("zerver_usermessage"."user_profile_id" = {hamlet_id} AND (NOT ("zerver_recipient"."type" = 2) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_stream" U0 \+WHERE (U0."recipient_id" = ("zerver_message"."recipient_id") AND (NOT U0."invite_only" OR U0."can_subscribe_group_id" IN {hamlet_groups} OR U0."can_add_subscribers_group_id" IN {hamlet_groups})) LIMIT 1) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_subscription" U0 \+WHERE (U0."active" AND U0."recipient_id" = ("zerver_message"."recipient_id") AND U0."user_profile_id" = {hamlet_id}) LIMIT 1)) AND "zerver_message"."id" = 0)\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query({"anchor": 0, "num_before": 0, "num_after": 0}, sql)sql_template = """\-SELECT anon_1.message_id, anon_1.flags \n\-FROM (SELECT message_id, flags \n\-FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\-WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\-FROM zerver_stream \n\-WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\-FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND message_id = 0) AS anon_1 ORDER BY message_id ASC\+SELECT "zerver_message"."id" AS "id", "zerver_usermessage"."flags" AS "user_flags" \+FROM "zerver_message" LEFT OUTER JOIN "zerver_usermessage" ON ("zerver_message"."id" = "zerver_usermessage"."message_id") INNER JOIN "zerver_recipient" ON ("zerver_message"."recipient_id" = "zerver_recipient"."id") \+WHERE ("zerver_usermessage"."user_profile_id" = {hamlet_id} AND (NOT ("zerver_recipient"."type" = 2) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_stream" U0 \+WHERE (U0."recipient_id" = ("zerver_message"."recipient_id") AND (NOT U0."invite_only" OR U0."can_subscribe_group_id" IN {hamlet_groups} OR U0."can_add_subscribers_group_id" IN {hamlet_groups})) LIMIT 1) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_subscription" U0 \+WHERE (U0."active" AND U0."recipient_id" = ("zerver_message"."recipient_id") AND U0."user_profile_id" = {hamlet_id}) LIMIT 1)) AND "zerver_message"."id" = 0)\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query({"anchor": 0, "num_before": 1, "num_after": 0}, sql)sql_template = """\-SELECT anon_1.message_id, anon_1.flags \n\-FROM (SELECT message_id, flags \n\-FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\-WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\-FROM zerver_stream \n\-WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\-FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) ORDER BY message_id ASC \n\- LIMIT 2) AS anon_1 ORDER BY message_id ASC\+SELECT "zerver_message"."id" AS "id", "zerver_usermessage"."flags" AS "user_flags" \+FROM "zerver_message" LEFT OUTER JOIN "zerver_usermessage" ON ("zerver_message"."id" = "zerver_usermessage"."message_id") INNER JOIN "zerver_recipient" ON ("zerver_message"."recipient_id" = "zerver_recipient"."id") \+WHERE ("zerver_usermessage"."user_profile_id" = {hamlet_id} AND (NOT ("zerver_recipient"."type" = 2) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_stream" U0 \+WHERE (U0."recipient_id" = ("zerver_message"."recipient_id") AND (NOT U0."invite_only" OR U0."can_subscribe_group_id" IN {hamlet_groups} OR U0."can_add_subscribers_group_id" IN {hamlet_groups})) LIMIT 1) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_subscription" U0 \+WHERE (U0."active" AND U0."recipient_id" = ("zerver_message"."recipient_id") AND U0."user_profile_id" = {hamlet_id}) LIMIT 1))) ORDER BY 1 ASC\+ LIMIT 2\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query({"anchor": 0, "num_before": 0, "num_after": 1}, sql)sql_template = """\-SELECT anon_1.message_id, anon_1.flags \n\-FROM (SELECT message_id, flags \n\-FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\-WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\-FROM zerver_stream \n\-WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\-FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) ORDER BY message_id ASC \n\- LIMIT 11) AS anon_1 ORDER BY message_id ASC\+SELECT "zerver_message"."id" AS "id", "zerver_usermessage"."flags" AS "user_flags" \+FROM "zerver_message" LEFT OUTER JOIN "zerver_usermessage" ON ("zerver_message"."id" = "zerver_usermessage"."message_id") INNER JOIN "zerver_recipient" ON ("zerver_message"."recipient_id" = "zerver_recipient"."id") \+WHERE ("zerver_usermessage"."user_profile_id" = {hamlet_id} AND (NOT ("zerver_recipient"."type" = 2) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_stream" U0 \+WHERE (U0."recipient_id" = ("zerver_message"."recipient_id") AND (NOT U0."invite_only" OR U0."can_subscribe_group_id" IN {hamlet_groups} OR U0."can_add_subscribers_group_id" IN {hamlet_groups})) LIMIT 1) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_subscription" U0 \+WHERE (U0."active" AND U0."recipient_id" = ("zerver_message"."recipient_id") AND U0."user_profile_id" = {hamlet_id}) LIMIT 1))) ORDER BY 1 ASC\+ LIMIT 11\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query({"anchor": 0, "num_before": 0, "num_after": 10}, sql)sql_template = """\-SELECT anon_1.message_id, anon_1.flags \n\-FROM (SELECT message_id, flags \n\-FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\-WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\-FROM zerver_stream \n\-WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\-FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND message_id <= 100 ORDER BY message_id DESC \n\- LIMIT 11) AS anon_1 ORDER BY message_id ASC\+SELECT "zerver_message"."id" AS "id", "zerver_usermessage"."flags" AS "user_flags" \+FROM "zerver_message" LEFT OUTER JOIN "zerver_usermessage" ON ("zerver_message"."id" = "zerver_usermessage"."message_id") INNER JOIN "zerver_recipient" ON ("zerver_message"."recipient_id" = "zerver_recipient"."id") \+WHERE ("zerver_usermessage"."user_profile_id" = {hamlet_id} AND (NOT ("zerver_recipient"."type" = 2) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_stream" U0 \+WHERE (U0."recipient_id" = ("zerver_message"."recipient_id") AND (NOT U0."invite_only" OR U0."can_subscribe_group_id" IN {hamlet_groups} OR U0."can_add_subscribers_group_id" IN {hamlet_groups})) LIMIT 1) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_subscription" U0 \+WHERE (U0."active" AND U0."recipient_id" = ("zerver_message"."recipient_id") AND U0."user_profile_id" = {hamlet_id}) LIMIT 1)) AND "zerver_message"."id" <= 100) ORDER BY 1 DESC\+ LIMIT 11\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query({"anchor": 100, "num_before": 10, "num_after": 0}, sql)sql_template = """\-SELECT anon_1.message_id, anon_1.flags \n\-FROM ((SELECT message_id, flags \n\-FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\-WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\-FROM zerver_stream \n\-WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\-FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND message_id <= 99 ORDER BY message_id DESC \n\- LIMIT 10) UNION ALL (SELECT message_id, flags \n\-FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\-WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\-FROM zerver_stream \n\-WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\-FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND message_id >= 100 ORDER BY message_id ASC \n\- LIMIT 11)) AS anon_1 ORDER BY message_id ASC\+(SELECT "zerver_message"."id" AS "id", "zerver_usermessage"."flags" AS "user_flags" \+FROM "zerver_message" LEFT OUTER JOIN "zerver_usermessage" ON ("zerver_message"."id" = "zerver_usermessage"."message_id") INNER JOIN "zerver_recipient" ON ("zerver_message"."recipient_id" = "zerver_recipient"."id") \+WHERE ("zerver_usermessage"."user_profile_id" = {hamlet_id} AND (NOT ("zerver_recipient"."type" = 2) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_stream" U0 \+WHERE (U0."recipient_id" = ("zerver_message"."recipient_id") AND (NOT U0."invite_only" OR U0."can_subscribe_group_id" IN {hamlet_groups} OR U0."can_add_subscribers_group_id" IN {hamlet_groups})) LIMIT 1) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_subscription" U0 \+WHERE (U0."active" AND U0."recipient_id" = ("zerver_message"."recipient_id") AND U0."user_profile_id" = {hamlet_id}) LIMIT 1)) AND "zerver_message"."id" <= 99) ORDER BY 1 DESC\+ LIMIT 10) UNION ALL (SELECT "zerver_message"."id" AS "id", "zerver_usermessage"."flags" AS "user_flags" \+FROM "zerver_message" LEFT OUTER JOIN "zerver_usermessage" ON ("zerver_message"."id" = "zerver_usermessage"."message_id") INNER JOIN "zerver_recipient" ON ("zerver_message"."recipient_id" = "zerver_recipient"."id") \+WHERE ("zerver_usermessage"."user_profile_id" = {hamlet_id} AND (NOT ("zerver_recipient"."type" = 2) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_stream" U0 \+WHERE (U0."recipient_id" = ("zerver_message"."recipient_id") AND (NOT U0."invite_only" OR U0."can_subscribe_group_id" IN {hamlet_groups} OR U0."can_add_subscribers_group_id" IN {hamlet_groups})) LIMIT 1) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_subscription" U0 \+WHERE (U0."active" AND U0."recipient_id" = ("zerver_message"."recipient_id") AND U0."user_profile_id" = {hamlet_id}) LIMIT 1)) AND "zerver_message"."id" >= 100) ORDER BY 1 ASC\+ LIMIT 11)\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query(@@ -5298,14 +5274,13 @@ WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.othello_email = self.example_user("othello").emailsql_template = """\-SELECT anon_1.message_id, anon_1.flags \n\-FROM (SELECT message_id, flags \n\-FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\-WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\-FROM zerver_stream \n\-WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\-FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND recipient_id = {hamlet_and_othello_recipient} AND message_id = 0) AS anon_1 ORDER BY message_id ASC\+SELECT "zerver_message"."id" AS "id", "zerver_usermessage"."flags" AS "user_flags" \+FROM "zerver_message" LEFT OUTER JOIN "zerver_usermessage" ON ("zerver_message"."id" = "zerver_usermessage"."message_id") INNER JOIN "zerver_recipient" ON ("zerver_message"."recipient_id" = "zerver_recipient"."id") \+WHERE ("zerver_usermessage"."user_profile_id" = {hamlet_id} AND (NOT ("zerver_recipient"."type" = 2) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_stream" U0 \+WHERE (U0."recipient_id" = ("zerver_message"."recipient_id") AND (NOT U0."invite_only" OR U0."can_subscribe_group_id" IN {hamlet_groups} OR U0."can_add_subscribers_group_id" IN {hamlet_groups})) LIMIT 1) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_subscription" U0 \+WHERE (U0."active" AND U0."recipient_id" = ("zerver_message"."recipient_id") AND U0."user_profile_id" = {hamlet_id}) LIMIT 1)) AND "zerver_message"."recipient_id" = {hamlet_and_othello_recipient} AND "zerver_message"."id" = 0)\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query(@@ -5319,14 +5294,13 @@ WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.)sql_template = """\-SELECT anon_1.message_id, anon_1.flags \n\-FROM (SELECT message_id, flags \n\-FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\-WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\-FROM zerver_stream \n\-WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\-FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND recipient_id = {hamlet_and_othello_recipient} AND message_id = 0) AS anon_1 ORDER BY message_id ASC\+SELECT "zerver_message"."id" AS "id", "zerver_usermessage"."flags" AS "user_flags" \+FROM "zerver_message" LEFT OUTER JOIN "zerver_usermessage" ON ("zerver_message"."id" = "zerver_usermessage"."message_id") INNER JOIN "zerver_recipient" ON ("zerver_message"."recipient_id" = "zerver_recipient"."id") \+WHERE ("zerver_usermessage"."user_profile_id" = {hamlet_id} AND (NOT ("zerver_recipient"."type" = 2) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_stream" U0 \+WHERE (U0."recipient_id" = ("zerver_message"."recipient_id") AND (NOT U0."invite_only" OR U0."can_subscribe_group_id" IN {hamlet_groups} OR U0."can_add_subscribers_group_id" IN {hamlet_groups})) LIMIT 1) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_subscription" U0 \+WHERE (U0."active" AND U0."recipient_id" = ("zerver_message"."recipient_id") AND U0."user_profile_id" = {hamlet_id}) LIMIT 1)) AND "zerver_message"."recipient_id" = {hamlet_and_othello_recipient} AND "zerver_message"."id" = 0)\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query(@@ -5340,15 +5314,14 @@ WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.)sql_template = """\-SELECT anon_1.message_id, anon_1.flags \n\-FROM (SELECT message_id, flags \n\-FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\-WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\-FROM zerver_stream \n\-WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\-FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND recipient_id = {hamlet_and_othello_recipient} ORDER BY message_id ASC \n\- LIMIT 10) AS anon_1 ORDER BY message_id ASC\+SELECT "zerver_message"."id" AS "id", "zerver_usermessage"."flags" AS "user_flags" \+FROM "zerver_message" LEFT OUTER JOIN "zerver_usermessage" ON ("zerver_message"."id" = "zerver_usermessage"."message_id") INNER JOIN "zerver_recipient" ON ("zerver_message"."recipient_id" = "zerver_recipient"."id") \+WHERE ("zerver_usermessage"."user_profile_id" = {hamlet_id} AND (NOT ("zerver_recipient"."type" = 2) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_stream" U0 \+WHERE (U0."recipient_id" = ("zerver_message"."recipient_id") AND (NOT U0."invite_only" OR U0."can_subscribe_group_id" IN {hamlet_groups} OR U0."can_add_subscribers_group_id" IN {hamlet_groups})) LIMIT 1) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_subscription" U0 \+WHERE (U0."active" AND U0."recipient_id" = ("zerver_message"."recipient_id") AND U0."user_profile_id" = {hamlet_id}) LIMIT 1)) AND "zerver_message"."recipient_id" = {hamlet_and_othello_recipient}) ORDER BY 1 ASC\+ LIMIT 10\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query(@@ -5362,15 +5335,14 @@ WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.)sql_template = """\-SELECT anon_1.message_id, anon_1.flags \n\-FROM (SELECT message_id, flags \n\-FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\-WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\-FROM zerver_stream \n\-WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\-FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND (flags & 2) != 0 ORDER BY message_id ASC \n\- LIMIT 10) AS anon_1 ORDER BY message_id ASC\+SELECT "zerver_message"."id" AS "id", "zerver_usermessage"."flags" AS "user_flags" \+FROM "zerver_message" LEFT OUTER JOIN "zerver_usermessage" ON ("zerver_message"."id" = "zerver_usermessage"."message_id") INNER JOIN "zerver_recipient" ON ("zerver_message"."recipient_id" = "zerver_recipient"."id") \+WHERE ("zerver_usermessage"."user_profile_id" = {hamlet_id} AND (NOT ("zerver_recipient"."type" = 2) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_stream" U0 \+WHERE (U0."recipient_id" = ("zerver_message"."recipient_id") AND (NOT U0."invite_only" OR U0."can_subscribe_group_id" IN {hamlet_groups} OR U0."can_add_subscribers_group_id" IN {hamlet_groups})) LIMIT 1) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_subscription" U0 \+WHERE (U0."active" AND U0."recipient_id" = ("zerver_message"."recipient_id") AND U0."user_profile_id" = {hamlet_id}) LIMIT 1)) AND "zerver_usermessage"."flags" & 2 != 0) ORDER BY 1 ASC\+ LIMIT 10\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query(@@ -5378,15 +5350,14 @@ WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.)sql_template = """\-SELECT anon_1.message_id, anon_1.flags \n\-FROM (SELECT message_id, flags \n\-FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\-WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\-FROM zerver_stream \n\-WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\-FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND sender_id = {othello_id} ORDER BY message_id ASC \n\- LIMIT 10) AS anon_1 ORDER BY message_id ASC\+SELECT "zerver_message"."id" AS "id", "zerver_usermessage"."flags" AS "user_flags" \+FROM "zerver_message" LEFT OUTER JOIN "zerver_usermessage" ON ("zerver_message"."id" = "zerver_usermessage"."message_id") INNER JOIN "zerver_recipient" ON ("zerver_message"."recipient_id" = "zerver_recipient"."id") \+WHERE ("zerver_usermessage"."user_profile_id" = {hamlet_id} AND (NOT ("zerver_recipient"."type" = 2) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_stream" U0 \+WHERE (U0."recipient_id" = ("zerver_message"."recipient_id") AND (NOT U0."invite_only" OR U0."can_subscribe_group_id" IN {hamlet_groups} OR U0."can_add_subscribers_group_id" IN {hamlet_groups})) LIMIT 1) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_subscription" U0 \+WHERE (U0."active" AND U0."recipient_id" = ("zerver_message"."recipient_id") AND U0."user_profile_id" = {hamlet_id}) LIMIT 1)) AND "zerver_message"."sender_id" = {othello_id}) ORDER BY 1 ASC\+ LIMIT 10\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query(@@ -5400,11 +5371,10 @@ WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.)sql_template = """\-SELECT anon_1.message_id \n\-FROM (SELECT id AS message_id \n\-FROM zerver_message \n\-WHERE realm_id = 2 AND recipient_id = {scotland_recipient} ORDER BY zerver_message.id ASC \n\- LIMIT 10) AS anon_1 ORDER BY message_id ASC\+SELECT "zerver_message"."id" AS "id" \+FROM "zerver_message" \+WHERE ("zerver_message"."realm_id" = 2 AND "zerver_message"."recipient_id" = {scotland_recipient}) ORDER BY 1 ASC\+ LIMIT 10\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query(@@ -5413,11 +5383,10 @@ WHERE realm_id = 2 AND recipient_id = {scotland_recipient} ORDER BY zerver_messa)sql_template = """\-SELECT anon_1.message_id \n\-FROM (SELECT id AS message_id \n\-FROM zerver_message \n\-WHERE realm_id = 2 AND recipient_id IN ({public_channels_recipients}) ORDER BY zerver_message.id ASC \n\- LIMIT 10) AS anon_1 ORDER BY message_id ASC\+SELECT "zerver_message"."id" AS "id" \+FROM "zerver_message" \+WHERE ("zerver_message"."realm_id" = 2 AND "zerver_message"."recipient_id" IN ({public_channels_recipients})) ORDER BY 1 ASC\+ LIMIT 10\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query(@@ -5426,15 +5395,14 @@ WHERE realm_id = 2 AND recipient_id IN ({public_channels_recipients}) ORDER BY z)sql_template = """\-SELECT anon_1.message_id, anon_1.flags \n\-FROM (SELECT message_id, flags \n\-FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\-WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\-FROM zerver_stream \n\-WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\-FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND (recipient_id NOT IN ({public_channels_recipients})) ORDER BY message_id ASC \n\- LIMIT 10) AS anon_1 ORDER BY message_id ASC\+SELECT "zerver_message"."id" AS "id", "zerver_usermessage"."flags" AS "user_flags" \+FROM "zerver_message" LEFT OUTER JOIN "zerver_usermessage" ON ("zerver_message"."id" = "zerver_usermessage"."message_id") INNER JOIN "zerver_recipient" ON ("zerver_message"."recipient_id" = "zerver_recipient"."id") \+WHERE ("zerver_usermessage"."user_profile_id" = {hamlet_id} AND (NOT ("zerver_recipient"."type" = 2) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_stream" U0 \+WHERE (U0."recipient_id" = ("zerver_message"."recipient_id") AND (NOT U0."invite_only" OR U0."can_subscribe_group_id" IN {hamlet_groups} OR U0."can_add_subscribers_group_id" IN {hamlet_groups})) LIMIT 1) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_subscription" U0 \+WHERE (U0."active" AND U0."recipient_id" = ("zerver_message"."recipient_id") AND U0."user_profile_id" = {hamlet_id}) LIMIT 1)) AND NOT ("zerver_message"."recipient_id" IN ({public_channels_recipients}))) ORDER BY 1 ASC\+ LIMIT 10\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query(@@ -5448,15 +5416,14 @@ WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.)sql_template = """\-SELECT anon_1.message_id, anon_1.flags \n\-FROM (SELECT message_id, flags \n\-FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\-WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\-FROM zerver_stream \n\-WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\-FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND upper(subject) = upper('blah') AND is_channel_message ORDER BY message_id ASC \n\- LIMIT 10) AS anon_1 ORDER BY message_id ASC\+SELECT "zerver_message"."id" AS "id", "zerver_usermessage"."flags" AS "user_flags" \+FROM "zerver_message" LEFT OUTER JOIN "zerver_usermessage" ON ("zerver_message"."id" = "zerver_usermessage"."message_id") INNER JOIN "zerver_recipient" ON ("zerver_message"."recipient_id" = "zerver_recipient"."id") \+WHERE ("zerver_usermessage"."user_profile_id" = {hamlet_id} AND (NOT ("zerver_recipient"."type" = 2) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_stream" U0 \+WHERE (U0."recipient_id" = ("zerver_message"."recipient_id") AND (NOT U0."invite_only" OR U0."can_subscribe_group_id" IN {hamlet_groups} OR U0."can_add_subscribers_group_id" IN {hamlet_groups})) LIMIT 1) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_subscription" U0 \+WHERE (U0."active" AND U0."recipient_id" = ("zerver_message"."recipient_id") AND U0."user_profile_id" = {hamlet_id}) LIMIT 1)) AND "zerver_message"."is_channel_message" AND UPPER("zerver_message"."subject"::text) = UPPER('blah')) ORDER BY 1 ASC\+ LIMIT 10\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query(@@ -5464,11 +5431,10 @@ WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.)sql_template = """\-SELECT anon_1.message_id \n\-FROM (SELECT id AS message_id \n\-FROM zerver_message \n\-WHERE realm_id = 2 AND recipient_id = {scotland_recipient} AND upper(subject) = upper('blah') AND is_channel_message ORDER BY zerver_message.id ASC \n\- LIMIT 10) AS anon_1 ORDER BY message_id ASC\+SELECT "zerver_message"."id" AS "id" \+FROM "zerver_message" \+WHERE ("zerver_message"."realm_id" = 2 AND "zerver_message"."recipient_id" = {scotland_recipient} AND "zerver_message"."is_channel_message" AND UPPER("zerver_message"."subject"::text) = UPPER('blah')) ORDER BY 1 ASC\+ LIMIT 10\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query(@@ -5483,15 +5449,14 @@ WHERE realm_id = 2 AND recipient_id = {scotland_recipient} AND upper(subject) =# Narrow to direct messages with yourselfsql_template = """\-SELECT anon_1.message_id, anon_1.flags \n\-FROM (SELECT message_id, flags \n\-FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\-WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\-FROM zerver_stream \n\-WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\-FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND recipient_id = {hamlet_recipient} ORDER BY message_id ASC \n\- LIMIT 10) AS anon_1 ORDER BY message_id ASC\+SELECT "zerver_message"."id" AS "id", "zerver_usermessage"."flags" AS "user_flags" \+FROM "zerver_message" LEFT OUTER JOIN "zerver_usermessage" ON ("zerver_message"."id" = "zerver_usermessage"."message_id") INNER JOIN "zerver_recipient" ON ("zerver_message"."recipient_id" = "zerver_recipient"."id") \+WHERE ("zerver_usermessage"."user_profile_id" = {hamlet_id} AND (NOT ("zerver_recipient"."type" = 2) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_stream" U0 \+WHERE (U0."recipient_id" = ("zerver_message"."recipient_id") AND (NOT U0."invite_only" OR U0."can_subscribe_group_id" IN {hamlet_groups} OR U0."can_add_subscribers_group_id" IN {hamlet_groups})) LIMIT 1) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_subscription" U0 \+WHERE (U0."active" AND U0."recipient_id" = ("zerver_message"."recipient_id") AND U0."user_profile_id" = {hamlet_id}) LIMIT 1)) AND "zerver_message"."recipient_id" = {hamlet_recipient}) ORDER BY 1 ASC\+ LIMIT 10\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query(@@ -5505,15 +5470,14 @@ WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.)sql_template = """\-SELECT anon_1.message_id, anon_1.flags \n\-FROM (SELECT message_id, flags \n\-FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\-WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\-FROM zerver_stream \n\-WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\-FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND recipient_id = {scotland_recipient} AND (flags & 2) != 0 ORDER BY message_id ASC \n\- LIMIT 10) AS anon_1 ORDER BY message_id ASC\+SELECT "zerver_message"."id" AS "id", "zerver_usermessage"."flags" AS "user_flags" \+FROM "zerver_message" LEFT OUTER JOIN "zerver_usermessage" ON ("zerver_message"."id" = "zerver_usermessage"."message_id") INNER JOIN "zerver_recipient" ON ("zerver_message"."recipient_id" = "zerver_recipient"."id") \+WHERE ("zerver_usermessage"."user_profile_id" = {hamlet_id} AND (NOT ("zerver_recipient"."type" = 2) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_stream" U0 \+WHERE (U0."recipient_id" = ("zerver_message"."recipient_id") AND (NOT U0."invite_only" OR U0."can_subscribe_group_id" IN {hamlet_groups} OR U0."can_add_subscribers_group_id" IN {hamlet_groups})) LIMIT 1) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_subscription" U0 \+WHERE (U0."active" AND U0."recipient_id" = ("zerver_message"."recipient_id") AND U0."user_profile_id" = {hamlet_id}) LIMIT 1)) AND "zerver_message"."recipient_id" = {scotland_recipient} AND "zerver_usermessage"."flags" & 2 != 0) ORDER BY 1 ASC\+ LIMIT 10\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query(@@ -5531,19 +5495,18 @@ WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.query_ids = self.get_query_ids()sql_template = """\-SELECT anon_1.message_id, anon_1.flags, anon_1.escaped_topic_name, anon_1.rendered_content, anon_1.content_matches, anon_1.topic_matches \n\-FROM (SELECT message_id, flags, escape_html(subject) AS escaped_topic_name, rendered_content, array((SELECT ARRAY[sum(length(anon_3) - 11) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) + 11, strpos(anon_3, '</ts-match>') - 1] AS anon_2 \n\-FROM unnest(string_to_array(ts_headline('zulip.english_us_search', rendered_content, plainto_tsquery('zulip.english_us_search', 'jumping'), 'HighlightAll = TRUE, StartSel = <ts-match>, StopSel = </ts-match>'), '<ts-match>')) AS anon_3\n\- LIMIT ALL OFFSET 1)) AS content_matches, array((SELECT ARRAY[sum(length(anon_5) - 11) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) + 11, strpos(anon_5, '</ts-match>') - 1] AS anon_4 \n\-FROM unnest(string_to_array(ts_headline('zulip.english_us_search', escape_html(subject), plainto_tsquery('zulip.english_us_search', 'jumping'), 'HighlightAll = TRUE, StartSel = <ts-match>, StopSel = </ts-match>'), '<ts-match>')) AS anon_5\n\- LIMIT ALL OFFSET 1)) AS topic_matches \n\-FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\-WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\-FROM zerver_stream \n\-WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\-FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND (search_tsvector @@ plainto_tsquery('zulip.english_us_search', 'jumping')) ORDER BY message_id ASC \n\- LIMIT 10) AS anon_1 ORDER BY message_id ASC\+SELECT "zerver_message"."id" AS "id", "zerver_usermessage"."flags" AS "user_flags", escape_html("zerver_message"."subject") AS "escaped_topic_name", "zerver_message"."rendered_content" AS "rendered_content", (array(SELECT ARRAY[sum(length(p) - 11) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) + 11, strpos(p, '</ts-match>') - 1] \+FROM unnest(string_to_array(ts_headline('zulip.english_us_search', "zerver_message"."rendered_content", plainto_tsquery('zulip.english_us_search', 'jumping'), 'HighlightAll = TRUE, StartSel = <ts-match>, StopSel = </ts-match>'), '<ts-match>')) AS p\+ OFFSET 1)) AS "content_matches", (array(SELECT ARRAY[sum(length(p) - 11) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) + 11, strpos(p, '</ts-match>') - 1] \+FROM unnest(string_to_array(ts_headline('zulip.english_us_search', escape_html("zerver_message"."subject"), plainto_tsquery('zulip.english_us_search', 'jumping'), 'HighlightAll = TRUE, StartSel = <ts-match>, StopSel = </ts-match>'), '<ts-match>')) AS p\+ OFFSET 1)) AS "topic_matches" \+FROM "zerver_message" LEFT OUTER JOIN "zerver_usermessage" ON ("zerver_message"."id" = "zerver_usermessage"."message_id") INNER JOIN "zerver_recipient" ON ("zerver_message"."recipient_id" = "zerver_recipient"."id") \+WHERE ("zerver_usermessage"."user_profile_id" = {hamlet_id} AND (NOT ("zerver_recipient"."type" = 2) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_stream" U0 \+WHERE (U0."recipient_id" = ("zerver_message"."recipient_id") AND (NOT U0."invite_only" OR U0."can_subscribe_group_id" IN {hamlet_groups} OR U0."can_add_subscribers_group_id" IN {hamlet_groups})) LIMIT 1) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_subscription" U0 \+WHERE (U0."active" AND U0."recipient_id" = ("zerver_message"."recipient_id") AND U0."user_profile_id" = {hamlet_id}) LIMIT 1)) AND ("zerver_message"."search_tsvector" @@ plainto_tsquery('zulip.english_us_search', 'jumping')) = true) ORDER BY 1 ASC\+ LIMIT 10\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query(@@ -5551,15 +5514,14 @@ WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.)sql_template = """\-SELECT anon_1.message_id, anon_1.escaped_topic_name, anon_1.rendered_content, anon_1.content_matches, anon_1.topic_matches \n\-FROM (SELECT id AS message_id, escape_html(subject) AS escaped_topic_name, rendered_content, array((SELECT ARRAY[sum(length(anon_3) - 11) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) + 11, strpos(anon_3, '</ts-match>') - 1] AS anon_2 \n\-FROM unnest(string_to_array(ts_headline('zulip.english_us_search', rendered_content, plainto_tsquery('zulip.english_us_search', 'jumping'), 'HighlightAll = TRUE, StartSel = <ts-match>, StopSel = </ts-match>'), '<ts-match>')) AS anon_3\n\- LIMIT ALL OFFSET 1)) AS content_matches, array((SELECT ARRAY[sum(length(anon_5) - 11) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) + 11, strpos(anon_5, '</ts-match>') - 1] AS anon_4 \n\-FROM unnest(string_to_array(ts_headline('zulip.english_us_search', escape_html(subject), plainto_tsquery('zulip.english_us_search', 'jumping'), 'HighlightAll = TRUE, StartSel = <ts-match>, StopSel = </ts-match>'), '<ts-match>')) AS anon_5\n\- LIMIT ALL OFFSET 1)) AS topic_matches \n\-FROM zerver_message \n\-WHERE realm_id = 2 AND recipient_id = {scotland_recipient} AND (search_tsvector @@ plainto_tsquery('zulip.english_us_search', 'jumping')) ORDER BY zerver_message.id ASC \n\- LIMIT 10) AS anon_1 ORDER BY message_id ASC\+SELECT "zerver_message"."id" AS "id", escape_html("zerver_message"."subject") AS "escaped_topic_name", "zerver_message"."rendered_content" AS "rendered_content", (array(SELECT ARRAY[sum(length(p) - 11) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) + 11, strpos(p, '</ts-match>') - 1] \+FROM unnest(string_to_array(ts_headline('zulip.english_us_search', "zerver_message"."rendered_content", plainto_tsquery('zulip.english_us_search', 'jumping'), 'HighlightAll = TRUE, StartSel = <ts-match>, StopSel = </ts-match>'), '<ts-match>')) AS p\+ OFFSET 1)) AS "content_matches", (array(SELECT ARRAY[sum(length(p) - 11) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) + 11, strpos(p, '</ts-match>') - 1] \+FROM unnest(string_to_array(ts_headline('zulip.english_us_search', escape_html("zerver_message"."subject"), plainto_tsquery('zulip.english_us_search', 'jumping'), 'HighlightAll = TRUE, StartSel = <ts-match>, StopSel = </ts-match>'), '<ts-match>')) AS p\+ OFFSET 1)) AS "topic_matches" \+FROM "zerver_message" \+WHERE ("zerver_message"."realm_id" = 2 AND "zerver_message"."recipient_id" = 112 AND ("zerver_message"."search_tsvector" @@ plainto_tsquery('zulip.english_us_search', 'jumping')) = true) ORDER BY 1 ASC\+ LIMIT 10\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query(@@ -5573,19 +5535,18 @@ WHERE realm_id = 2 AND recipient_id = {scotland_recipient} AND (search_tsvector)sql_template = """\-SELECT anon_1.message_id, anon_1.flags, anon_1.escaped_topic_name, anon_1.rendered_content, anon_1.content_matches, anon_1.topic_matches \n\-FROM (SELECT message_id, flags, escape_html(subject) AS escaped_topic_name, rendered_content, array((SELECT ARRAY[sum(length(anon_3) - 11) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) + 11, strpos(anon_3, '</ts-match>') - 1] AS anon_2 \n\-FROM unnest(string_to_array(ts_headline('zulip.english_us_search', rendered_content, plainto_tsquery('zulip.english_us_search', '"jumping" quickly'), 'HighlightAll = TRUE, StartSel = <ts-match>, StopSel = </ts-match>'), '<ts-match>')) AS anon_3\n\- LIMIT ALL OFFSET 1)) AS content_matches, array((SELECT ARRAY[sum(length(anon_5) - 11) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) + 11, strpos(anon_5, '</ts-match>') - 1] AS anon_4 \n\-FROM unnest(string_to_array(ts_headline('zulip.english_us_search', escape_html(subject), plainto_tsquery('zulip.english_us_search', '"jumping" quickly'), 'HighlightAll = TRUE, StartSel = <ts-match>, StopSel = </ts-match>'), '<ts-match>')) AS anon_5\n\- LIMIT ALL OFFSET 1)) AS topic_matches \n\-FROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id JOIN zerver_recipient ON zerver_message.recipient_id = zerver_recipient.id \n\-WHERE user_profile_id = {hamlet_id} AND (zerver_recipient.type != 2 OR (EXISTS (SELECT \n\-FROM zerver_stream \n\-WHERE zerver_stream.recipient_id = zerver_recipient.id AND (NOT zerver_stream.invite_only OR zerver_stream.can_subscribe_group_id IN {hamlet_groups} OR zerver_stream.can_add_subscribers_group_id IN {hamlet_groups}))) OR (EXISTS (SELECT \n\-FROM zerver_subscription \n\-WHERE zerver_subscription.user_profile_id = {hamlet_id} AND zerver_subscription.recipient_id = zerver_recipient.id AND zerver_subscription.active))) AND (content ILIKE '%jumping%' OR subject ILIKE '%jumping%' AND is_channel_message) AND (search_tsvector @@ plainto_tsquery('zulip.english_us_search', '"jumping" quickly')) ORDER BY message_id ASC \n\- LIMIT 10) AS anon_1 ORDER BY message_id ASC\+SELECT "zerver_message"."id" AS "id", "zerver_usermessage"."flags" AS "user_flags", escape_html("zerver_message"."subject") AS "escaped_topic_name", "zerver_message"."rendered_content" AS "rendered_content", (array(SELECT ARRAY[sum(length(p) - 11) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) + 11, strpos(p, '</ts-match>') - 1] \+FROM unnest(string_to_array(ts_headline('zulip.english_us_search', "zerver_message"."rendered_content", plainto_tsquery('zulip.english_us_search', '"jumping" quickly'), 'HighlightAll = TRUE, StartSel = <ts-match>, StopSel = </ts-match>'), '<ts-match>')) AS p\+ OFFSET 1)) AS "content_matches", (array(SELECT ARRAY[sum(length(p) - 11) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) + 11, strpos(p, '</ts-match>') - 1] \+FROM unnest(string_to_array(ts_headline('zulip.english_us_search', escape_html("zerver_message"."subject"), plainto_tsquery('zulip.english_us_search', '"jumping" quickly'), 'HighlightAll = TRUE, StartSel = <ts-match>, StopSel = </ts-match>'), '<ts-match>')) AS p\+ OFFSET 1)) AS "topic_matches" \+FROM "zerver_message" LEFT OUTER JOIN "zerver_usermessage" ON ("zerver_message"."id" = "zerver_usermessage"."message_id") INNER JOIN "zerver_recipient" ON ("zerver_message"."recipient_id" = "zerver_recipient"."id") \+WHERE ("zerver_usermessage"."user_profile_id" = {hamlet_id} AND (NOT ("zerver_recipient"."type" = 2) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_stream" U0 \+WHERE (U0."recipient_id" = ("zerver_message"."recipient_id") AND (NOT U0."invite_only" OR U0."can_subscribe_group_id" IN {hamlet_groups} OR U0."can_add_subscribers_group_id" IN {hamlet_groups})) LIMIT 1) OR EXISTS(SELECT 1 AS "a" \+FROM "zerver_subscription" U0 \+WHERE (U0."active" AND U0."recipient_id" = ("zerver_message"."recipient_id") AND U0."user_profile_id" = {hamlet_id}) LIMIT 1)) AND (UPPER("zerver_message"."content"::text) LIKE UPPER('%jumping%') OR ("zerver_message"."is_channel_message" AND UPPER("zerver_message"."subject"::text) LIKE UPPER('%jumping%'))) AND ("zerver_message"."search_tsvector" @@ plainto_tsquery('zulip.english_us_search', '"jumping" quickly')) = true) ORDER BY 1 ASC\+ LIMIT 10\"""sql = sql_template.format(**query_ids)self.common_check_get_messages_query(diff --git a/zerver/views/message_fetch.py b/zerver/views/message_fetch.pyindex 4b7193a2cd2..c14c42317d6 100644--- a/zerver/views/message_fetch.py+++ b/zerver/views/message_fetch.py@@ -4,11 +4,10 @@ from typing import Annotatedfrom django.conf import settingsfrom django.contrib.auth.models import AnonymousUserfrom django.db import connection, transaction+from django.db.models import F, Func, TextFieldfrom django.http import HttpRequest, HttpResponsefrom django.utils.translation import gettext as _from pydantic import Json, NonNegativeInt-from sqlalchemy.sql import column, func-from sqlalchemy.types import Integer, Textfrom zerver.context_processors import get_valid_realm_from_requestfrom zerver.lib.exceptions import (@@ -29,9 +28,7 @@ from zerver.lib.narrow import ()from zerver.lib.request import RequestNotesfrom zerver.lib.response import json_success-from zerver.lib.sqlalchemy_utils import get_sqlalchemy_connection-from zerver.lib.topic import MATCH_TOPIC-from zerver.lib.topic_sqlalchemy import topic_column_sa+from zerver.lib.topic import DB_TOPIC_NAME, MATCH_TOPICfrom zerver.lib.typed_endpoint import ApiParamConfig, typed_endpointfrom zerver.models import UserMessage, UserProfile@@ -347,15 +344,12 @@ def messages_in_narrow_backend(msg_ids = [message_id for message_id in msg_ids if message_id >= first_visible_message_id]# This query is limited to messages the user has access to because they# actually received them, as reflected in `zerver_usermessage`.- query, inner_msg_id_col = get_base_query_for_search(- user_profile.realm_id, user_profile, need_user_message=True- )- query = query.where(column("message_id", Integer).in_(msg_ids))+ query = get_base_query_for_search(user_profile.realm_id, user_profile, need_user_message=True)+ query = query.filter(id__in=msg_ids)cleaned_narrow = clean_narrow_for_message_fetch(narrow, user_profile.realm, user_profile)query, is_search, _is_dm_narrow = add_narrow_conditions(user_profile=user_profile,- inner_msg_id_col=inner_msg_id_col,query=query,narrow=cleaned_narrow,is_web_public_query=False,@@ -364,24 +358,29 @@ def messages_in_narrow_backend(if not is_search:# `add_narrow_conditions` adds the following columns only if narrow has search operands.- query = query.add_columns(- func.escape_html(topic_column_sa(), type_=Text).label("escaped_topic_name"),- column("rendered_content", Text),+ query = query.annotate(+ escaped_topic_name=Func(+ F(DB_TOPIC_NAME), function="escape_html", output_field=TextField()+ ),)search_fields = {}- with get_sqlalchemy_connection() as sa_conn:- for row in sa_conn.execute(query).mappings():- message_id = row["message_id"]- escaped_topic_name: str = row["escaped_topic_name"]- rendered_content: str = row["rendered_content"]- content_matches = row.get("content_matches", [])- topic_matches = row.get("topic_matches", [])- search_fields[str(message_id)] = get_search_fields(- rendered_content,- escaped_topic_name,- content_matches,- topic_matches,- )+ for row in query.values(+ "id",+ "escaped_topic_name",+ "rendered_content",+ *["content_matches", "topic_matches"] if is_search else [],+ ):+ message_id = row["id"]+ escaped_topic_name: str = row["escaped_topic_name"]+ rendered_content: str = row["rendered_content"]+ content_matches = row.get("content_matches", [])+ topic_matches = row.get("topic_matches", [])+ search_fields[str(message_id)] = get_search_fields(+ rendered_content,+ escaped_topic_name,+ content_matches,+ topic_matches,+ )return json_success(request, data={"messages": search_fields})