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.
 
 
 
 
 
 

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