Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

2098 linhas
70 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2017-2018 New Vector Ltd
  4. # Copyright 2019 The Matrix.org Foundation C.I.C.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import logging
  18. import time
  19. from sys import intern
  20. from time import monotonic as monotonic_time
  21. from typing import (
  22. Any,
  23. Callable,
  24. Dict,
  25. Iterable,
  26. Iterator,
  27. List,
  28. Optional,
  29. Tuple,
  30. TypeVar,
  31. cast,
  32. overload,
  33. )
  34. import attr
  35. from prometheus_client import Histogram
  36. from typing_extensions import Literal
  37. from twisted.enterprise import adbapi
  38. from synapse.api.errors import StoreError
  39. from synapse.config.database import DatabaseConnectionConfig
  40. from synapse.logging.context import (
  41. LoggingContext,
  42. current_context,
  43. make_deferred_yieldable,
  44. )
  45. from synapse.metrics.background_process_metrics import run_as_background_process
  46. from synapse.storage.background_updates import BackgroundUpdater
  47. from synapse.storage.engines import BaseDatabaseEngine, PostgresEngine, Sqlite3Engine
  48. from synapse.storage.types import Connection, Cursor
  49. from synapse.types import Collection
  50. # python 3 does not have a maximum int value
  51. MAX_TXN_ID = 2 ** 63 - 1
  52. logger = logging.getLogger(__name__)
  53. sql_logger = logging.getLogger("synapse.storage.SQL")
  54. transaction_logger = logging.getLogger("synapse.storage.txn")
  55. perf_logger = logging.getLogger("synapse.storage.TIME")
  56. sql_scheduling_timer = Histogram("synapse_storage_schedule_time", "sec")
  57. sql_query_timer = Histogram("synapse_storage_query_time", "sec", ["verb"])
  58. sql_txn_timer = Histogram("synapse_storage_transaction_time", "sec", ["desc"])
  59. # Unique indexes which have been added in background updates. Maps from table name
  60. # to the name of the background update which added the unique index to that table.
  61. #
  62. # This is used by the upsert logic to figure out which tables are safe to do a proper
  63. # UPSERT on: until the relevant background update has completed, we
  64. # have to emulate an upsert by locking the table.
  65. #
  66. UNIQUE_INDEX_BACKGROUND_UPDATES = {
  67. "user_ips": "user_ips_device_unique_index",
  68. "device_lists_remote_extremeties": "device_lists_remote_extremeties_unique_idx",
  69. "device_lists_remote_cache": "device_lists_remote_cache_unique_idx",
  70. "event_search": "event_search_event_id_idx",
  71. }
  72. def make_pool(
  73. reactor, db_config: DatabaseConnectionConfig, engine: BaseDatabaseEngine
  74. ) -> adbapi.ConnectionPool:
  75. """Get the connection pool for the database.
  76. """
  77. # By default enable `cp_reconnect`. We need to fiddle with db_args in case
  78. # someone has explicitly set `cp_reconnect`.
  79. db_args = dict(db_config.config.get("args", {}))
  80. db_args.setdefault("cp_reconnect", True)
  81. return adbapi.ConnectionPool(
  82. db_config.config["name"],
  83. cp_reactor=reactor,
  84. cp_openfun=lambda conn: engine.on_new_connection(
  85. LoggingDatabaseConnection(conn, engine, "on_new_connection")
  86. ),
  87. **db_args,
  88. )
  89. def make_conn(
  90. db_config: DatabaseConnectionConfig,
  91. engine: BaseDatabaseEngine,
  92. default_txn_name: str,
  93. ) -> Connection:
  94. """Make a new connection to the database and return it.
  95. Returns:
  96. Connection
  97. """
  98. db_params = {
  99. k: v
  100. for k, v in db_config.config.get("args", {}).items()
  101. if not k.startswith("cp_")
  102. }
  103. native_db_conn = engine.module.connect(**db_params)
  104. db_conn = LoggingDatabaseConnection(native_db_conn, engine, default_txn_name)
  105. engine.on_new_connection(db_conn)
  106. return db_conn
  107. @attr.s(slots=True)
  108. class LoggingDatabaseConnection:
  109. """A wrapper around a database connection that returns `LoggingTransaction`
  110. as its cursor class.
  111. This is mainly used on startup to ensure that queries get logged correctly
  112. """
  113. conn = attr.ib(type=Connection)
  114. engine = attr.ib(type=BaseDatabaseEngine)
  115. default_txn_name = attr.ib(type=str)
  116. def cursor(
  117. self, *, txn_name=None, after_callbacks=None, exception_callbacks=None
  118. ) -> "LoggingTransaction":
  119. if not txn_name:
  120. txn_name = self.default_txn_name
  121. return LoggingTransaction(
  122. self.conn.cursor(),
  123. name=txn_name,
  124. database_engine=self.engine,
  125. after_callbacks=after_callbacks,
  126. exception_callbacks=exception_callbacks,
  127. )
  128. def close(self) -> None:
  129. self.conn.close()
  130. def commit(self) -> None:
  131. self.conn.commit()
  132. def rollback(self, *args, **kwargs) -> None:
  133. self.conn.rollback(*args, **kwargs)
  134. def __enter__(self) -> "Connection":
  135. self.conn.__enter__()
  136. return self
  137. def __exit__(self, exc_type, exc_value, traceback) -> Optional[bool]:
  138. return self.conn.__exit__(exc_type, exc_value, traceback)
  139. # Proxy through any unknown lookups to the DB conn class.
  140. def __getattr__(self, name):
  141. return getattr(self.conn, name)
  142. # The type of entry which goes on our after_callbacks and exception_callbacks lists.
  143. #
  144. # Python 3.5.2 doesn't support Callable with an ellipsis, so we wrap it in quotes so
  145. # that mypy sees the type but the runtime python doesn't.
  146. _CallbackListEntry = Tuple["Callable[..., None]", Iterable[Any], Dict[str, Any]]
  147. R = TypeVar("R")
  148. class LoggingTransaction:
  149. """An object that almost-transparently proxies for the 'txn' object
  150. passed to the constructor. Adds logging and metrics to the .execute()
  151. method.
  152. Args:
  153. txn: The database transaction object to wrap.
  154. name: The name of this transactions for logging.
  155. database_engine
  156. after_callbacks: A list that callbacks will be appended to
  157. that have been added by `call_after` which should be run on
  158. successful completion of the transaction. None indicates that no
  159. callbacks should be allowed to be scheduled to run.
  160. exception_callbacks: A list that callbacks will be appended
  161. to that have been added by `call_on_exception` which should be run
  162. if transaction ends with an error. None indicates that no callbacks
  163. should be allowed to be scheduled to run.
  164. """
  165. __slots__ = [
  166. "txn",
  167. "name",
  168. "database_engine",
  169. "after_callbacks",
  170. "exception_callbacks",
  171. ]
  172. def __init__(
  173. self,
  174. txn: Cursor,
  175. name: str,
  176. database_engine: BaseDatabaseEngine,
  177. after_callbacks: Optional[List[_CallbackListEntry]] = None,
  178. exception_callbacks: Optional[List[_CallbackListEntry]] = None,
  179. ):
  180. self.txn = txn
  181. self.name = name
  182. self.database_engine = database_engine
  183. self.after_callbacks = after_callbacks
  184. self.exception_callbacks = exception_callbacks
  185. def call_after(self, callback: "Callable[..., None]", *args: Any, **kwargs: Any):
  186. """Call the given callback on the main twisted thread after the
  187. transaction has finished. Used to invalidate the caches on the
  188. correct thread.
  189. """
  190. # if self.after_callbacks is None, that means that whatever constructed the
  191. # LoggingTransaction isn't expecting there to be any callbacks; assert that
  192. # is not the case.
  193. assert self.after_callbacks is not None
  194. self.after_callbacks.append((callback, args, kwargs))
  195. def call_on_exception(
  196. self, callback: "Callable[..., None]", *args: Any, **kwargs: Any
  197. ):
  198. # if self.exception_callbacks is None, that means that whatever constructed the
  199. # LoggingTransaction isn't expecting there to be any callbacks; assert that
  200. # is not the case.
  201. assert self.exception_callbacks is not None
  202. self.exception_callbacks.append((callback, args, kwargs))
  203. def fetchall(self) -> List[Tuple]:
  204. return self.txn.fetchall()
  205. def fetchone(self) -> Tuple:
  206. return self.txn.fetchone()
  207. def __iter__(self) -> Iterator[Tuple]:
  208. return self.txn.__iter__()
  209. @property
  210. def rowcount(self) -> int:
  211. return self.txn.rowcount
  212. @property
  213. def description(self) -> Any:
  214. return self.txn.description
  215. def execute_batch(self, sql: str, args: Iterable[Iterable[Any]]) -> None:
  216. if isinstance(self.database_engine, PostgresEngine):
  217. from psycopg2.extras import execute_batch # type: ignore
  218. self._do_execute(lambda *x: execute_batch(self.txn, *x), sql, args)
  219. else:
  220. for val in args:
  221. self.execute(sql, val)
  222. def execute_values(self, sql: str, *args: Any) -> List[Tuple]:
  223. """Corresponds to psycopg2.extras.execute_values. Only available when
  224. using postgres.
  225. Always sets fetch=True when caling `execute_values`, so will return the
  226. results.
  227. """
  228. assert isinstance(self.database_engine, PostgresEngine)
  229. from psycopg2.extras import execute_values # type: ignore
  230. return self._do_execute(
  231. lambda *x: execute_values(self.txn, *x, fetch=True), sql, *args
  232. )
  233. def execute(self, sql: str, *args: Any) -> None:
  234. self._do_execute(self.txn.execute, sql, *args)
  235. def executemany(self, sql: str, *args: Any) -> None:
  236. self._do_execute(self.txn.executemany, sql, *args)
  237. def _make_sql_one_line(self, sql: str) -> str:
  238. "Strip newlines out of SQL so that the loggers in the DB are on one line"
  239. return " ".join(line.strip() for line in sql.splitlines() if line.strip())
  240. def _do_execute(self, func: Callable[..., R], sql: str, *args: Any) -> R:
  241. sql = self._make_sql_one_line(sql)
  242. # TODO(paul): Maybe use 'info' and 'debug' for values?
  243. sql_logger.debug("[SQL] {%s} %s", self.name, sql)
  244. sql = self.database_engine.convert_param_style(sql)
  245. if args:
  246. try:
  247. sql_logger.debug("[SQL values] {%s} %r", self.name, args[0])
  248. except Exception:
  249. # Don't let logging failures stop SQL from working
  250. pass
  251. start = time.time()
  252. try:
  253. return func(sql, *args)
  254. except Exception as e:
  255. sql_logger.debug("[SQL FAIL] {%s} %s", self.name, e)
  256. raise
  257. finally:
  258. secs = time.time() - start
  259. sql_logger.debug("[SQL time] {%s} %f sec", self.name, secs)
  260. sql_query_timer.labels(sql.split()[0]).observe(secs)
  261. def close(self) -> None:
  262. self.txn.close()
  263. def __enter__(self) -> "LoggingTransaction":
  264. return self
  265. def __exit__(self, exc_type, exc_value, traceback):
  266. self.close()
  267. class PerformanceCounters:
  268. def __init__(self):
  269. self.current_counters = {}
  270. self.previous_counters = {}
  271. def update(self, key: str, duration_secs: float) -> None:
  272. count, cum_time = self.current_counters.get(key, (0, 0))
  273. count += 1
  274. cum_time += duration_secs
  275. self.current_counters[key] = (count, cum_time)
  276. def interval(self, interval_duration_secs: float, limit: int = 3) -> str:
  277. counters = []
  278. for name, (count, cum_time) in self.current_counters.items():
  279. prev_count, prev_time = self.previous_counters.get(name, (0, 0))
  280. counters.append(
  281. (
  282. (cum_time - prev_time) / interval_duration_secs,
  283. count - prev_count,
  284. name,
  285. )
  286. )
  287. self.previous_counters = dict(self.current_counters)
  288. counters.sort(reverse=True)
  289. top_n_counters = ", ".join(
  290. "%s(%d): %.3f%%" % (name, count, 100 * ratio)
  291. for ratio, count, name in counters[:limit]
  292. )
  293. return top_n_counters
  294. class DatabasePool:
  295. """Wraps a single physical database and connection pool.
  296. A single database may be used by multiple data stores.
  297. """
  298. _TXN_ID = 0
  299. def __init__(
  300. self, hs, database_config: DatabaseConnectionConfig, engine: BaseDatabaseEngine
  301. ):
  302. self.hs = hs
  303. self._clock = hs.get_clock()
  304. self._database_config = database_config
  305. self._db_pool = make_pool(hs.get_reactor(), database_config, engine)
  306. self.updates = BackgroundUpdater(hs, self)
  307. self._previous_txn_total_time = 0.0
  308. self._current_txn_total_time = 0.0
  309. self._previous_loop_ts = 0.0
  310. # TODO(paul): These can eventually be removed once the metrics code
  311. # is running in mainline, and we have some nice monitoring frontends
  312. # to watch it
  313. self._txn_perf_counters = PerformanceCounters()
  314. self.engine = engine
  315. # A set of tables that are not safe to use native upserts in.
  316. self._unsafe_to_upsert_tables = set(UNIQUE_INDEX_BACKGROUND_UPDATES.keys())
  317. # We add the user_directory_search table to the blacklist on SQLite
  318. # because the existing search table does not have an index, making it
  319. # unsafe to use native upserts.
  320. if isinstance(self.engine, Sqlite3Engine):
  321. self._unsafe_to_upsert_tables.add("user_directory_search")
  322. if self.engine.can_native_upsert:
  323. # Check ASAP (and then later, every 1s) to see if we have finished
  324. # background updates of tables that aren't safe to update.
  325. self._clock.call_later(
  326. 0.0,
  327. run_as_background_process,
  328. "upsert_safety_check",
  329. self._check_safe_to_upsert,
  330. )
  331. def is_running(self) -> bool:
  332. """Is the database pool currently running
  333. """
  334. return self._db_pool.running
  335. async def _check_safe_to_upsert(self) -> None:
  336. """
  337. Is it safe to use native UPSERT?
  338. If there are background updates, we will need to wait, as they may be
  339. the addition of indexes that set the UNIQUE constraint that we require.
  340. If the background updates have not completed, wait 15 sec and check again.
  341. """
  342. updates = await self.simple_select_list(
  343. "background_updates",
  344. keyvalues=None,
  345. retcols=["update_name"],
  346. desc="check_background_updates",
  347. )
  348. updates = [x["update_name"] for x in updates]
  349. for table, update_name in UNIQUE_INDEX_BACKGROUND_UPDATES.items():
  350. if update_name not in updates:
  351. logger.debug("Now safe to upsert in %s", table)
  352. self._unsafe_to_upsert_tables.discard(table)
  353. # If there's any updates still running, reschedule to run.
  354. if updates:
  355. self._clock.call_later(
  356. 15.0,
  357. run_as_background_process,
  358. "upsert_safety_check",
  359. self._check_safe_to_upsert,
  360. )
  361. def start_profiling(self) -> None:
  362. self._previous_loop_ts = monotonic_time()
  363. def loop():
  364. curr = self._current_txn_total_time
  365. prev = self._previous_txn_total_time
  366. self._previous_txn_total_time = curr
  367. time_now = monotonic_time()
  368. time_then = self._previous_loop_ts
  369. self._previous_loop_ts = time_now
  370. duration = time_now - time_then
  371. ratio = (curr - prev) / duration
  372. top_three_counters = self._txn_perf_counters.interval(duration, limit=3)
  373. perf_logger.debug(
  374. "Total database time: %.3f%% {%s}", ratio * 100, top_three_counters
  375. )
  376. self._clock.looping_call(loop, 10000)
  377. def new_transaction(
  378. self,
  379. conn: LoggingDatabaseConnection,
  380. desc: str,
  381. after_callbacks: List[_CallbackListEntry],
  382. exception_callbacks: List[_CallbackListEntry],
  383. func: "Callable[..., R]",
  384. *args: Any,
  385. **kwargs: Any
  386. ) -> R:
  387. """Start a new database transaction with the given connection.
  388. Note: The given func may be called multiple times under certain
  389. failure modes. This is normally fine when in a standard transaction,
  390. but care must be taken if the connection is in `autocommit` mode that
  391. the function will correctly handle being aborted and retried half way
  392. through its execution.
  393. Args:
  394. conn
  395. desc
  396. after_callbacks
  397. exception_callbacks
  398. func
  399. *args
  400. **kwargs
  401. """
  402. start = monotonic_time()
  403. txn_id = self._TXN_ID
  404. # We don't really need these to be unique, so lets stop it from
  405. # growing really large.
  406. self._TXN_ID = (self._TXN_ID + 1) % (MAX_TXN_ID)
  407. name = "%s-%x" % (desc, txn_id)
  408. transaction_logger.debug("[TXN START] {%s}", name)
  409. try:
  410. i = 0
  411. N = 5
  412. while True:
  413. cursor = conn.cursor(
  414. txn_name=name,
  415. after_callbacks=after_callbacks,
  416. exception_callbacks=exception_callbacks,
  417. )
  418. try:
  419. r = func(cursor, *args, **kwargs)
  420. conn.commit()
  421. return r
  422. except self.engine.module.OperationalError as e:
  423. # This can happen if the database disappears mid
  424. # transaction.
  425. transaction_logger.warning(
  426. "[TXN OPERROR] {%s} %s %d/%d", name, e, i, N,
  427. )
  428. if i < N:
  429. i += 1
  430. try:
  431. conn.rollback()
  432. except self.engine.module.Error as e1:
  433. transaction_logger.warning("[TXN EROLL] {%s} %s", name, e1)
  434. continue
  435. raise
  436. except self.engine.module.DatabaseError as e:
  437. if self.engine.is_deadlock(e):
  438. transaction_logger.warning(
  439. "[TXN DEADLOCK] {%s} %d/%d", name, i, N
  440. )
  441. if i < N:
  442. i += 1
  443. try:
  444. conn.rollback()
  445. except self.engine.module.Error as e1:
  446. transaction_logger.warning(
  447. "[TXN EROLL] {%s} %s", name, e1,
  448. )
  449. continue
  450. raise
  451. finally:
  452. # we're either about to retry with a new cursor, or we're about to
  453. # release the connection. Once we release the connection, it could
  454. # get used for another query, which might do a conn.rollback().
  455. #
  456. # In the latter case, even though that probably wouldn't affect the
  457. # results of this transaction, python's sqlite will reset all
  458. # statements on the connection [1], which will make our cursor
  459. # invalid [2].
  460. #
  461. # In any case, continuing to read rows after commit()ing seems
  462. # dubious from the PoV of ACID transactional semantics
  463. # (sqlite explicitly says that once you commit, you may see rows
  464. # from subsequent updates.)
  465. #
  466. # In psycopg2, cursors are essentially a client-side fabrication -
  467. # all the data is transferred to the client side when the statement
  468. # finishes executing - so in theory we could go on streaming results
  469. # from the cursor, but attempting to do so would make us
  470. # incompatible with sqlite, so let's make sure we're not doing that
  471. # by closing the cursor.
  472. #
  473. # (*named* cursors in psycopg2 are different and are proper server-
  474. # side things, but (a) we don't use them and (b) they are implicitly
  475. # closed by ending the transaction anyway.)
  476. #
  477. # In short, if we haven't finished with the cursor yet, that's a
  478. # problem waiting to bite us.
  479. #
  480. # TL;DR: we're done with the cursor, so we can close it.
  481. #
  482. # [1]: https://github.com/python/cpython/blob/v3.8.0/Modules/_sqlite/connection.c#L465
  483. # [2]: https://github.com/python/cpython/blob/v3.8.0/Modules/_sqlite/cursor.c#L236
  484. cursor.close()
  485. except Exception as e:
  486. transaction_logger.debug("[TXN FAIL] {%s} %s", name, e)
  487. raise
  488. finally:
  489. end = monotonic_time()
  490. duration = end - start
  491. current_context().add_database_transaction(duration)
  492. transaction_logger.debug("[TXN END] {%s} %f sec", name, duration)
  493. self._current_txn_total_time += duration
  494. self._txn_perf_counters.update(desc, duration)
  495. sql_txn_timer.labels(desc).observe(duration)
  496. async def runInteraction(
  497. self,
  498. desc: str,
  499. func: "Callable[..., R]",
  500. *args: Any,
  501. db_autocommit: bool = False,
  502. **kwargs: Any
  503. ) -> R:
  504. """Starts a transaction on the database and runs a given function
  505. Arguments:
  506. desc: description of the transaction, for logging and metrics
  507. func: callback function, which will be called with a
  508. database transaction (twisted.enterprise.adbapi.Transaction) as
  509. its first argument, followed by `args` and `kwargs`.
  510. db_autocommit: Whether to run the function in "autocommit" mode,
  511. i.e. outside of a transaction. This is useful for transactions
  512. that are only a single query.
  513. Currently, this is only implemented for Postgres. SQLite will still
  514. run the function inside a transaction.
  515. WARNING: This means that if func fails half way through then
  516. the changes will *not* be rolled back. `func` may also get
  517. called multiple times if the transaction is retried, so must
  518. correctly handle that case.
  519. args: positional args to pass to `func`
  520. kwargs: named args to pass to `func`
  521. Returns:
  522. The result of func
  523. """
  524. after_callbacks = [] # type: List[_CallbackListEntry]
  525. exception_callbacks = [] # type: List[_CallbackListEntry]
  526. if not current_context():
  527. logger.warning("Starting db txn '%s' from sentinel context", desc)
  528. try:
  529. result = await self.runWithConnection(
  530. self.new_transaction,
  531. desc,
  532. after_callbacks,
  533. exception_callbacks,
  534. func,
  535. *args,
  536. db_autocommit=db_autocommit,
  537. **kwargs,
  538. )
  539. for after_callback, after_args, after_kwargs in after_callbacks:
  540. after_callback(*after_args, **after_kwargs)
  541. except: # noqa: E722, as we reraise the exception this is fine.
  542. for after_callback, after_args, after_kwargs in exception_callbacks:
  543. after_callback(*after_args, **after_kwargs)
  544. raise
  545. return cast(R, result)
  546. async def runWithConnection(
  547. self,
  548. func: "Callable[..., R]",
  549. *args: Any,
  550. db_autocommit: bool = False,
  551. **kwargs: Any
  552. ) -> R:
  553. """Wraps the .runWithConnection() method on the underlying db_pool.
  554. Arguments:
  555. func: callback function, which will be called with a
  556. database connection (twisted.enterprise.adbapi.Connection) as
  557. its first argument, followed by `args` and `kwargs`.
  558. args: positional args to pass to `func`
  559. db_autocommit: Whether to run the function in "autocommit" mode,
  560. i.e. outside of a transaction. This is useful for transaction
  561. that are only a single query. Currently only affects postgres.
  562. kwargs: named args to pass to `func`
  563. Returns:
  564. The result of func
  565. """
  566. curr_context = current_context()
  567. if not curr_context:
  568. logger.warning(
  569. "Starting db connection from sentinel context: metrics will be lost"
  570. )
  571. parent_context = None
  572. else:
  573. assert isinstance(curr_context, LoggingContext)
  574. parent_context = curr_context
  575. start_time = monotonic_time()
  576. def inner_func(conn, *args, **kwargs):
  577. # We shouldn't be in a transaction. If we are then something
  578. # somewhere hasn't committed after doing work. (This is likely only
  579. # possible during startup, as `run*` will ensure changes are
  580. # committed/rolled back before putting the connection back in the
  581. # pool).
  582. assert not self.engine.in_transaction(conn)
  583. with LoggingContext("runWithConnection", parent_context) as context:
  584. sched_duration_sec = monotonic_time() - start_time
  585. sql_scheduling_timer.observe(sched_duration_sec)
  586. context.add_database_scheduled(sched_duration_sec)
  587. if self.engine.is_connection_closed(conn):
  588. logger.debug("Reconnecting closed database connection")
  589. conn.reconnect()
  590. try:
  591. if db_autocommit:
  592. self.engine.attempt_to_set_autocommit(conn, True)
  593. db_conn = LoggingDatabaseConnection(
  594. conn, self.engine, "runWithConnection"
  595. )
  596. return func(db_conn, *args, **kwargs)
  597. finally:
  598. if db_autocommit:
  599. self.engine.attempt_to_set_autocommit(conn, False)
  600. return await make_deferred_yieldable(
  601. self._db_pool.runWithConnection(inner_func, *args, **kwargs)
  602. )
  603. @staticmethod
  604. def cursor_to_dict(cursor: Cursor) -> List[Dict[str, Any]]:
  605. """Converts a SQL cursor into an list of dicts.
  606. Args:
  607. cursor: The DBAPI cursor which has executed a query.
  608. Returns:
  609. A list of dicts where the key is the column header.
  610. """
  611. col_headers = [intern(str(column[0])) for column in cursor.description]
  612. results = [dict(zip(col_headers, row)) for row in cursor]
  613. return results
  614. @overload
  615. async def execute(
  616. self, desc: str, decoder: Literal[None], query: str, *args: Any
  617. ) -> List[Tuple[Any, ...]]:
  618. ...
  619. @overload
  620. async def execute(
  621. self, desc: str, decoder: Callable[[Cursor], R], query: str, *args: Any
  622. ) -> R:
  623. ...
  624. async def execute(
  625. self,
  626. desc: str,
  627. decoder: Optional[Callable[[Cursor], R]],
  628. query: str,
  629. *args: Any
  630. ) -> R:
  631. """Runs a single query for a result set.
  632. Args:
  633. desc: description of the transaction, for logging and metrics
  634. decoder - The function which can resolve the cursor results to
  635. something meaningful.
  636. query - The query string to execute
  637. *args - Query args.
  638. Returns:
  639. The result of decoder(results)
  640. """
  641. def interaction(txn):
  642. txn.execute(query, args)
  643. if decoder:
  644. return decoder(txn)
  645. else:
  646. return txn.fetchall()
  647. return await self.runInteraction(desc, interaction)
  648. # "Simple" SQL API methods that operate on a single table with no JOINs,
  649. # no complex WHERE clauses, just a dict of values for columns.
  650. async def simple_insert(
  651. self,
  652. table: str,
  653. values: Dict[str, Any],
  654. or_ignore: bool = False,
  655. desc: str = "simple_insert",
  656. ) -> bool:
  657. """Executes an INSERT query on the named table.
  658. Args:
  659. table: string giving the table name
  660. values: dict of new column names and values for them
  661. or_ignore: bool stating whether an exception should be raised
  662. when a conflicting row already exists. If True, False will be
  663. returned by the function instead
  664. desc: description of the transaction, for logging and metrics
  665. Returns:
  666. Whether the row was inserted or not. Only useful when `or_ignore` is True
  667. """
  668. try:
  669. await self.runInteraction(desc, self.simple_insert_txn, table, values)
  670. except self.engine.module.IntegrityError:
  671. # We have to do or_ignore flag at this layer, since we can't reuse
  672. # a cursor after we receive an error from the db.
  673. if not or_ignore:
  674. raise
  675. return False
  676. return True
  677. @staticmethod
  678. def simple_insert_txn(
  679. txn: LoggingTransaction, table: str, values: Dict[str, Any]
  680. ) -> None:
  681. keys, vals = zip(*values.items())
  682. sql = "INSERT INTO %s (%s) VALUES(%s)" % (
  683. table,
  684. ", ".join(k for k in keys),
  685. ", ".join("?" for _ in keys),
  686. )
  687. txn.execute(sql, vals)
  688. async def simple_insert_many(
  689. self, table: str, values: List[Dict[str, Any]], desc: str
  690. ) -> None:
  691. """Executes an INSERT query on the named table.
  692. Args:
  693. table: string giving the table name
  694. values: dict of new column names and values for them
  695. desc: description of the transaction, for logging and metrics
  696. """
  697. await self.runInteraction(desc, self.simple_insert_many_txn, table, values)
  698. @staticmethod
  699. def simple_insert_many_txn(
  700. txn: LoggingTransaction, table: str, values: List[Dict[str, Any]]
  701. ) -> None:
  702. """Executes an INSERT query on the named table.
  703. Args:
  704. txn: The transaction to use.
  705. table: string giving the table name
  706. values: dict of new column names and values for them
  707. """
  708. if not values:
  709. return
  710. # This is a *slight* abomination to get a list of tuples of key names
  711. # and a list of tuples of value names.
  712. #
  713. # i.e. [{"a": 1, "b": 2}, {"c": 3, "d": 4}]
  714. # => [("a", "b",), ("c", "d",)] and [(1, 2,), (3, 4,)]
  715. #
  716. # The sort is to ensure that we don't rely on dictionary iteration
  717. # order.
  718. keys, vals = zip(
  719. *[zip(*(sorted(i.items(), key=lambda kv: kv[0]))) for i in values if i]
  720. )
  721. for k in keys:
  722. if k != keys[0]:
  723. raise RuntimeError("All items must have the same keys")
  724. sql = "INSERT INTO %s (%s) VALUES(%s)" % (
  725. table,
  726. ", ".join(k for k in keys[0]),
  727. ", ".join("?" for _ in keys[0]),
  728. )
  729. txn.executemany(sql, vals)
  730. async def simple_upsert(
  731. self,
  732. table: str,
  733. keyvalues: Dict[str, Any],
  734. values: Dict[str, Any],
  735. insertion_values: Dict[str, Any] = {},
  736. desc: str = "simple_upsert",
  737. lock: bool = True,
  738. ) -> Optional[bool]:
  739. """
  740. `lock` should generally be set to True (the default), but can be set
  741. to False if either of the following are true:
  742. * there is a UNIQUE INDEX on the key columns. In this case a conflict
  743. will cause an IntegrityError in which case this function will retry
  744. the update.
  745. * we somehow know that we are the only thread which will be updating
  746. this table.
  747. Args:
  748. table: The table to upsert into
  749. keyvalues: The unique key columns and their new values
  750. values: The nonunique columns and their new values
  751. insertion_values: additional key/values to use only when inserting
  752. desc: description of the transaction, for logging and metrics
  753. lock: True to lock the table when doing the upsert.
  754. Returns:
  755. Native upserts always return None. Emulated upserts return True if a
  756. new entry was created, False if an existing one was updated.
  757. """
  758. attempts = 0
  759. while True:
  760. try:
  761. # We can autocommit if we are going to use native upserts
  762. autocommit = (
  763. self.engine.can_native_upsert
  764. and table not in self._unsafe_to_upsert_tables
  765. )
  766. return await self.runInteraction(
  767. desc,
  768. self.simple_upsert_txn,
  769. table,
  770. keyvalues,
  771. values,
  772. insertion_values,
  773. lock=lock,
  774. db_autocommit=autocommit,
  775. )
  776. except self.engine.module.IntegrityError as e:
  777. attempts += 1
  778. if attempts >= 5:
  779. # don't retry forever, because things other than races
  780. # can cause IntegrityErrors
  781. raise
  782. # presumably we raced with another transaction: let's retry.
  783. logger.warning(
  784. "IntegrityError when upserting into %s; retrying: %s", table, e
  785. )
  786. def simple_upsert_txn(
  787. self,
  788. txn: LoggingTransaction,
  789. table: str,
  790. keyvalues: Dict[str, Any],
  791. values: Dict[str, Any],
  792. insertion_values: Dict[str, Any] = {},
  793. lock: bool = True,
  794. ) -> Optional[bool]:
  795. """
  796. Pick the UPSERT method which works best on the platform. Either the
  797. native one (Pg9.5+, recent SQLites), or fall back to an emulated method.
  798. Args:
  799. txn: The transaction to use.
  800. table: The table to upsert into
  801. keyvalues: The unique key tables and their new values
  802. values: The nonunique columns and their new values
  803. insertion_values: additional key/values to use only when inserting
  804. lock: True to lock the table when doing the upsert.
  805. Returns:
  806. Native upserts always return None. Emulated upserts return True if a
  807. new entry was created, False if an existing one was updated.
  808. """
  809. if self.engine.can_native_upsert and table not in self._unsafe_to_upsert_tables:
  810. self.simple_upsert_txn_native_upsert(
  811. txn, table, keyvalues, values, insertion_values=insertion_values
  812. )
  813. return None
  814. else:
  815. return self.simple_upsert_txn_emulated(
  816. txn,
  817. table,
  818. keyvalues,
  819. values,
  820. insertion_values=insertion_values,
  821. lock=lock,
  822. )
  823. def simple_upsert_txn_emulated(
  824. self,
  825. txn: LoggingTransaction,
  826. table: str,
  827. keyvalues: Dict[str, Any],
  828. values: Dict[str, Any],
  829. insertion_values: Dict[str, Any] = {},
  830. lock: bool = True,
  831. ) -> bool:
  832. """
  833. Args:
  834. table: The table to upsert into
  835. keyvalues: The unique key tables and their new values
  836. values: The nonunique columns and their new values
  837. insertion_values: additional key/values to use only when inserting
  838. lock: True to lock the table when doing the upsert.
  839. Returns:
  840. Returns True if a new entry was created, False if an existing
  841. one was updated.
  842. """
  843. # We need to lock the table :(, unless we're *really* careful
  844. if lock:
  845. self.engine.lock_table(txn, table)
  846. def _getwhere(key):
  847. # If the value we're passing in is None (aka NULL), we need to use
  848. # IS, not =, as NULL = NULL equals NULL (False).
  849. if keyvalues[key] is None:
  850. return "%s IS ?" % (key,)
  851. else:
  852. return "%s = ?" % (key,)
  853. if not values:
  854. # If `values` is empty, then all of the values we care about are in
  855. # the unique key, so there is nothing to UPDATE. We can just do a
  856. # SELECT instead to see if it exists.
  857. sql = "SELECT 1 FROM %s WHERE %s" % (
  858. table,
  859. " AND ".join(_getwhere(k) for k in keyvalues),
  860. )
  861. sqlargs = list(keyvalues.values())
  862. txn.execute(sql, sqlargs)
  863. if txn.fetchall():
  864. # We have an existing record.
  865. return False
  866. else:
  867. # First try to update.
  868. sql = "UPDATE %s SET %s WHERE %s" % (
  869. table,
  870. ", ".join("%s = ?" % (k,) for k in values),
  871. " AND ".join(_getwhere(k) for k in keyvalues),
  872. )
  873. sqlargs = list(values.values()) + list(keyvalues.values())
  874. txn.execute(sql, sqlargs)
  875. if txn.rowcount > 0:
  876. # successfully updated at least one row.
  877. return False
  878. # We didn't find any existing rows, so insert a new one
  879. allvalues = {} # type: Dict[str, Any]
  880. allvalues.update(keyvalues)
  881. allvalues.update(values)
  882. allvalues.update(insertion_values)
  883. sql = "INSERT INTO %s (%s) VALUES (%s)" % (
  884. table,
  885. ", ".join(k for k in allvalues),
  886. ", ".join("?" for _ in allvalues),
  887. )
  888. txn.execute(sql, list(allvalues.values()))
  889. # successfully inserted
  890. return True
  891. def simple_upsert_txn_native_upsert(
  892. self,
  893. txn: LoggingTransaction,
  894. table: str,
  895. keyvalues: Dict[str, Any],
  896. values: Dict[str, Any],
  897. insertion_values: Dict[str, Any] = {},
  898. ) -> None:
  899. """
  900. Use the native UPSERT functionality in recent PostgreSQL versions.
  901. Args:
  902. table: The table to upsert into
  903. keyvalues: The unique key tables and their new values
  904. values: The nonunique columns and their new values
  905. insertion_values: additional key/values to use only when inserting
  906. """
  907. allvalues = {} # type: Dict[str, Any]
  908. allvalues.update(keyvalues)
  909. allvalues.update(insertion_values)
  910. if not values:
  911. latter = "NOTHING"
  912. else:
  913. allvalues.update(values)
  914. latter = "UPDATE SET " + ", ".join(k + "=EXCLUDED." + k for k in values)
  915. sql = ("INSERT INTO %s (%s) VALUES (%s) ON CONFLICT (%s) DO %s") % (
  916. table,
  917. ", ".join(k for k in allvalues),
  918. ", ".join("?" for _ in allvalues),
  919. ", ".join(k for k in keyvalues),
  920. latter,
  921. )
  922. txn.execute(sql, list(allvalues.values()))
  923. async def simple_upsert_many(
  924. self,
  925. table: str,
  926. key_names: Collection[str],
  927. key_values: Collection[Iterable[Any]],
  928. value_names: Collection[str],
  929. value_values: Iterable[Iterable[Any]],
  930. desc: str,
  931. ) -> None:
  932. """
  933. Upsert, many times.
  934. Args:
  935. table: The table to upsert into
  936. key_names: The key column names.
  937. key_values: A list of each row's key column values.
  938. value_names: The value column names
  939. value_values: A list of each row's value column values.
  940. Ignored if value_names is empty.
  941. """
  942. # We can autocommit if we are going to use native upserts
  943. autocommit = (
  944. self.engine.can_native_upsert and table not in self._unsafe_to_upsert_tables
  945. )
  946. return await self.runInteraction(
  947. desc,
  948. self.simple_upsert_many_txn,
  949. table,
  950. key_names,
  951. key_values,
  952. value_names,
  953. value_values,
  954. db_autocommit=autocommit,
  955. )
  956. def simple_upsert_many_txn(
  957. self,
  958. txn: LoggingTransaction,
  959. table: str,
  960. key_names: Collection[str],
  961. key_values: Collection[Iterable[Any]],
  962. value_names: Collection[str],
  963. value_values: Iterable[Iterable[Any]],
  964. ) -> None:
  965. """
  966. Upsert, many times.
  967. Args:
  968. table: The table to upsert into
  969. key_names: The key column names.
  970. key_values: A list of each row's key column values.
  971. value_names: The value column names
  972. value_values: A list of each row's value column values.
  973. Ignored if value_names is empty.
  974. """
  975. if self.engine.can_native_upsert and table not in self._unsafe_to_upsert_tables:
  976. return self.simple_upsert_many_txn_native_upsert(
  977. txn, table, key_names, key_values, value_names, value_values
  978. )
  979. else:
  980. return self.simple_upsert_many_txn_emulated(
  981. txn, table, key_names, key_values, value_names, value_values
  982. )
  983. def simple_upsert_many_txn_emulated(
  984. self,
  985. txn: LoggingTransaction,
  986. table: str,
  987. key_names: Iterable[str],
  988. key_values: Collection[Iterable[Any]],
  989. value_names: Collection[str],
  990. value_values: Iterable[Iterable[Any]],
  991. ) -> None:
  992. """
  993. Upsert, many times, but without native UPSERT support or batching.
  994. Args:
  995. table: The table to upsert into
  996. key_names: The key column names.
  997. key_values: A list of each row's key column values.
  998. value_names: The value column names
  999. value_values: A list of each row's value column values.
  1000. Ignored if value_names is empty.
  1001. """
  1002. # No value columns, therefore make a blank list so that the following
  1003. # zip() works correctly.
  1004. if not value_names:
  1005. value_values = [() for x in range(len(key_values))]
  1006. for keyv, valv in zip(key_values, value_values):
  1007. _keys = {x: y for x, y in zip(key_names, keyv)}
  1008. _vals = {x: y for x, y in zip(value_names, valv)}
  1009. self.simple_upsert_txn_emulated(txn, table, _keys, _vals)
  1010. def simple_upsert_many_txn_native_upsert(
  1011. self,
  1012. txn: LoggingTransaction,
  1013. table: str,
  1014. key_names: Collection[str],
  1015. key_values: Collection[Iterable[Any]],
  1016. value_names: Collection[str],
  1017. value_values: Iterable[Iterable[Any]],
  1018. ) -> None:
  1019. """
  1020. Upsert, many times, using batching where possible.
  1021. Args:
  1022. table: The table to upsert into
  1023. key_names: The key column names.
  1024. key_values: A list of each row's key column values.
  1025. value_names: The value column names
  1026. value_values: A list of each row's value column values.
  1027. Ignored if value_names is empty.
  1028. """
  1029. allnames = [] # type: List[str]
  1030. allnames.extend(key_names)
  1031. allnames.extend(value_names)
  1032. if not value_names:
  1033. # No value columns, therefore make a blank list so that the
  1034. # following zip() works correctly.
  1035. latter = "NOTHING"
  1036. value_values = [() for x in range(len(key_values))]
  1037. else:
  1038. latter = "UPDATE SET " + ", ".join(
  1039. k + "=EXCLUDED." + k for k in value_names
  1040. )
  1041. sql = "INSERT INTO %s (%s) VALUES (%s) ON CONFLICT (%s) DO %s" % (
  1042. table,
  1043. ", ".join(k for k in allnames),
  1044. ", ".join("?" for _ in allnames),
  1045. ", ".join(key_names),
  1046. latter,
  1047. )
  1048. args = []
  1049. for x, y in zip(key_values, value_values):
  1050. args.append(tuple(x) + tuple(y))
  1051. return txn.execute_batch(sql, args)
  1052. @overload
  1053. async def simple_select_one(
  1054. self,
  1055. table: str,
  1056. keyvalues: Dict[str, Any],
  1057. retcols: Iterable[str],
  1058. allow_none: Literal[False] = False,
  1059. desc: str = "simple_select_one",
  1060. ) -> Dict[str, Any]:
  1061. ...
  1062. @overload
  1063. async def simple_select_one(
  1064. self,
  1065. table: str,
  1066. keyvalues: Dict[str, Any],
  1067. retcols: Iterable[str],
  1068. allow_none: Literal[True] = True,
  1069. desc: str = "simple_select_one",
  1070. ) -> Optional[Dict[str, Any]]:
  1071. ...
  1072. async def simple_select_one(
  1073. self,
  1074. table: str,
  1075. keyvalues: Dict[str, Any],
  1076. retcols: Iterable[str],
  1077. allow_none: bool = False,
  1078. desc: str = "simple_select_one",
  1079. ) -> Optional[Dict[str, Any]]:
  1080. """Executes a SELECT query on the named table, which is expected to
  1081. return a single row, returning multiple columns from it.
  1082. Args:
  1083. table: string giving the table name
  1084. keyvalues: dict of column names and values to select the row with
  1085. retcols: list of strings giving the names of the columns to return
  1086. allow_none: If true, return None instead of failing if the SELECT
  1087. statement returns no rows
  1088. desc: description of the transaction, for logging and metrics
  1089. """
  1090. return await self.runInteraction(
  1091. desc,
  1092. self.simple_select_one_txn,
  1093. table,
  1094. keyvalues,
  1095. retcols,
  1096. allow_none,
  1097. db_autocommit=True,
  1098. )
  1099. @overload
  1100. async def simple_select_one_onecol(
  1101. self,
  1102. table: str,
  1103. keyvalues: Dict[str, Any],
  1104. retcol: str,
  1105. allow_none: Literal[False] = False,
  1106. desc: str = "simple_select_one_onecol",
  1107. ) -> Any:
  1108. ...
  1109. @overload
  1110. async def simple_select_one_onecol(
  1111. self,
  1112. table: str,
  1113. keyvalues: Dict[str, Any],
  1114. retcol: str,
  1115. allow_none: Literal[True] = True,
  1116. desc: str = "simple_select_one_onecol",
  1117. ) -> Optional[Any]:
  1118. ...
  1119. async def simple_select_one_onecol(
  1120. self,
  1121. table: str,
  1122. keyvalues: Dict[str, Any],
  1123. retcol: str,
  1124. allow_none: bool = False,
  1125. desc: str = "simple_select_one_onecol",
  1126. ) -> Optional[Any]:
  1127. """Executes a SELECT query on the named table, which is expected to
  1128. return a single row, returning a single column from it.
  1129. Args:
  1130. table: string giving the table name
  1131. keyvalues: dict of column names and values to select the row with
  1132. retcol: string giving the name of the column to return
  1133. allow_none: If true, return None instead of failing if the SELECT
  1134. statement returns no rows
  1135. desc: description of the transaction, for logging and metrics
  1136. """
  1137. return await self.runInteraction(
  1138. desc,
  1139. self.simple_select_one_onecol_txn,
  1140. table,
  1141. keyvalues,
  1142. retcol,
  1143. allow_none=allow_none,
  1144. db_autocommit=True,
  1145. )
  1146. @overload
  1147. @classmethod
  1148. def simple_select_one_onecol_txn(
  1149. cls,
  1150. txn: LoggingTransaction,
  1151. table: str,
  1152. keyvalues: Dict[str, Any],
  1153. retcol: str,
  1154. allow_none: Literal[False] = False,
  1155. ) -> Any:
  1156. ...
  1157. @overload
  1158. @classmethod
  1159. def simple_select_one_onecol_txn(
  1160. cls,
  1161. txn: LoggingTransaction,
  1162. table: str,
  1163. keyvalues: Dict[str, Any],
  1164. retcol: str,
  1165. allow_none: Literal[True] = True,
  1166. ) -> Optional[Any]:
  1167. ...
  1168. @classmethod
  1169. def simple_select_one_onecol_txn(
  1170. cls,
  1171. txn: LoggingTransaction,
  1172. table: str,
  1173. keyvalues: Dict[str, Any],
  1174. retcol: str,
  1175. allow_none: bool = False,
  1176. ) -> Optional[Any]:
  1177. ret = cls.simple_select_onecol_txn(
  1178. txn, table=table, keyvalues=keyvalues, retcol=retcol
  1179. )
  1180. if ret:
  1181. return ret[0]
  1182. else:
  1183. if allow_none:
  1184. return None
  1185. else:
  1186. raise StoreError(404, "No row found")
  1187. @staticmethod
  1188. def simple_select_onecol_txn(
  1189. txn: LoggingTransaction, table: str, keyvalues: Dict[str, Any], retcol: str,
  1190. ) -> List[Any]:
  1191. sql = ("SELECT %(retcol)s FROM %(table)s") % {"retcol": retcol, "table": table}
  1192. if keyvalues:
  1193. sql += " WHERE %s" % " AND ".join("%s = ?" % k for k in keyvalues.keys())
  1194. txn.execute(sql, list(keyvalues.values()))
  1195. else:
  1196. txn.execute(sql)
  1197. return [r[0] for r in txn]
  1198. async def simple_select_onecol(
  1199. self,
  1200. table: str,
  1201. keyvalues: Optional[Dict[str, Any]],
  1202. retcol: str,
  1203. desc: str = "simple_select_onecol",
  1204. ) -> List[Any]:
  1205. """Executes a SELECT query on the named table, which returns a list
  1206. comprising of the values of the named column from the selected rows.
  1207. Args:
  1208. table: table name
  1209. keyvalues: column names and values to select the rows with
  1210. retcol: column whos value we wish to retrieve.
  1211. desc: description of the transaction, for logging and metrics
  1212. Returns:
  1213. Results in a list
  1214. """
  1215. return await self.runInteraction(
  1216. desc,
  1217. self.simple_select_onecol_txn,
  1218. table,
  1219. keyvalues,
  1220. retcol,
  1221. db_autocommit=True,
  1222. )
  1223. async def simple_select_list(
  1224. self,
  1225. table: str,
  1226. keyvalues: Optional[Dict[str, Any]],
  1227. retcols: Iterable[str],
  1228. desc: str = "simple_select_list",
  1229. ) -> List[Dict[str, Any]]:
  1230. """Executes a SELECT query on the named table, which may return zero or
  1231. more rows, returning the result as a list of dicts.
  1232. Args:
  1233. table: the table name
  1234. keyvalues:
  1235. column names and values to select the rows with, or None to not
  1236. apply a WHERE clause.
  1237. retcols: the names of the columns to return
  1238. desc: description of the transaction, for logging and metrics
  1239. Returns:
  1240. A list of dictionaries.
  1241. """
  1242. return await self.runInteraction(
  1243. desc,
  1244. self.simple_select_list_txn,
  1245. table,
  1246. keyvalues,
  1247. retcols,
  1248. db_autocommit=True,
  1249. )
  1250. @classmethod
  1251. def simple_select_list_txn(
  1252. cls,
  1253. txn: LoggingTransaction,
  1254. table: str,
  1255. keyvalues: Optional[Dict[str, Any]],
  1256. retcols: Iterable[str],
  1257. ) -> List[Dict[str, Any]]:
  1258. """Executes a SELECT query on the named table, which may return zero or
  1259. more rows, returning the result as a list of dicts.
  1260. Args:
  1261. txn: Transaction object
  1262. table: the table name
  1263. keyvalues:
  1264. column names and values to select the rows with, or None to not
  1265. apply a WHERE clause.
  1266. retcols: the names of the columns to return
  1267. """
  1268. if keyvalues:
  1269. sql = "SELECT %s FROM %s WHERE %s" % (
  1270. ", ".join(retcols),
  1271. table,
  1272. " AND ".join("%s = ?" % (k,) for k in keyvalues),
  1273. )
  1274. txn.execute(sql, list(keyvalues.values()))
  1275. else:
  1276. sql = "SELECT %s FROM %s" % (", ".join(retcols), table)
  1277. txn.execute(sql)
  1278. return cls.cursor_to_dict(txn)
  1279. async def simple_select_many_batch(
  1280. self,
  1281. table: str,
  1282. column: str,
  1283. iterable: Iterable[Any],
  1284. retcols: Iterable[str],
  1285. keyvalues: Dict[str, Any] = {},
  1286. desc: str = "simple_select_many_batch",
  1287. batch_size: int = 100,
  1288. ) -> List[Any]:
  1289. """Executes a SELECT query on the named table, which may return zero or
  1290. more rows, returning the result as a list of dicts.
  1291. Filters rows by whether the value of `column` is in `iterable`.
  1292. Args:
  1293. table: string giving the table name
  1294. column: column name to test for inclusion against `iterable`
  1295. iterable: list
  1296. retcols: list of strings giving the names of the columns to return
  1297. keyvalues: dict of column names and values to select the rows with
  1298. desc: description of the transaction, for logging and metrics
  1299. batch_size: the number of rows for each select query
  1300. """
  1301. results = [] # type: List[Dict[str, Any]]
  1302. if not iterable:
  1303. return results
  1304. # iterables can not be sliced, so convert it to a list first
  1305. it_list = list(iterable)
  1306. chunks = [
  1307. it_list[i : i + batch_size] for i in range(0, len(it_list), batch_size)
  1308. ]
  1309. for chunk in chunks:
  1310. rows = await self.runInteraction(
  1311. desc,
  1312. self.simple_select_many_txn,
  1313. table,
  1314. column,
  1315. chunk,
  1316. keyvalues,
  1317. retcols,
  1318. db_autocommit=True,
  1319. )
  1320. results.extend(rows)
  1321. return results
  1322. @classmethod
  1323. def simple_select_many_txn(
  1324. cls,
  1325. txn: LoggingTransaction,
  1326. table: str,
  1327. column: str,
  1328. iterable: Iterable[Any],
  1329. keyvalues: Dict[str, Any],
  1330. retcols: Iterable[str],
  1331. ) -> List[Dict[str, Any]]:
  1332. """Executes a SELECT query on the named table, which may return zero or
  1333. more rows, returning the result as a list of dicts.
  1334. Filters rows by whether the value of `column` is in `iterable`.
  1335. Args:
  1336. txn: Transaction object
  1337. table: string giving the table name
  1338. column: column name to test for inclusion against `iterable`
  1339. iterable: list
  1340. keyvalues: dict of column names and values to select the rows with
  1341. retcols: list of strings giving the names of the columns to return
  1342. """
  1343. if not iterable:
  1344. return []
  1345. clause, values = make_in_list_sql_clause(txn.database_engine, column, iterable)
  1346. clauses = [clause]
  1347. for key, value in keyvalues.items():
  1348. clauses.append("%s = ?" % (key,))
  1349. values.append(value)
  1350. sql = "SELECT %s FROM %s WHERE %s" % (
  1351. ", ".join(retcols),
  1352. table,
  1353. " AND ".join(clauses),
  1354. )
  1355. txn.execute(sql, values)
  1356. return cls.cursor_to_dict(txn)
  1357. async def simple_update(
  1358. self,
  1359. table: str,
  1360. keyvalues: Dict[str, Any],
  1361. updatevalues: Dict[str, Any],
  1362. desc: str,
  1363. ) -> int:
  1364. return await self.runInteraction(
  1365. desc, self.simple_update_txn, table, keyvalues, updatevalues
  1366. )
  1367. @staticmethod
  1368. def simple_update_txn(
  1369. txn: LoggingTransaction,
  1370. table: str,
  1371. keyvalues: Dict[str, Any],
  1372. updatevalues: Dict[str, Any],
  1373. ) -> int:
  1374. if keyvalues:
  1375. where = "WHERE %s" % " AND ".join("%s = ?" % k for k in keyvalues.keys())
  1376. else:
  1377. where = ""
  1378. update_sql = "UPDATE %s SET %s %s" % (
  1379. table,
  1380. ", ".join("%s = ?" % (k,) for k in updatevalues),
  1381. where,
  1382. )
  1383. txn.execute(update_sql, list(updatevalues.values()) + list(keyvalues.values()))
  1384. return txn.rowcount
  1385. async def simple_update_one(
  1386. self,
  1387. table: str,
  1388. keyvalues: Dict[str, Any],
  1389. updatevalues: Dict[str, Any],
  1390. desc: str = "simple_update_one",
  1391. ) -> None:
  1392. """Executes an UPDATE query on the named table, setting new values for
  1393. columns in a row matching the key values.
  1394. Args:
  1395. table: string giving the table name
  1396. keyvalues: dict of column names and values to select the row with
  1397. updatevalues: dict giving column names and values to update
  1398. desc: description of the transaction, for logging and metrics
  1399. """
  1400. await self.runInteraction(
  1401. desc,
  1402. self.simple_update_one_txn,
  1403. table,
  1404. keyvalues,
  1405. updatevalues,
  1406. db_autocommit=True,
  1407. )
  1408. @classmethod
  1409. def simple_update_one_txn(
  1410. cls,
  1411. txn: LoggingTransaction,
  1412. table: str,
  1413. keyvalues: Dict[str, Any],
  1414. updatevalues: Dict[str, Any],
  1415. ) -> None:
  1416. rowcount = cls.simple_update_txn(txn, table, keyvalues, updatevalues)
  1417. if rowcount == 0:
  1418. raise StoreError(404, "No row found (%s)" % (table,))
  1419. if rowcount > 1:
  1420. raise StoreError(500, "More than one row matched (%s)" % (table,))
  1421. # Ideally we could use the overload decorator here to specify that the
  1422. # return type is only optional if allow_none is True, but this does not work
  1423. # when you call a static method from an instance.
  1424. # See https://github.com/python/mypy/issues/7781
  1425. @staticmethod
  1426. def simple_select_one_txn(
  1427. txn: LoggingTransaction,
  1428. table: str,
  1429. keyvalues: Dict[str, Any],
  1430. retcols: Iterable[str],
  1431. allow_none: bool = False,
  1432. ) -> Optional[Dict[str, Any]]:
  1433. select_sql = "SELECT %s FROM %s WHERE %s" % (
  1434. ", ".join(retcols),
  1435. table,
  1436. " AND ".join("%s = ?" % (k,) for k in keyvalues),
  1437. )
  1438. txn.execute(select_sql, list(keyvalues.values()))
  1439. row = txn.fetchone()
  1440. if not row:
  1441. if allow_none:
  1442. return None
  1443. raise StoreError(404, "No row found (%s)" % (table,))
  1444. if txn.rowcount > 1:
  1445. raise StoreError(500, "More than one row matched (%s)" % (table,))
  1446. return dict(zip(retcols, row))
  1447. async def simple_delete_one(
  1448. self, table: str, keyvalues: Dict[str, Any], desc: str = "simple_delete_one"
  1449. ) -> None:
  1450. """Executes a DELETE query on the named table, expecting to delete a
  1451. single row.
  1452. Args:
  1453. table: string giving the table name
  1454. keyvalues: dict of column names and values to select the row with
  1455. desc: description of the transaction, for logging and metrics
  1456. """
  1457. await self.runInteraction(
  1458. desc, self.simple_delete_one_txn, table, keyvalues, db_autocommit=True,
  1459. )
  1460. @staticmethod
  1461. def simple_delete_one_txn(
  1462. txn: LoggingTransaction, table: str, keyvalues: Dict[str, Any]
  1463. ) -> None:
  1464. """Executes a DELETE query on the named table, expecting to delete a
  1465. single row.
  1466. Args:
  1467. table: string giving the table name
  1468. keyvalues: dict of column names and values to select the row with
  1469. """
  1470. sql = "DELETE FROM %s WHERE %s" % (
  1471. table,
  1472. " AND ".join("%s = ?" % (k,) for k in keyvalues),
  1473. )
  1474. txn.execute(sql, list(keyvalues.values()))
  1475. if txn.rowcount == 0:
  1476. raise StoreError(404, "No row found (%s)" % (table,))
  1477. if txn.rowcount > 1:
  1478. raise StoreError(500, "More than one row matched (%s)" % (table,))
  1479. async def simple_delete(
  1480. self, table: str, keyvalues: Dict[str, Any], desc: str
  1481. ) -> int:
  1482. """Executes a DELETE query on the named table.
  1483. Filters rows by the key-value pairs.
  1484. Args:
  1485. table: string giving the table name
  1486. keyvalues: dict of column names and values to select the row with
  1487. desc: description of the transaction, for logging and metrics
  1488. Returns:
  1489. The number of deleted rows.
  1490. """
  1491. return await self.runInteraction(
  1492. desc, self.simple_delete_txn, table, keyvalues, db_autocommit=True
  1493. )
  1494. @staticmethod
  1495. def simple_delete_txn(
  1496. txn: LoggingTransaction, table: str, keyvalues: Dict[str, Any]
  1497. ) -> int:
  1498. """Executes a DELETE query on the named table.
  1499. Filters rows by the key-value pairs.
  1500. Args:
  1501. table: string giving the table name
  1502. keyvalues: dict of column names and values to select the row with
  1503. Returns:
  1504. The number of deleted rows.
  1505. """
  1506. sql = "DELETE FROM %s WHERE %s" % (
  1507. table,
  1508. " AND ".join("%s = ?" % (k,) for k in keyvalues),
  1509. )
  1510. txn.execute(sql, list(keyvalues.values()))
  1511. return txn.rowcount
  1512. async def simple_delete_many(
  1513. self,
  1514. table: str,
  1515. column: str,
  1516. iterable: Iterable[Any],
  1517. keyvalues: Dict[str, Any],
  1518. desc: str,
  1519. ) -> int:
  1520. """Executes a DELETE query on the named table.
  1521. Filters rows by if value of `column` is in `iterable`.
  1522. Args:
  1523. table: string giving the table name
  1524. column: column name to test for inclusion against `iterable`
  1525. iterable: list
  1526. keyvalues: dict of column names and values to select the rows with
  1527. desc: description of the transaction, for logging and metrics
  1528. Returns:
  1529. Number rows deleted
  1530. """
  1531. return await self.runInteraction(
  1532. desc,
  1533. self.simple_delete_many_txn,
  1534. table,
  1535. column,
  1536. iterable,
  1537. keyvalues,
  1538. db_autocommit=True,
  1539. )
  1540. @staticmethod
  1541. def simple_delete_many_txn(
  1542. txn: LoggingTransaction,
  1543. table: str,
  1544. column: str,
  1545. iterable: Iterable[Any],
  1546. keyvalues: Dict[str, Any],
  1547. ) -> int:
  1548. """Executes a DELETE query on the named table.
  1549. Filters rows by if value of `column` is in `iterable`.
  1550. Args:
  1551. txn: Transaction object
  1552. table: string giving the table name
  1553. column: column name to test for inclusion against `iterable`
  1554. iterable: list
  1555. keyvalues: dict of column names and values to select the rows with
  1556. Returns:
  1557. Number rows deleted
  1558. """
  1559. if not iterable:
  1560. return 0
  1561. sql = "DELETE FROM %s" % table
  1562. clause, values = make_in_list_sql_clause(txn.database_engine, column, iterable)
  1563. clauses = [clause]
  1564. for key, value in keyvalues.items():
  1565. clauses.append("%s = ?" % (key,))
  1566. values.append(value)
  1567. if clauses:
  1568. sql = "%s WHERE %s" % (sql, " AND ".join(clauses))
  1569. txn.execute(sql, values)
  1570. return txn.rowcount
  1571. def get_cache_dict(
  1572. self,
  1573. db_conn: LoggingDatabaseConnection,
  1574. table: str,
  1575. entity_column: str,
  1576. stream_column: str,
  1577. max_value: int,
  1578. limit: int = 100000,
  1579. ) -> Tuple[Dict[Any, int], int]:
  1580. # Fetch a mapping of room_id -> max stream position for "recent" rooms.
  1581. # It doesn't really matter how many we get, the StreamChangeCache will
  1582. # do the right thing to ensure it respects the max size of cache.
  1583. sql = (
  1584. "SELECT %(entity)s, MAX(%(stream)s) FROM %(table)s"
  1585. " WHERE %(stream)s > ? - %(limit)s"
  1586. " GROUP BY %(entity)s"
  1587. ) % {
  1588. "table": table,
  1589. "entity": entity_column,
  1590. "stream": stream_column,
  1591. "limit": limit,
  1592. }
  1593. txn = db_conn.cursor(txn_name="get_cache_dict")
  1594. txn.execute(sql, (int(max_value),))
  1595. cache = {row[0]: int(row[1]) for row in txn}
  1596. txn.close()
  1597. if cache:
  1598. min_val = min(cache.values())
  1599. else:
  1600. min_val = max_value
  1601. return cache, min_val
  1602. @classmethod
  1603. def simple_select_list_paginate_txn(
  1604. cls,
  1605. txn: LoggingTransaction,
  1606. table: str,
  1607. orderby: str,
  1608. start: int,
  1609. limit: int,
  1610. retcols: Iterable[str],
  1611. filters: Optional[Dict[str, Any]] = None,
  1612. keyvalues: Optional[Dict[str, Any]] = None,
  1613. order_direction: str = "ASC",
  1614. ) -> List[Dict[str, Any]]:
  1615. """
  1616. Executes a SELECT query on the named table with start and limit,
  1617. of row numbers, which may return zero or number of rows from start to limit,
  1618. returning the result as a list of dicts.
  1619. Use `filters` to search attributes using SQL wildcards and/or `keyvalues` to
  1620. select attributes with exact matches. All constraints are joined together
  1621. using 'AND'.
  1622. Args:
  1623. txn: Transaction object
  1624. table: the table name
  1625. orderby: Column to order the results by.
  1626. start: Index to begin the query at.
  1627. limit: Number of results to return.
  1628. retcols: the names of the columns to return
  1629. filters:
  1630. column names and values to filter the rows with, or None to not
  1631. apply a WHERE ? LIKE ? clause.
  1632. keyvalues:
  1633. column names and values to select the rows with, or None to not
  1634. apply a WHERE clause.
  1635. order_direction: Whether the results should be ordered "ASC" or "DESC".
  1636. Returns:
  1637. The result as a list of dictionaries.
  1638. """
  1639. if order_direction not in ["ASC", "DESC"]:
  1640. raise ValueError("order_direction must be one of 'ASC' or 'DESC'.")
  1641. where_clause = "WHERE " if filters or keyvalues else ""
  1642. arg_list = [] # type: List[Any]
  1643. if filters:
  1644. where_clause += " AND ".join("%s LIKE ?" % (k,) for k in filters)
  1645. arg_list += list(filters.values())
  1646. where_clause += " AND " if filters and keyvalues else ""
  1647. if keyvalues:
  1648. where_clause += " AND ".join("%s = ?" % (k,) for k in keyvalues)
  1649. arg_list += list(keyvalues.values())
  1650. sql = "SELECT %s FROM %s %s ORDER BY %s %s LIMIT ? OFFSET ?" % (
  1651. ", ".join(retcols),
  1652. table,
  1653. where_clause,
  1654. orderby,
  1655. order_direction,
  1656. )
  1657. txn.execute(sql, arg_list + [limit, start])
  1658. return cls.cursor_to_dict(txn)
  1659. async def simple_search_list(
  1660. self,
  1661. table: str,
  1662. term: Optional[str],
  1663. col: str,
  1664. retcols: Iterable[str],
  1665. desc="simple_search_list",
  1666. ) -> Optional[List[Dict[str, Any]]]:
  1667. """Executes a SELECT query on the named table, which may return zero or
  1668. more rows, returning the result as a list of dicts.
  1669. Args:
  1670. table: the table name
  1671. term: term for searching the table matched to a column.
  1672. col: column to query term should be matched to
  1673. retcols: the names of the columns to return
  1674. Returns:
  1675. A list of dictionaries or None.
  1676. """
  1677. return await self.runInteraction(
  1678. desc,
  1679. self.simple_search_list_txn,
  1680. table,
  1681. term,
  1682. col,
  1683. retcols,
  1684. db_autocommit=True,
  1685. )
  1686. @classmethod
  1687. def simple_search_list_txn(
  1688. cls,
  1689. txn: LoggingTransaction,
  1690. table: str,
  1691. term: Optional[str],
  1692. col: str,
  1693. retcols: Iterable[str],
  1694. ) -> Optional[List[Dict[str, Any]]]:
  1695. """Executes a SELECT query on the named table, which may return zero or
  1696. more rows, returning the result as a list of dicts.
  1697. Args:
  1698. txn: Transaction object
  1699. table: the table name
  1700. term: term for searching the table matched to a column.
  1701. col: column to query term should be matched to
  1702. retcols: the names of the columns to return
  1703. Returns:
  1704. None if no term is given, otherwise a list of dictionaries.
  1705. """
  1706. if term:
  1707. sql = "SELECT %s FROM %s WHERE %s LIKE ?" % (", ".join(retcols), table, col)
  1708. termvalues = ["%%" + term + "%%"]
  1709. txn.execute(sql, termvalues)
  1710. else:
  1711. return None
  1712. return cls.cursor_to_dict(txn)
  1713. def make_in_list_sql_clause(
  1714. database_engine: BaseDatabaseEngine, column: str, iterable: Iterable
  1715. ) -> Tuple[str, list]:
  1716. """Returns an SQL clause that checks the given column is in the iterable.
  1717. On SQLite this expands to `column IN (?, ?, ...)`, whereas on Postgres
  1718. it expands to `column = ANY(?)`. While both DBs support the `IN` form,
  1719. using the `ANY` form on postgres means that it views queries with
  1720. different length iterables as the same, helping the query stats.
  1721. Args:
  1722. database_engine
  1723. column: Name of the column
  1724. iterable: The values to check the column against.
  1725. Returns:
  1726. A tuple of SQL query and the args
  1727. """
  1728. if database_engine.supports_using_any_list:
  1729. # This should hopefully be faster, but also makes postgres query
  1730. # stats easier to understand.
  1731. return "%s = ANY(?)" % (column,), [list(iterable)]
  1732. else:
  1733. return "%s IN (%s)" % (column, ",".join("?" for _ in iterable)), list(iterable)
  1734. KV = TypeVar("KV")
  1735. def make_tuple_comparison_clause(
  1736. database_engine: BaseDatabaseEngine, keys: List[Tuple[str, KV]]
  1737. ) -> Tuple[str, List[KV]]:
  1738. """Returns a tuple comparison SQL clause
  1739. Depending what the SQL engine supports, builds a SQL clause that looks like either
  1740. "(a, b) > (?, ?)", or "(a > ?) OR (a == ? AND b > ?)".
  1741. Args:
  1742. database_engine
  1743. keys: A set of (column, value) pairs to be compared.
  1744. Returns:
  1745. A tuple of SQL query and the args
  1746. """
  1747. if database_engine.supports_tuple_comparison:
  1748. return (
  1749. "(%s) > (%s)" % (",".join(k[0] for k in keys), ",".join("?" for _ in keys)),
  1750. [k[1] for k in keys],
  1751. )
  1752. # we want to build a clause
  1753. # (a > ?) OR
  1754. # (a == ? AND b > ?) OR
  1755. # (a == ? AND b == ? AND c > ?)
  1756. # ...
  1757. # (a == ? AND b == ? AND ... AND z > ?)
  1758. #
  1759. # or, equivalently:
  1760. #
  1761. # (a > ? OR (a == ? AND
  1762. # (b > ? OR (b == ? AND
  1763. # ...
  1764. # (y > ? OR (y == ? AND
  1765. # z > ?
  1766. # ))
  1767. # ...
  1768. # ))
  1769. # ))
  1770. #
  1771. # which itself is equivalent to (and apparently easier for the query optimiser):
  1772. #
  1773. # (a >= ? AND (a > ? OR
  1774. # (b >= ? AND (b > ? OR
  1775. # ...
  1776. # (y >= ? AND (y > ? OR
  1777. # z > ?
  1778. # ))
  1779. # ...
  1780. # ))
  1781. # ))
  1782. #
  1783. #
  1784. clause = ""
  1785. args = [] # type: List[KV]
  1786. for k, v in keys[:-1]:
  1787. clause = clause + "(%s >= ? AND (%s > ? OR " % (k, k)
  1788. args.extend([v, v])
  1789. (k, v) = keys[-1]
  1790. clause += "%s > ?" % (k,)
  1791. args.append(v)
  1792. clause += "))" * (len(keys) - 1)
  1793. return clause, args