From 19f2f1fa862320afa1e86a153eb312aaaced663e Mon Sep 17 00:00:00 2001 From: Stu Tomlinson Date: Mon, 12 Dec 2022 16:05:46 +0000 Subject: [PATCH] Fix MS SQL error caused by ORDER BY in subquery 'The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.' Omit the ORDER BY clause from subquery if the SELECT is not constrained by TOP. --- src/mod_mam_sql.erl | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/mod_mam_sql.erl b/src/mod_mam_sql.erl index 2d60aea4b..695542387 100644 --- a/src/mod_mam_sql.erl +++ b/src/mod_mam_sql.erl @@ -441,6 +441,11 @@ make_sql_query(User, LServer, MAMQuery, RSM, ExtraUsernames) -> true -> [] end, + SubOrderClause = if LimitClause /= [], TopClause /= [] -> + <<" ORDER BY timestamp DESC ">>; + true -> + [] + end, WithTextClause = if is_binary(WithText), WithText /= <<>> -> [<<" and match (txt) against (">>, ToString(WithText), <<")">>]; @@ -528,7 +533,7 @@ make_sql_query(User, LServer, MAMQuery, RSM, ExtraUsernames) -> % XEP-0059: Result Set Management % 2.5 Requesting the Last Page in a Result Set [<<"SELECT">>, UserSel, <<" timestamp, xml, peer, kind, nick FROM (">>, - Query, <<" ORDER BY timestamp DESC ">>, + Query, SubOrderClause, LimitClause, <<") AS t ORDER BY timestamp ASC;">>]; _ -> [Query, <<" ORDER BY timestamp ASC ">>,