Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit 118f41d

Browse files
committed
Merge commit '30426c706' into anoa/dinsic_release_1_21_x
* commit '30426c706': Convert additional database methods to async (select list, search, insert_many, delete_*) (#8168)
2 parents a89a160 + 30426c7 commit 118f41d

File tree

8 files changed

+67
-84
lines changed

8 files changed

+67
-84
lines changed

changelog.d/8168.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Convert various parts of the codebase to async/await.

synapse/storage/background_updates.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -414,21 +414,22 @@ async def updater(progress, batch_size):
414414

415415
self.register_background_update_handler(update_name, updater)
416416

417-
def _end_background_update(self, update_name):
417+
async def _end_background_update(self, update_name: str) -> None:
418418
"""Removes a completed background update task from the queue.
419419
420420
Args:
421-
update_name(str): The name of the completed task to remove
421+
update_name:: The name of the completed task to remove
422+
422423
Returns:
423-
A deferred that completes once the task is removed.
424+
None, completes once the task is removed.
424425
"""
425426
if update_name != self._current_background_update:
426427
raise Exception(
427428
"Cannot end background update %s which isn't currently running"
428429
% update_name
429430
)
430431
self._current_background_update = None
431-
return self.db_pool.simple_delete_one(
432+
await self.db_pool.simple_delete_one(
432433
"background_updates", keyvalues={"update_name": update_name}
433434
)
434435

synapse/storage/database.py

+37-62
Original file line numberDiff line numberDiff line change
@@ -605,7 +605,13 @@ def cursor_to_dict(cursor: Cursor) -> List[Dict[str, Any]]:
605605
results = [dict(zip(col_headers, row)) for row in cursor]
606606
return results
607607

608-
def execute(self, desc: str, decoder: Callable, query: str, *args: Any):
608+
async def execute(
609+
self,
610+
desc: str,
611+
decoder: Optional[Callable[[Cursor], R]],
612+
query: str,
613+
*args: Any
614+
) -> R:
609615
"""Runs a single query for a result set.
610616
611617
Args:
@@ -614,7 +620,7 @@ def execute(self, desc: str, decoder: Callable, query: str, *args: Any):
614620
query - The query string to execute
615621
*args - Query args.
616622
Returns:
617-
Deferred which results to the result of decoder(results)
623+
The result of decoder(results)
618624
"""
619625

620626
def interaction(txn):
@@ -624,7 +630,7 @@ def interaction(txn):
624630
else:
625631
return txn.fetchall()
626632

627-
return self.runInteraction(desc, interaction)
633+
return await self.runInteraction(desc, interaction)
628634

629635
# "Simple" SQL API methods that operate on a single table with no JOINs,
630636
# no complex WHERE clauses, just a dict of values for columns.
@@ -673,15 +679,30 @@ def simple_insert_txn(
673679

674680
txn.execute(sql, vals)
675681

676-
def simple_insert_many(
682+
async def simple_insert_many(
677683
self, table: str, values: List[Dict[str, Any]], desc: str
678-
) -> defer.Deferred:
679-
return self.runInteraction(desc, self.simple_insert_many_txn, table, values)
684+
) -> None:
685+
"""Executes an INSERT query on the named table.
686+
687+
Args:
688+
table: string giving the table name
689+
values: dict of new column names and values for them
690+
desc: string giving a description of the transaction
691+
"""
692+
await self.runInteraction(desc, self.simple_insert_many_txn, table, values)
680693

681694
@staticmethod
682695
def simple_insert_many_txn(
683696
txn: LoggingTransaction, table: str, values: List[Dict[str, Any]]
684697
) -> None:
698+
"""Executes an INSERT query on the named table.
699+
700+
Args:
701+
txn: The transaction to use.
702+
table: string giving the table name
703+
values: dict of new column names and values for them
704+
desc: string giving a description of the transaction
705+
"""
685706
if not values:
686707
return
687708

@@ -1397,17 +1418,17 @@ def simple_select_one_txn(
13971418

13981419
return dict(zip(retcols, row))
13991420

1400-
def simple_delete_one(
1421+
async def simple_delete_one(
14011422
self, table: str, keyvalues: Dict[str, Any], desc: str = "simple_delete_one"
1402-
) -> defer.Deferred:
1423+
) -> None:
14031424
"""Executes a DELETE query on the named table, expecting to delete a
14041425
single row.
14051426
14061427
Args:
14071428
table: string giving the table name
14081429
keyvalues: dict of column names and values to select the row with
14091430
"""
1410-
return self.runInteraction(desc, self.simple_delete_one_txn, table, keyvalues)
1431+
await self.runInteraction(desc, self.simple_delete_one_txn, table, keyvalues)
14111432

14121433
@staticmethod
14131434
def simple_delete_one_txn(
@@ -1446,15 +1467,15 @@ def simple_delete_txn(
14461467
txn.execute(sql, list(keyvalues.values()))
14471468
return txn.rowcount
14481469

1449-
def simple_delete_many(
1470+
async def simple_delete_many(
14501471
self,
14511472
table: str,
14521473
column: str,
14531474
iterable: Iterable[Any],
14541475
keyvalues: Dict[str, Any],
14551476
desc: str,
1456-
) -> defer.Deferred:
1457-
return self.runInteraction(
1477+
) -> int:
1478+
return await self.runInteraction(
14581479
desc, self.simple_delete_many_txn, table, column, iterable, keyvalues
14591480
)
14601481

@@ -1537,52 +1558,6 @@ def get_cache_dict(
15371558

15381559
return cache, min_val
15391560

1540-
def simple_select_list_paginate(
1541-
self,
1542-
table: str,
1543-
orderby: str,
1544-
start: int,
1545-
limit: int,
1546-
retcols: Iterable[str],
1547-
filters: Optional[Dict[str, Any]] = None,
1548-
keyvalues: Optional[Dict[str, Any]] = None,
1549-
order_direction: str = "ASC",
1550-
desc: str = "simple_select_list_paginate",
1551-
) -> defer.Deferred:
1552-
"""
1553-
Executes a SELECT query on the named table with start and limit,
1554-
of row numbers, which may return zero or number of rows from start to limit,
1555-
returning the result as a list of dicts.
1556-
1557-
Args:
1558-
table: the table name
1559-
orderby: Column to order the results by.
1560-
start: Index to begin the query at.
1561-
limit: Number of results to return.
1562-
retcols: the names of the columns to return
1563-
filters:
1564-
column names and values to filter the rows with, or None to not
1565-
apply a WHERE ? LIKE ? clause.
1566-
keyvalues:
1567-
column names and values to select the rows with, or None to not
1568-
apply a WHERE clause.
1569-
order_direction: Whether the results should be ordered "ASC" or "DESC".
1570-
Returns:
1571-
defer.Deferred: resolves to list[dict[str, Any]]
1572-
"""
1573-
return self.runInteraction(
1574-
desc,
1575-
self.simple_select_list_paginate_txn,
1576-
table,
1577-
orderby,
1578-
start,
1579-
limit,
1580-
retcols,
1581-
filters=filters,
1582-
keyvalues=keyvalues,
1583-
order_direction=order_direction,
1584-
)
1585-
15861561
@classmethod
15871562
def simple_select_list_paginate_txn(
15881563
cls,
@@ -1647,14 +1622,14 @@ def simple_select_list_paginate_txn(
16471622

16481623
return cls.cursor_to_dict(txn)
16491624

1650-
def simple_search_list(
1625+
async def simple_search_list(
16511626
self,
16521627
table: str,
16531628
term: Optional[str],
16541629
col: str,
16551630
retcols: Iterable[str],
16561631
desc="simple_search_list",
1657-
):
1632+
) -> Optional[List[Dict[str, Any]]]:
16581633
"""Executes a SELECT query on the named table, which may return zero or
16591634
more rows, returning the result as a list of dicts.
16601635
@@ -1665,10 +1640,10 @@ def simple_search_list(
16651640
retcols: the names of the columns to return
16661641
16671642
Returns:
1668-
defer.Deferred: resolves to list[dict[str, Any]] or None
1643+
A list of dictionaries or None.
16691644
"""
16701645

1671-
return self.runInteraction(
1646+
return await self.runInteraction(
16721647
desc, self.simple_search_list_txn, table, term, col, retcols
16731648
)
16741649

synapse/storage/databases/main/__init__.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
import calendar
1919
import logging
2020
import time
21-
from typing import Any, Dict, List
21+
from typing import Any, Dict, List, Optional
2222

2323
from synapse.api.constants import PresenceState
2424
from synapse.config.homeserver import HomeServerConfig
@@ -559,17 +559,17 @@ def get_users_paginate_txn(txn):
559559
"get_users_paginate_txn", get_users_paginate_txn
560560
)
561561

562-
def search_users(self, term):
562+
async def search_users(self, term: str) -> Optional[List[Dict[str, Any]]]:
563563
"""Function to search users list for one or more users with
564564
the matched term.
565565
566566
Args:
567-
term (str): search term
568-
col (str): column to query term should be matched to
567+
term: search term
568+
569569
Returns:
570-
defer.Deferred: resolves to list[dict[str, Any]]
570+
A list of dictionaries or None.
571571
"""
572-
return self.db_pool.simple_search_list(
572+
return await self.db_pool.simple_search_list(
573573
table="users",
574574
term=term,
575575
col="name",

synapse/storage/databases/main/end_to_end_keys.py

+10-5
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1515
# See the License for the specific language governing permissions and
1616
# limitations under the License.
17-
from typing import Dict, Iterable, List, Optional, Tuple
17+
from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Tuple
1818

1919
from canonicaljson import encode_canonical_json
2020

@@ -27,6 +27,9 @@
2727
from synapse.util.caches.descriptors import cached, cachedList
2828
from synapse.util.iterutils import batch_iter
2929

30+
if TYPE_CHECKING:
31+
from synapse.handlers.e2e_keys import SignatureListItem
32+
3033

3134
class EndToEndKeyWorkerStore(SQLBaseStore):
3235
@trace
@@ -730,14 +733,16 @@ async def set_e2e_cross_signing_key(self, user_id, key_type, key):
730733
stream_id,
731734
)
732735

733-
def store_e2e_cross_signing_signatures(self, user_id, signatures):
736+
async def store_e2e_cross_signing_signatures(
737+
self, user_id: str, signatures: "Iterable[SignatureListItem]"
738+
) -> None:
734739
"""Stores cross-signing signatures.
735740
736741
Args:
737-
user_id (str): the user who made the signatures
738-
signatures (iterable[SignatureListItem]): signatures to add
742+
user_id: the user who made the signatures
743+
signatures: signatures to add
739744
"""
740-
return self.db_pool.simple_insert_many(
745+
await self.db_pool.simple_insert_many(
741746
"e2e_cross_signing_signatures",
742747
[
743748
{

synapse/storage/databases/main/media_repository.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -314,14 +314,14 @@ def store_remote_media_thumbnail(
314314
desc="store_remote_media_thumbnail",
315315
)
316316

317-
def get_remote_media_before(self, before_ts):
317+
async def get_remote_media_before(self, before_ts):
318318
sql = (
319319
"SELECT media_origin, media_id, filesystem_id"
320320
" FROM remote_media_cache"
321321
" WHERE last_access_ts < ?"
322322
)
323323

324-
return self.db_pool.execute(
324+
return await self.db_pool.execute(
325325
"get_remote_media_before", self.db_pool.cursor_to_dict, sql, before_ts
326326
)
327327

tests/storage/test_background_update.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -67,13 +67,12 @@ def update(progress, count):
6767

6868
# second step: complete the update
6969
# we should now get run with a much bigger number of items to update
70-
@defer.inlineCallbacks
71-
def update(progress, count):
70+
async def update(progress, count):
7271
self.assertEqual(progress, {"my_key": 2})
7372
self.assertAlmostEqual(
7473
count, target_background_update_duration_ms / duration_ms, places=0,
7574
)
76-
yield self.updates._end_background_update("test_update")
75+
await self.updates._end_background_update("test_update")
7776
return count
7877

7978
self.update_handler.side_effect = update

tests/storage/test_base.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -197,8 +197,10 @@ def test_update_one_4cols(self):
197197
def test_delete_one(self):
198198
self.mock_txn.rowcount = 1
199199

200-
yield self.datastore.db_pool.simple_delete_one(
201-
table="tablename", keyvalues={"keycol": "Go away"}
200+
yield defer.ensureDeferred(
201+
self.datastore.db_pool.simple_delete_one(
202+
table="tablename", keyvalues={"keycol": "Go away"}
203+
)
202204
)
203205

204206
self.mock_txn.execute.assert_called_with(

0 commit comments

Comments
 (0)