database.py 57 KB

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