_base.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  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*", 2000 * 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. """
  309. try:
  310. yield self.runInteraction(
  311. desc,
  312. self._simple_insert_txn, table, values,
  313. )
  314. except self.database_engine.module.IntegrityError:
  315. # We have to do or_ignore flag at this layer, since we can't reuse
  316. # a cursor after we receive an error from the db.
  317. if not or_ignore:
  318. raise
  319. @staticmethod
  320. def _simple_insert_txn(txn, table, values):
  321. keys, vals = zip(*values.items())
  322. sql = "INSERT INTO %s (%s) VALUES(%s)" % (
  323. table,
  324. ", ".join(k for k in keys),
  325. ", ".join("?" for _ in keys)
  326. )
  327. txn.execute(sql, vals)
  328. @staticmethod
  329. def _simple_insert_many_txn(txn, table, values):
  330. if not values:
  331. return
  332. # This is a *slight* abomination to get a list of tuples of key names
  333. # and a list of tuples of value names.
  334. #
  335. # i.e. [{"a": 1, "b": 2}, {"c": 3, "d": 4}]
  336. # => [("a", "b",), ("c", "d",)] and [(1, 2,), (3, 4,)]
  337. #
  338. # The sort is to ensure that we don't rely on dictionary iteration
  339. # order.
  340. keys, vals = zip(*[
  341. zip(
  342. *(sorted(i.items(), key=lambda kv: kv[0]))
  343. )
  344. for i in values
  345. if i
  346. ])
  347. for k in keys:
  348. if k != keys[0]:
  349. raise RuntimeError(
  350. "All items must have the same keys"
  351. )
  352. sql = "INSERT INTO %s (%s) VALUES(%s)" % (
  353. table,
  354. ", ".join(k for k in keys[0]),
  355. ", ".join("?" for _ in keys[0])
  356. )
  357. txn.executemany(sql, vals)
  358. def _simple_upsert(self, table, keyvalues, values,
  359. insertion_values={}, desc="_simple_upsert", lock=True):
  360. """
  361. Args:
  362. table (str): The table to upsert into
  363. keyvalues (dict): The unique key tables and their new values
  364. values (dict): The nonunique columns and their new values
  365. insertion_values (dict): key/values to use when inserting
  366. Returns:
  367. Deferred(bool): True if a new entry was created, False if an
  368. existing one was updated.
  369. """
  370. return self.runInteraction(
  371. desc,
  372. self._simple_upsert_txn, table, keyvalues, values, insertion_values,
  373. lock
  374. )
  375. def _simple_upsert_txn(self, txn, table, keyvalues, values, insertion_values={},
  376. lock=True):
  377. # We need to lock the table :(, unless we're *really* careful
  378. if lock:
  379. self.database_engine.lock_table(txn, table)
  380. # Try to update
  381. sql = "UPDATE %s SET %s WHERE %s" % (
  382. table,
  383. ", ".join("%s = ?" % (k,) for k in values),
  384. " AND ".join("%s = ?" % (k,) for k in keyvalues)
  385. )
  386. sqlargs = values.values() + keyvalues.values()
  387. logger.debug(
  388. "[SQL] %s Args=%s",
  389. sql, sqlargs,
  390. )
  391. txn.execute(sql, sqlargs)
  392. if txn.rowcount == 0:
  393. # We didn't update and rows so insert a new one
  394. allvalues = {}
  395. allvalues.update(keyvalues)
  396. allvalues.update(values)
  397. allvalues.update(insertion_values)
  398. sql = "INSERT INTO %s (%s) VALUES (%s)" % (
  399. table,
  400. ", ".join(k for k in allvalues),
  401. ", ".join("?" for _ in allvalues)
  402. )
  403. logger.debug(
  404. "[SQL] %s Args=%s",
  405. sql, keyvalues.values(),
  406. )
  407. txn.execute(sql, allvalues.values())
  408. return True
  409. else:
  410. return False
  411. def _simple_select_one(self, table, keyvalues, retcols,
  412. allow_none=False, desc="_simple_select_one"):
  413. """Executes a SELECT query on the named table, which is expected to
  414. return a single row, returning a single column from it.
  415. Args:
  416. table : string giving the table name
  417. keyvalues : dict of column names and values to select the row with
  418. retcols : list of strings giving the names of the columns to return
  419. allow_none : If true, return None instead of failing if the SELECT
  420. statement returns no rows
  421. """
  422. return self.runInteraction(
  423. desc,
  424. self._simple_select_one_txn,
  425. table, keyvalues, retcols, allow_none,
  426. )
  427. def _simple_select_one_onecol(self, table, keyvalues, retcol,
  428. allow_none=False,
  429. desc="_simple_select_one_onecol"):
  430. """Executes a SELECT query on the named table, which is expected to
  431. return a single row, returning a single column from it.
  432. Args:
  433. table : string giving the table name
  434. keyvalues : dict of column names and values to select the row with
  435. retcol : string giving the name of the column to return
  436. """
  437. return self.runInteraction(
  438. desc,
  439. self._simple_select_one_onecol_txn,
  440. table, keyvalues, retcol, allow_none=allow_none,
  441. )
  442. @classmethod
  443. def _simple_select_one_onecol_txn(cls, txn, table, keyvalues, retcol,
  444. allow_none=False):
  445. ret = cls._simple_select_onecol_txn(
  446. txn,
  447. table=table,
  448. keyvalues=keyvalues,
  449. retcol=retcol,
  450. )
  451. if ret:
  452. return ret[0]
  453. else:
  454. if allow_none:
  455. return None
  456. else:
  457. raise StoreError(404, "No row found")
  458. @staticmethod
  459. def _simple_select_onecol_txn(txn, table, keyvalues, retcol):
  460. if keyvalues:
  461. where = "WHERE %s" % " AND ".join("%s = ?" % k for k in keyvalues.keys())
  462. else:
  463. where = ""
  464. sql = (
  465. "SELECT %(retcol)s FROM %(table)s %(where)s"
  466. ) % {
  467. "retcol": retcol,
  468. "table": table,
  469. "where": where,
  470. }
  471. txn.execute(sql, keyvalues.values())
  472. return [r[0] for r in txn.fetchall()]
  473. def _simple_select_onecol(self, table, keyvalues, retcol,
  474. desc="_simple_select_onecol"):
  475. """Executes a SELECT query on the named table, which returns a list
  476. comprising of the values of the named column from the selected rows.
  477. Args:
  478. table (str): table name
  479. keyvalues (dict): column names and values to select the rows with
  480. retcol (str): column whos value we wish to retrieve.
  481. Returns:
  482. Deferred: Results in a list
  483. """
  484. return self.runInteraction(
  485. desc,
  486. self._simple_select_onecol_txn,
  487. table, keyvalues, retcol
  488. )
  489. def _simple_select_list(self, table, keyvalues, retcols,
  490. desc="_simple_select_list"):
  491. """Executes a SELECT query on the named table, which may return zero or
  492. more rows, returning the result as a list of dicts.
  493. Args:
  494. table (str): the table name
  495. keyvalues (dict[str, Any] | None):
  496. column names and values to select the rows with, or None to not
  497. apply a WHERE clause.
  498. retcols (iterable[str]): the names of the columns to return
  499. Returns:
  500. defer.Deferred: resolves to list[dict[str, Any]]
  501. """
  502. return self.runInteraction(
  503. desc,
  504. self._simple_select_list_txn,
  505. table, keyvalues, retcols
  506. )
  507. @classmethod
  508. def _simple_select_list_txn(cls, txn, table, keyvalues, retcols):
  509. """Executes a SELECT query on the named table, which may return zero or
  510. more rows, returning the result as a list of dicts.
  511. Args:
  512. txn : Transaction object
  513. table (str): the table name
  514. keyvalues (dict[str, T] | None):
  515. column names and values to select the rows with, or None to not
  516. apply a WHERE clause.
  517. retcols (iterable[str]): the names of the columns to return
  518. """
  519. if keyvalues:
  520. sql = "SELECT %s FROM %s WHERE %s" % (
  521. ", ".join(retcols),
  522. table,
  523. " AND ".join("%s = ?" % (k, ) for k in keyvalues)
  524. )
  525. txn.execute(sql, keyvalues.values())
  526. else:
  527. sql = "SELECT %s FROM %s" % (
  528. ", ".join(retcols),
  529. table
  530. )
  531. txn.execute(sql)
  532. return cls.cursor_to_dict(txn)
  533. @defer.inlineCallbacks
  534. def _simple_select_many_batch(self, table, column, iterable, retcols,
  535. keyvalues={}, desc="_simple_select_many_batch",
  536. batch_size=100):
  537. """Executes a SELECT query on the named table, which may return zero or
  538. more rows, returning the result as a list of dicts.
  539. Filters rows by if value of `column` is in `iterable`.
  540. Args:
  541. table : string giving the table name
  542. column : column name to test for inclusion against `iterable`
  543. iterable : list
  544. keyvalues : dict of column names and values to select the rows with
  545. retcols : list of strings giving the names of the columns to return
  546. """
  547. results = []
  548. if not iterable:
  549. defer.returnValue(results)
  550. chunks = [
  551. iterable[i:i + batch_size]
  552. for i in xrange(0, len(iterable), batch_size)
  553. ]
  554. for chunk in chunks:
  555. rows = yield self.runInteraction(
  556. desc,
  557. self._simple_select_many_txn,
  558. table, column, chunk, keyvalues, retcols
  559. )
  560. results.extend(rows)
  561. defer.returnValue(results)
  562. @classmethod
  563. def _simple_select_many_txn(cls, txn, table, column, iterable, keyvalues, retcols):
  564. """Executes a SELECT query on the named table, which may return zero or
  565. more rows, returning the result as a list of dicts.
  566. Filters rows by if value of `column` is in `iterable`.
  567. Args:
  568. txn : Transaction object
  569. table : string giving the table name
  570. column : column name to test for inclusion against `iterable`
  571. iterable : list
  572. keyvalues : dict of column names and values to select the rows with
  573. retcols : list of strings giving the names of the columns to return
  574. """
  575. if not iterable:
  576. return []
  577. sql = "SELECT %s FROM %s" % (", ".join(retcols), table)
  578. clauses = []
  579. values = []
  580. clauses.append(
  581. "%s IN (%s)" % (column, ",".join("?" for _ in iterable))
  582. )
  583. values.extend(iterable)
  584. for key, value in keyvalues.items():
  585. clauses.append("%s = ?" % (key,))
  586. values.append(value)
  587. if clauses:
  588. sql = "%s WHERE %s" % (
  589. sql,
  590. " AND ".join(clauses),
  591. )
  592. txn.execute(sql, values)
  593. return cls.cursor_to_dict(txn)
  594. def _simple_update_one(self, table, keyvalues, updatevalues,
  595. desc="_simple_update_one"):
  596. """Executes an UPDATE query on the named table, setting new values for
  597. columns in a row matching the key values.
  598. Args:
  599. table : string giving the table name
  600. keyvalues : dict of column names and values to select the row with
  601. updatevalues : dict giving column names and values to update
  602. retcols : optional list of column names to return
  603. If present, retcols gives a list of column names on which to perform
  604. a SELECT statement *before* performing the UPDATE statement. The values
  605. of these will be returned in a dict.
  606. These are performed within the same transaction, allowing an atomic
  607. get-and-set. This can be used to implement compare-and-set by putting
  608. the update column in the 'keyvalues' dict as well.
  609. """
  610. return self.runInteraction(
  611. desc,
  612. self._simple_update_one_txn,
  613. table, keyvalues, updatevalues,
  614. )
  615. @staticmethod
  616. def _simple_update_one_txn(txn, table, keyvalues, updatevalues):
  617. if keyvalues:
  618. where = "WHERE %s" % " AND ".join("%s = ?" % k for k in keyvalues.keys())
  619. else:
  620. where = ""
  621. update_sql = "UPDATE %s SET %s %s" % (
  622. table,
  623. ", ".join("%s = ?" % (k,) for k in updatevalues),
  624. where,
  625. )
  626. txn.execute(
  627. update_sql,
  628. updatevalues.values() + keyvalues.values()
  629. )
  630. if txn.rowcount == 0:
  631. raise StoreError(404, "No row found")
  632. if txn.rowcount > 1:
  633. raise StoreError(500, "More than one row matched")
  634. @staticmethod
  635. def _simple_select_one_txn(txn, table, keyvalues, retcols,
  636. allow_none=False):
  637. select_sql = "SELECT %s FROM %s WHERE %s" % (
  638. ", ".join(retcols),
  639. table,
  640. " AND ".join("%s = ?" % (k,) for k in keyvalues)
  641. )
  642. txn.execute(select_sql, keyvalues.values())
  643. row = txn.fetchone()
  644. if not row:
  645. if allow_none:
  646. return None
  647. raise StoreError(404, "No row found")
  648. if txn.rowcount > 1:
  649. raise StoreError(500, "More than one row matched")
  650. return dict(zip(retcols, row))
  651. def _simple_delete_one(self, table, keyvalues, desc="_simple_delete_one"):
  652. """Executes a DELETE query on the named table, expecting to delete a
  653. single row.
  654. Args:
  655. table : string giving the table name
  656. keyvalues : dict of column names and values to select the row with
  657. """
  658. return self.runInteraction(
  659. desc, self._simple_delete_one_txn, table, keyvalues
  660. )
  661. @staticmethod
  662. def _simple_delete_one_txn(txn, table, keyvalues):
  663. """Executes a DELETE query on the named table, expecting to delete a
  664. single row.
  665. Args:
  666. table : string giving the table name
  667. keyvalues : dict of column names and values to select the row with
  668. """
  669. sql = "DELETE FROM %s WHERE %s" % (
  670. table,
  671. " AND ".join("%s = ?" % (k, ) for k in keyvalues)
  672. )
  673. txn.execute(sql, keyvalues.values())
  674. if txn.rowcount == 0:
  675. raise StoreError(404, "No row found")
  676. if txn.rowcount > 1:
  677. raise StoreError(500, "more than one row matched")
  678. def _simple_delete(self, table, keyvalues, desc):
  679. return self.runInteraction(
  680. desc, self._simple_delete_txn, table, keyvalues
  681. )
  682. @staticmethod
  683. def _simple_delete_txn(txn, table, keyvalues):
  684. sql = "DELETE FROM %s WHERE %s" % (
  685. table,
  686. " AND ".join("%s = ?" % (k, ) for k in keyvalues)
  687. )
  688. return txn.execute(sql, keyvalues.values())
  689. def _get_cache_dict(self, db_conn, table, entity_column, stream_column,
  690. max_value):
  691. # Fetch a mapping of room_id -> max stream position for "recent" rooms.
  692. # It doesn't really matter how many we get, the StreamChangeCache will
  693. # do the right thing to ensure it respects the max size of cache.
  694. sql = (
  695. "SELECT %(entity)s, MAX(%(stream)s) FROM %(table)s"
  696. " WHERE %(stream)s > ? - 100000"
  697. " GROUP BY %(entity)s"
  698. ) % {
  699. "table": table,
  700. "entity": entity_column,
  701. "stream": stream_column,
  702. }
  703. sql = self.database_engine.convert_param_style(sql)
  704. txn = db_conn.cursor()
  705. txn.execute(sql, (int(max_value),))
  706. rows = txn.fetchall()
  707. txn.close()
  708. cache = {
  709. row[0]: int(row[1])
  710. for row in rows
  711. }
  712. if cache:
  713. min_val = min(cache.values())
  714. else:
  715. min_val = max_value
  716. return cache, min_val
  717. def _invalidate_cache_and_stream(self, txn, cache_func, keys):
  718. """Invalidates the cache and adds it to the cache stream so slaves
  719. will know to invalidate their caches.
  720. This should only be used to invalidate caches where slaves won't
  721. otherwise know from other replication streams that the cache should
  722. be invalidated.
  723. """
  724. txn.call_after(cache_func.invalidate, keys)
  725. if isinstance(self.database_engine, PostgresEngine):
  726. # get_next() returns a context manager which is designed to wrap
  727. # the transaction. However, we want to only get an ID when we want
  728. # to use it, here, so we need to call __enter__ manually, and have
  729. # __exit__ called after the transaction finishes.
  730. ctx = self._cache_id_gen.get_next()
  731. stream_id = ctx.__enter__()
  732. txn.call_after(ctx.__exit__, None, None, None)
  733. txn.call_after(self.hs.get_notifier().on_new_replication_data)
  734. self._simple_insert_txn(
  735. txn,
  736. table="cache_invalidation_stream",
  737. values={
  738. "stream_id": stream_id,
  739. "cache_func": cache_func.__name__,
  740. "keys": list(keys),
  741. "invalidation_ts": self.clock.time_msec(),
  742. }
  743. )
  744. def get_all_updated_caches(self, last_id, current_id, limit):
  745. if last_id == current_id:
  746. return defer.succeed([])
  747. def get_all_updated_caches_txn(txn):
  748. # We purposefully don't bound by the current token, as we want to
  749. # send across cache invalidations as quickly as possible. Cache
  750. # invalidations are idempotent, so duplicates are fine.
  751. sql = (
  752. "SELECT stream_id, cache_func, keys, invalidation_ts"
  753. " FROM cache_invalidation_stream"
  754. " WHERE stream_id > ? ORDER BY stream_id ASC LIMIT ?"
  755. )
  756. txn.execute(sql, (last_id, limit,))
  757. return txn.fetchall()
  758. return self.runInteraction(
  759. "get_all_updated_caches", get_all_updated_caches_txn
  760. )
  761. def get_cache_stream_token(self):
  762. if self._cache_id_gen:
  763. return self._cache_id_gen.get_current_token()
  764. else:
  765. return 0
  766. class _RollbackButIsFineException(Exception):
  767. """ This exception is used to rollback a transaction without implying
  768. something went wrong.
  769. """
  770. pass