Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

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