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.
 
 
 
 
 
 

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