Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

748 rindas
26 KiB

  1. # Copyright 2018, 2019 New Vector Ltd
  2. # Copyright 2019 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from enum import Enum
  17. from itertools import chain
  18. from typing import Any, Dict, List, Optional, Tuple
  19. from typing_extensions import Counter
  20. from twisted.internet.defer import DeferredLock
  21. from synapse.api.constants import EventTypes, Membership
  22. from synapse.api.errors import StoreError
  23. from synapse.storage.database import DatabasePool
  24. from synapse.storage.databases.main.state_deltas import StateDeltasStore
  25. from synapse.types import JsonDict
  26. from synapse.util.caches.descriptors import cached
  27. logger = logging.getLogger(__name__)
  28. # these fields track absolutes (e.g. total number of rooms on the server)
  29. # You can think of these as Prometheus Gauges.
  30. # You can draw these stats on a line graph.
  31. # Example: number of users in a room
  32. ABSOLUTE_STATS_FIELDS = {
  33. "room": (
  34. "current_state_events",
  35. "joined_members",
  36. "invited_members",
  37. "knocked_members",
  38. "left_members",
  39. "banned_members",
  40. "local_users_in_room",
  41. ),
  42. "user": ("joined_rooms",),
  43. }
  44. TYPE_TO_TABLE = {"room": ("room_stats", "room_id"), "user": ("user_stats", "user_id")}
  45. # these are the tables (& ID columns) which contain our actual subjects
  46. TYPE_TO_ORIGIN_TABLE = {"room": ("rooms", "room_id"), "user": ("users", "name")}
  47. class UserSortOrder(Enum):
  48. """
  49. Enum to define the sorting method used when returning users
  50. with get_users_paginate in __init__.py
  51. and get_users_media_usage_paginate in stats.py
  52. When moves this to __init__.py gets `builtins.ImportError` with
  53. `most likely due to a circular import`
  54. MEDIA_LENGTH = ordered by size of uploaded media.
  55. MEDIA_COUNT = ordered by number of uploaded media.
  56. USER_ID = ordered alphabetically by `user_id`.
  57. NAME = ordered alphabetically by `user_id`. This is for compatibility reasons,
  58. as the user_id is returned in the name field in the response in list users admin API.
  59. DISPLAYNAME = ordered alphabetically by `displayname`
  60. GUEST = ordered by `is_guest`
  61. ADMIN = ordered by `admin`
  62. DEACTIVATED = ordered by `deactivated`
  63. USER_TYPE = ordered alphabetically by `user_type`
  64. AVATAR_URL = ordered alphabetically by `avatar_url`
  65. SHADOW_BANNED = ordered by `shadow_banned`
  66. """
  67. MEDIA_LENGTH = "media_length"
  68. MEDIA_COUNT = "media_count"
  69. USER_ID = "user_id"
  70. NAME = "name"
  71. DISPLAYNAME = "displayname"
  72. GUEST = "is_guest"
  73. ADMIN = "admin"
  74. DEACTIVATED = "deactivated"
  75. USER_TYPE = "user_type"
  76. AVATAR_URL = "avatar_url"
  77. SHADOW_BANNED = "shadow_banned"
  78. class StatsStore(StateDeltasStore):
  79. def __init__(self, database: DatabasePool, db_conn, hs):
  80. super().__init__(database, db_conn, hs)
  81. self.server_name = hs.hostname
  82. self.clock = self.hs.get_clock()
  83. self.stats_enabled = hs.config.stats_enabled
  84. self.stats_delta_processing_lock = DeferredLock()
  85. self.db_pool.updates.register_background_update_handler(
  86. "populate_stats_process_rooms", self._populate_stats_process_rooms
  87. )
  88. self.db_pool.updates.register_background_update_handler(
  89. "populate_stats_process_users", self._populate_stats_process_users
  90. )
  91. # we no longer need to perform clean-up, but we will give ourselves
  92. # the potential to reintroduce it in the future – so documentation
  93. # will still encourage the use of this no-op handler.
  94. self.db_pool.updates.register_noop_background_update("populate_stats_cleanup")
  95. self.db_pool.updates.register_noop_background_update("populate_stats_prepare")
  96. async def _populate_stats_process_users(self, progress, batch_size):
  97. """
  98. This is a background update which regenerates statistics for users.
  99. """
  100. if not self.stats_enabled:
  101. await self.db_pool.updates._end_background_update(
  102. "populate_stats_process_users"
  103. )
  104. return 1
  105. last_user_id = progress.get("last_user_id", "")
  106. def _get_next_batch(txn):
  107. sql = """
  108. SELECT DISTINCT name FROM users
  109. WHERE name > ?
  110. ORDER BY name ASC
  111. LIMIT ?
  112. """
  113. txn.execute(sql, (last_user_id, batch_size))
  114. return [r for r, in txn]
  115. users_to_work_on = await self.db_pool.runInteraction(
  116. "_populate_stats_process_users", _get_next_batch
  117. )
  118. # No more rooms -- complete the transaction.
  119. if not users_to_work_on:
  120. await self.db_pool.updates._end_background_update(
  121. "populate_stats_process_users"
  122. )
  123. return 1
  124. for user_id in users_to_work_on:
  125. await self._calculate_and_set_initial_state_for_user(user_id)
  126. progress["last_user_id"] = user_id
  127. await self.db_pool.runInteraction(
  128. "populate_stats_process_users",
  129. self.db_pool.updates._background_update_progress_txn,
  130. "populate_stats_process_users",
  131. progress,
  132. )
  133. return len(users_to_work_on)
  134. async def _populate_stats_process_rooms(self, progress, batch_size):
  135. """This is a background update which regenerates statistics for rooms."""
  136. if not self.stats_enabled:
  137. await self.db_pool.updates._end_background_update(
  138. "populate_stats_process_rooms"
  139. )
  140. return 1
  141. last_room_id = progress.get("last_room_id", "")
  142. def _get_next_batch(txn):
  143. sql = """
  144. SELECT DISTINCT room_id FROM current_state_events
  145. WHERE room_id > ?
  146. ORDER BY room_id ASC
  147. LIMIT ?
  148. """
  149. txn.execute(sql, (last_room_id, batch_size))
  150. return [r for r, in txn]
  151. rooms_to_work_on = await self.db_pool.runInteraction(
  152. "populate_stats_rooms_get_batch", _get_next_batch
  153. )
  154. # No more rooms -- complete the transaction.
  155. if not rooms_to_work_on:
  156. await self.db_pool.updates._end_background_update(
  157. "populate_stats_process_rooms"
  158. )
  159. return 1
  160. for room_id in rooms_to_work_on:
  161. await self._calculate_and_set_initial_state_for_room(room_id)
  162. progress["last_room_id"] = room_id
  163. await self.db_pool.runInteraction(
  164. "_populate_stats_process_rooms",
  165. self.db_pool.updates._background_update_progress_txn,
  166. "populate_stats_process_rooms",
  167. progress,
  168. )
  169. return len(rooms_to_work_on)
  170. async def get_stats_positions(self) -> int:
  171. """
  172. Returns the stats processor positions.
  173. """
  174. return await self.db_pool.simple_select_one_onecol(
  175. table="stats_incremental_position",
  176. keyvalues={},
  177. retcol="stream_id",
  178. desc="stats_incremental_position",
  179. )
  180. async def update_room_state(self, room_id: str, fields: Dict[str, Any]) -> None:
  181. """Update the state of a room.
  182. fields can contain the following keys with string values:
  183. * join_rules
  184. * history_visibility
  185. * encryption
  186. * name
  187. * topic
  188. * avatar
  189. * canonical_alias
  190. * guest_access
  191. A is_federatable key can also be included with a boolean value.
  192. Args:
  193. room_id: The room ID to update the state of.
  194. fields: The fields to update. This can include a partial list of the
  195. above fields to only update some room information.
  196. """
  197. # Ensure that the values to update are valid, they should be strings and
  198. # not contain any null bytes.
  199. #
  200. # Invalid data gets overwritten with null.
  201. #
  202. # Note that a missing value should not be overwritten (it keeps the
  203. # previous value).
  204. sentinel = object()
  205. for col in (
  206. "join_rules",
  207. "history_visibility",
  208. "encryption",
  209. "name",
  210. "topic",
  211. "avatar",
  212. "canonical_alias",
  213. "guest_access",
  214. ):
  215. field = fields.get(col, sentinel)
  216. if field is not sentinel and (not isinstance(field, str) or "\0" in field):
  217. fields[col] = None
  218. await self.db_pool.simple_upsert(
  219. table="room_stats_state",
  220. keyvalues={"room_id": room_id},
  221. values=fields,
  222. desc="update_room_state",
  223. )
  224. @cached()
  225. async def get_earliest_token_for_stats(
  226. self, stats_type: str, id: str
  227. ) -> Optional[int]:
  228. """
  229. Fetch the "earliest token". This is used by the room stats delta
  230. processor to ignore deltas that have been processed between the
  231. start of the background task and any particular room's stats
  232. being calculated.
  233. Returns:
  234. The earliest token.
  235. """
  236. table, id_col = TYPE_TO_TABLE[stats_type]
  237. return await self.db_pool.simple_select_one_onecol(
  238. "%s_current" % (table,),
  239. keyvalues={id_col: id},
  240. retcol="completed_delta_stream_id",
  241. allow_none=True,
  242. )
  243. async def bulk_update_stats_delta(
  244. self, ts: int, updates: Dict[str, Dict[str, Counter[str]]], stream_id: int
  245. ) -> None:
  246. """Bulk update stats tables for a given stream_id and updates the stats
  247. incremental position.
  248. Args:
  249. ts: Current timestamp in ms
  250. updates: The updates to commit as a mapping of
  251. stats_type -> stats_id -> field -> delta.
  252. stream_id: Current position.
  253. """
  254. def _bulk_update_stats_delta_txn(txn):
  255. for stats_type, stats_updates in updates.items():
  256. for stats_id, fields in stats_updates.items():
  257. logger.debug(
  258. "Updating %s stats for %s: %s", stats_type, stats_id, fields
  259. )
  260. self._update_stats_delta_txn(
  261. txn,
  262. ts=ts,
  263. stats_type=stats_type,
  264. stats_id=stats_id,
  265. fields=fields,
  266. complete_with_stream_id=stream_id,
  267. )
  268. self.db_pool.simple_update_one_txn(
  269. txn,
  270. table="stats_incremental_position",
  271. keyvalues={},
  272. updatevalues={"stream_id": stream_id},
  273. )
  274. await self.db_pool.runInteraction(
  275. "bulk_update_stats_delta", _bulk_update_stats_delta_txn
  276. )
  277. async def update_stats_delta(
  278. self,
  279. ts: int,
  280. stats_type: str,
  281. stats_id: str,
  282. fields: Dict[str, int],
  283. complete_with_stream_id: Optional[int],
  284. absolute_field_overrides: Optional[Dict[str, int]] = None,
  285. ) -> None:
  286. """
  287. Updates the statistics for a subject, with a delta (difference/relative
  288. change).
  289. Args:
  290. ts: timestamp of the change
  291. stats_type: "room" or "user" – the kind of subject
  292. stats_id: the subject's ID (room ID or user ID)
  293. fields: Deltas of stats values.
  294. complete_with_stream_id:
  295. If supplied, converts an incomplete row into a complete row,
  296. with the supplied stream_id marked as the stream_id where the
  297. row was completed.
  298. absolute_field_overrides: Current stats values (i.e. not deltas) of
  299. absolute fields. Does not work with per-slice fields.
  300. """
  301. await self.db_pool.runInteraction(
  302. "update_stats_delta",
  303. self._update_stats_delta_txn,
  304. ts,
  305. stats_type,
  306. stats_id,
  307. fields,
  308. complete_with_stream_id=complete_with_stream_id,
  309. absolute_field_overrides=absolute_field_overrides,
  310. )
  311. def _update_stats_delta_txn(
  312. self,
  313. txn,
  314. ts,
  315. stats_type,
  316. stats_id,
  317. fields,
  318. complete_with_stream_id,
  319. absolute_field_overrides=None,
  320. ):
  321. if absolute_field_overrides is None:
  322. absolute_field_overrides = {}
  323. table, id_col = TYPE_TO_TABLE[stats_type]
  324. # Lets be paranoid and check that all the given field names are known
  325. abs_field_names = ABSOLUTE_STATS_FIELDS[stats_type]
  326. for field in chain(fields.keys(), absolute_field_overrides.keys()):
  327. if field not in abs_field_names:
  328. # guard against potential SQL injection dodginess
  329. raise ValueError(
  330. "%s is not a recognised field"
  331. " for stats type %s" % (field, stats_type)
  332. )
  333. # Per slice fields do not get added to the _current table
  334. # This calculates the deltas (`field = field + ?` values)
  335. # for absolute fields,
  336. # * defaulting to 0 if not specified
  337. # (required for the INSERT part of upserting to work)
  338. # * omitting overrides specified in `absolute_field_overrides`
  339. deltas_of_absolute_fields = {
  340. key: fields.get(key, 0)
  341. for key in abs_field_names
  342. if key not in absolute_field_overrides
  343. }
  344. # Keep the delta stream ID field up to date
  345. absolute_field_overrides = absolute_field_overrides.copy()
  346. absolute_field_overrides["completed_delta_stream_id"] = complete_with_stream_id
  347. # first upsert the `_current` table
  348. self._upsert_with_additive_relatives_txn(
  349. txn=txn,
  350. table=table + "_current",
  351. keyvalues={id_col: stats_id},
  352. absolutes=absolute_field_overrides,
  353. additive_relatives=deltas_of_absolute_fields,
  354. )
  355. def _upsert_with_additive_relatives_txn(
  356. self, txn, table, keyvalues, absolutes, additive_relatives
  357. ):
  358. """Used to update values in the stats tables.
  359. This is basically a slightly convoluted upsert that *adds* to any
  360. existing rows.
  361. Args:
  362. txn
  363. table (str): Table name
  364. keyvalues (dict[str, any]): Row-identifying key values
  365. absolutes (dict[str, any]): Absolute (set) fields
  366. additive_relatives (dict[str, int]): Fields that will be added onto
  367. if existing row present.
  368. """
  369. if self.database_engine.can_native_upsert:
  370. absolute_updates = [
  371. "%(field)s = EXCLUDED.%(field)s" % {"field": field}
  372. for field in absolutes.keys()
  373. ]
  374. relative_updates = [
  375. "%(field)s = EXCLUDED.%(field)s + %(table)s.%(field)s"
  376. % {"table": table, "field": field}
  377. for field in additive_relatives.keys()
  378. ]
  379. insert_cols = []
  380. qargs = []
  381. for (key, val) in chain(
  382. keyvalues.items(), absolutes.items(), additive_relatives.items()
  383. ):
  384. insert_cols.append(key)
  385. qargs.append(val)
  386. sql = """
  387. INSERT INTO %(table)s (%(insert_cols_cs)s)
  388. VALUES (%(insert_vals_qs)s)
  389. ON CONFLICT (%(key_columns)s) DO UPDATE SET %(updates)s
  390. """ % {
  391. "table": table,
  392. "insert_cols_cs": ", ".join(insert_cols),
  393. "insert_vals_qs": ", ".join(
  394. ["?"] * (len(keyvalues) + len(absolutes) + len(additive_relatives))
  395. ),
  396. "key_columns": ", ".join(keyvalues),
  397. "updates": ", ".join(chain(absolute_updates, relative_updates)),
  398. }
  399. txn.execute(sql, qargs)
  400. else:
  401. self.database_engine.lock_table(txn, table)
  402. retcols = list(chain(absolutes.keys(), additive_relatives.keys()))
  403. current_row = self.db_pool.simple_select_one_txn(
  404. txn, table, keyvalues, retcols, allow_none=True
  405. )
  406. if current_row is None:
  407. merged_dict = {**keyvalues, **absolutes, **additive_relatives}
  408. self.db_pool.simple_insert_txn(txn, table, merged_dict)
  409. else:
  410. for (key, val) in additive_relatives.items():
  411. current_row[key] += val
  412. current_row.update(absolutes)
  413. self.db_pool.simple_update_one_txn(txn, table, keyvalues, current_row)
  414. async def _calculate_and_set_initial_state_for_room(
  415. self, room_id: str
  416. ) -> Tuple[dict, dict, int]:
  417. """Calculate and insert an entry into room_stats_current.
  418. Args:
  419. room_id: The room ID under calculation.
  420. Returns:
  421. A tuple of room state, membership counts and stream position.
  422. """
  423. def _fetch_current_state_stats(txn):
  424. pos = self.get_room_max_stream_ordering()
  425. rows = self.db_pool.simple_select_many_txn(
  426. txn,
  427. table="current_state_events",
  428. column="type",
  429. iterable=[
  430. EventTypes.Create,
  431. EventTypes.JoinRules,
  432. EventTypes.RoomHistoryVisibility,
  433. EventTypes.RoomEncryption,
  434. EventTypes.Name,
  435. EventTypes.Topic,
  436. EventTypes.RoomAvatar,
  437. EventTypes.CanonicalAlias,
  438. ],
  439. keyvalues={"room_id": room_id, "state_key": ""},
  440. retcols=["event_id"],
  441. )
  442. event_ids = [row["event_id"] for row in rows]
  443. txn.execute(
  444. """
  445. SELECT membership, count(*) FROM current_state_events
  446. WHERE room_id = ? AND type = 'm.room.member'
  447. GROUP BY membership
  448. """,
  449. (room_id,),
  450. )
  451. membership_counts = {membership: cnt for membership, cnt in txn}
  452. txn.execute(
  453. """
  454. SELECT COALESCE(count(*), 0) FROM current_state_events
  455. WHERE room_id = ?
  456. """,
  457. (room_id,),
  458. )
  459. (current_state_events_count,) = txn.fetchone()
  460. users_in_room = self.get_users_in_room_txn(txn, room_id)
  461. return (
  462. event_ids,
  463. membership_counts,
  464. current_state_events_count,
  465. users_in_room,
  466. pos,
  467. )
  468. (
  469. event_ids,
  470. membership_counts,
  471. current_state_events_count,
  472. users_in_room,
  473. pos,
  474. ) = await self.db_pool.runInteraction(
  475. "get_initial_state_for_room", _fetch_current_state_stats
  476. )
  477. state_event_map = await self.get_events(event_ids, get_prev_content=False)
  478. room_state = {
  479. "join_rules": None,
  480. "history_visibility": None,
  481. "encryption": None,
  482. "name": None,
  483. "topic": None,
  484. "avatar": None,
  485. "canonical_alias": None,
  486. "is_federatable": True,
  487. }
  488. for event in state_event_map.values():
  489. if event.type == EventTypes.JoinRules:
  490. room_state["join_rules"] = event.content.get("join_rule")
  491. elif event.type == EventTypes.RoomHistoryVisibility:
  492. room_state["history_visibility"] = event.content.get(
  493. "history_visibility"
  494. )
  495. elif event.type == EventTypes.RoomEncryption:
  496. room_state["encryption"] = event.content.get("algorithm")
  497. elif event.type == EventTypes.Name:
  498. room_state["name"] = event.content.get("name")
  499. elif event.type == EventTypes.Topic:
  500. room_state["topic"] = event.content.get("topic")
  501. elif event.type == EventTypes.RoomAvatar:
  502. room_state["avatar"] = event.content.get("url")
  503. elif event.type == EventTypes.CanonicalAlias:
  504. room_state["canonical_alias"] = event.content.get("alias")
  505. elif event.type == EventTypes.Create:
  506. room_state["is_federatable"] = (
  507. event.content.get("m.federate", True) is True
  508. )
  509. await self.update_room_state(room_id, room_state)
  510. local_users_in_room = [u for u in users_in_room if self.hs.is_mine_id(u)]
  511. await self.update_stats_delta(
  512. ts=self.clock.time_msec(),
  513. stats_type="room",
  514. stats_id=room_id,
  515. fields={},
  516. complete_with_stream_id=pos,
  517. absolute_field_overrides={
  518. "current_state_events": current_state_events_count,
  519. "joined_members": membership_counts.get(Membership.JOIN, 0),
  520. "invited_members": membership_counts.get(Membership.INVITE, 0),
  521. "left_members": membership_counts.get(Membership.LEAVE, 0),
  522. "banned_members": membership_counts.get(Membership.BAN, 0),
  523. "local_users_in_room": len(local_users_in_room),
  524. },
  525. )
  526. async def _calculate_and_set_initial_state_for_user(self, user_id):
  527. def _calculate_and_set_initial_state_for_user_txn(txn):
  528. pos = self._get_max_stream_id_in_current_state_deltas_txn(txn)
  529. txn.execute(
  530. """
  531. SELECT COUNT(distinct room_id) FROM current_state_events
  532. WHERE type = 'm.room.member' AND state_key = ?
  533. AND membership = 'join'
  534. """,
  535. (user_id,),
  536. )
  537. (count,) = txn.fetchone()
  538. return count, pos
  539. joined_rooms, pos = await self.db_pool.runInteraction(
  540. "calculate_and_set_initial_state_for_user",
  541. _calculate_and_set_initial_state_for_user_txn,
  542. )
  543. await self.update_stats_delta(
  544. ts=self.clock.time_msec(),
  545. stats_type="user",
  546. stats_id=user_id,
  547. fields={},
  548. complete_with_stream_id=pos,
  549. absolute_field_overrides={"joined_rooms": joined_rooms},
  550. )
  551. async def get_users_media_usage_paginate(
  552. self,
  553. start: int,
  554. limit: int,
  555. from_ts: Optional[int] = None,
  556. until_ts: Optional[int] = None,
  557. order_by: Optional[UserSortOrder] = UserSortOrder.USER_ID.value,
  558. direction: Optional[str] = "f",
  559. search_term: Optional[str] = None,
  560. ) -> Tuple[List[JsonDict], Dict[str, int]]:
  561. """Function to retrieve a paginated list of users and their uploaded local media
  562. (size and number). This will return a json list of users and the
  563. total number of users matching the filter criteria.
  564. Args:
  565. start: offset to begin the query from
  566. limit: number of rows to retrieve
  567. from_ts: request only media that are created later than this timestamp (ms)
  568. until_ts: request only media that are created earlier than this timestamp (ms)
  569. order_by: the sort order of the returned list
  570. direction: sort ascending or descending
  571. search_term: a string to filter user names by
  572. Returns:
  573. A list of user dicts and an integer representing the total number of
  574. users that exist given this query
  575. """
  576. def get_users_media_usage_paginate_txn(txn):
  577. filters = []
  578. args = [self.hs.config.server_name]
  579. if search_term:
  580. filters.append("(lmr.user_id LIKE ? OR displayname LIKE ?)")
  581. args.extend(["@%" + search_term + "%:%", "%" + search_term + "%"])
  582. if from_ts:
  583. filters.append("created_ts >= ?")
  584. args.extend([from_ts])
  585. if until_ts:
  586. filters.append("created_ts <= ?")
  587. args.extend([until_ts])
  588. # Set ordering
  589. if UserSortOrder(order_by) == UserSortOrder.MEDIA_LENGTH:
  590. order_by_column = "media_length"
  591. elif UserSortOrder(order_by) == UserSortOrder.MEDIA_COUNT:
  592. order_by_column = "media_count"
  593. elif UserSortOrder(order_by) == UserSortOrder.USER_ID:
  594. order_by_column = "lmr.user_id"
  595. elif UserSortOrder(order_by) == UserSortOrder.DISPLAYNAME:
  596. order_by_column = "displayname"
  597. else:
  598. raise StoreError(
  599. 500, "Incorrect value for order_by provided: %s" % order_by
  600. )
  601. if direction == "b":
  602. order = "DESC"
  603. else:
  604. order = "ASC"
  605. where_clause = "WHERE " + " AND ".join(filters) if len(filters) > 0 else ""
  606. sql_base = """
  607. FROM local_media_repository as lmr
  608. LEFT JOIN profiles AS p ON lmr.user_id = '@' || p.user_id || ':' || ?
  609. {}
  610. GROUP BY lmr.user_id, displayname
  611. """.format(
  612. where_clause
  613. )
  614. # SQLite does not support SELECT COUNT(*) OVER()
  615. sql = """
  616. SELECT COUNT(*) FROM (
  617. SELECT lmr.user_id
  618. {sql_base}
  619. ) AS count_user_ids
  620. """.format(
  621. sql_base=sql_base,
  622. )
  623. txn.execute(sql, args)
  624. count = txn.fetchone()[0]
  625. sql = """
  626. SELECT
  627. lmr.user_id,
  628. displayname,
  629. COUNT(lmr.user_id) as media_count,
  630. SUM(media_length) as media_length
  631. {sql_base}
  632. ORDER BY {order_by_column} {order}
  633. LIMIT ? OFFSET ?
  634. """.format(
  635. sql_base=sql_base,
  636. order_by_column=order_by_column,
  637. order=order,
  638. )
  639. args += [limit, start]
  640. txn.execute(sql, args)
  641. users = self.db_pool.cursor_to_dict(txn)
  642. return users, count
  643. return await self.db_pool.runInteraction(
  644. "get_users_media_usage_paginate_txn", get_users_media_usage_paginate_txn
  645. )