You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

2569 rivejä
92 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2017-2018 New Vector Ltd
  3. # Copyright 2019 The Matrix.org Foundation C.I.C.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import inspect
  17. import logging
  18. import time
  19. import types
  20. from collections import defaultdict
  21. from time import monotonic as monotonic_time
  22. from typing import (
  23. TYPE_CHECKING,
  24. Any,
  25. Awaitable,
  26. Callable,
  27. Collection,
  28. Dict,
  29. Iterable,
  30. Iterator,
  31. List,
  32. Optional,
  33. Sequence,
  34. Tuple,
  35. Type,
  36. TypeVar,
  37. cast,
  38. overload,
  39. )
  40. import attr
  41. from prometheus_client import Counter, Histogram
  42. from typing_extensions import Concatenate, Literal, ParamSpec
  43. from twisted.enterprise import adbapi
  44. from twisted.internet.interfaces import IReactorCore
  45. from synapse.api.errors import StoreError
  46. from synapse.config.database import DatabaseConnectionConfig
  47. from synapse.logging import opentracing
  48. from synapse.logging.context import (
  49. LoggingContext,
  50. current_context,
  51. make_deferred_yieldable,
  52. )
  53. from synapse.metrics import LaterGauge, register_threadpool
  54. from synapse.metrics.background_process_metrics import run_as_background_process
  55. from synapse.storage.background_updates import BackgroundUpdater
  56. from synapse.storage.engines import BaseDatabaseEngine, PostgresEngine, Sqlite3Engine
  57. from synapse.storage.types import Connection, Cursor, SQLQueryParameters
  58. from synapse.util.async_helpers import delay_cancellation
  59. from synapse.util.iterutils import batch_iter
  60. if TYPE_CHECKING:
  61. from synapse.server import HomeServer
  62. # python 3 does not have a maximum int value
  63. MAX_TXN_ID = 2**63 - 1
  64. logger = logging.getLogger(__name__)
  65. sql_logger = logging.getLogger("synapse.storage.SQL")
  66. transaction_logger = logging.getLogger("synapse.storage.txn")
  67. perf_logger = logging.getLogger("synapse.storage.TIME")
  68. sql_scheduling_timer = Histogram("synapse_storage_schedule_time", "sec")
  69. sql_query_timer = Histogram("synapse_storage_query_time", "sec", ["verb"])
  70. sql_txn_count = Counter("synapse_storage_transaction_time_count", "sec", ["desc"])
  71. sql_txn_duration = Counter("synapse_storage_transaction_time_sum", "sec", ["desc"])
  72. # Unique indexes which have been added in background updates. Maps from table name
  73. # to the name of the background update which added the unique index to that table.
  74. #
  75. # This is used by the upsert logic to figure out which tables are safe to do a proper
  76. # UPSERT on: until the relevant background update has completed, we
  77. # have to emulate an upsert by locking the table.
  78. #
  79. UNIQUE_INDEX_BACKGROUND_UPDATES = {
  80. "user_ips": "user_ips_device_unique_index",
  81. "device_lists_remote_extremeties": "device_lists_remote_extremeties_unique_idx",
  82. "device_lists_remote_cache": "device_lists_remote_cache_unique_idx",
  83. "event_search": "event_search_event_id_idx",
  84. "local_media_repository_thumbnails": "local_media_repository_thumbnails_method_idx",
  85. "remote_media_cache_thumbnails": "remote_media_repository_thumbnails_method_idx",
  86. "event_push_summary": "event_push_summary_unique_index2",
  87. "receipts_linearized": "receipts_linearized_unique_index",
  88. "receipts_graph": "receipts_graph_unique_index",
  89. }
  90. class _PoolConnection(Connection):
  91. """
  92. A Connection from twisted.enterprise.adbapi.Connection.
  93. """
  94. def reconnect(self) -> None:
  95. ...
  96. def make_pool(
  97. reactor: IReactorCore,
  98. db_config: DatabaseConnectionConfig,
  99. engine: BaseDatabaseEngine,
  100. ) -> adbapi.ConnectionPool:
  101. """Get the connection pool for the database."""
  102. # By default enable `cp_reconnect`. We need to fiddle with db_args in case
  103. # someone has explicitly set `cp_reconnect`.
  104. db_args = dict(db_config.config.get("args", {}))
  105. db_args.setdefault("cp_reconnect", True)
  106. def _on_new_connection(conn: Connection) -> None:
  107. # Ensure we have a logging context so we can correctly track queries,
  108. # etc.
  109. with LoggingContext("db.on_new_connection"):
  110. engine.on_new_connection(
  111. LoggingDatabaseConnection(conn, engine, "on_new_connection")
  112. )
  113. connection_pool = adbapi.ConnectionPool(
  114. db_config.config["name"],
  115. cp_reactor=reactor,
  116. cp_openfun=_on_new_connection,
  117. **db_args,
  118. )
  119. register_threadpool(f"database-{db_config.name}", connection_pool.threadpool)
  120. return connection_pool
  121. def make_conn(
  122. db_config: DatabaseConnectionConfig,
  123. engine: BaseDatabaseEngine,
  124. default_txn_name: str,
  125. ) -> "LoggingDatabaseConnection":
  126. """Make a new connection to the database and return it.
  127. Returns:
  128. Connection
  129. """
  130. db_params = {
  131. k: v
  132. for k, v in db_config.config.get("args", {}).items()
  133. if not k.startswith("cp_")
  134. }
  135. native_db_conn = engine.module.connect(**db_params)
  136. db_conn = LoggingDatabaseConnection(native_db_conn, engine, default_txn_name)
  137. engine.on_new_connection(db_conn)
  138. return db_conn
  139. @attr.s(slots=True, auto_attribs=True)
  140. class LoggingDatabaseConnection:
  141. """A wrapper around a database connection that returns `LoggingTransaction`
  142. as its cursor class.
  143. This is mainly used on startup to ensure that queries get logged correctly
  144. """
  145. conn: Connection
  146. engine: BaseDatabaseEngine
  147. default_txn_name: str
  148. def cursor(
  149. self,
  150. *,
  151. txn_name: Optional[str] = None,
  152. after_callbacks: Optional[List["_CallbackListEntry"]] = None,
  153. async_after_callbacks: Optional[List["_AsyncCallbackListEntry"]] = None,
  154. exception_callbacks: Optional[List["_CallbackListEntry"]] = None,
  155. ) -> "LoggingTransaction":
  156. if not txn_name:
  157. txn_name = self.default_txn_name
  158. return LoggingTransaction(
  159. self.conn.cursor(),
  160. name=txn_name,
  161. database_engine=self.engine,
  162. after_callbacks=after_callbacks,
  163. async_after_callbacks=async_after_callbacks,
  164. exception_callbacks=exception_callbacks,
  165. )
  166. def close(self) -> None:
  167. self.conn.close()
  168. def commit(self) -> None:
  169. self.conn.commit()
  170. def rollback(self) -> None:
  171. self.conn.rollback()
  172. def __enter__(self) -> "LoggingDatabaseConnection":
  173. self.conn.__enter__()
  174. return self
  175. def __exit__(
  176. self,
  177. exc_type: Optional[Type[BaseException]],
  178. exc_value: Optional[BaseException],
  179. traceback: Optional[types.TracebackType],
  180. ) -> Optional[bool]:
  181. return self.conn.__exit__(exc_type, exc_value, traceback)
  182. # Proxy through any unknown lookups to the DB conn class.
  183. def __getattr__(self, name: str) -> Any:
  184. return getattr(self.conn, name)
  185. # The type of entry which goes on our after_callbacks and exception_callbacks lists.
  186. _CallbackListEntry = Tuple[Callable[..., object], Tuple[object, ...], Dict[str, object]]
  187. _AsyncCallbackListEntry = Tuple[
  188. Callable[..., Awaitable], Tuple[object, ...], Dict[str, object]
  189. ]
  190. P = ParamSpec("P")
  191. R = TypeVar("R")
  192. class LoggingTransaction:
  193. """An object that almost-transparently proxies for the 'txn' object
  194. passed to the constructor. Adds logging and metrics to the .execute()
  195. method.
  196. Args:
  197. txn: The database transaction object to wrap.
  198. name: The name of this transactions for logging.
  199. database_engine
  200. after_callbacks: A list that callbacks will be appended to
  201. that have been added by `call_after` which should be run on
  202. successful completion of the transaction. None indicates that no
  203. callbacks should be allowed to be scheduled to run.
  204. async_after_callbacks: A list that asynchronous callbacks will be appended
  205. to by `async_call_after` which should run, before after_callbacks, on
  206. successful completion of the transaction. None indicates that no
  207. callbacks should be allowed to be scheduled to run.
  208. exception_callbacks: A list that callbacks will be appended
  209. to that have been added by `call_on_exception` which should be run
  210. if transaction ends with an error. None indicates that no callbacks
  211. should be allowed to be scheduled to run.
  212. """
  213. __slots__ = [
  214. "txn",
  215. "name",
  216. "database_engine",
  217. "after_callbacks",
  218. "async_after_callbacks",
  219. "exception_callbacks",
  220. ]
  221. def __init__(
  222. self,
  223. txn: Cursor,
  224. name: str,
  225. database_engine: BaseDatabaseEngine,
  226. after_callbacks: Optional[List[_CallbackListEntry]] = None,
  227. async_after_callbacks: Optional[List[_AsyncCallbackListEntry]] = None,
  228. exception_callbacks: Optional[List[_CallbackListEntry]] = None,
  229. ):
  230. self.txn = txn
  231. self.name = name
  232. self.database_engine = database_engine
  233. self.after_callbacks = after_callbacks
  234. self.async_after_callbacks = async_after_callbacks
  235. self.exception_callbacks = exception_callbacks
  236. def call_after(
  237. self, callback: Callable[P, object], *args: P.args, **kwargs: P.kwargs
  238. ) -> None:
  239. """Call the given callback on the main twisted thread after the transaction has
  240. finished.
  241. Mostly used to invalidate the caches on the correct thread.
  242. Note that transactions may be retried a few times if they encounter database
  243. errors such as serialization failures. Callbacks given to `call_after`
  244. will accumulate across transaction attempts and will _all_ be called once a
  245. transaction attempt succeeds, regardless of whether previous transaction
  246. attempts failed. Otherwise, if all transaction attempts fail, all
  247. `call_on_exception` callbacks will be run instead.
  248. """
  249. # if self.after_callbacks is None, that means that whatever constructed the
  250. # LoggingTransaction isn't expecting there to be any callbacks; assert that
  251. # is not the case.
  252. assert self.after_callbacks is not None
  253. self.after_callbacks.append((callback, args, kwargs))
  254. def async_call_after(
  255. self, callback: Callable[P, Awaitable], *args: P.args, **kwargs: P.kwargs
  256. ) -> None:
  257. """Call the given asynchronous callback on the main twisted thread after
  258. the transaction has finished (but before those added in `call_after`).
  259. Mostly used to invalidate remote caches after transactions.
  260. Note that transactions may be retried a few times if they encounter database
  261. errors such as serialization failures. Callbacks given to `async_call_after`
  262. will accumulate across transaction attempts and will _all_ be called once a
  263. transaction attempt succeeds, regardless of whether previous transaction
  264. attempts failed. Otherwise, if all transaction attempts fail, all
  265. `call_on_exception` callbacks will be run instead.
  266. """
  267. # if self.async_after_callbacks is None, that means that whatever constructed the
  268. # LoggingTransaction isn't expecting there to be any callbacks; assert that
  269. # is not the case.
  270. assert self.async_after_callbacks is not None
  271. self.async_after_callbacks.append((callback, args, kwargs))
  272. def call_on_exception(
  273. self, callback: Callable[P, object], *args: P.args, **kwargs: P.kwargs
  274. ) -> None:
  275. """Call the given callback on the main twisted thread after the transaction has
  276. failed.
  277. Note that transactions may be retried a few times if they encounter database
  278. errors such as serialization failures. Callbacks given to `call_on_exception`
  279. will accumulate across transaction attempts and will _all_ be called once the
  280. final transaction attempt fails. No `call_on_exception` callbacks will be run
  281. if any transaction attempt succeeds.
  282. """
  283. # if self.exception_callbacks is None, that means that whatever constructed the
  284. # LoggingTransaction isn't expecting there to be any callbacks; assert that
  285. # is not the case.
  286. assert self.exception_callbacks is not None
  287. self.exception_callbacks.append((callback, args, kwargs))
  288. def fetchone(self) -> Optional[Tuple]:
  289. return self.txn.fetchone()
  290. def fetchmany(self, size: Optional[int] = None) -> List[Tuple]:
  291. return self.txn.fetchmany(size=size)
  292. def fetchall(self) -> List[Tuple]:
  293. return self.txn.fetchall()
  294. def __iter__(self) -> Iterator[Tuple]:
  295. return self.txn.__iter__()
  296. @property
  297. def rowcount(self) -> int:
  298. return self.txn.rowcount
  299. @property
  300. def description(
  301. self,
  302. ) -> Optional[Sequence[Any]]:
  303. return self.txn.description
  304. def execute_batch(self, sql: str, args: Iterable[Iterable[Any]]) -> None:
  305. """Similar to `executemany`, except `txn.rowcount` will not be correct
  306. afterwards.
  307. More efficient than `executemany` on PostgreSQL
  308. """
  309. if isinstance(self.database_engine, PostgresEngine):
  310. from psycopg2.extras import execute_batch
  311. # TODO: is it safe for values to be Iterable[Iterable[Any]] here?
  312. # https://www.psycopg.org/docs/extras.html?highlight=execute_batch#psycopg2.extras.execute_batch
  313. # suggests each arg in args should be a sequence or mapping
  314. self._do_execute(
  315. lambda the_sql: execute_batch(self.txn, the_sql, args), sql
  316. )
  317. else:
  318. # TODO: is it safe for values to be Iterable[Iterable[Any]] here?
  319. # https://docs.python.org/3/library/sqlite3.html?highlight=sqlite3#sqlite3.Cursor.executemany
  320. # suggests that the outer collection may be iterable, but
  321. # https://docs.python.org/3/library/sqlite3.html?highlight=sqlite3#how-to-use-placeholders-to-bind-values-in-sql-queries
  322. # suggests that the inner collection should be a sequence or dict.
  323. self.executemany(sql, args)
  324. def execute_values(
  325. self,
  326. sql: str,
  327. values: Iterable[Iterable[Any]],
  328. template: Optional[str] = None,
  329. fetch: bool = True,
  330. ) -> List[Tuple]:
  331. """Corresponds to psycopg2.extras.execute_values. Only available when
  332. using postgres.
  333. The `fetch` parameter must be set to False if the query does not return
  334. rows (e.g. INSERTs).
  335. The `template` is the snippet to merge to every item in argslist to
  336. compose the query.
  337. """
  338. assert isinstance(self.database_engine, PostgresEngine)
  339. from psycopg2.extras import execute_values
  340. return self._do_execute(
  341. # TODO: is it safe for values to be Iterable[Iterable[Any]] here?
  342. # https://www.psycopg.org/docs/extras.html?highlight=execute_batch#psycopg2.extras.execute_values says values should be Sequence[Sequence]
  343. lambda the_sql, the_values: execute_values(
  344. self.txn, the_sql, the_values, template=template, fetch=fetch
  345. ),
  346. sql,
  347. values,
  348. )
  349. def execute(self, sql: str, parameters: SQLQueryParameters = ()) -> None:
  350. self._do_execute(self.txn.execute, sql, parameters)
  351. def executemany(self, sql: str, *args: Any) -> None:
  352. """Repeatedly execute the same piece of SQL with different parameters.
  353. See https://peps.python.org/pep-0249/#executemany. Note in particular that
  354. > Use of this method for an operation which produces one or more result sets
  355. > constitutes undefined behavior
  356. so you can't use this for e.g. a SELECT, an UPDATE ... RETURNING, or a
  357. DELETE FROM... RETURNING.
  358. """
  359. # TODO: we should add a type for *args here. Looking at Cursor.executemany
  360. # and DBAPI2 it ought to be Sequence[_Parameter], but we pass in
  361. # Iterable[Iterable[Any]] in execute_batch and execute_values above, which mypy
  362. # complains about.
  363. self._do_execute(self.txn.executemany, sql, *args)
  364. def executescript(self, sql: str) -> None:
  365. if isinstance(self.database_engine, Sqlite3Engine):
  366. self._do_execute(self.txn.executescript, sql) # type: ignore[attr-defined]
  367. else:
  368. raise NotImplementedError(
  369. f"executescript only exists for sqlite driver, not {type(self.database_engine)}"
  370. )
  371. def _make_sql_one_line(self, sql: str) -> str:
  372. "Strip newlines out of SQL so that the loggers in the DB are on one line"
  373. return " ".join(line.strip() for line in sql.splitlines() if line.strip())
  374. def _do_execute(
  375. self,
  376. func: Callable[Concatenate[str, P], R],
  377. sql: str,
  378. *args: P.args,
  379. **kwargs: P.kwargs,
  380. ) -> R:
  381. # Generate a one-line version of the SQL to better log it.
  382. one_line_sql = self._make_sql_one_line(sql)
  383. # TODO(paul): Maybe use 'info' and 'debug' for values?
  384. sql_logger.debug("[SQL] {%s} %s", self.name, one_line_sql)
  385. sql = self.database_engine.convert_param_style(sql)
  386. if args:
  387. try:
  388. sql_logger.debug("[SQL values] {%s} %r", self.name, args[0])
  389. except Exception:
  390. # Don't let logging failures stop SQL from working
  391. pass
  392. start = time.time()
  393. try:
  394. with opentracing.start_active_span(
  395. "db.query",
  396. tags={
  397. opentracing.tags.DATABASE_TYPE: "sql",
  398. opentracing.tags.DATABASE_STATEMENT: one_line_sql,
  399. },
  400. ):
  401. return func(sql, *args, **kwargs)
  402. except Exception as e:
  403. sql_logger.debug("[SQL FAIL] {%s} %s", self.name, e)
  404. raise
  405. finally:
  406. secs = time.time() - start
  407. sql_logger.debug("[SQL time] {%s} %f sec", self.name, secs)
  408. sql_query_timer.labels(sql.split()[0]).observe(secs)
  409. def close(self) -> None:
  410. self.txn.close()
  411. def __enter__(self) -> "LoggingTransaction":
  412. return self
  413. def __exit__(
  414. self,
  415. exc_type: Optional[Type[BaseException]],
  416. exc_value: Optional[BaseException],
  417. traceback: Optional[types.TracebackType],
  418. ) -> None:
  419. self.close()
  420. class PerformanceCounters:
  421. def __init__(self) -> None:
  422. self.current_counters: Dict[str, Tuple[int, float]] = {}
  423. self.previous_counters: Dict[str, Tuple[int, float]] = {}
  424. def update(self, key: str, duration_secs: float) -> None:
  425. count, cum_time = self.current_counters.get(key, (0, 0.0))
  426. count += 1
  427. cum_time += duration_secs
  428. self.current_counters[key] = (count, cum_time)
  429. def interval(self, interval_duration_secs: float, limit: int = 3) -> str:
  430. counters = []
  431. for name, (count, cum_time) in self.current_counters.items():
  432. prev_count, prev_time = self.previous_counters.get(name, (0, 0))
  433. counters.append(
  434. (
  435. (cum_time - prev_time) / interval_duration_secs,
  436. count - prev_count,
  437. name,
  438. )
  439. )
  440. self.previous_counters = dict(self.current_counters)
  441. counters.sort(reverse=True)
  442. top_n_counters = ", ".join(
  443. "%s(%d): %.3f%%" % (name, count, 100 * ratio)
  444. for ratio, count, name in counters[:limit]
  445. )
  446. return top_n_counters
  447. class DatabasePool:
  448. """Wraps a single physical database and connection pool.
  449. A single database may be used by multiple data stores.
  450. """
  451. _TXN_ID = 0
  452. engine: BaseDatabaseEngine
  453. def __init__(
  454. self,
  455. hs: "HomeServer",
  456. database_config: DatabaseConnectionConfig,
  457. engine: BaseDatabaseEngine,
  458. ):
  459. self.hs = hs
  460. self._clock = hs.get_clock()
  461. self._txn_limit = database_config.config.get("txn_limit", 0)
  462. self._database_config = database_config
  463. self._db_pool = make_pool(hs.get_reactor(), database_config, engine)
  464. self.updates = BackgroundUpdater(hs, self)
  465. LaterGauge(
  466. "synapse_background_update_status",
  467. "Background update status",
  468. [],
  469. self.updates.get_status,
  470. )
  471. self._previous_txn_total_time = 0.0
  472. self._current_txn_total_time = 0.0
  473. self._previous_loop_ts = 0.0
  474. # Transaction counter: key is the twisted thread id, value is the current count
  475. self._txn_counters: Dict[int, int] = defaultdict(int)
  476. # TODO(paul): These can eventually be removed once the metrics code
  477. # is running in mainline, and we have some nice monitoring frontends
  478. # to watch it
  479. self._txn_perf_counters = PerformanceCounters()
  480. self.engine = engine
  481. # A set of tables that are not safe to use native upserts in.
  482. self._unsafe_to_upsert_tables = set(UNIQUE_INDEX_BACKGROUND_UPDATES.keys())
  483. # The user_directory_search table is unsafe to use native upserts
  484. # on SQLite because the existing search table does not have an index.
  485. if isinstance(self.engine, Sqlite3Engine):
  486. self._unsafe_to_upsert_tables.add("user_directory_search")
  487. # Check ASAP (and then later, every 1s) to see if we have finished
  488. # background updates of tables that aren't safe to update.
  489. self._clock.call_later(
  490. 0.0,
  491. run_as_background_process,
  492. "upsert_safety_check",
  493. self._check_safe_to_upsert,
  494. )
  495. def name(self) -> str:
  496. "Return the name of this database"
  497. return self._database_config.name
  498. def is_running(self) -> bool:
  499. """Is the database pool currently running"""
  500. return self._db_pool.running
  501. async def _check_safe_to_upsert(self) -> None:
  502. """
  503. Is it safe to use native UPSERT?
  504. If there are background updates, we will need to wait, as they may be
  505. the addition of indexes that set the UNIQUE constraint that we require.
  506. If the background updates have not completed, wait 15 sec and check again.
  507. """
  508. updates = cast(
  509. List[Tuple[str]],
  510. await self.simple_select_list(
  511. "background_updates",
  512. keyvalues=None,
  513. retcols=["update_name"],
  514. desc="check_background_updates",
  515. ),
  516. )
  517. background_update_names = [x[0] for x in updates]
  518. for table, update_name in UNIQUE_INDEX_BACKGROUND_UPDATES.items():
  519. if update_name not in background_update_names:
  520. logger.debug("Now safe to upsert in %s", table)
  521. self._unsafe_to_upsert_tables.discard(table)
  522. # If there's any updates still running, reschedule to run.
  523. if background_update_names:
  524. self._clock.call_later(
  525. 15.0,
  526. run_as_background_process,
  527. "upsert_safety_check",
  528. self._check_safe_to_upsert,
  529. )
  530. def start_profiling(self) -> None:
  531. self._previous_loop_ts = monotonic_time()
  532. def loop() -> None:
  533. curr = self._current_txn_total_time
  534. prev = self._previous_txn_total_time
  535. self._previous_txn_total_time = curr
  536. time_now = monotonic_time()
  537. time_then = self._previous_loop_ts
  538. self._previous_loop_ts = time_now
  539. duration = time_now - time_then
  540. ratio = (curr - prev) / duration
  541. top_three_counters = self._txn_perf_counters.interval(duration, limit=3)
  542. perf_logger.debug(
  543. "Total database time: %.3f%% {%s}", ratio * 100, top_three_counters
  544. )
  545. self._clock.looping_call(loop, 10000)
  546. def new_transaction(
  547. self,
  548. conn: LoggingDatabaseConnection,
  549. desc: str,
  550. after_callbacks: List[_CallbackListEntry],
  551. async_after_callbacks: List[_AsyncCallbackListEntry],
  552. exception_callbacks: List[_CallbackListEntry],
  553. func: Callable[Concatenate[LoggingTransaction, P], R],
  554. *args: P.args,
  555. **kwargs: P.kwargs,
  556. ) -> R:
  557. """Start a new database transaction with the given connection.
  558. Note: The given func may be called multiple times under certain
  559. failure modes. This is normally fine when in a standard transaction,
  560. but care must be taken if the connection is in `autocommit` mode that
  561. the function will correctly handle being aborted and retried half way
  562. through its execution.
  563. Similarly, the arguments to `func` (`args`, `kwargs`) should not be generators,
  564. since they could be evaluated multiple times (which would produce an empty
  565. result on the second or subsequent evaluation). Likewise, the closure of `func`
  566. must not reference any generators. This method attempts to detect such usage
  567. and will log an error.
  568. Args:
  569. conn
  570. desc
  571. after_callbacks
  572. async_after_callbacks
  573. exception_callbacks
  574. func
  575. *args
  576. **kwargs
  577. """
  578. # Robustness check: ensure that none of the arguments are generators, since that
  579. # will fail if we have to repeat the transaction.
  580. # For now, we just log an error, and hope that it works on the first attempt.
  581. # TODO: raise an exception.
  582. for i, arg in enumerate(args):
  583. if inspect.isgenerator(arg):
  584. logger.error(
  585. "Programming error: generator passed to new_transaction as "
  586. "argument %i to function %s",
  587. i,
  588. func,
  589. )
  590. for name, val in kwargs.items():
  591. if inspect.isgenerator(val):
  592. logger.error(
  593. "Programming error: generator passed to new_transaction as "
  594. "argument %s to function %s",
  595. name,
  596. func,
  597. )
  598. # also check variables referenced in func's closure
  599. if inspect.isfunction(func):
  600. # Keep the cast for now---it helps PyCharm to understand what `func` is.
  601. f = cast(types.FunctionType, func) # type: ignore[redundant-cast]
  602. if f.__closure__:
  603. for i, cell in enumerate(f.__closure__):
  604. try:
  605. contents = cell.cell_contents
  606. except ValueError:
  607. # cell.cell_contents can raise if the "cell" is empty,
  608. # which indicates that the variable is currently
  609. # unbound.
  610. continue
  611. if inspect.isgenerator(contents):
  612. logger.error(
  613. "Programming error: function %s references generator %s "
  614. "via its closure",
  615. f,
  616. f.__code__.co_freevars[i],
  617. )
  618. start = monotonic_time()
  619. txn_id = self._TXN_ID
  620. # We don't really need these to be unique, so lets stop it from
  621. # growing really large.
  622. self._TXN_ID = (self._TXN_ID + 1) % (MAX_TXN_ID)
  623. name = "%s-%x" % (desc, txn_id)
  624. transaction_logger.debug("[TXN START] {%s}", name)
  625. try:
  626. i = 0
  627. N = 5
  628. while True:
  629. cursor = conn.cursor(
  630. txn_name=name,
  631. after_callbacks=after_callbacks,
  632. async_after_callbacks=async_after_callbacks,
  633. exception_callbacks=exception_callbacks,
  634. )
  635. try:
  636. with opentracing.start_active_span(
  637. "db.txn",
  638. tags={
  639. opentracing.SynapseTags.DB_TXN_DESC: desc,
  640. opentracing.SynapseTags.DB_TXN_ID: name,
  641. },
  642. ):
  643. r = func(cursor, *args, **kwargs)
  644. opentracing.log_kv({"message": "commit"})
  645. conn.commit()
  646. return r
  647. except self.engine.module.OperationalError as e:
  648. # This can happen if the database disappears mid
  649. # transaction.
  650. transaction_logger.warning(
  651. "[TXN OPERROR] {%s} %s %d/%d",
  652. name,
  653. e,
  654. i,
  655. N,
  656. )
  657. if i < N:
  658. i += 1
  659. try:
  660. with opentracing.start_active_span("db.rollback"):
  661. conn.rollback()
  662. except self.engine.module.Error as e1:
  663. transaction_logger.warning("[TXN EROLL] {%s} %s", name, e1)
  664. continue
  665. raise
  666. except self.engine.module.DatabaseError as e:
  667. if self.engine.is_deadlock(e):
  668. transaction_logger.warning(
  669. "[TXN DEADLOCK] {%s} %d/%d", name, i, N
  670. )
  671. if i < N:
  672. i += 1
  673. try:
  674. with opentracing.start_active_span("db.rollback"):
  675. conn.rollback()
  676. except self.engine.module.Error as e1:
  677. transaction_logger.warning(
  678. "[TXN EROLL] {%s} %s",
  679. name,
  680. e1,
  681. )
  682. continue
  683. raise
  684. finally:
  685. # we're either about to retry with a new cursor, or we're about to
  686. # release the connection. Once we release the connection, it could
  687. # get used for another query, which might do a conn.rollback().
  688. #
  689. # In the latter case, even though that probably wouldn't affect the
  690. # results of this transaction, python's sqlite will reset all
  691. # statements on the connection [1], which will make our cursor
  692. # invalid [2].
  693. #
  694. # In any case, continuing to read rows after commit()ing seems
  695. # dubious from the PoV of ACID transactional semantics
  696. # (sqlite explicitly says that once you commit, you may see rows
  697. # from subsequent updates.)
  698. #
  699. # In psycopg2, cursors are essentially a client-side fabrication -
  700. # all the data is transferred to the client side when the statement
  701. # finishes executing - so in theory we could go on streaming results
  702. # from the cursor, but attempting to do so would make us
  703. # incompatible with sqlite, so let's make sure we're not doing that
  704. # by closing the cursor.
  705. #
  706. # (*named* cursors in psycopg2 are different and are proper server-
  707. # side things, but (a) we don't use them and (b) they are implicitly
  708. # closed by ending the transaction anyway.)
  709. #
  710. # In short, if we haven't finished with the cursor yet, that's a
  711. # problem waiting to bite us.
  712. #
  713. # TL;DR: we're done with the cursor, so we can close it.
  714. #
  715. # [1]: https://github.com/python/cpython/blob/v3.8.0/Modules/_sqlite/connection.c#L465
  716. # [2]: https://github.com/python/cpython/blob/v3.8.0/Modules/_sqlite/cursor.c#L236
  717. cursor.close()
  718. except Exception as e:
  719. transaction_logger.debug("[TXN FAIL] {%s} %s", name, e)
  720. raise
  721. finally:
  722. end = monotonic_time()
  723. duration = end - start
  724. current_context().add_database_transaction(duration)
  725. transaction_logger.debug("[TXN END] {%s} %f sec", name, duration)
  726. self._current_txn_total_time += duration
  727. self._txn_perf_counters.update(desc, duration)
  728. sql_txn_count.labels(desc).inc(1)
  729. sql_txn_duration.labels(desc).inc(duration)
  730. async def runInteraction(
  731. self,
  732. desc: str,
  733. func: Callable[..., R],
  734. *args: Any,
  735. db_autocommit: bool = False,
  736. isolation_level: Optional[int] = None,
  737. **kwargs: Any,
  738. ) -> R:
  739. """Starts a transaction on the database and runs a given function
  740. Arguments:
  741. desc: description of the transaction, for logging and metrics
  742. func: callback function, which will be called with a
  743. database transaction (twisted.enterprise.adbapi.Transaction) as
  744. its first argument, followed by `args` and `kwargs`.
  745. db_autocommit: Whether to run the function in "autocommit" mode,
  746. i.e. outside of a transaction. This is useful for transactions
  747. that are only a single query.
  748. Currently, this is only implemented for Postgres. SQLite will still
  749. run the function inside a transaction.
  750. WARNING: This means that if func fails half way through then
  751. the changes will *not* be rolled back. `func` may also get
  752. called multiple times if the transaction is retried, so must
  753. correctly handle that case.
  754. isolation_level: Set the server isolation level for this transaction.
  755. args: positional args to pass to `func`
  756. kwargs: named args to pass to `func`
  757. Returns:
  758. The result of func
  759. """
  760. async def _runInteraction() -> R:
  761. after_callbacks: List[_CallbackListEntry] = []
  762. async_after_callbacks: List[_AsyncCallbackListEntry] = []
  763. exception_callbacks: List[_CallbackListEntry] = []
  764. if not current_context():
  765. logger.warning("Starting db txn '%s' from sentinel context", desc)
  766. try:
  767. with opentracing.start_active_span(f"db.{desc}"):
  768. result = await self.runWithConnection(
  769. # mypy seems to have an issue with this, maybe a bug?
  770. self.new_transaction, # type: ignore[arg-type]
  771. desc,
  772. after_callbacks,
  773. async_after_callbacks,
  774. exception_callbacks,
  775. func,
  776. *args,
  777. db_autocommit=db_autocommit,
  778. isolation_level=isolation_level,
  779. **kwargs,
  780. )
  781. # We order these assuming that async functions call out to external
  782. # systems (e.g. to invalidate a cache) and the sync functions make these
  783. # changes on any local in-memory caches/similar, and thus must be second.
  784. for async_callback, async_args, async_kwargs in async_after_callbacks:
  785. await async_callback(*async_args, **async_kwargs)
  786. for after_callback, after_args, after_kwargs in after_callbacks:
  787. after_callback(*after_args, **after_kwargs)
  788. return cast(R, result)
  789. except Exception:
  790. for exception_callback, after_args, after_kwargs in exception_callbacks:
  791. exception_callback(*after_args, **after_kwargs)
  792. raise
  793. # To handle cancellation, we ensure that `after_callback`s and
  794. # `exception_callback`s are always run, since the transaction will complete
  795. # on another thread regardless of cancellation.
  796. #
  797. # We also wait until everything above is done before releasing the
  798. # `CancelledError`, so that logging contexts won't get used after they have been
  799. # finished.
  800. return await delay_cancellation(_runInteraction())
  801. async def runWithConnection(
  802. self,
  803. func: Callable[Concatenate[LoggingDatabaseConnection, P], R],
  804. *args: Any,
  805. db_autocommit: bool = False,
  806. isolation_level: Optional[int] = None,
  807. **kwargs: Any,
  808. ) -> R:
  809. """Wraps the .runWithConnection() method on the underlying db_pool.
  810. Arguments:
  811. func: callback function, which will be called with a
  812. database connection (twisted.enterprise.adbapi.Connection) as
  813. its first argument, followed by `args` and `kwargs`.
  814. args: positional args to pass to `func`
  815. db_autocommit: Whether to run the function in "autocommit" mode,
  816. i.e. outside of a transaction. This is useful for transaction
  817. that are only a single query. Currently only affects postgres.
  818. isolation_level: Set the server isolation level for this transaction.
  819. kwargs: named args to pass to `func`
  820. Returns:
  821. The result of func
  822. """
  823. curr_context = current_context()
  824. if not curr_context:
  825. logger.warning(
  826. "Starting db connection from sentinel context: metrics will be lost"
  827. )
  828. parent_context = None
  829. else:
  830. assert isinstance(curr_context, LoggingContext)
  831. parent_context = curr_context
  832. start_time = monotonic_time()
  833. def inner_func(conn: _PoolConnection, *args: P.args, **kwargs: P.kwargs) -> R:
  834. # We shouldn't be in a transaction. If we are then something
  835. # somewhere hasn't committed after doing work. (This is likely only
  836. # possible during startup, as `run*` will ensure changes are
  837. # committed/rolled back before putting the connection back in the
  838. # pool).
  839. assert not self.engine.in_transaction(conn)
  840. with LoggingContext(
  841. str(curr_context), parent_context=parent_context
  842. ) as context:
  843. with opentracing.start_active_span(
  844. operation_name="db.connection",
  845. ):
  846. sched_duration_sec = monotonic_time() - start_time
  847. sql_scheduling_timer.observe(sched_duration_sec)
  848. context.add_database_scheduled(sched_duration_sec)
  849. if self._txn_limit > 0:
  850. tid = self._db_pool.threadID()
  851. self._txn_counters[tid] += 1
  852. if self._txn_counters[tid] > self._txn_limit:
  853. logger.debug(
  854. "Reconnecting database connection over transaction limit"
  855. )
  856. conn.reconnect()
  857. opentracing.log_kv(
  858. {"message": "reconnected due to txn limit"}
  859. )
  860. self._txn_counters[tid] = 1
  861. if self.engine.is_connection_closed(conn):
  862. logger.debug("Reconnecting closed database connection")
  863. conn.reconnect()
  864. opentracing.log_kv({"message": "reconnected"})
  865. if self._txn_limit > 0:
  866. self._txn_counters[tid] = 1
  867. try:
  868. if db_autocommit:
  869. self.engine.attempt_to_set_autocommit(conn, True)
  870. if isolation_level is not None:
  871. self.engine.attempt_to_set_isolation_level(
  872. conn, isolation_level
  873. )
  874. db_conn = LoggingDatabaseConnection(
  875. conn, self.engine, "runWithConnection"
  876. )
  877. return func(db_conn, *args, **kwargs)
  878. finally:
  879. if db_autocommit:
  880. self.engine.attempt_to_set_autocommit(conn, False)
  881. if isolation_level:
  882. self.engine.attempt_to_set_isolation_level(conn, None)
  883. return await make_deferred_yieldable(
  884. self._db_pool.runWithConnection(inner_func, *args, **kwargs)
  885. )
  886. async def execute(self, desc: str, query: str, *args: Any) -> List[Tuple[Any, ...]]:
  887. """Runs a single query for a result set.
  888. Args:
  889. desc: description of the transaction, for logging and metrics
  890. query - The query string to execute
  891. *args - Query args.
  892. Returns:
  893. The result of decoder(results)
  894. """
  895. def interaction(txn: LoggingTransaction) -> List[Tuple[Any, ...]]:
  896. txn.execute(query, args)
  897. return txn.fetchall()
  898. return await self.runInteraction(desc, interaction)
  899. # "Simple" SQL API methods that operate on a single table with no JOINs,
  900. # no complex WHERE clauses, just a dict of values for columns.
  901. async def simple_insert(
  902. self,
  903. table: str,
  904. values: Dict[str, Any],
  905. desc: str = "simple_insert",
  906. ) -> None:
  907. """Executes an INSERT query on the named table.
  908. Args:
  909. table: string giving the table name
  910. values: dict of new column names and values for them
  911. desc: description of the transaction, for logging and metrics
  912. """
  913. await self.runInteraction(desc, self.simple_insert_txn, table, values)
  914. @staticmethod
  915. def simple_insert_txn(
  916. txn: LoggingTransaction, table: str, values: Dict[str, Any]
  917. ) -> None:
  918. keys, vals = zip(*values.items())
  919. sql = "INSERT INTO %s (%s) VALUES(%s)" % (
  920. table,
  921. ", ".join(k for k in keys),
  922. ", ".join("?" for _ in keys),
  923. )
  924. txn.execute(sql, vals)
  925. async def simple_insert_many(
  926. self,
  927. table: str,
  928. keys: Collection[str],
  929. values: Collection[Collection[Any]],
  930. desc: str,
  931. ) -> None:
  932. """Executes an INSERT query on the named table.
  933. The input is given as a list of rows, where each row is a list of values.
  934. (Actually any iterable is fine.)
  935. Args:
  936. table: string giving the table name
  937. keys: list of column names
  938. values: for each row, a list of values in the same order as `keys`
  939. desc: description of the transaction, for logging and metrics
  940. """
  941. await self.runInteraction(
  942. desc, self.simple_insert_many_txn, table, keys, values
  943. )
  944. @staticmethod
  945. def simple_insert_many_txn(
  946. txn: LoggingTransaction,
  947. table: str,
  948. keys: Sequence[str],
  949. values: Collection[Iterable[Any]],
  950. ) -> None:
  951. """Executes an INSERT query on the named table.
  952. The input is given as a list of rows, where each row is a list of values.
  953. (Actually any iterable is fine.)
  954. Args:
  955. txn: The transaction to use.
  956. table: string giving the table name
  957. keys: list of column names
  958. values: for each row, a list of values in the same order as `keys`
  959. """
  960. # If there's nothing to insert, then skip executing the query.
  961. if not values:
  962. return
  963. if isinstance(txn.database_engine, PostgresEngine):
  964. # We use `execute_values` as it can be a lot faster than `execute_batch`,
  965. # but it's only available on postgres.
  966. sql = "INSERT INTO %s (%s) VALUES ?" % (
  967. table,
  968. ", ".join(k for k in keys),
  969. )
  970. txn.execute_values(sql, values, fetch=False)
  971. else:
  972. sql = "INSERT INTO %s (%s) VALUES(%s)" % (
  973. table,
  974. ", ".join(k for k in keys),
  975. ", ".join("?" for _ in keys),
  976. )
  977. txn.execute_batch(sql, values)
  978. async def simple_upsert(
  979. self,
  980. table: str,
  981. keyvalues: Dict[str, Any],
  982. values: Dict[str, Any],
  983. insertion_values: Optional[Dict[str, Any]] = None,
  984. where_clause: Optional[str] = None,
  985. desc: str = "simple_upsert",
  986. ) -> bool:
  987. """Insert a row with values + insertion_values; on conflict, update with values.
  988. All of our supported databases accept the nonstandard "upsert" statement in
  989. their dialect of SQL. We call this a "native upsert". The syntax looks roughly
  990. like:
  991. INSERT INTO table VALUES (values + insertion_values)
  992. ON CONFLICT (keyvalues)
  993. DO UPDATE SET (values); -- overwrite `values` columns only
  994. If (values) is empty, the resulting query is slighlty simpler:
  995. INSERT INTO table VALUES (insertion_values)
  996. ON CONFLICT (keyvalues)
  997. DO NOTHING; -- do not overwrite any columns
  998. This function is a helper to build such queries.
  999. In order for upserts to make sense, the database must be able to determine when
  1000. an upsert CONFLICTs with an existing row. Postgres and SQLite ensure this by
  1001. requiring that a unique index exist on the column names used to detect a
  1002. conflict (i.e. `keyvalues.keys()`).
  1003. If there is no such index yet[*], we can "emulate" an upsert with a SELECT
  1004. followed by either an INSERT or an UPDATE. This is unsafe unless *all* upserters
  1005. run at the SERIALIZABLE isolation level: we cannot make the same atomicity
  1006. guarantees that a native upsert can and are very vulnerable to races and
  1007. crashes. Therefore to upsert without an appropriate unique index, we acquire a
  1008. table-level lock before the emulated upsert.
  1009. [*]: Some tables have unique indices added to them in the background. Those
  1010. tables `T` are keys in the dictionary UNIQUE_INDEX_BACKGROUND_UPDATES,
  1011. where `T` maps to the background update that adds a unique index to `T`.
  1012. This dictionary is maintained by hand.
  1013. At runtime, we constantly check to see if each of these background updates
  1014. has run. If so, we deem the coresponding table safe to upsert into, because
  1015. we can now use a native insert to do so. If not, we deem the table unsafe
  1016. to upsert into and require an emulated upsert.
  1017. Tables that do not appear in this dictionary are assumed to have an
  1018. appropriate unique index and therefore be safe to upsert into.
  1019. Args:
  1020. table: The table to upsert into
  1021. keyvalues: The unique key columns and their new values
  1022. values: The nonunique columns and their new values
  1023. insertion_values: additional key/values to use only when inserting
  1024. where_clause: An index predicate to apply to the upsert.
  1025. desc: description of the transaction, for logging and metrics
  1026. Returns:
  1027. Returns True if a row was inserted or updated (i.e. if `values` is
  1028. not empty then this always returns True)
  1029. """
  1030. insertion_values = insertion_values or {}
  1031. attempts = 0
  1032. while True:
  1033. try:
  1034. # We can autocommit if it is safe to upsert
  1035. autocommit = table not in self._unsafe_to_upsert_tables
  1036. return await self.runInteraction(
  1037. desc,
  1038. self.simple_upsert_txn,
  1039. table,
  1040. keyvalues,
  1041. values,
  1042. insertion_values,
  1043. where_clause,
  1044. db_autocommit=autocommit,
  1045. )
  1046. except self.engine.module.IntegrityError as e:
  1047. attempts += 1
  1048. if attempts >= 5:
  1049. # don't retry forever, because things other than races
  1050. # can cause IntegrityErrors
  1051. raise
  1052. # presumably we raced with another transaction: let's retry.
  1053. logger.warning(
  1054. "IntegrityError when upserting into %s; retrying: %s", table, e
  1055. )
  1056. def simple_upsert_txn(
  1057. self,
  1058. txn: LoggingTransaction,
  1059. table: str,
  1060. keyvalues: Dict[str, Any],
  1061. values: Dict[str, Any],
  1062. insertion_values: Optional[Dict[str, Any]] = None,
  1063. where_clause: Optional[str] = None,
  1064. ) -> bool:
  1065. """
  1066. Pick the UPSERT method which works best on the platform. Either the
  1067. native one (Pg9.5+, SQLite >= 3.24), or fall back to an emulated method.
  1068. Args:
  1069. txn: The transaction to use.
  1070. table: The table to upsert into
  1071. keyvalues: The unique key tables and their new values
  1072. values: The nonunique columns and their new values
  1073. insertion_values: additional key/values to use only when inserting
  1074. where_clause: An index predicate to apply to the upsert.
  1075. Returns:
  1076. Returns True if a row was inserted or updated (i.e. if `values` is
  1077. not empty then this always returns True)
  1078. """
  1079. insertion_values = insertion_values or {}
  1080. if table not in self._unsafe_to_upsert_tables:
  1081. return self.simple_upsert_txn_native_upsert(
  1082. txn,
  1083. table,
  1084. keyvalues,
  1085. values,
  1086. insertion_values=insertion_values,
  1087. where_clause=where_clause,
  1088. )
  1089. else:
  1090. return self.simple_upsert_txn_emulated(
  1091. txn,
  1092. table,
  1093. keyvalues,
  1094. values,
  1095. insertion_values=insertion_values,
  1096. where_clause=where_clause,
  1097. )
  1098. def simple_upsert_txn_emulated(
  1099. self,
  1100. txn: LoggingTransaction,
  1101. table: str,
  1102. keyvalues: Dict[str, Any],
  1103. values: Dict[str, Any],
  1104. insertion_values: Optional[Dict[str, Any]] = None,
  1105. where_clause: Optional[str] = None,
  1106. lock: bool = True,
  1107. ) -> bool:
  1108. """
  1109. Args:
  1110. table: The table to upsert into
  1111. keyvalues: The unique key tables and their new values
  1112. values: The nonunique columns and their new values
  1113. insertion_values: additional key/values to use only when inserting
  1114. where_clause: An index predicate to apply to the upsert.
  1115. lock: True to lock the table when doing the upsert.
  1116. Must not be False unless the table has already been locked.
  1117. Returns:
  1118. Returns True if a row was inserted or updated (i.e. if `values` is
  1119. not empty then this always returns True)
  1120. """
  1121. insertion_values = insertion_values or {}
  1122. if lock:
  1123. # We need to lock the table :(
  1124. self.engine.lock_table(txn, table)
  1125. def _getwhere(key: str) -> str:
  1126. # If the value we're passing in is None (aka NULL), we need to use
  1127. # IS, not =, as NULL = NULL equals NULL (False).
  1128. if keyvalues[key] is None:
  1129. return "%s IS ?" % (key,)
  1130. else:
  1131. return "%s = ?" % (key,)
  1132. # Generate a where clause of each keyvalue and optionally the provided
  1133. # index predicate.
  1134. where = [_getwhere(k) for k in keyvalues]
  1135. if where_clause:
  1136. where.append(where_clause)
  1137. if not values:
  1138. # If `values` is empty, then all of the values we care about are in
  1139. # the unique key, so there is nothing to UPDATE. We can just do a
  1140. # SELECT instead to see if it exists.
  1141. sql = "SELECT 1 FROM %s WHERE %s" % (table, " AND ".join(where))
  1142. sqlargs = list(keyvalues.values())
  1143. txn.execute(sql, sqlargs)
  1144. if txn.fetchall():
  1145. # We have an existing record.
  1146. return False
  1147. else:
  1148. # First try to update.
  1149. sql = "UPDATE %s SET %s WHERE %s" % (
  1150. table,
  1151. ", ".join("%s = ?" % (k,) for k in values),
  1152. " AND ".join(where),
  1153. )
  1154. sqlargs = list(values.values()) + list(keyvalues.values())
  1155. txn.execute(sql, sqlargs)
  1156. if txn.rowcount > 0:
  1157. return True
  1158. # We didn't find any existing rows, so insert a new one
  1159. allvalues: Dict[str, Any] = {}
  1160. allvalues.update(keyvalues)
  1161. allvalues.update(values)
  1162. allvalues.update(insertion_values)
  1163. sql = "INSERT INTO %s (%s) VALUES (%s)" % (
  1164. table,
  1165. ", ".join(k for k in allvalues),
  1166. ", ".join("?" for _ in allvalues),
  1167. )
  1168. txn.execute(sql, list(allvalues.values()))
  1169. # successfully inserted
  1170. return True
  1171. def simple_upsert_txn_native_upsert(
  1172. self,
  1173. txn: LoggingTransaction,
  1174. table: str,
  1175. keyvalues: Dict[str, Any],
  1176. values: Dict[str, Any],
  1177. insertion_values: Optional[Dict[str, Any]] = None,
  1178. where_clause: Optional[str] = None,
  1179. ) -> bool:
  1180. """
  1181. Use the native UPSERT functionality in PostgreSQL.
  1182. Args:
  1183. table: The table to upsert into
  1184. keyvalues: The unique key tables and their new values
  1185. values: The nonunique columns and their new values
  1186. insertion_values: additional key/values to use only when inserting
  1187. where_clause: An index predicate to apply to the upsert.
  1188. Returns:
  1189. Returns True if a row was inserted or updated (i.e. if `values` is
  1190. not empty then this always returns True)
  1191. """
  1192. allvalues: Dict[str, Any] = {}
  1193. allvalues.update(keyvalues)
  1194. allvalues.update(insertion_values or {})
  1195. if not values:
  1196. latter = "NOTHING"
  1197. else:
  1198. allvalues.update(values)
  1199. latter = "UPDATE SET " + ", ".join(k + "=EXCLUDED." + k for k in values)
  1200. sql = "INSERT INTO %s (%s) VALUES (%s) ON CONFLICT (%s) %sDO %s" % (
  1201. table,
  1202. ", ".join(k for k in allvalues),
  1203. ", ".join("?" for _ in allvalues),
  1204. ", ".join(k for k in keyvalues),
  1205. f"WHERE {where_clause} " if where_clause else "",
  1206. latter,
  1207. )
  1208. txn.execute(sql, list(allvalues.values()))
  1209. return bool(txn.rowcount)
  1210. async def simple_upsert_many(
  1211. self,
  1212. table: str,
  1213. key_names: Collection[str],
  1214. key_values: Collection[Collection[Any]],
  1215. value_names: Collection[str],
  1216. value_values: Collection[Collection[Any]],
  1217. desc: str,
  1218. ) -> None:
  1219. """
  1220. Upsert, many times.
  1221. Args:
  1222. table: The table to upsert into
  1223. key_names: The key column names.
  1224. key_values: A list of each row's key column values.
  1225. value_names: The value column names
  1226. value_values: A list of each row's value column values.
  1227. Ignored if value_names is empty.
  1228. """
  1229. # We can autocommit if it safe to upsert
  1230. autocommit = table not in self._unsafe_to_upsert_tables
  1231. await self.runInteraction(
  1232. desc,
  1233. self.simple_upsert_many_txn,
  1234. table,
  1235. key_names,
  1236. key_values,
  1237. value_names,
  1238. value_values,
  1239. db_autocommit=autocommit,
  1240. )
  1241. def simple_upsert_many_txn(
  1242. self,
  1243. txn: LoggingTransaction,
  1244. table: str,
  1245. key_names: Collection[str],
  1246. key_values: Collection[Iterable[Any]],
  1247. value_names: Collection[str],
  1248. value_values: Collection[Iterable[Any]],
  1249. ) -> None:
  1250. """
  1251. Upsert, many times.
  1252. Args:
  1253. table: The table to upsert into
  1254. key_names: The key column names.
  1255. key_values: A list of each row's key column values.
  1256. value_names: The value column names
  1257. value_values: A list of each row's value column values.
  1258. Ignored if value_names is empty.
  1259. """
  1260. # If there's nothing to upsert, then skip executing the query.
  1261. if not key_values:
  1262. return
  1263. # No value columns, therefore make a blank list so that the following
  1264. # zip() works correctly.
  1265. if not value_names:
  1266. value_values = [() for x in range(len(key_values))]
  1267. elif len(value_values) != len(key_values):
  1268. raise ValueError(
  1269. f"{len(key_values)} key rows and {len(value_values)} value rows: should be the same number."
  1270. )
  1271. if table not in self._unsafe_to_upsert_tables:
  1272. return self.simple_upsert_many_txn_native_upsert(
  1273. txn, table, key_names, key_values, value_names, value_values
  1274. )
  1275. else:
  1276. return self.simple_upsert_many_txn_emulated(
  1277. txn,
  1278. table,
  1279. key_names,
  1280. key_values,
  1281. value_names,
  1282. value_values,
  1283. )
  1284. def simple_upsert_many_txn_emulated(
  1285. self,
  1286. txn: LoggingTransaction,
  1287. table: str,
  1288. key_names: Iterable[str],
  1289. key_values: Collection[Iterable[Any]],
  1290. value_names: Collection[str],
  1291. value_values: Iterable[Iterable[Any]],
  1292. ) -> None:
  1293. """
  1294. Upsert, many times, but without native UPSERT support or batching.
  1295. Args:
  1296. table: The table to upsert into
  1297. key_names: The key column names.
  1298. key_values: A list of each row's key column values.
  1299. value_names: The value column names
  1300. value_values: A list of each row's value column values.
  1301. Ignored if value_names is empty.
  1302. """
  1303. # Lock the table just once, to prevent it being done once per row.
  1304. # Note that, according to Postgres' documentation, once obtained,
  1305. # the lock is held for the remainder of the current transaction.
  1306. self.engine.lock_table(txn, table)
  1307. for keyv, valv in zip(key_values, value_values):
  1308. _keys = dict(zip(key_names, keyv))
  1309. _vals = dict(zip(value_names, valv))
  1310. self.simple_upsert_txn_emulated(txn, table, _keys, _vals, lock=False)
  1311. def simple_upsert_many_txn_native_upsert(
  1312. self,
  1313. txn: LoggingTransaction,
  1314. table: str,
  1315. key_names: Collection[str],
  1316. key_values: Collection[Iterable[Any]],
  1317. value_names: Collection[str],
  1318. value_values: Iterable[Iterable[Any]],
  1319. ) -> None:
  1320. """
  1321. Upsert, many times, using batching where possible.
  1322. Args:
  1323. table: The table to upsert into
  1324. key_names: The key column names.
  1325. key_values: A list of each row's key column values.
  1326. value_names: The value column names
  1327. value_values: A list of each row's value column values.
  1328. Ignored if value_names is empty.
  1329. """
  1330. allnames: List[str] = []
  1331. allnames.extend(key_names)
  1332. allnames.extend(value_names)
  1333. if not value_names:
  1334. latter = "NOTHING"
  1335. else:
  1336. latter = "UPDATE SET " + ", ".join(
  1337. k + "=EXCLUDED." + k for k in value_names
  1338. )
  1339. args = []
  1340. for x, y in zip(key_values, value_values):
  1341. args.append(tuple(x) + tuple(y))
  1342. if isinstance(txn.database_engine, PostgresEngine):
  1343. # We use `execute_values` as it can be a lot faster than `execute_batch`,
  1344. # but it's only available on postgres.
  1345. sql = "INSERT INTO %s (%s) VALUES ? ON CONFLICT (%s) DO %s" % (
  1346. table,
  1347. ", ".join(k for k in allnames),
  1348. ", ".join(key_names),
  1349. latter,
  1350. )
  1351. txn.execute_values(sql, args, fetch=False)
  1352. else:
  1353. sql = "INSERT INTO %s (%s) VALUES (%s) ON CONFLICT (%s) DO %s" % (
  1354. table,
  1355. ", ".join(k for k in allnames),
  1356. ", ".join("?" for _ in allnames),
  1357. ", ".join(key_names),
  1358. latter,
  1359. )
  1360. return txn.execute_batch(sql, args)
  1361. @overload
  1362. async def simple_select_one(
  1363. self,
  1364. table: str,
  1365. keyvalues: Dict[str, Any],
  1366. retcols: Collection[str],
  1367. allow_none: Literal[False] = False,
  1368. desc: str = "simple_select_one",
  1369. ) -> Tuple[Any, ...]:
  1370. ...
  1371. @overload
  1372. async def simple_select_one(
  1373. self,
  1374. table: str,
  1375. keyvalues: Dict[str, Any],
  1376. retcols: Collection[str],
  1377. allow_none: Literal[True] = True,
  1378. desc: str = "simple_select_one",
  1379. ) -> Optional[Tuple[Any, ...]]:
  1380. ...
  1381. async def simple_select_one(
  1382. self,
  1383. table: str,
  1384. keyvalues: Dict[str, Any],
  1385. retcols: Collection[str],
  1386. allow_none: bool = False,
  1387. desc: str = "simple_select_one",
  1388. ) -> Optional[Tuple[Any, ...]]:
  1389. """Executes a SELECT query on the named table, which is expected to
  1390. return a single row, returning multiple columns from it.
  1391. Args:
  1392. table: string giving the table name
  1393. keyvalues: dict of column names and values to select the row with
  1394. retcols: list of strings giving the names of the columns to return
  1395. allow_none: If true, return None instead of failing if the SELECT
  1396. statement returns no rows
  1397. desc: description of the transaction, for logging and metrics
  1398. """
  1399. return await self.runInteraction(
  1400. desc,
  1401. self.simple_select_one_txn,
  1402. table,
  1403. keyvalues,
  1404. retcols,
  1405. allow_none,
  1406. db_autocommit=True,
  1407. )
  1408. @overload
  1409. async def simple_select_one_onecol(
  1410. self,
  1411. table: str,
  1412. keyvalues: Dict[str, Any],
  1413. retcol: str,
  1414. allow_none: Literal[False] = False,
  1415. desc: str = "simple_select_one_onecol",
  1416. ) -> Any:
  1417. ...
  1418. @overload
  1419. async def simple_select_one_onecol(
  1420. self,
  1421. table: str,
  1422. keyvalues: Dict[str, Any],
  1423. retcol: str,
  1424. allow_none: Literal[True] = True,
  1425. desc: str = "simple_select_one_onecol",
  1426. ) -> Optional[Any]:
  1427. ...
  1428. async def simple_select_one_onecol(
  1429. self,
  1430. table: str,
  1431. keyvalues: Dict[str, Any],
  1432. retcol: str,
  1433. allow_none: bool = False,
  1434. desc: str = "simple_select_one_onecol",
  1435. ) -> Optional[Any]:
  1436. """Executes a SELECT query on the named table, which is expected to
  1437. return a single row, returning a single column from it.
  1438. Args:
  1439. table: string giving the table name
  1440. keyvalues: dict of column names and values to select the row with
  1441. retcol: string giving the name of the column to return
  1442. allow_none: If true, return None instead of raising StoreError if the SELECT
  1443. statement returns no rows
  1444. desc: description of the transaction, for logging and metrics
  1445. """
  1446. return await self.runInteraction(
  1447. desc,
  1448. self.simple_select_one_onecol_txn,
  1449. table,
  1450. keyvalues,
  1451. retcol,
  1452. allow_none=allow_none,
  1453. db_autocommit=True,
  1454. )
  1455. @overload
  1456. @classmethod
  1457. def simple_select_one_onecol_txn(
  1458. cls,
  1459. txn: LoggingTransaction,
  1460. table: str,
  1461. keyvalues: Dict[str, Any],
  1462. retcol: str,
  1463. allow_none: Literal[False] = False,
  1464. ) -> Any:
  1465. ...
  1466. @overload
  1467. @classmethod
  1468. def simple_select_one_onecol_txn(
  1469. cls,
  1470. txn: LoggingTransaction,
  1471. table: str,
  1472. keyvalues: Dict[str, Any],
  1473. retcol: str,
  1474. allow_none: Literal[True] = True,
  1475. ) -> Optional[Any]:
  1476. ...
  1477. @classmethod
  1478. def simple_select_one_onecol_txn(
  1479. cls,
  1480. txn: LoggingTransaction,
  1481. table: str,
  1482. keyvalues: Dict[str, Any],
  1483. retcol: str,
  1484. allow_none: bool = False,
  1485. ) -> Optional[Any]:
  1486. ret = cls.simple_select_onecol_txn(
  1487. txn, table=table, keyvalues=keyvalues, retcol=retcol
  1488. )
  1489. if ret:
  1490. return ret[0]
  1491. else:
  1492. if allow_none:
  1493. return None
  1494. else:
  1495. raise StoreError(404, "No row found")
  1496. @staticmethod
  1497. def simple_select_onecol_txn(
  1498. txn: LoggingTransaction,
  1499. table: str,
  1500. keyvalues: Dict[str, Any],
  1501. retcol: str,
  1502. ) -> List[Any]:
  1503. sql = ("SELECT %(retcol)s FROM %(table)s") % {"retcol": retcol, "table": table}
  1504. if keyvalues:
  1505. sql += " WHERE %s" % " AND ".join("%s = ?" % k for k in keyvalues.keys())
  1506. txn.execute(sql, list(keyvalues.values()))
  1507. else:
  1508. txn.execute(sql)
  1509. return [r[0] for r in txn]
  1510. async def simple_select_onecol(
  1511. self,
  1512. table: str,
  1513. keyvalues: Optional[Dict[str, Any]],
  1514. retcol: str,
  1515. desc: str = "simple_select_onecol",
  1516. ) -> List[Any]:
  1517. """Executes a SELECT query on the named table, which returns a list
  1518. comprising of the values of the named column from the selected rows.
  1519. Args:
  1520. table: table name
  1521. keyvalues: column names and values to select the rows with
  1522. retcol: column whos value we wish to retrieve.
  1523. desc: description of the transaction, for logging and metrics
  1524. Returns:
  1525. Results in a list
  1526. """
  1527. return await self.runInteraction(
  1528. desc,
  1529. self.simple_select_onecol_txn,
  1530. table,
  1531. keyvalues,
  1532. retcol,
  1533. db_autocommit=True,
  1534. )
  1535. async def simple_select_list(
  1536. self,
  1537. table: str,
  1538. keyvalues: Optional[Dict[str, Any]],
  1539. retcols: Collection[str],
  1540. desc: str = "simple_select_list",
  1541. ) -> List[Tuple[Any, ...]]:
  1542. """Executes a SELECT query on the named table, which may return zero or
  1543. more rows, returning the result as a list of tuples.
  1544. Args:
  1545. table: the table name
  1546. keyvalues:
  1547. column names and values to select the rows with, or None to not
  1548. apply a WHERE clause.
  1549. retcols: the names of the columns to return
  1550. desc: description of the transaction, for logging and metrics
  1551. Returns:
  1552. A list of tuples, one per result row, each the retcolumn's value for the row.
  1553. """
  1554. return await self.runInteraction(
  1555. desc,
  1556. self.simple_select_list_txn,
  1557. table,
  1558. keyvalues,
  1559. retcols,
  1560. db_autocommit=True,
  1561. )
  1562. @classmethod
  1563. def simple_select_list_txn(
  1564. cls,
  1565. txn: LoggingTransaction,
  1566. table: str,
  1567. keyvalues: Optional[Dict[str, Any]],
  1568. retcols: Iterable[str],
  1569. ) -> List[Tuple[Any, ...]]:
  1570. """Executes a SELECT query on the named table, which may return zero or
  1571. more rows, returning the result as a list of tuples.
  1572. Args:
  1573. txn: Transaction object
  1574. table: the table name
  1575. keyvalues:
  1576. column names and values to select the rows with, or None to not
  1577. apply a WHERE clause.
  1578. retcols: the names of the columns to return
  1579. Returns:
  1580. A list of tuples, one per result row, each the retcolumn's value for the row.
  1581. """
  1582. if keyvalues:
  1583. sql = "SELECT %s FROM %s WHERE %s" % (
  1584. ", ".join(retcols),
  1585. table,
  1586. " AND ".join("%s = ?" % (k,) for k in keyvalues),
  1587. )
  1588. txn.execute(sql, list(keyvalues.values()))
  1589. else:
  1590. sql = "SELECT %s FROM %s" % (", ".join(retcols), table)
  1591. txn.execute(sql)
  1592. return txn.fetchall()
  1593. async def simple_select_many_batch(
  1594. self,
  1595. table: str,
  1596. column: str,
  1597. iterable: Iterable[Any],
  1598. retcols: Collection[str],
  1599. keyvalues: Optional[Dict[str, Any]] = None,
  1600. desc: str = "simple_select_many_batch",
  1601. batch_size: int = 100,
  1602. ) -> List[Tuple[Any, ...]]:
  1603. """Executes a SELECT query on the named table, which may return zero or
  1604. more rows.
  1605. Filters rows by whether the value of `column` is in `iterable`.
  1606. Args:
  1607. table: string giving the table name
  1608. column: column name to test for inclusion against `iterable`
  1609. iterable: list
  1610. retcols: list of strings giving the names of the columns to return
  1611. keyvalues: dict of column names and values to select the rows with
  1612. desc: description of the transaction, for logging and metrics
  1613. batch_size: the number of rows for each select query
  1614. Returns:
  1615. The results as a list of tuples.
  1616. """
  1617. keyvalues = keyvalues or {}
  1618. results: List[Tuple[Any, ...]] = []
  1619. for chunk in batch_iter(iterable, batch_size):
  1620. rows = await self.runInteraction(
  1621. desc,
  1622. self.simple_select_many_txn,
  1623. table,
  1624. column,
  1625. chunk,
  1626. keyvalues,
  1627. retcols,
  1628. db_autocommit=True,
  1629. )
  1630. results.extend(rows)
  1631. return results
  1632. @classmethod
  1633. def simple_select_many_txn(
  1634. cls,
  1635. txn: LoggingTransaction,
  1636. table: str,
  1637. column: str,
  1638. iterable: Collection[Any],
  1639. keyvalues: Dict[str, Any],
  1640. retcols: Iterable[str],
  1641. ) -> List[Tuple[Any, ...]]:
  1642. """Executes a SELECT query on the named table, which may return zero or
  1643. more rows.
  1644. Filters rows by whether the value of `column` is in `iterable`.
  1645. Args:
  1646. txn: Transaction object
  1647. table: string giving the table name
  1648. column: column name to test for inclusion against `iterable`
  1649. iterable: list
  1650. keyvalues: dict of column names and values to select the rows with
  1651. retcols: list of strings giving the names of the columns to return
  1652. Returns:
  1653. The results as a list of tuples.
  1654. """
  1655. # If there's nothing to select, then skip executing the query.
  1656. if not iterable:
  1657. return []
  1658. clause, values = make_in_list_sql_clause(txn.database_engine, column, iterable)
  1659. clauses = [clause]
  1660. for key, value in keyvalues.items():
  1661. clauses.append("%s = ?" % (key,))
  1662. values.append(value)
  1663. sql = "SELECT %s FROM %s WHERE %s" % (
  1664. ", ".join(retcols),
  1665. table,
  1666. " AND ".join(clauses),
  1667. )
  1668. txn.execute(sql, values)
  1669. return txn.fetchall()
  1670. async def simple_update(
  1671. self,
  1672. table: str,
  1673. keyvalues: Dict[str, Any],
  1674. updatevalues: Dict[str, Any],
  1675. desc: str,
  1676. ) -> int:
  1677. """
  1678. Update rows in the given database table.
  1679. If the given keyvalues don't match anything, nothing will be updated.
  1680. Args:
  1681. table: The database table to update.
  1682. keyvalues: A mapping of column name to value to match rows on.
  1683. updatevalues: A mapping of column name to value to replace in any matched rows.
  1684. desc: description of the transaction, for logging and metrics.
  1685. Returns:
  1686. The number of rows that were updated. Will be 0 if no matching rows were found.
  1687. """
  1688. return await self.runInteraction(
  1689. desc, self.simple_update_txn, table, keyvalues, updatevalues
  1690. )
  1691. @staticmethod
  1692. def simple_update_txn(
  1693. txn: LoggingTransaction,
  1694. table: str,
  1695. keyvalues: Dict[str, Any],
  1696. updatevalues: Dict[str, Any],
  1697. ) -> int:
  1698. """
  1699. Update rows in the given database table.
  1700. If the given keyvalues don't match anything, nothing will be updated.
  1701. Args:
  1702. txn: The database transaction object.
  1703. table: The database table to update.
  1704. keyvalues: A mapping of column name to value to match rows on.
  1705. updatevalues: A mapping of column name to value to replace in any matched rows.
  1706. Returns:
  1707. The number of rows that were updated. Will be 0 if no matching rows were found.
  1708. """
  1709. if keyvalues:
  1710. where = "WHERE %s" % " AND ".join("%s = ?" % k for k in keyvalues.keys())
  1711. else:
  1712. where = ""
  1713. update_sql = "UPDATE %s SET %s %s" % (
  1714. table,
  1715. ", ".join("%s = ?" % (k,) for k in updatevalues),
  1716. where,
  1717. )
  1718. txn.execute(update_sql, list(updatevalues.values()) + list(keyvalues.values()))
  1719. return txn.rowcount
  1720. async def simple_update_many(
  1721. self,
  1722. table: str,
  1723. key_names: Collection[str],
  1724. key_values: Collection[Iterable[Any]],
  1725. value_names: Collection[str],
  1726. value_values: Iterable[Iterable[Any]],
  1727. desc: str,
  1728. ) -> None:
  1729. """
  1730. Update, many times, using batching where possible.
  1731. If the keys don't match anything, nothing will be updated.
  1732. Args:
  1733. table: The table to update
  1734. key_names: The key column names.
  1735. key_values: A list of each row's key column values.
  1736. value_names: The names of value columns to update.
  1737. value_values: A list of each row's value column values.
  1738. """
  1739. await self.runInteraction(
  1740. desc,
  1741. self.simple_update_many_txn,
  1742. table,
  1743. key_names,
  1744. key_values,
  1745. value_names,
  1746. value_values,
  1747. )
  1748. @staticmethod
  1749. def simple_update_many_txn(
  1750. txn: LoggingTransaction,
  1751. table: str,
  1752. key_names: Collection[str],
  1753. key_values: Collection[Iterable[Any]],
  1754. value_names: Collection[str],
  1755. value_values: Collection[Iterable[Any]],
  1756. ) -> None:
  1757. """
  1758. Update, many times, using batching where possible.
  1759. If the keys don't match anything, nothing will be updated.
  1760. Args:
  1761. table: The table to update
  1762. key_names: The key column names.
  1763. key_values: A list of each row's key column values.
  1764. value_names: The names of value columns to update.
  1765. value_values: A list of each row's value column values.
  1766. """
  1767. if len(value_values) != len(key_values):
  1768. raise ValueError(
  1769. f"{len(key_values)} key rows and {len(value_values)} value rows: should be the same number."
  1770. )
  1771. # If there is nothing to update, then skip executing the query.
  1772. if not key_values:
  1773. return
  1774. # List of tuples of (value values, then key values)
  1775. # (This matches the order needed for the query)
  1776. args = [tuple(vv) + tuple(kv) for vv, kv in zip(value_values, key_values)]
  1777. # 'col1 = ?, col2 = ?, ...'
  1778. set_clause = ", ".join(f"{n} = ?" for n in value_names)
  1779. if key_names:
  1780. # 'WHERE col3 = ? AND col4 = ? AND col5 = ?'
  1781. where_clause = "WHERE " + (" AND ".join(f"{n} = ?" for n in key_names))
  1782. else:
  1783. where_clause = ""
  1784. # UPDATE mytable SET col1 = ?, col2 = ? WHERE col3 = ? AND col4 = ?
  1785. sql = f"UPDATE {table} SET {set_clause} {where_clause}"
  1786. txn.execute_batch(sql, args)
  1787. async def simple_update_one(
  1788. self,
  1789. table: str,
  1790. keyvalues: Dict[str, Any],
  1791. updatevalues: Dict[str, Any],
  1792. desc: str = "simple_update_one",
  1793. ) -> None:
  1794. """Executes an UPDATE query on the named table, setting new values for
  1795. columns in a row matching the key values.
  1796. Args:
  1797. table: string giving the table name
  1798. keyvalues: dict of column names and values to select the row with
  1799. updatevalues: dict giving column names and values to update
  1800. desc: description of the transaction, for logging and metrics
  1801. """
  1802. await self.runInteraction(
  1803. desc,
  1804. self.simple_update_one_txn,
  1805. table,
  1806. keyvalues,
  1807. updatevalues,
  1808. db_autocommit=True,
  1809. )
  1810. @classmethod
  1811. def simple_update_one_txn(
  1812. cls,
  1813. txn: LoggingTransaction,
  1814. table: str,
  1815. keyvalues: Dict[str, Any],
  1816. updatevalues: Dict[str, Any],
  1817. ) -> None:
  1818. rowcount = cls.simple_update_txn(txn, table, keyvalues, updatevalues)
  1819. if rowcount == 0:
  1820. raise StoreError(404, "No row found (%s)" % (table,))
  1821. if rowcount > 1:
  1822. raise StoreError(500, "More than one row matched (%s)" % (table,))
  1823. # Ideally we could use the overload decorator here to specify that the
  1824. # return type is only optional if allow_none is True, but this does not work
  1825. # when you call a static method from an instance.
  1826. # See https://github.com/python/mypy/issues/7781
  1827. @staticmethod
  1828. def simple_select_one_txn(
  1829. txn: LoggingTransaction,
  1830. table: str,
  1831. keyvalues: Dict[str, Any],
  1832. retcols: Collection[str],
  1833. allow_none: bool = False,
  1834. ) -> Optional[Tuple[Any, ...]]:
  1835. select_sql = "SELECT %s FROM %s" % (", ".join(retcols), table)
  1836. if keyvalues:
  1837. select_sql += " WHERE %s" % (" AND ".join("%s = ?" % k for k in keyvalues),)
  1838. txn.execute(select_sql, list(keyvalues.values()))
  1839. else:
  1840. txn.execute(select_sql)
  1841. row = txn.fetchone()
  1842. if not row:
  1843. if allow_none:
  1844. return None
  1845. raise StoreError(404, "No row found (%s)" % (table,))
  1846. if txn.rowcount > 1:
  1847. raise StoreError(500, "More than one row matched (%s)" % (table,))
  1848. return row
  1849. async def simple_delete_one(
  1850. self, table: str, keyvalues: Dict[str, Any], desc: str = "simple_delete_one"
  1851. ) -> None:
  1852. """Executes a DELETE query on the named table, expecting to delete a
  1853. single row.
  1854. Args:
  1855. table: string giving the table name
  1856. keyvalues: dict of column names and values to select the row with
  1857. desc: description of the transaction, for logging and metrics
  1858. """
  1859. await self.runInteraction(
  1860. desc,
  1861. self.simple_delete_one_txn,
  1862. table,
  1863. keyvalues,
  1864. db_autocommit=True,
  1865. )
  1866. @staticmethod
  1867. def simple_delete_one_txn(
  1868. txn: LoggingTransaction, table: str, keyvalues: Dict[str, Any]
  1869. ) -> None:
  1870. """Executes a DELETE query on the named table, expecting to delete a
  1871. single row.
  1872. Args:
  1873. table: string giving the table name
  1874. keyvalues: dict of column names and values to select the row with
  1875. """
  1876. sql = "DELETE FROM %s WHERE %s" % (
  1877. table,
  1878. " AND ".join("%s = ?" % (k,) for k in keyvalues),
  1879. )
  1880. txn.execute(sql, list(keyvalues.values()))
  1881. if txn.rowcount == 0:
  1882. raise StoreError(404, "No row found (%s)" % (table,))
  1883. if txn.rowcount > 1:
  1884. raise StoreError(500, "More than one row matched (%s)" % (table,))
  1885. async def simple_delete(
  1886. self, table: str, keyvalues: Dict[str, Any], desc: str
  1887. ) -> int:
  1888. """Executes a DELETE query on the named table.
  1889. Filters rows by the key-value pairs.
  1890. Args:
  1891. table: string giving the table name
  1892. keyvalues: dict of column names and values to select the row with
  1893. desc: description of the transaction, for logging and metrics
  1894. Returns:
  1895. The number of deleted rows.
  1896. """
  1897. return await self.runInteraction(
  1898. desc, self.simple_delete_txn, table, keyvalues, db_autocommit=True
  1899. )
  1900. @staticmethod
  1901. def simple_delete_txn(
  1902. txn: LoggingTransaction, table: str, keyvalues: Dict[str, Any]
  1903. ) -> int:
  1904. """Executes a DELETE query on the named table.
  1905. Filters rows by the key-value pairs.
  1906. Args:
  1907. table: string giving the table name
  1908. keyvalues: dict of column names and values to select the row with
  1909. Returns:
  1910. The number of deleted rows.
  1911. """
  1912. sql = "DELETE FROM %s WHERE %s" % (
  1913. table,
  1914. " AND ".join("%s = ?" % (k,) for k in keyvalues),
  1915. )
  1916. txn.execute(sql, list(keyvalues.values()))
  1917. return txn.rowcount
  1918. async def simple_delete_many(
  1919. self,
  1920. table: str,
  1921. column: str,
  1922. iterable: Collection[Any],
  1923. keyvalues: Dict[str, Any],
  1924. desc: str,
  1925. ) -> int:
  1926. """Executes a DELETE query on the named table.
  1927. Filters rows by if value of `column` is in `iterable`.
  1928. Args:
  1929. table: string giving the table name
  1930. column: column name to test for inclusion against `iterable`
  1931. iterable: list of values to match against `column`. NB cannot be a generator
  1932. as it may be evaluated multiple times.
  1933. keyvalues: dict of column names and values to select the rows with
  1934. desc: description of the transaction, for logging and metrics
  1935. Returns:
  1936. Number rows deleted
  1937. """
  1938. return await self.runInteraction(
  1939. desc,
  1940. self.simple_delete_many_txn,
  1941. table,
  1942. column,
  1943. iterable,
  1944. keyvalues,
  1945. db_autocommit=True,
  1946. )
  1947. @staticmethod
  1948. def simple_delete_many_txn(
  1949. txn: LoggingTransaction,
  1950. table: str,
  1951. column: str,
  1952. values: Collection[Any],
  1953. keyvalues: Dict[str, Any],
  1954. ) -> int:
  1955. """Executes a DELETE query on the named table.
  1956. Deletes the rows:
  1957. - whose value of `column` is in `values`; AND
  1958. - that match extra column-value pairs specified in `keyvalues`.
  1959. Args:
  1960. txn: Transaction object
  1961. table: string giving the table name
  1962. column: column name to test for inclusion against `values`
  1963. values: values of `column` which choose rows to delete
  1964. keyvalues: dict of extra column names and values to select the rows
  1965. with. They will be ANDed together with the main predicate.
  1966. Returns:
  1967. Number rows deleted
  1968. """
  1969. # If there's nothing to delete, then skip executing the query.
  1970. if not values:
  1971. return 0
  1972. clause, values = make_in_list_sql_clause(txn.database_engine, column, values)
  1973. clauses = [clause]
  1974. for key, value in keyvalues.items():
  1975. clauses.append("%s = ?" % (key,))
  1976. values.append(value)
  1977. sql = "DELETE FROM %s WHERE %s" % (table, " AND ".join(clauses))
  1978. txn.execute(sql, values)
  1979. return txn.rowcount
  1980. @staticmethod
  1981. def simple_delete_many_batch_txn(
  1982. txn: LoggingTransaction,
  1983. table: str,
  1984. keys: Collection[str],
  1985. values: Iterable[Iterable[Any]],
  1986. ) -> None:
  1987. """Executes a DELETE query on the named table.
  1988. The input is given as a list of rows, where each row is a list of values.
  1989. (Actually any iterable is fine.)
  1990. Args:
  1991. txn: The transaction to use.
  1992. table: string giving the table name
  1993. keys: list of column names
  1994. values: for each row, a list of values in the same order as `keys`
  1995. """
  1996. if isinstance(txn.database_engine, PostgresEngine):
  1997. # We use `execute_values` as it can be a lot faster than `execute_batch`,
  1998. # but it's only available on postgres.
  1999. sql = "DELETE FROM %s WHERE (%s) IN (VALUES ?)" % (
  2000. table,
  2001. ", ".join(k for k in keys),
  2002. )
  2003. txn.execute_values(sql, values, fetch=False)
  2004. else:
  2005. sql = "DELETE FROM %s WHERE (%s) = (%s)" % (
  2006. table,
  2007. ", ".join(k for k in keys),
  2008. ", ".join("?" for _ in keys),
  2009. )
  2010. txn.execute_batch(sql, values)
  2011. def get_cache_dict(
  2012. self,
  2013. db_conn: LoggingDatabaseConnection,
  2014. table: str,
  2015. entity_column: str,
  2016. stream_column: str,
  2017. max_value: int,
  2018. limit: int = 100000,
  2019. ) -> Tuple[Dict[Any, int], int]:
  2020. """Gets roughly the last N changes in the given stream table as a
  2021. map from entity to the stream ID of the most recent change.
  2022. Also returns the minimum stream ID.
  2023. """
  2024. # This may return many rows for the same entity, but the `limit` is only
  2025. # a suggestion so we don't care that much.
  2026. #
  2027. # Note: Some stream tables can have multiple rows with the same stream
  2028. # ID. Instead of handling this with complicated SQL, we instead simply
  2029. # add one to the returned minimum stream ID to ensure correctness.
  2030. sql = f"""
  2031. SELECT {entity_column}, {stream_column}
  2032. FROM {table}
  2033. ORDER BY {stream_column} DESC
  2034. LIMIT ?
  2035. """
  2036. txn = db_conn.cursor(txn_name="get_cache_dict")
  2037. txn.execute(sql, (limit,))
  2038. # The rows come out in reverse stream ID order, so we want to keep the
  2039. # stream ID of the first row for each entity.
  2040. cache: Dict[Any, int] = {}
  2041. for row in txn:
  2042. cache.setdefault(row[0], int(row[1]))
  2043. txn.close()
  2044. if cache:
  2045. # We add one here as we don't know if we have all rows for the
  2046. # minimum stream ID.
  2047. min_val = min(cache.values()) + 1
  2048. else:
  2049. min_val = max_value
  2050. return cache, min_val
  2051. @classmethod
  2052. def simple_select_list_paginate_txn(
  2053. cls,
  2054. txn: LoggingTransaction,
  2055. table: str,
  2056. orderby: str,
  2057. start: int,
  2058. limit: int,
  2059. retcols: Iterable[str],
  2060. filters: Optional[Dict[str, Any]] = None,
  2061. keyvalues: Optional[Dict[str, Any]] = None,
  2062. exclude_keyvalues: Optional[Dict[str, Any]] = None,
  2063. order_direction: str = "ASC",
  2064. ) -> List[Tuple[Any, ...]]:
  2065. """
  2066. Executes a SELECT query on the named table with start and limit,
  2067. of row numbers, which may return zero or number of rows from start to limit,
  2068. returning the result as a list of dicts.
  2069. Use `filters` to search attributes using SQL wildcards and/or `keyvalues` to
  2070. select attributes with exact matches. All constraints are joined together
  2071. using 'AND'.
  2072. Args:
  2073. txn: Transaction object
  2074. table: the table name
  2075. orderby: Column to order the results by.
  2076. start: Index to begin the query at.
  2077. limit: Number of results to return.
  2078. retcols: the names of the columns to return
  2079. filters:
  2080. column names and values to filter the rows with, or None to not
  2081. apply a WHERE ? LIKE ? clause.
  2082. keyvalues:
  2083. column names and values to select the rows with, or None to not
  2084. apply a WHERE key = value clause.
  2085. exclude_keyvalues:
  2086. column names and values to exclude rows with, or None to not
  2087. apply a WHERE key != value clause.
  2088. order_direction: Whether the results should be ordered "ASC" or "DESC".
  2089. Returns:
  2090. The result as a list of tuples.
  2091. """
  2092. if order_direction not in ["ASC", "DESC"]:
  2093. raise ValueError("order_direction must be one of 'ASC' or 'DESC'.")
  2094. where_clause = "WHERE " if filters or keyvalues or exclude_keyvalues else ""
  2095. arg_list: List[Any] = []
  2096. if filters:
  2097. where_clause += " AND ".join("%s LIKE ?" % (k,) for k in filters)
  2098. arg_list += list(filters.values())
  2099. where_clause += " AND " if filters and keyvalues else ""
  2100. if keyvalues:
  2101. where_clause += " AND ".join("%s = ?" % (k,) for k in keyvalues)
  2102. arg_list += list(keyvalues.values())
  2103. if exclude_keyvalues:
  2104. where_clause += " AND ".join("%s != ?" % (k,) for k in exclude_keyvalues)
  2105. arg_list += list(exclude_keyvalues.values())
  2106. sql = "SELECT %s FROM %s %s ORDER BY %s %s LIMIT ? OFFSET ?" % (
  2107. ", ".join(retcols),
  2108. table,
  2109. where_clause,
  2110. orderby,
  2111. order_direction,
  2112. )
  2113. txn.execute(sql, arg_list + [limit, start])
  2114. return txn.fetchall()
  2115. def make_in_list_sql_clause(
  2116. database_engine: BaseDatabaseEngine, column: str, iterable: Collection[Any]
  2117. ) -> Tuple[str, list]:
  2118. """Returns an SQL clause that checks the given column is in the iterable.
  2119. On SQLite this expands to `column IN (?, ?, ...)`, whereas on Postgres
  2120. it expands to `column = ANY(?)`. While both DBs support the `IN` form,
  2121. using the `ANY` form on postgres means that it views queries with
  2122. different length iterables as the same, helping the query stats.
  2123. Args:
  2124. database_engine
  2125. column: Name of the column
  2126. iterable: The values to check the column against.
  2127. Returns:
  2128. A tuple of SQL query and the args
  2129. """
  2130. if database_engine.supports_using_any_list:
  2131. # This should hopefully be faster, but also makes postgres query
  2132. # stats easier to understand.
  2133. return "%s = ANY(?)" % (column,), [list(iterable)]
  2134. else:
  2135. return "%s IN (%s)" % (column, ",".join("?" for _ in iterable)), list(iterable)
  2136. # These overloads ensure that `columns` and `iterable` values have the same length.
  2137. # Suppress "Single overload definition, multiple required" complaint.
  2138. @overload # type: ignore[misc]
  2139. def make_tuple_in_list_sql_clause(
  2140. database_engine: BaseDatabaseEngine,
  2141. columns: Tuple[str, str],
  2142. iterable: Collection[Tuple[Any, Any]],
  2143. ) -> Tuple[str, list]:
  2144. ...
  2145. def make_tuple_in_list_sql_clause(
  2146. database_engine: BaseDatabaseEngine,
  2147. columns: Tuple[str, ...],
  2148. iterable: Collection[Tuple[Any, ...]],
  2149. ) -> Tuple[str, list]:
  2150. """Returns an SQL clause that checks the given tuple of columns is in the iterable.
  2151. Args:
  2152. database_engine
  2153. columns: Names of the columns in the tuple.
  2154. iterable: The tuples to check the columns against.
  2155. Returns:
  2156. A tuple of SQL query and the args
  2157. """
  2158. if len(columns) == 0:
  2159. # Should be unreachable due to mypy, as long as the overloads are set up right.
  2160. if () in iterable:
  2161. return "TRUE", []
  2162. else:
  2163. return "FALSE", []
  2164. if len(columns) == 1:
  2165. # Use `= ANY(?)` on postgres.
  2166. return make_in_list_sql_clause(
  2167. database_engine, next(iter(columns)), [values[0] for values in iterable]
  2168. )
  2169. # There are multiple columns. Avoid using an `= ANY(?)` clause on postgres, as
  2170. # indices are not used when there are multiple columns. Instead, use an `IN`
  2171. # expression.
  2172. #
  2173. # `IN ((?, ...), ...)` with tuples is supported by postgres only, whereas
  2174. # `IN (VALUES (?, ...), ...)` is supported by both sqlite and postgres.
  2175. # Thus, the latter is chosen.
  2176. if len(iterable) == 0:
  2177. # A 0-length `VALUES` list is not allowed in sqlite or postgres.
  2178. # Also note that a 0-length `IN (...)` clause (not using `VALUES`) is not
  2179. # allowed in postgres.
  2180. return "FALSE", []
  2181. tuple_sql = "(%s)" % (",".join("?" for _ in columns),)
  2182. return "(%s) IN (VALUES %s)" % (
  2183. ",".join(column for column in columns),
  2184. ",".join(tuple_sql for _ in iterable),
  2185. ), [value for values in iterable for value in values]
  2186. KV = TypeVar("KV")
  2187. def make_tuple_comparison_clause(keys: List[Tuple[str, KV]]) -> Tuple[str, List[KV]]:
  2188. """Returns a tuple comparison SQL clause
  2189. Builds a SQL clause that looks like "(a, b) > (?, ?)"
  2190. Args:
  2191. keys: A set of (column, value) pairs to be compared.
  2192. Returns:
  2193. A tuple of SQL query and the args
  2194. """
  2195. return (
  2196. "(%s) > (%s)" % (",".join(k[0] for k in keys), ",".join("?" for _ in keys)),
  2197. [k[1] for k in keys],
  2198. )