_base.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  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.dictionary_cache import DictionaryCache
  19. from synapse.util.caches.descriptors import Cache
  20. from synapse.util.caches import intern_dict
  21. from synapse.storage.engines import PostgresEngine
  22. import synapse.metrics
  23. from twisted.internet import defer
  24. import sys
  25. import time
  26. import threading
  27. import os
  28. CACHE_SIZE_FACTOR = float(os.environ.get("SYNAPSE_CACHE_FACTOR", 0.1))
  29. logger = logging.getLogger(__name__)
  30. sql_logger = logging.getLogger("synapse.storage.SQL")
  31. transaction_logger = logging.getLogger("synapse.storage.txn")
  32. perf_logger = logging.getLogger("synapse.storage.TIME")
  33. metrics = synapse.metrics.get_metrics_for("synapse.storage")
  34. sql_scheduling_timer = metrics.register_distribution("schedule_time")
  35. sql_query_timer = metrics.register_distribution("query_time", labels=["verb"])
  36. sql_txn_timer = metrics.register_distribution("transaction_time", labels=["desc"])
  37. class LoggingTransaction(object):
  38. """An object that almost-transparently proxies for the 'txn' object
  39. passed to the constructor. Adds logging and metrics to the .execute()
  40. method."""
  41. __slots__ = ["txn", "name", "database_engine", "after_callbacks"]
  42. def __init__(self, txn, name, database_engine, after_callbacks):
  43. object.__setattr__(self, "txn", txn)
  44. object.__setattr__(self, "name", name)
  45. object.__setattr__(self, "database_engine", database_engine)
  46. object.__setattr__(self, "after_callbacks", after_callbacks)
  47. def call_after(self, callback, *args):
  48. """Call the given callback on the main twisted thread after the
  49. transaction has finished. Used to invalidate the caches on the
  50. correct thread.
  51. """
  52. self.after_callbacks.append((callback, args))
  53. def __getattr__(self, name):
  54. return getattr(self.txn, name)
  55. def __setattr__(self, name, value):
  56. setattr(self.txn, name, value)
  57. def execute(self, sql, *args):
  58. self._do_execute(self.txn.execute, sql, *args)
  59. def executemany(self, sql, *args):
  60. self._do_execute(self.txn.executemany, sql, *args)
  61. def _do_execute(self, func, sql, *args):
  62. # TODO(paul): Maybe use 'info' and 'debug' for values?
  63. sql_logger.debug("[SQL] {%s} %s", self.name, sql)
  64. sql = self.database_engine.convert_param_style(sql)
  65. if args:
  66. try:
  67. sql_logger.debug(
  68. "[SQL values] {%s} %r",
  69. self.name, args[0]
  70. )
  71. except:
  72. # Don't let logging failures stop SQL from working
  73. pass
  74. start = time.time() * 1000
  75. try:
  76. return func(
  77. sql, *args
  78. )
  79. except Exception as e:
  80. logger.debug("[SQL FAIL] {%s} %s", self.name, e)
  81. raise
  82. finally:
  83. msecs = (time.time() * 1000) - start
  84. sql_logger.debug("[SQL time] {%s} %f", self.name, msecs)
  85. sql_query_timer.inc_by(msecs, sql.split()[0])
  86. class PerformanceCounters(object):
  87. def __init__(self):
  88. self.current_counters = {}
  89. self.previous_counters = {}
  90. def update(self, key, start_time, end_time=None):
  91. if end_time is None:
  92. end_time = time.time() * 1000
  93. duration = end_time - start_time
  94. count, cum_time = self.current_counters.get(key, (0, 0))
  95. count += 1
  96. cum_time += duration
  97. self.current_counters[key] = (count, cum_time)
  98. return end_time
  99. def interval(self, interval_duration, limit=3):
  100. counters = []
  101. for name, (count, cum_time) in self.current_counters.items():
  102. prev_count, prev_time = self.previous_counters.get(name, (0, 0))
  103. counters.append((
  104. (cum_time - prev_time) / interval_duration,
  105. count - prev_count,
  106. name
  107. ))
  108. self.previous_counters = dict(self.current_counters)
  109. counters.sort(reverse=True)
  110. top_n_counters = ", ".join(
  111. "%s(%d): %.3f%%" % (name, count, 100 * ratio)
  112. for ratio, count, name in counters[:limit]
  113. )
  114. return top_n_counters
  115. class SQLBaseStore(object):
  116. _TXN_ID = 0
  117. def __init__(self, hs):
  118. self.hs = hs
  119. self._clock = hs.get_clock()
  120. self._db_pool = hs.get_db_pool()
  121. self._previous_txn_total_time = 0
  122. self._current_txn_total_time = 0
  123. self._previous_loop_ts = 0
  124. # TODO(paul): These can eventually be removed once the metrics code
  125. # is running in mainline, and we have some nice monitoring frontends
  126. # to watch it
  127. self._txn_perf_counters = PerformanceCounters()
  128. self._get_event_counters = PerformanceCounters()
  129. self._get_event_cache = Cache("*getEvent*", keylen=3,
  130. max_entries=hs.config.event_cache_size)
  131. self._state_group_cache = DictionaryCache(
  132. "*stateGroupCache*", 100000 * CACHE_SIZE_FACTOR
  133. )
  134. self._event_fetch_lock = threading.Condition()
  135. self._event_fetch_list = []
  136. self._event_fetch_ongoing = 0
  137. self._pending_ds = []
  138. self.database_engine = hs.database_engine
  139. def start_profiling(self):
  140. self._previous_loop_ts = self._clock.time_msec()
  141. def loop():
  142. curr = self._current_txn_total_time
  143. prev = self._previous_txn_total_time
  144. self._previous_txn_total_time = curr
  145. time_now = self._clock.time_msec()
  146. time_then = self._previous_loop_ts
  147. self._previous_loop_ts = time_now
  148. ratio = (curr - prev) / (time_now - time_then)
  149. top_three_counters = self._txn_perf_counters.interval(
  150. time_now - time_then, limit=3
  151. )
  152. top_3_event_counters = self._get_event_counters.interval(
  153. time_now - time_then, limit=3
  154. )
  155. perf_logger.info(
  156. "Total database time: %.3f%% {%s} {%s}",
  157. ratio * 100, top_three_counters, top_3_event_counters
  158. )
  159. self._clock.looping_call(loop, 10000)
  160. def _new_transaction(self, conn, desc, after_callbacks, logging_context,
  161. func, *args, **kwargs):
  162. start = time.time() * 1000
  163. txn_id = self._TXN_ID
  164. # We don't really need these to be unique, so lets stop it from
  165. # growing really large.
  166. self._TXN_ID = (self._TXN_ID + 1) % (sys.maxint - 1)
  167. name = "%s-%x" % (desc, txn_id, )
  168. transaction_logger.debug("[TXN START] {%s}", name)
  169. try:
  170. i = 0
  171. N = 5
  172. while True:
  173. try:
  174. txn = conn.cursor()
  175. txn = LoggingTransaction(
  176. txn, name, self.database_engine, after_callbacks
  177. )
  178. r = func(txn, *args, **kwargs)
  179. conn.commit()
  180. return r
  181. except self.database_engine.module.OperationalError as e:
  182. # This can happen if the database disappears mid
  183. # transaction.
  184. logger.warn(
  185. "[TXN OPERROR] {%s} %s %d/%d",
  186. name, e, i, N
  187. )
  188. if i < N:
  189. i += 1
  190. try:
  191. conn.rollback()
  192. except self.database_engine.module.Error as e1:
  193. logger.warn(
  194. "[TXN EROLL] {%s} %s",
  195. name, e1,
  196. )
  197. continue
  198. raise
  199. except self.database_engine.module.DatabaseError as e:
  200. if self.database_engine.is_deadlock(e):
  201. logger.warn("[TXN DEADLOCK] {%s} %d/%d", name, i, N)
  202. if i < N:
  203. i += 1
  204. try:
  205. conn.rollback()
  206. except self.database_engine.module.Error as e1:
  207. logger.warn(
  208. "[TXN EROLL] {%s} %s",
  209. name, e1,
  210. )
  211. continue
  212. raise
  213. except Exception as e:
  214. logger.debug("[TXN FAIL] {%s} %s", name, e)
  215. raise
  216. finally:
  217. end = time.time() * 1000
  218. duration = end - start
  219. if logging_context is not None:
  220. logging_context.add_database_transaction(duration)
  221. transaction_logger.debug("[TXN END] {%s} %f", name, duration)
  222. self._current_txn_total_time += duration
  223. self._txn_perf_counters.update(desc, start, end)
  224. sql_txn_timer.inc_by(duration, desc)
  225. @defer.inlineCallbacks
  226. def runInteraction(self, desc, func, *args, **kwargs):
  227. """Wraps the .runInteraction() method on the underlying db_pool."""
  228. current_context = LoggingContext.current_context()
  229. start_time = time.time() * 1000
  230. after_callbacks = []
  231. def inner_func(conn, *args, **kwargs):
  232. with LoggingContext("runInteraction") as context:
  233. sql_scheduling_timer.inc_by(time.time() * 1000 - start_time)
  234. if self.database_engine.is_connection_closed(conn):
  235. logger.debug("Reconnecting closed database connection")
  236. conn.reconnect()
  237. current_context.copy_to(context)
  238. return self._new_transaction(
  239. conn, desc, after_callbacks, current_context,
  240. func, *args, **kwargs
  241. )
  242. try:
  243. with PreserveLoggingContext():
  244. result = yield self._db_pool.runWithConnection(
  245. inner_func, *args, **kwargs
  246. )
  247. finally:
  248. for after_callback, after_args in after_callbacks:
  249. after_callback(*after_args)
  250. defer.returnValue(result)
  251. @defer.inlineCallbacks
  252. def runWithConnection(self, func, *args, **kwargs):
  253. """Wraps the .runInteraction() method on the underlying db_pool."""
  254. current_context = LoggingContext.current_context()
  255. start_time = time.time() * 1000
  256. def inner_func(conn, *args, **kwargs):
  257. with LoggingContext("runWithConnection") as context:
  258. sql_scheduling_timer.inc_by(time.time() * 1000 - start_time)
  259. if self.database_engine.is_connection_closed(conn):
  260. logger.debug("Reconnecting closed database connection")
  261. conn.reconnect()
  262. current_context.copy_to(context)
  263. return func(conn, *args, **kwargs)
  264. with PreserveLoggingContext():
  265. result = yield self._db_pool.runWithConnection(
  266. inner_func, *args, **kwargs
  267. )
  268. defer.returnValue(result)
  269. @staticmethod
  270. def cursor_to_dict(cursor):
  271. """Converts a SQL cursor into an list of dicts.
  272. Args:
  273. cursor : The DBAPI cursor which has executed a query.
  274. Returns:
  275. A list of dicts where the key is the column header.
  276. """
  277. col_headers = list(column[0] for column in cursor.description)
  278. results = list(
  279. intern_dict(dict(zip(col_headers, row))) for row in cursor.fetchall()
  280. )
  281. return results
  282. def _execute(self, desc, decoder, query, *args):
  283. """Runs a single query for a result set.
  284. Args:
  285. decoder - The function which can resolve the cursor results to
  286. something meaningful.
  287. query - The query string to execute
  288. *args - Query args.
  289. Returns:
  290. The result of decoder(results)
  291. """
  292. def interaction(txn):
  293. txn.execute(query, args)
  294. if decoder:
  295. return decoder(txn)
  296. else:
  297. return txn.fetchall()
  298. return self.runInteraction(desc, interaction)
  299. # "Simple" SQL API methods that operate on a single table with no JOINs,
  300. # no complex WHERE clauses, just a dict of values for columns.
  301. @defer.inlineCallbacks
  302. def _simple_insert(self, table, values, or_ignore=False,
  303. desc="_simple_insert"):
  304. """Executes an INSERT query on the named table.
  305. Args:
  306. table : string giving the table name
  307. values : dict of new column names and values for them
  308. Returns:
  309. bool: Whether the row was inserted or not. Only useful when
  310. `or_ignore` is True
  311. """
  312. try:
  313. yield self.runInteraction(
  314. desc,
  315. self._simple_insert_txn, table, values,
  316. )
  317. except self.database_engine.module.IntegrityError:
  318. # We have to do or_ignore flag at this layer, since we can't reuse
  319. # a cursor after we receive an error from the db.
  320. if not or_ignore:
  321. raise
  322. defer.returnValue(False)
  323. defer.returnValue(True)
  324. @staticmethod
  325. def _simple_insert_txn(txn, table, values):
  326. keys, vals = zip(*values.items())
  327. sql = "INSERT INTO %s (%s) VALUES(%s)" % (
  328. table,
  329. ", ".join(k for k in keys),
  330. ", ".join("?" for _ in keys)
  331. )
  332. txn.execute(sql, vals)
  333. @staticmethod
  334. def _simple_insert_many_txn(txn, table, values):
  335. if not values:
  336. return
  337. # This is a *slight* abomination to get a list of tuples of key names
  338. # and a list of tuples of value names.
  339. #
  340. # i.e. [{"a": 1, "b": 2}, {"c": 3, "d": 4}]
  341. # => [("a", "b",), ("c", "d",)] and [(1, 2,), (3, 4,)]
  342. #
  343. # The sort is to ensure that we don't rely on dictionary iteration
  344. # order.
  345. keys, vals = zip(*[
  346. zip(
  347. *(sorted(i.items(), key=lambda kv: kv[0]))
  348. )
  349. for i in values
  350. if i
  351. ])
  352. for k in keys:
  353. if k != keys[0]:
  354. raise RuntimeError(
  355. "All items must have the same keys"
  356. )
  357. sql = "INSERT INTO %s (%s) VALUES(%s)" % (
  358. table,
  359. ", ".join(k for k in keys[0]),
  360. ", ".join("?" for _ in keys[0])
  361. )
  362. txn.executemany(sql, vals)
  363. def _simple_upsert(self, table, keyvalues, values,
  364. insertion_values={}, desc="_simple_upsert", lock=True):
  365. """
  366. Args:
  367. table (str): The table to upsert into
  368. keyvalues (dict): The unique key tables and their new values
  369. values (dict): The nonunique columns and their new values
  370. insertion_values (dict): key/values to use when inserting
  371. Returns:
  372. Deferred(bool): True if a new entry was created, False if an
  373. existing one was updated.
  374. """
  375. return self.runInteraction(
  376. desc,
  377. self._simple_upsert_txn, table, keyvalues, values, insertion_values,
  378. lock
  379. )
  380. def _simple_upsert_txn(self, txn, table, keyvalues, values, insertion_values={},
  381. lock=True):
  382. # We need to lock the table :(, unless we're *really* careful
  383. if lock:
  384. self.database_engine.lock_table(txn, table)
  385. # Try to update
  386. sql = "UPDATE %s SET %s WHERE %s" % (
  387. table,
  388. ", ".join("%s = ?" % (k,) for k in values),
  389. " AND ".join("%s = ?" % (k,) for k in keyvalues)
  390. )
  391. sqlargs = values.values() + keyvalues.values()
  392. logger.debug(
  393. "[SQL] %s Args=%s",
  394. sql, sqlargs,
  395. )
  396. txn.execute(sql, sqlargs)
  397. if txn.rowcount == 0:
  398. # We didn't update and rows so insert a new one
  399. allvalues = {}
  400. allvalues.update(keyvalues)
  401. allvalues.update(values)
  402. allvalues.update(insertion_values)
  403. sql = "INSERT INTO %s (%s) VALUES (%s)" % (
  404. table,
  405. ", ".join(k for k in allvalues),
  406. ", ".join("?" for _ in allvalues)
  407. )
  408. logger.debug(
  409. "[SQL] %s Args=%s",
  410. sql, keyvalues.values(),
  411. )
  412. txn.execute(sql, allvalues.values())
  413. return True
  414. else:
  415. return False
  416. def _simple_select_one(self, table, keyvalues, retcols,
  417. allow_none=False, desc="_simple_select_one"):
  418. """Executes a SELECT query on the named table, which is expected to
  419. return a single row, returning a single column from it.
  420. Args:
  421. table : string giving the table name
  422. keyvalues : dict of column names and values to select the row with
  423. retcols : list of strings giving the names of the columns to return
  424. allow_none : If true, return None instead of failing if the SELECT
  425. statement returns no rows
  426. """
  427. return self.runInteraction(
  428. desc,
  429. self._simple_select_one_txn,
  430. table, keyvalues, retcols, allow_none,
  431. )
  432. def _simple_select_one_onecol(self, table, keyvalues, retcol,
  433. allow_none=False,
  434. desc="_simple_select_one_onecol"):
  435. """Executes a SELECT query on the named table, which is expected to
  436. return a single row, returning a single column from it.
  437. Args:
  438. table : string giving the table name
  439. keyvalues : dict of column names and values to select the row with
  440. retcol : string giving the name of the column to return
  441. """
  442. return self.runInteraction(
  443. desc,
  444. self._simple_select_one_onecol_txn,
  445. table, keyvalues, retcol, allow_none=allow_none,
  446. )
  447. @classmethod
  448. def _simple_select_one_onecol_txn(cls, txn, table, keyvalues, retcol,
  449. allow_none=False):
  450. ret = cls._simple_select_onecol_txn(
  451. txn,
  452. table=table,
  453. keyvalues=keyvalues,
  454. retcol=retcol,
  455. )
  456. if ret:
  457. return ret[0]
  458. else:
  459. if allow_none:
  460. return None
  461. else:
  462. raise StoreError(404, "No row found")
  463. @staticmethod
  464. def _simple_select_onecol_txn(txn, table, keyvalues, retcol):
  465. if keyvalues:
  466. where = "WHERE %s" % " AND ".join("%s = ?" % k for k in keyvalues.keys())
  467. else:
  468. where = ""
  469. sql = (
  470. "SELECT %(retcol)s FROM %(table)s %(where)s"
  471. ) % {
  472. "retcol": retcol,
  473. "table": table,
  474. "where": where,
  475. }
  476. txn.execute(sql, keyvalues.values())
  477. return [r[0] for r in txn.fetchall()]
  478. def _simple_select_onecol(self, table, keyvalues, retcol,
  479. desc="_simple_select_onecol"):
  480. """Executes a SELECT query on the named table, which returns a list
  481. comprising of the values of the named column from the selected rows.
  482. Args:
  483. table (str): table name
  484. keyvalues (dict): column names and values to select the rows with
  485. retcol (str): column whos value we wish to retrieve.
  486. Returns:
  487. Deferred: Results in a list
  488. """
  489. return self.runInteraction(
  490. desc,
  491. self._simple_select_onecol_txn,
  492. table, keyvalues, retcol
  493. )
  494. def _simple_select_list(self, table, keyvalues, retcols,
  495. desc="_simple_select_list"):
  496. """Executes a SELECT query on the named table, which may return zero or
  497. more rows, returning the result as a list of dicts.
  498. Args:
  499. table (str): the table name
  500. keyvalues (dict[str, Any] | None):
  501. column names and values to select the rows with, or None to not
  502. apply a WHERE clause.
  503. retcols (iterable[str]): the names of the columns to return
  504. Returns:
  505. defer.Deferred: resolves to list[dict[str, Any]]
  506. """
  507. return self.runInteraction(
  508. desc,
  509. self._simple_select_list_txn,
  510. table, keyvalues, retcols
  511. )
  512. @classmethod
  513. def _simple_select_list_txn(cls, txn, table, keyvalues, retcols):
  514. """Executes a SELECT query on the named table, which may return zero or
  515. more rows, returning the result as a list of dicts.
  516. Args:
  517. txn : Transaction object
  518. table (str): the table name
  519. keyvalues (dict[str, T] | None):
  520. column names and values to select the rows with, or None to not
  521. apply a WHERE clause.
  522. retcols (iterable[str]): the names of the columns to return
  523. """
  524. if keyvalues:
  525. sql = "SELECT %s FROM %s WHERE %s" % (
  526. ", ".join(retcols),
  527. table,
  528. " AND ".join("%s = ?" % (k, ) for k in keyvalues)
  529. )
  530. txn.execute(sql, keyvalues.values())
  531. else:
  532. sql = "SELECT %s FROM %s" % (
  533. ", ".join(retcols),
  534. table
  535. )
  536. txn.execute(sql)
  537. return cls.cursor_to_dict(txn)
  538. @defer.inlineCallbacks
  539. def _simple_select_many_batch(self, table, column, iterable, retcols,
  540. keyvalues={}, desc="_simple_select_many_batch",
  541. batch_size=100):
  542. """Executes a SELECT query on the named table, which may return zero or
  543. more rows, returning the result as a list of dicts.
  544. Filters rows by if value of `column` is in `iterable`.
  545. Args:
  546. table : string giving the table name
  547. column : column name to test for inclusion against `iterable`
  548. iterable : list
  549. keyvalues : dict of column names and values to select the rows with
  550. retcols : list of strings giving the names of the columns to return
  551. """
  552. results = []
  553. if not iterable:
  554. defer.returnValue(results)
  555. chunks = [
  556. iterable[i:i + batch_size]
  557. for i in xrange(0, len(iterable), batch_size)
  558. ]
  559. for chunk in chunks:
  560. rows = yield self.runInteraction(
  561. desc,
  562. self._simple_select_many_txn,
  563. table, column, chunk, keyvalues, retcols
  564. )
  565. results.extend(rows)
  566. defer.returnValue(results)
  567. @classmethod
  568. def _simple_select_many_txn(cls, txn, table, column, iterable, keyvalues, retcols):
  569. """Executes a SELECT query on the named table, which may return zero or
  570. more rows, returning the result as a list of dicts.
  571. Filters rows by if value of `column` is in `iterable`.
  572. Args:
  573. txn : Transaction object
  574. table : string giving the table name
  575. column : column name to test for inclusion against `iterable`
  576. iterable : list
  577. keyvalues : dict of column names and values to select the rows with
  578. retcols : list of strings giving the names of the columns to return
  579. """
  580. if not iterable:
  581. return []
  582. sql = "SELECT %s FROM %s" % (", ".join(retcols), table)
  583. clauses = []
  584. values = []
  585. clauses.append(
  586. "%s IN (%s)" % (column, ",".join("?" for _ in iterable))
  587. )
  588. values.extend(iterable)
  589. for key, value in keyvalues.items():
  590. clauses.append("%s = ?" % (key,))
  591. values.append(value)
  592. if clauses:
  593. sql = "%s WHERE %s" % (
  594. sql,
  595. " AND ".join(clauses),
  596. )
  597. txn.execute(sql, values)
  598. return cls.cursor_to_dict(txn)
  599. def _simple_update_one(self, table, keyvalues, updatevalues,
  600. desc="_simple_update_one"):
  601. """Executes an UPDATE query on the named table, setting new values for
  602. columns in a row matching the key values.
  603. Args:
  604. table : string giving the table name
  605. keyvalues : dict of column names and values to select the row with
  606. updatevalues : dict giving column names and values to update
  607. retcols : optional list of column names to return
  608. If present, retcols gives a list of column names on which to perform
  609. a SELECT statement *before* performing the UPDATE statement. The values
  610. of these will be returned in a dict.
  611. These are performed within the same transaction, allowing an atomic
  612. get-and-set. This can be used to implement compare-and-set by putting
  613. the update column in the 'keyvalues' dict as well.
  614. """
  615. return self.runInteraction(
  616. desc,
  617. self._simple_update_one_txn,
  618. table, keyvalues, updatevalues,
  619. )
  620. @staticmethod
  621. def _simple_update_one_txn(txn, table, keyvalues, updatevalues):
  622. if keyvalues:
  623. where = "WHERE %s" % " AND ".join("%s = ?" % k for k in keyvalues.keys())
  624. else:
  625. where = ""
  626. update_sql = "UPDATE %s SET %s %s" % (
  627. table,
  628. ", ".join("%s = ?" % (k,) for k in updatevalues),
  629. where,
  630. )
  631. txn.execute(
  632. update_sql,
  633. updatevalues.values() + keyvalues.values()
  634. )
  635. if txn.rowcount == 0:
  636. raise StoreError(404, "No row found")
  637. if txn.rowcount > 1:
  638. raise StoreError(500, "More than one row matched")
  639. @staticmethod
  640. def _simple_select_one_txn(txn, table, keyvalues, retcols,
  641. allow_none=False):
  642. select_sql = "SELECT %s FROM %s WHERE %s" % (
  643. ", ".join(retcols),
  644. table,
  645. " AND ".join("%s = ?" % (k,) for k in keyvalues)
  646. )
  647. txn.execute(select_sql, keyvalues.values())
  648. row = txn.fetchone()
  649. if not row:
  650. if allow_none:
  651. return None
  652. raise StoreError(404, "No row found")
  653. if txn.rowcount > 1:
  654. raise StoreError(500, "More than one row matched")
  655. return dict(zip(retcols, row))
  656. def _simple_delete_one(self, table, keyvalues, desc="_simple_delete_one"):
  657. """Executes a DELETE query on the named table, expecting to delete a
  658. single row.
  659. Args:
  660. table : string giving the table name
  661. keyvalues : dict of column names and values to select the row with
  662. """
  663. return self.runInteraction(
  664. desc, self._simple_delete_one_txn, table, keyvalues
  665. )
  666. @staticmethod
  667. def _simple_delete_one_txn(txn, table, keyvalues):
  668. """Executes a DELETE query on the named table, expecting to delete a
  669. single row.
  670. Args:
  671. table : string giving the table name
  672. keyvalues : dict of column names and values to select the row with
  673. """
  674. sql = "DELETE FROM %s WHERE %s" % (
  675. table,
  676. " AND ".join("%s = ?" % (k, ) for k in keyvalues)
  677. )
  678. txn.execute(sql, keyvalues.values())
  679. if txn.rowcount == 0:
  680. raise StoreError(404, "No row found")
  681. if txn.rowcount > 1:
  682. raise StoreError(500, "more than one row matched")
  683. def _simple_delete(self, table, keyvalues, desc):
  684. return self.runInteraction(
  685. desc, self._simple_delete_txn, table, keyvalues
  686. )
  687. @staticmethod
  688. def _simple_delete_txn(txn, table, keyvalues):
  689. sql = "DELETE FROM %s WHERE %s" % (
  690. table,
  691. " AND ".join("%s = ?" % (k, ) for k in keyvalues)
  692. )
  693. return txn.execute(sql, keyvalues.values())
  694. def _get_cache_dict(self, db_conn, table, entity_column, stream_column,
  695. max_value, limit=100000):
  696. # Fetch a mapping of room_id -> max stream position for "recent" rooms.
  697. # It doesn't really matter how many we get, the StreamChangeCache will
  698. # do the right thing to ensure it respects the max size of cache.
  699. sql = (
  700. "SELECT %(entity)s, MAX(%(stream)s) FROM %(table)s"
  701. " WHERE %(stream)s > ? - %(limit)s"
  702. " GROUP BY %(entity)s"
  703. ) % {
  704. "table": table,
  705. "entity": entity_column,
  706. "stream": stream_column,
  707. "limit": limit,
  708. }
  709. sql = self.database_engine.convert_param_style(sql)
  710. txn = db_conn.cursor()
  711. txn.execute(sql, (int(max_value),))
  712. rows = txn.fetchall()
  713. txn.close()
  714. cache = {
  715. row[0]: int(row[1])
  716. for row in rows
  717. }
  718. if cache:
  719. min_val = min(cache.values())
  720. else:
  721. min_val = max_value
  722. return cache, min_val
  723. def _invalidate_cache_and_stream(self, txn, cache_func, keys):
  724. """Invalidates the cache and adds it to the cache stream so slaves
  725. will know to invalidate their caches.
  726. This should only be used to invalidate caches where slaves won't
  727. otherwise know from other replication streams that the cache should
  728. be invalidated.
  729. """
  730. txn.call_after(cache_func.invalidate, keys)
  731. if isinstance(self.database_engine, PostgresEngine):
  732. # get_next() returns a context manager which is designed to wrap
  733. # the transaction. However, we want to only get an ID when we want
  734. # to use it, here, so we need to call __enter__ manually, and have
  735. # __exit__ called after the transaction finishes.
  736. ctx = self._cache_id_gen.get_next()
  737. stream_id = ctx.__enter__()
  738. txn.call_after(ctx.__exit__, None, None, None)
  739. txn.call_after(self.hs.get_notifier().on_new_replication_data)
  740. self._simple_insert_txn(
  741. txn,
  742. table="cache_invalidation_stream",
  743. values={
  744. "stream_id": stream_id,
  745. "cache_func": cache_func.__name__,
  746. "keys": list(keys),
  747. "invalidation_ts": self.clock.time_msec(),
  748. }
  749. )
  750. def get_all_updated_caches(self, last_id, current_id, limit):
  751. if last_id == current_id:
  752. return defer.succeed([])
  753. def get_all_updated_caches_txn(txn):
  754. # We purposefully don't bound by the current token, as we want to
  755. # send across cache invalidations as quickly as possible. Cache
  756. # invalidations are idempotent, so duplicates are fine.
  757. sql = (
  758. "SELECT stream_id, cache_func, keys, invalidation_ts"
  759. " FROM cache_invalidation_stream"
  760. " WHERE stream_id > ? ORDER BY stream_id ASC LIMIT ?"
  761. )
  762. txn.execute(sql, (last_id, limit,))
  763. return txn.fetchall()
  764. return self.runInteraction(
  765. "get_all_updated_caches", get_all_updated_caches_txn
  766. )
  767. def get_cache_stream_token(self):
  768. if self._cache_id_gen:
  769. return self._cache_id_gen.get_current_token()
  770. else:
  771. return 0
  772. class _RollbackButIsFineException(Exception):
  773. """ This exception is used to rollback a transaction without implying
  774. something went wrong.
  775. """
  776. pass