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

Commit 8a47d6e

Browse files
author
David Robertson
authored
More precise type for LoggingTransaction.execute (#15432)
* More precise type for LoggingTransaction.execute * Add an annotation for stream_ordering_month_ago This would have spotted the error that was fixed in "Add comma missing from #15382. (#15429)"
1 parent 24b61f3 commit 8a47d6e

File tree

4 files changed

+32
-14
lines changed

4 files changed

+32
-14
lines changed

changelog.d/15432.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Improve type hints.

synapse/storage/database.py

+17-3
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@
5858
from synapse.metrics.background_process_metrics import run_as_background_process
5959
from synapse.storage.background_updates import BackgroundUpdater
6060
from synapse.storage.engines import BaseDatabaseEngine, PostgresEngine, Sqlite3Engine
61-
from synapse.storage.types import Connection, Cursor
61+
from synapse.storage.types import Connection, Cursor, SQLQueryParameters
6262
from synapse.util.async_helpers import delay_cancellation
6363
from synapse.util.iterutils import batch_iter
6464

@@ -371,10 +371,18 @@ def execute_batch(self, sql: str, args: Iterable[Iterable[Any]]) -> None:
371371
if isinstance(self.database_engine, PostgresEngine):
372372
from psycopg2.extras import execute_batch
373373

374+
# TODO: is it safe for values to be Iterable[Iterable[Any]] here?
375+
# https://www.psycopg.org/docs/extras.html?highlight=execute_batch#psycopg2.extras.execute_batch
376+
# suggests each arg in args should be a sequence or mapping
374377
self._do_execute(
375378
lambda the_sql: execute_batch(self.txn, the_sql, args), sql
376379
)
377380
else:
381+
# TODO: is it safe for values to be Iterable[Iterable[Any]] here?
382+
# https://docs.python.org/3/library/sqlite3.html?highlight=sqlite3#sqlite3.Cursor.executemany
383+
# suggests that the outer collection may be iterable, but
384+
# https://docs.python.org/3/library/sqlite3.html?highlight=sqlite3#how-to-use-placeholders-to-bind-values-in-sql-queries
385+
# suggests that the inner collection should be a sequence or dict.
378386
self.executemany(sql, args)
379387

380388
def execute_values(
@@ -390,14 +398,20 @@ def execute_values(
390398
from psycopg2.extras import execute_values
391399

392400
return self._do_execute(
401+
# TODO: is it safe for values to be Iterable[Iterable[Any]] here?
402+
# https://www.psycopg.org/docs/extras.html?highlight=execute_batch#psycopg2.extras.execute_values says values should be Sequence[Sequence]
393403
lambda the_sql: execute_values(self.txn, the_sql, values, fetch=fetch),
394404
sql,
395405
)
396406

397-
def execute(self, sql: str, *args: Any) -> None:
398-
self._do_execute(self.txn.execute, sql, *args)
407+
def execute(self, sql: str, parameters: SQLQueryParameters = ()) -> None:
408+
self._do_execute(self.txn.execute, sql, parameters)
399409

400410
def executemany(self, sql: str, *args: Any) -> None:
411+
# TODO: we should add a type for *args here. Looking at Cursor.executemany
412+
# and DBAPI2 it ought to be Sequence[_Parameter], but we pass in
413+
# Iterable[Iterable[Any]] in execute_batch and execute_values above, which mypy
414+
# complains about.
401415
self._do_execute(self.txn.executemany, sql, *args)
402416

403417
def executescript(self, sql: str) -> None:

synapse/storage/databases/main/event_federation.py

+11-8
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,10 @@ def __init__(self, room_id: str):
114114

115115

116116
class EventFederationWorkerStore(SignatureWorkerStore, EventsWorkerStore, SQLBaseStore):
117+
# TODO: this attribute comes from EventPushActionWorkerStore. Should we inherit from
118+
# that store so that mypy can deduce this for itself?
119+
stream_ordering_month_ago: Optional[int]
120+
117121
def __init__(
118122
self,
119123
database: DatabasePool,
@@ -1182,8 +1186,8 @@ async def have_room_forward_extremities_changed_since(
11821186
Throws a StoreError if we have since purged the index for
11831187
stream_orderings from that point.
11841188
"""
1185-
1186-
if stream_ordering <= self.stream_ordering_month_ago: # type: ignore[attr-defined]
1189+
assert self.stream_ordering_month_ago is not None
1190+
if stream_ordering <= self.stream_ordering_month_ago:
11871191
raise StoreError(400, f"stream_ordering too old {stream_ordering}")
11881192

11891193
sql = """
@@ -1231,7 +1235,8 @@ async def get_forward_extremities_for_room_at_stream_ordering(
12311235

12321236
# provided the last_change is recent enough, we now clamp the requested
12331237
# stream_ordering to it.
1234-
if last_change > self.stream_ordering_month_ago: # type: ignore[attr-defined]
1238+
assert self.stream_ordering_month_ago is not None
1239+
if last_change > self.stream_ordering_month_ago:
12351240
stream_ordering = min(last_change, stream_ordering)
12361241

12371242
return await self._get_forward_extremeties_for_room(room_id, stream_ordering)
@@ -1246,8 +1251,8 @@ async def _get_forward_extremeties_for_room(
12461251
Throws a StoreError if we have since purged the index for
12471252
stream_orderings from that point.
12481253
"""
1249-
1250-
if stream_ordering <= self.stream_ordering_month_ago: # type: ignore[attr-defined]
1254+
assert self.stream_ordering_month_ago is not None
1255+
if stream_ordering <= self.stream_ordering_month_ago:
12511256
raise StoreError(400, "stream_ordering too old %s" % (stream_ordering,))
12521257

12531258
sql = """
@@ -1707,9 +1712,7 @@ def _delete_old_forward_extrem_cache_txn(txn: LoggingTransaction) -> None:
17071712
DELETE FROM stream_ordering_to_exterm
17081713
WHERE stream_ordering < ?
17091714
"""
1710-
txn.execute(
1711-
sql, (self.stream_ordering_month_ago,) # type: ignore[attr-defined]
1712-
)
1715+
txn.execute(sql, (self.stream_ordering_month_ago,))
17131716

17141717
await self.db_pool.runInteraction(
17151718
"_delete_old_forward_extrem_cache",

synapse/storage/types.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -31,14 +31,14 @@
3131
Some very basic protocol definitions for the DB-API2 classes specified in PEP-249
3232
"""
3333

34-
_Parameters = Union[Sequence[Any], Mapping[str, Any]]
34+
SQLQueryParameters = Union[Sequence[Any], Mapping[str, Any]]
3535

3636

3737
class Cursor(Protocol):
38-
def execute(self, sql: str, parameters: _Parameters = ...) -> Any:
38+
def execute(self, sql: str, parameters: SQLQueryParameters = ...) -> Any:
3939
...
4040

41-
def executemany(self, sql: str, parameters: Sequence[_Parameters]) -> Any:
41+
def executemany(self, sql: str, parameters: Sequence[SQLQueryParameters]) -> Any:
4242
...
4343

4444
def fetchone(self) -> Optional[Tuple]:

0 commit comments

Comments
 (0)