_base.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  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 synapse.api.errors import StoreError
  17. from synapse.util.logcontext import LoggingContext, PreserveLoggingContext
  18. from synapse.util.caches.descriptors import Cache
  19. from synapse.storage.engines import PostgresEngine
  20. from prometheus_client import Histogram
  21. from twisted.internet import defer
  22. import sys
  23. import time
  24. import threading
  25. from six import itervalues, iterkeys, iteritems
  26. from six.moves import intern, range
  27. logger = logging.getLogger(__name__)
  28. try:
  29. MAX_TXN_ID = sys.maxint - 1
  30. except AttributeError:
  31. # python 3 does not have a maximum int value
  32. MAX_TXN_ID = 2**63 - 1
  33. sql_logger = logging.getLogger("synapse.storage.SQL")
  34. transaction_logger = logging.getLogger("synapse.storage.txn")
  35. perf_logger = logging.getLogger("synapse.storage.TIME")
  36. sql_scheduling_timer = Histogram("synapse_storage_schedule_time", "sec")
  37. sql_query_timer = Histogram("synapse_storage_query_time", "sec", ["verb"])
  38. sql_txn_timer = Histogram("synapse_storage_transaction_time", "sec", ["desc"])
  39. class LoggingTransaction(object):
  40. """An object that almost-transparently proxies for the 'txn' object
  41. passed to the constructor. Adds logging and metrics to the .execute()
  42. method."""
  43. __slots__ = [
  44. "txn", "name", "database_engine", "after_callbacks", "exception_callbacks",
  45. ]
  46. def __init__(self, txn, name, database_engine, after_callbacks,
  47. exception_callbacks):
  48. object.__setattr__(self, "txn", txn)
  49. object.__setattr__(self, "name", name)
  50. object.__setattr__(self, "database_engine", database_engine)
  51. object.__setattr__(self, "after_callbacks", after_callbacks)
  52. object.__setattr__(self, "exception_callbacks", exception_callbacks)
  53. def call_after(self, callback, *args, **kwargs):
  54. """Call the given callback on the main twisted thread after the
  55. transaction has finished. Used to invalidate the caches on the
  56. correct thread.
  57. """
  58. self.after_callbacks.append((callback, args, kwargs))
  59. def call_on_exception(self, callback, *args, **kwargs):
  60. self.exception_callbacks.append((callback, args, kwargs))
  61. def __getattr__(self, name):
  62. return getattr(self.txn, name)
  63. def __setattr__(self, name, value):
  64. setattr(self.txn, name, value)
  65. def __iter__(self):
  66. return self.txn.__iter__()
  67. def execute(self, sql, *args):
  68. self._do_execute(self.txn.execute, sql, *args)
  69. def executemany(self, sql, *args):
  70. self._do_execute(self.txn.executemany, sql, *args)
  71. def _make_sql_one_line(self, sql):
  72. "Strip newlines out of SQL so that the loggers in the DB are on one line"
  73. return " ".join(l.strip() for l in sql.splitlines() if l.strip())
  74. def _do_execute(self, func, sql, *args):
  75. sql = self._make_sql_one_line(sql)
  76. # TODO(paul): Maybe use 'info' and 'debug' for values?
  77. sql_logger.debug("[SQL] {%s} %s", self.name, sql)
  78. sql = self.database_engine.convert_param_style(sql)
  79. if args:
  80. try:
  81. sql_logger.debug(
  82. "[SQL values] {%s} %r",
  83. self.name, args[0]
  84. )
  85. except Exception:
  86. # Don't let logging failures stop SQL from working
  87. pass
  88. start = time.time()
  89. try:
  90. return func(
  91. sql, *args
  92. )
  93. except Exception as e:
  94. logger.debug("[SQL FAIL] {%s} %s", self.name, e)
  95. raise
  96. finally:
  97. secs = time.time() - start
  98. sql_logger.debug("[SQL time] {%s} %f sec", self.name, secs)
  99. sql_query_timer.labels(sql.split()[0]).observe(secs)
  100. class PerformanceCounters(object):
  101. def __init__(self):
  102. self.current_counters = {}
  103. self.previous_counters = {}
  104. def update(self, key, start_time, end_time=None):
  105. if end_time is None:
  106. end_time = time.time()
  107. duration = end_time - start_time
  108. count, cum_time = self.current_counters.get(key, (0, 0))
  109. count += 1
  110. cum_time += duration
  111. self.current_counters[key] = (count, cum_time)
  112. return end_time
  113. def interval(self, interval_duration, limit=3):
  114. counters = []
  115. for name, (count, cum_time) in iteritems(self.current_counters):
  116. prev_count, prev_time = self.previous_counters.get(name, (0, 0))
  117. counters.append((
  118. (cum_time - prev_time) / interval_duration,
  119. count - prev_count,
  120. name
  121. ))
  122. self.previous_counters = dict(self.current_counters)
  123. counters.sort(reverse=True)
  124. top_n_counters = ", ".join(
  125. "%s(%d): %.3f%%" % (name, count, 100 * ratio)
  126. for ratio, count, name in counters[:limit]
  127. )
  128. return top_n_counters
  129. class SQLBaseStore(object):
  130. _TXN_ID = 0
  131. def __init__(self, db_conn, hs):
  132. self.hs = hs
  133. self._clock = hs.get_clock()
  134. self._db_pool = hs.get_db_pool()
  135. self._previous_txn_total_time = 0
  136. self._current_txn_total_time = 0
  137. self._previous_loop_ts = 0
  138. # TODO(paul): These can eventually be removed once the metrics code
  139. # is running in mainline, and we have some nice monitoring frontends
  140. # to watch it
  141. self._txn_perf_counters = PerformanceCounters()
  142. self._get_event_counters = PerformanceCounters()
  143. self._get_event_cache = Cache("*getEvent*", keylen=3,
  144. max_entries=hs.config.event_cache_size)
  145. self._event_fetch_lock = threading.Condition()
  146. self._event_fetch_list = []
  147. self._event_fetch_ongoing = 0
  148. self._pending_ds = []
  149. self.database_engine = hs.database_engine
  150. def start_profiling(self):
  151. self._previous_loop_ts = self._clock.time_msec()
  152. def loop():
  153. curr = self._current_txn_total_time
  154. prev = self._previous_txn_total_time
  155. self._previous_txn_total_time = curr
  156. time_now = self._clock.time_msec()
  157. time_then = self._previous_loop_ts
  158. self._previous_loop_ts = time_now
  159. ratio = (curr - prev) / (time_now - time_then)
  160. top_three_counters = self._txn_perf_counters.interval(
  161. time_now - time_then, limit=3
  162. )
  163. top_3_event_counters = self._get_event_counters.interval(
  164. time_now - time_then, limit=3
  165. )
  166. perf_logger.info(
  167. "Total database time: %.3f%% {%s} {%s}",
  168. ratio * 100, top_three_counters, top_3_event_counters
  169. )
  170. self._clock.looping_call(loop, 10000)
  171. def _new_transaction(self, conn, desc, after_callbacks, exception_callbacks,
  172. logging_context, func, *args, **kwargs):
  173. start = time.time()
  174. txn_id = self._TXN_ID
  175. # We don't really need these to be unique, so lets stop it from
  176. # growing really large.
  177. self._TXN_ID = (self._TXN_ID + 1) % (MAX_TXN_ID)
  178. name = "%s-%x" % (desc, txn_id, )
  179. transaction_logger.debug("[TXN START] {%s}", name)
  180. try:
  181. i = 0
  182. N = 5
  183. while True:
  184. try:
  185. txn = conn.cursor()
  186. txn = LoggingTransaction(
  187. txn, name, self.database_engine, after_callbacks,
  188. exception_callbacks,
  189. )
  190. r = func(txn, *args, **kwargs)
  191. conn.commit()
  192. return r
  193. except self.database_engine.module.OperationalError as e:
  194. # This can happen if the database disappears mid
  195. # transaction.
  196. logger.warn(
  197. "[TXN OPERROR] {%s} %s %d/%d",
  198. name, e, i, N
  199. )
  200. if i < N:
  201. i += 1
  202. try:
  203. conn.rollback()
  204. except self.database_engine.module.Error as e1:
  205. logger.warn(
  206. "[TXN EROLL] {%s} %s",
  207. name, e1,
  208. )
  209. continue
  210. raise
  211. except self.database_engine.module.DatabaseError as e:
  212. if self.database_engine.is_deadlock(e):
  213. logger.warn("[TXN DEADLOCK] {%s} %d/%d", name, i, N)
  214. if i < N:
  215. i += 1
  216. try:
  217. conn.rollback()
  218. except self.database_engine.module.Error as e1:
  219. logger.warn(
  220. "[TXN EROLL] {%s} %s",
  221. name, e1,
  222. )
  223. continue
  224. raise
  225. except Exception as e:
  226. logger.debug("[TXN FAIL] {%s} %s", name, e)
  227. raise
  228. finally:
  229. end = time.time()
  230. duration = end - start
  231. if logging_context is not None:
  232. logging_context.add_database_transaction(duration)
  233. transaction_logger.debug("[TXN END] {%s} %f sec", name, duration)
  234. self._current_txn_total_time += duration
  235. self._txn_perf_counters.update(desc, start, end)
  236. sql_txn_timer.labels(desc).observe(duration)
  237. @defer.inlineCallbacks
  238. def runInteraction(self, desc, func, *args, **kwargs):
  239. """Starts a transaction on the database and runs a given function
  240. Arguments:
  241. desc (str): description of the transaction, for logging and metrics
  242. func (func): callback function, which will be called with a
  243. database transaction (twisted.enterprise.adbapi.Transaction) as
  244. its first argument, followed by `args` and `kwargs`.
  245. args (list): positional args to pass to `func`
  246. kwargs (dict): named args to pass to `func`
  247. Returns:
  248. Deferred: The result of func
  249. """
  250. current_context = LoggingContext.current_context()
  251. after_callbacks = []
  252. exception_callbacks = []
  253. def inner_func(conn, *args, **kwargs):
  254. return self._new_transaction(
  255. conn, desc, after_callbacks, exception_callbacks, current_context,
  256. func, *args, **kwargs
  257. )
  258. try:
  259. result = yield self.runWithConnection(inner_func, *args, **kwargs)
  260. for after_callback, after_args, after_kwargs in after_callbacks:
  261. after_callback(*after_args, **after_kwargs)
  262. except: # noqa: E722, as we reraise the exception this is fine.
  263. for after_callback, after_args, after_kwargs in exception_callbacks:
  264. after_callback(*after_args, **after_kwargs)
  265. raise
  266. defer.returnValue(result)
  267. @defer.inlineCallbacks
  268. def runWithConnection(self, func, *args, **kwargs):
  269. """Wraps the .runWithConnection() method on the underlying db_pool.
  270. Arguments:
  271. func (func): callback function, which will be called with a
  272. database connection (twisted.enterprise.adbapi.Connection) as
  273. its first argument, followed by `args` and `kwargs`.
  274. args (list): positional args to pass to `func`
  275. kwargs (dict): named args to pass to `func`
  276. Returns:
  277. Deferred: The result of func
  278. """
  279. current_context = LoggingContext.current_context()
  280. start_time = time.time()
  281. def inner_func(conn, *args, **kwargs):
  282. with LoggingContext("runWithConnection") as context:
  283. sched_duration_sec = time.time() - start_time
  284. sql_scheduling_timer.observe(sched_duration_sec)
  285. current_context.add_database_scheduled(sched_duration_sec)
  286. if self.database_engine.is_connection_closed(conn):
  287. logger.debug("Reconnecting closed database connection")
  288. conn.reconnect()
  289. current_context.copy_to(context)
  290. return func(conn, *args, **kwargs)
  291. with PreserveLoggingContext():
  292. result = yield self._db_pool.runWithConnection(
  293. inner_func, *args, **kwargs
  294. )
  295. defer.returnValue(result)
  296. @staticmethod
  297. def cursor_to_dict(cursor):
  298. """Converts a SQL cursor into an list of dicts.
  299. Args:
  300. cursor : The DBAPI cursor which has executed a query.
  301. Returns:
  302. A list of dicts where the key is the column header.
  303. """
  304. col_headers = list(intern(str(column[0])) for column in cursor.description)
  305. results = list(
  306. dict(zip(col_headers, row)) for row in cursor
  307. )
  308. return results
  309. def _execute(self, desc, decoder, query, *args):
  310. """Runs a single query for a result set.
  311. Args:
  312. decoder - The function which can resolve the cursor results to
  313. something meaningful.
  314. query - The query string to execute
  315. *args - Query args.
  316. Returns:
  317. The result of decoder(results)
  318. """
  319. def interaction(txn):
  320. txn.execute(query, args)
  321. if decoder:
  322. return decoder(txn)
  323. else:
  324. return txn.fetchall()
  325. return self.runInteraction(desc, interaction)
  326. # "Simple" SQL API methods that operate on a single table with no JOINs,
  327. # no complex WHERE clauses, just a dict of values for columns.
  328. @defer.inlineCallbacks
  329. def _simple_insert(self, table, values, or_ignore=False,
  330. desc="_simple_insert"):
  331. """Executes an INSERT query on the named table.
  332. Args:
  333. table : string giving the table name
  334. values : dict of new column names and values for them
  335. Returns:
  336. bool: Whether the row was inserted or not. Only useful when
  337. `or_ignore` is True
  338. """
  339. try:
  340. yield self.runInteraction(
  341. desc,
  342. self._simple_insert_txn, table, values,
  343. )
  344. except self.database_engine.module.IntegrityError:
  345. # We have to do or_ignore flag at this layer, since we can't reuse
  346. # a cursor after we receive an error from the db.
  347. if not or_ignore:
  348. raise
  349. defer.returnValue(False)
  350. defer.returnValue(True)
  351. @staticmethod
  352. def _simple_insert_txn(txn, table, values):
  353. keys, vals = zip(*values.items())
  354. sql = "INSERT INTO %s (%s) VALUES(%s)" % (
  355. table,
  356. ", ".join(k for k in keys),
  357. ", ".join("?" for _ in keys)
  358. )
  359. txn.execute(sql, vals)
  360. def _simple_insert_many(self, table, values, desc):
  361. return self.runInteraction(
  362. desc, self._simple_insert_many_txn, table, values
  363. )
  364. @staticmethod
  365. def _simple_insert_many_txn(txn, table, values):
  366. if not values:
  367. return
  368. # This is a *slight* abomination to get a list of tuples of key names
  369. # and a list of tuples of value names.
  370. #
  371. # i.e. [{"a": 1, "b": 2}, {"c": 3, "d": 4}]
  372. # => [("a", "b",), ("c", "d",)] and [(1, 2,), (3, 4,)]
  373. #
  374. # The sort is to ensure that we don't rely on dictionary iteration
  375. # order.
  376. keys, vals = zip(*[
  377. zip(
  378. *(sorted(i.items(), key=lambda kv: kv[0]))
  379. )
  380. for i in values
  381. if i
  382. ])
  383. for k in keys:
  384. if k != keys[0]:
  385. raise RuntimeError(
  386. "All items must have the same keys"
  387. )
  388. sql = "INSERT INTO %s (%s) VALUES(%s)" % (
  389. table,
  390. ", ".join(k for k in keys[0]),
  391. ", ".join("?" for _ in keys[0])
  392. )
  393. txn.executemany(sql, vals)
  394. @defer.inlineCallbacks
  395. def _simple_upsert(self, table, keyvalues, values,
  396. insertion_values={}, desc="_simple_upsert", lock=True):
  397. """
  398. `lock` should generally be set to True (the default), but can be set
  399. to False if either of the following are true:
  400. * there is a UNIQUE INDEX on the key columns. In this case a conflict
  401. will cause an IntegrityError in which case this function will retry
  402. the update.
  403. * we somehow know that we are the only thread which will be updating
  404. this table.
  405. Args:
  406. table (str): The table to upsert into
  407. keyvalues (dict): The unique key tables and their new values
  408. values (dict): The nonunique columns and their new values
  409. insertion_values (dict): additional key/values to use only when
  410. inserting
  411. lock (bool): True to lock the table when doing the upsert.
  412. Returns:
  413. Deferred(bool): True if a new entry was created, False if an
  414. existing one was updated.
  415. """
  416. attempts = 0
  417. while True:
  418. try:
  419. result = yield self.runInteraction(
  420. desc,
  421. self._simple_upsert_txn, table, keyvalues, values, insertion_values,
  422. lock=lock
  423. )
  424. defer.returnValue(result)
  425. except self.database_engine.module.IntegrityError as e:
  426. attempts += 1
  427. if attempts >= 5:
  428. # don't retry forever, because things other than races
  429. # can cause IntegrityErrors
  430. raise
  431. # presumably we raced with another transaction: let's retry.
  432. logger.warn(
  433. "IntegrityError when upserting into %s; retrying: %s",
  434. table, e
  435. )
  436. def _simple_upsert_txn(self, txn, table, keyvalues, values, insertion_values={},
  437. lock=True):
  438. # We need to lock the table :(, unless we're *really* careful
  439. if lock:
  440. self.database_engine.lock_table(txn, table)
  441. # First try to update.
  442. sql = "UPDATE %s SET %s WHERE %s" % (
  443. table,
  444. ", ".join("%s = ?" % (k,) for k in values),
  445. " AND ".join("%s = ?" % (k,) for k in keyvalues)
  446. )
  447. sqlargs = list(values.values()) + list(keyvalues.values())
  448. txn.execute(sql, sqlargs)
  449. if txn.rowcount > 0:
  450. # successfully updated at least one row.
  451. return False
  452. # We didn't update any rows so insert a new one
  453. allvalues = {}
  454. allvalues.update(keyvalues)
  455. allvalues.update(values)
  456. allvalues.update(insertion_values)
  457. sql = "INSERT INTO %s (%s) VALUES (%s)" % (
  458. table,
  459. ", ".join(k for k in allvalues),
  460. ", ".join("?" for _ in allvalues)
  461. )
  462. txn.execute(sql, list(allvalues.values()))
  463. # successfully inserted
  464. return True
  465. def _simple_select_one(self, table, keyvalues, retcols,
  466. allow_none=False, desc="_simple_select_one"):
  467. """Executes a SELECT query on the named table, which is expected to
  468. return a single row, returning multiple columns from it.
  469. Args:
  470. table : string giving the table name
  471. keyvalues : dict of column names and values to select the row with
  472. retcols : list of strings giving the names of the columns to return
  473. allow_none : If true, return None instead of failing if the SELECT
  474. statement returns no rows
  475. """
  476. return self.runInteraction(
  477. desc,
  478. self._simple_select_one_txn,
  479. table, keyvalues, retcols, allow_none,
  480. )
  481. def _simple_select_one_onecol(self, table, keyvalues, retcol,
  482. allow_none=False,
  483. desc="_simple_select_one_onecol"):
  484. """Executes a SELECT query on the named table, which is expected to
  485. return a single row, returning a single column from it.
  486. Args:
  487. table : string giving the table name
  488. keyvalues : dict of column names and values to select the row with
  489. retcol : string giving the name of the column to return
  490. """
  491. return self.runInteraction(
  492. desc,
  493. self._simple_select_one_onecol_txn,
  494. table, keyvalues, retcol, allow_none=allow_none,
  495. )
  496. @classmethod
  497. def _simple_select_one_onecol_txn(cls, txn, table, keyvalues, retcol,
  498. allow_none=False):
  499. ret = cls._simple_select_onecol_txn(
  500. txn,
  501. table=table,
  502. keyvalues=keyvalues,
  503. retcol=retcol,
  504. )
  505. if ret:
  506. return ret[0]
  507. else:
  508. if allow_none:
  509. return None
  510. else:
  511. raise StoreError(404, "No row found")
  512. @staticmethod
  513. def _simple_select_onecol_txn(txn, table, keyvalues, retcol):
  514. sql = (
  515. "SELECT %(retcol)s FROM %(table)s"
  516. ) % {
  517. "retcol": retcol,
  518. "table": table,
  519. }
  520. if keyvalues:
  521. sql += " WHERE %s" % " AND ".join("%s = ?" % k for k in iterkeys(keyvalues))
  522. txn.execute(sql, list(keyvalues.values()))
  523. else:
  524. txn.execute(sql)
  525. return [r[0] for r in txn]
  526. def _simple_select_onecol(self, table, keyvalues, retcol,
  527. desc="_simple_select_onecol"):
  528. """Executes a SELECT query on the named table, which returns a list
  529. comprising of the values of the named column from the selected rows.
  530. Args:
  531. table (str): table name
  532. keyvalues (dict|None): column names and values to select the rows with
  533. retcol (str): column whos value we wish to retrieve.
  534. Returns:
  535. Deferred: Results in a list
  536. """
  537. return self.runInteraction(
  538. desc,
  539. self._simple_select_onecol_txn,
  540. table, keyvalues, retcol
  541. )
  542. def _simple_select_list(self, table, keyvalues, retcols,
  543. desc="_simple_select_list"):
  544. """Executes a SELECT query on the named table, which may return zero or
  545. more rows, returning the result as a list of dicts.
  546. Args:
  547. table (str): the table name
  548. keyvalues (dict[str, Any] | None):
  549. column names and values to select the rows with, or None to not
  550. apply a WHERE clause.
  551. retcols (iterable[str]): the names of the columns to return
  552. Returns:
  553. defer.Deferred: resolves to list[dict[str, Any]]
  554. """
  555. return self.runInteraction(
  556. desc,
  557. self._simple_select_list_txn,
  558. table, keyvalues, retcols
  559. )
  560. @classmethod
  561. def _simple_select_list_txn(cls, txn, table, keyvalues, retcols):
  562. """Executes a SELECT query on the named table, which may return zero or
  563. more rows, returning the result as a list of dicts.
  564. Args:
  565. txn : Transaction object
  566. table (str): the table name
  567. keyvalues (dict[str, T] | None):
  568. column names and values to select the rows with, or None to not
  569. apply a WHERE clause.
  570. retcols (iterable[str]): the names of the columns to return
  571. """
  572. if keyvalues:
  573. sql = "SELECT %s FROM %s WHERE %s" % (
  574. ", ".join(retcols),
  575. table,
  576. " AND ".join("%s = ?" % (k, ) for k in keyvalues)
  577. )
  578. txn.execute(sql, list(keyvalues.values()))
  579. else:
  580. sql = "SELECT %s FROM %s" % (
  581. ", ".join(retcols),
  582. table
  583. )
  584. txn.execute(sql)
  585. return cls.cursor_to_dict(txn)
  586. @defer.inlineCallbacks
  587. def _simple_select_many_batch(self, table, column, iterable, retcols,
  588. keyvalues={}, desc="_simple_select_many_batch",
  589. batch_size=100):
  590. """Executes a SELECT query on the named table, which may return zero or
  591. more rows, returning the result as a list of dicts.
  592. Filters rows by if value of `column` is in `iterable`.
  593. Args:
  594. table : string giving the table name
  595. column : column name to test for inclusion against `iterable`
  596. iterable : list
  597. keyvalues : dict of column names and values to select the rows with
  598. retcols : list of strings giving the names of the columns to return
  599. """
  600. results = []
  601. if not iterable:
  602. defer.returnValue(results)
  603. # iterables can not be sliced, so convert it to a list first
  604. it_list = list(iterable)
  605. chunks = [
  606. it_list[i:i + batch_size]
  607. for i in range(0, len(it_list), batch_size)
  608. ]
  609. for chunk in chunks:
  610. rows = yield self.runInteraction(
  611. desc,
  612. self._simple_select_many_txn,
  613. table, column, chunk, keyvalues, retcols
  614. )
  615. results.extend(rows)
  616. defer.returnValue(results)
  617. @classmethod
  618. def _simple_select_many_txn(cls, txn, table, column, iterable, keyvalues, retcols):
  619. """Executes a SELECT query on the named table, which may return zero or
  620. more rows, returning the result as a list of dicts.
  621. Filters rows by if value of `column` is in `iterable`.
  622. Args:
  623. txn : Transaction object
  624. table : string giving the table name
  625. column : column name to test for inclusion against `iterable`
  626. iterable : list
  627. keyvalues : dict of column names and values to select the rows with
  628. retcols : list of strings giving the names of the columns to return
  629. """
  630. if not iterable:
  631. return []
  632. sql = "SELECT %s FROM %s" % (", ".join(retcols), table)
  633. clauses = []
  634. values = []
  635. clauses.append(
  636. "%s IN (%s)" % (column, ",".join("?" for _ in iterable))
  637. )
  638. values.extend(iterable)
  639. for key, value in iteritems(keyvalues):
  640. clauses.append("%s = ?" % (key,))
  641. values.append(value)
  642. if clauses:
  643. sql = "%s WHERE %s" % (
  644. sql,
  645. " AND ".join(clauses),
  646. )
  647. txn.execute(sql, values)
  648. return cls.cursor_to_dict(txn)
  649. def _simple_update(self, table, keyvalues, updatevalues, desc):
  650. return self.runInteraction(
  651. desc,
  652. self._simple_update_txn,
  653. table, keyvalues, updatevalues,
  654. )
  655. @staticmethod
  656. def _simple_update_txn(txn, table, keyvalues, updatevalues):
  657. if keyvalues:
  658. where = "WHERE %s" % " AND ".join("%s = ?" % k for k in iterkeys(keyvalues))
  659. else:
  660. where = ""
  661. update_sql = "UPDATE %s SET %s %s" % (
  662. table,
  663. ", ".join("%s = ?" % (k,) for k in updatevalues),
  664. where,
  665. )
  666. txn.execute(
  667. update_sql,
  668. list(updatevalues.values()) + list(keyvalues.values())
  669. )
  670. return txn.rowcount
  671. def _simple_update_one(self, table, keyvalues, updatevalues,
  672. desc="_simple_update_one"):
  673. """Executes an UPDATE query on the named table, setting new values for
  674. columns in a row matching the key values.
  675. Args:
  676. table : string giving the table name
  677. keyvalues : dict of column names and values to select the row with
  678. updatevalues : dict giving column names and values to update
  679. retcols : optional list of column names to return
  680. If present, retcols gives a list of column names on which to perform
  681. a SELECT statement *before* performing the UPDATE statement. The values
  682. of these will be returned in a dict.
  683. These are performed within the same transaction, allowing an atomic
  684. get-and-set. This can be used to implement compare-and-set by putting
  685. the update column in the 'keyvalues' dict as well.
  686. """
  687. return self.runInteraction(
  688. desc,
  689. self._simple_update_one_txn,
  690. table, keyvalues, updatevalues,
  691. )
  692. @classmethod
  693. def _simple_update_one_txn(cls, txn, table, keyvalues, updatevalues):
  694. rowcount = cls._simple_update_txn(txn, table, keyvalues, updatevalues)
  695. if rowcount == 0:
  696. raise StoreError(404, "No row found")
  697. if rowcount > 1:
  698. raise StoreError(500, "More than one row matched")
  699. @staticmethod
  700. def _simple_select_one_txn(txn, table, keyvalues, retcols,
  701. allow_none=False):
  702. select_sql = "SELECT %s FROM %s WHERE %s" % (
  703. ", ".join(retcols),
  704. table,
  705. " AND ".join("%s = ?" % (k,) for k in keyvalues)
  706. )
  707. txn.execute(select_sql, list(keyvalues.values()))
  708. row = txn.fetchone()
  709. if not row:
  710. if allow_none:
  711. return None
  712. raise StoreError(404, "No row found")
  713. if txn.rowcount > 1:
  714. raise StoreError(500, "More than one row matched")
  715. return dict(zip(retcols, row))
  716. def _simple_delete_one(self, table, keyvalues, desc="_simple_delete_one"):
  717. """Executes a DELETE query on the named table, expecting to delete a
  718. single row.
  719. Args:
  720. table : string giving the table name
  721. keyvalues : dict of column names and values to select the row with
  722. """
  723. return self.runInteraction(
  724. desc, self._simple_delete_one_txn, table, keyvalues
  725. )
  726. @staticmethod
  727. def _simple_delete_one_txn(txn, table, keyvalues):
  728. """Executes a DELETE query on the named table, expecting to delete a
  729. single row.
  730. Args:
  731. table : string giving the table name
  732. keyvalues : dict of column names and values to select the row with
  733. """
  734. sql = "DELETE FROM %s WHERE %s" % (
  735. table,
  736. " AND ".join("%s = ?" % (k, ) for k in keyvalues)
  737. )
  738. txn.execute(sql, list(keyvalues.values()))
  739. if txn.rowcount == 0:
  740. raise StoreError(404, "No row found")
  741. if txn.rowcount > 1:
  742. raise StoreError(500, "more than one row matched")
  743. def _simple_delete(self, table, keyvalues, desc):
  744. return self.runInteraction(
  745. desc, self._simple_delete_txn, table, keyvalues
  746. )
  747. @staticmethod
  748. def _simple_delete_txn(txn, table, keyvalues):
  749. sql = "DELETE FROM %s WHERE %s" % (
  750. table,
  751. " AND ".join("%s = ?" % (k, ) for k in keyvalues)
  752. )
  753. return txn.execute(sql, list(keyvalues.values()))
  754. def _simple_delete_many(self, table, column, iterable, keyvalues, desc):
  755. return self.runInteraction(
  756. desc, self._simple_delete_many_txn, table, column, iterable, keyvalues
  757. )
  758. @staticmethod
  759. def _simple_delete_many_txn(txn, table, column, iterable, keyvalues):
  760. """Executes a DELETE query on the named table.
  761. Filters rows by if value of `column` is in `iterable`.
  762. Args:
  763. txn : Transaction object
  764. table : string giving the table name
  765. column : column name to test for inclusion against `iterable`
  766. iterable : list
  767. keyvalues : dict of column names and values to select the rows with
  768. """
  769. if not iterable:
  770. return
  771. sql = "DELETE FROM %s" % table
  772. clauses = []
  773. values = []
  774. clauses.append(
  775. "%s IN (%s)" % (column, ",".join("?" for _ in iterable))
  776. )
  777. values.extend(iterable)
  778. for key, value in iteritems(keyvalues):
  779. clauses.append("%s = ?" % (key,))
  780. values.append(value)
  781. if clauses:
  782. sql = "%s WHERE %s" % (
  783. sql,
  784. " AND ".join(clauses),
  785. )
  786. return txn.execute(sql, values)
  787. def _get_cache_dict(self, db_conn, table, entity_column, stream_column,
  788. max_value, limit=100000):
  789. # Fetch a mapping of room_id -> max stream position for "recent" rooms.
  790. # It doesn't really matter how many we get, the StreamChangeCache will
  791. # do the right thing to ensure it respects the max size of cache.
  792. sql = (
  793. "SELECT %(entity)s, MAX(%(stream)s) FROM %(table)s"
  794. " WHERE %(stream)s > ? - %(limit)s"
  795. " GROUP BY %(entity)s"
  796. ) % {
  797. "table": table,
  798. "entity": entity_column,
  799. "stream": stream_column,
  800. "limit": limit,
  801. }
  802. sql = self.database_engine.convert_param_style(sql)
  803. txn = db_conn.cursor()
  804. txn.execute(sql, (int(max_value),))
  805. cache = {
  806. row[0]: int(row[1])
  807. for row in txn
  808. }
  809. txn.close()
  810. if cache:
  811. min_val = min(itervalues(cache))
  812. else:
  813. min_val = max_value
  814. return cache, min_val
  815. def _invalidate_cache_and_stream(self, txn, cache_func, keys):
  816. """Invalidates the cache and adds it to the cache stream so slaves
  817. will know to invalidate their caches.
  818. This should only be used to invalidate caches where slaves won't
  819. otherwise know from other replication streams that the cache should
  820. be invalidated.
  821. """
  822. txn.call_after(cache_func.invalidate, keys)
  823. if isinstance(self.database_engine, PostgresEngine):
  824. # get_next() returns a context manager which is designed to wrap
  825. # the transaction. However, we want to only get an ID when we want
  826. # to use it, here, so we need to call __enter__ manually, and have
  827. # __exit__ called after the transaction finishes.
  828. ctx = self._cache_id_gen.get_next()
  829. stream_id = ctx.__enter__()
  830. txn.call_on_exception(ctx.__exit__, None, None, None)
  831. txn.call_after(ctx.__exit__, None, None, None)
  832. txn.call_after(self.hs.get_notifier().on_new_replication_data)
  833. self._simple_insert_txn(
  834. txn,
  835. table="cache_invalidation_stream",
  836. values={
  837. "stream_id": stream_id,
  838. "cache_func": cache_func.__name__,
  839. "keys": list(keys),
  840. "invalidation_ts": self.clock.time_msec(),
  841. }
  842. )
  843. def get_all_updated_caches(self, last_id, current_id, limit):
  844. if last_id == current_id:
  845. return defer.succeed([])
  846. def get_all_updated_caches_txn(txn):
  847. # We purposefully don't bound by the current token, as we want to
  848. # send across cache invalidations as quickly as possible. Cache
  849. # invalidations are idempotent, so duplicates are fine.
  850. sql = (
  851. "SELECT stream_id, cache_func, keys, invalidation_ts"
  852. " FROM cache_invalidation_stream"
  853. " WHERE stream_id > ? ORDER BY stream_id ASC LIMIT ?"
  854. )
  855. txn.execute(sql, (last_id, limit,))
  856. return txn.fetchall()
  857. return self.runInteraction(
  858. "get_all_updated_caches", get_all_updated_caches_txn
  859. )
  860. def get_cache_stream_token(self):
  861. if self._cache_id_gen:
  862. return self._cache_id_gen.get_current_token()
  863. else:
  864. return 0
  865. def _simple_select_list_paginate(self, table, keyvalues, pagevalues, retcols,
  866. desc="_simple_select_list_paginate"):
  867. """Executes a SELECT query on the named table with start and limit,
  868. of row numbers, which may return zero or number of rows from start to limit,
  869. returning the result as a list of dicts.
  870. Args:
  871. table (str): the table name
  872. keyvalues (dict[str, Any] | None):
  873. column names and values to select the rows with, or None to not
  874. apply a WHERE clause.
  875. retcols (iterable[str]): the names of the columns to return
  876. order (str): order the select by this column
  877. start (int): start number to begin the query from
  878. limit (int): number of rows to reterive
  879. Returns:
  880. defer.Deferred: resolves to list[dict[str, Any]]
  881. """
  882. return self.runInteraction(
  883. desc,
  884. self._simple_select_list_paginate_txn,
  885. table, keyvalues, pagevalues, retcols
  886. )
  887. @classmethod
  888. def _simple_select_list_paginate_txn(cls, txn, table, keyvalues, pagevalues, retcols):
  889. """Executes a SELECT query on the named table with start and limit,
  890. of row numbers, which may return zero or number of rows from start to limit,
  891. returning the result as a list of dicts.
  892. Args:
  893. txn : Transaction object
  894. table (str): the table name
  895. keyvalues (dict[str, T] | None):
  896. column names and values to select the rows with, or None to not
  897. apply a WHERE clause.
  898. pagevalues ([]):
  899. order (str): order the select by this column
  900. start (int): start number to begin the query from
  901. limit (int): number of rows to reterive
  902. retcols (iterable[str]): the names of the columns to return
  903. Returns:
  904. defer.Deferred: resolves to list[dict[str, Any]]
  905. """
  906. if keyvalues:
  907. sql = "SELECT %s FROM %s WHERE %s ORDER BY %s" % (
  908. ", ".join(retcols),
  909. table,
  910. " AND ".join("%s = ?" % (k,) for k in keyvalues),
  911. " ? ASC LIMIT ? OFFSET ?"
  912. )
  913. txn.execute(sql, list(keyvalues.values()) + list(pagevalues))
  914. else:
  915. sql = "SELECT %s FROM %s ORDER BY %s" % (
  916. ", ".join(retcols),
  917. table,
  918. " ? ASC LIMIT ? OFFSET ?"
  919. )
  920. txn.execute(sql, pagevalues)
  921. return cls.cursor_to_dict(txn)
  922. @defer.inlineCallbacks
  923. def get_user_list_paginate(self, table, keyvalues, pagevalues, retcols,
  924. desc="get_user_list_paginate"):
  925. """Get a list of users from start row to a limit number of rows. This will
  926. return a json object with users and total number of users in users list.
  927. Args:
  928. table (str): the table name
  929. keyvalues (dict[str, Any] | None):
  930. column names and values to select the rows with, or None to not
  931. apply a WHERE clause.
  932. pagevalues ([]):
  933. order (str): order the select by this column
  934. start (int): start number to begin the query from
  935. limit (int): number of rows to reterive
  936. retcols (iterable[str]): the names of the columns to return
  937. Returns:
  938. defer.Deferred: resolves to json object {list[dict[str, Any]], count}
  939. """
  940. users = yield self.runInteraction(
  941. desc,
  942. self._simple_select_list_paginate_txn,
  943. table, keyvalues, pagevalues, retcols
  944. )
  945. count = yield self.runInteraction(
  946. desc,
  947. self.get_user_count_txn
  948. )
  949. retval = {
  950. "users": users,
  951. "total": count
  952. }
  953. defer.returnValue(retval)
  954. def get_user_count_txn(self, txn):
  955. """Get a total number of registerd users in the users list.
  956. Args:
  957. txn : Transaction object
  958. Returns:
  959. defer.Deferred: resolves to int
  960. """
  961. sql_count = "SELECT COUNT(*) FROM users WHERE is_guest = 0;"
  962. txn.execute(sql_count)
  963. count = txn.fetchone()[0]
  964. defer.returnValue(count)
  965. def _simple_search_list(self, table, term, col, retcols,
  966. desc="_simple_search_list"):
  967. """Executes a SELECT query on the named table, which may return zero or
  968. more rows, returning the result as a list of dicts.
  969. Args:
  970. table (str): the table name
  971. term (str | None):
  972. term for searching the table matched to a column.
  973. col (str): column to query term should be matched to
  974. retcols (iterable[str]): the names of the columns to return
  975. Returns:
  976. defer.Deferred: resolves to list[dict[str, Any]] or None
  977. """
  978. return self.runInteraction(
  979. desc,
  980. self._simple_search_list_txn,
  981. table, term, col, retcols
  982. )
  983. @classmethod
  984. def _simple_search_list_txn(cls, txn, table, term, col, retcols):
  985. """Executes a SELECT query on the named table, which may return zero or
  986. more rows, returning the result as a list of dicts.
  987. Args:
  988. txn : Transaction object
  989. table (str): the table name
  990. term (str | None):
  991. term for searching the table matched to a column.
  992. col (str): column to query term should be matched to
  993. retcols (iterable[str]): the names of the columns to return
  994. Returns:
  995. defer.Deferred: resolves to list[dict[str, Any]] or None
  996. """
  997. if term:
  998. sql = "SELECT %s FROM %s WHERE %s LIKE ?" % (
  999. ", ".join(retcols),
  1000. table,
  1001. col
  1002. )
  1003. termvalues = ["%%" + term + "%%"]
  1004. txn.execute(sql, termvalues)
  1005. else:
  1006. return 0
  1007. return cls.cursor_to_dict(txn)
  1008. class _RollbackButIsFineException(Exception):
  1009. """ This exception is used to rollback a transaction without implying
  1010. something went wrong.
  1011. """
  1012. pass