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

Commit 467b2a0

Browse files
author
David Robertson
committed
Let's disallow untyped defs while I'm at it
1 parent 7cf1719 commit 467b2a0

File tree

4 files changed

+75
-60
lines changed

4 files changed

+75
-60
lines changed

mypy.ini

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,9 @@ disallow_untyped_defs = True
232232
[mypy-synapse.storage.databases.main.user_erasure_store]
233233
disallow_untyped_defs = True
234234

235+
[mypy-synapse.storage.engines.*]
236+
disallow_untyped_defs = True
237+
235238
[mypy-synapse.storage.prepare_database]
236239
disallow_untyped_defs = True
237240

synapse/storage/engines/_base.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,12 @@
1313
# limitations under the License.
1414
import abc
1515
from enum import IntEnum
16-
from typing import Generic, Optional, TypeVar
16+
from typing import TYPE_CHECKING, Generic, Optional, TypeVar
1717

18-
from synapse.storage.types import Connection, DBAPI2Module
18+
from synapse.storage.types import Connection, Cursor, DBAPI2Module
19+
20+
if TYPE_CHECKING:
21+
from synapse.storage.database import LoggingDatabaseConnection
1922

2023

2124
class IsolationLevel(IntEnum):
@@ -69,7 +72,7 @@ def check_database(
6972
...
7073

7174
@abc.abstractmethod
72-
def check_new_database(self, txn) -> None:
75+
def check_new_database(self, txn: Cursor) -> None:
7376
"""Gets called when setting up a brand new database. This allows us to
7477
apply stricter checks on new databases versus existing database.
7578
"""
@@ -79,8 +82,11 @@ def check_new_database(self, txn) -> None:
7982
def convert_param_style(self, sql: str) -> str:
8083
...
8184

85+
# This method would ideally take a plain ConnectionType, but it seems that
86+
# the Sqlite engine expects to use LoggingDatabaseConnection.cursor
87+
# instead of sqlite3.Connection.cursor: only the former takes a txn_name.
8288
@abc.abstractmethod
83-
def on_new_connection(self, db_conn: ConnectionType) -> None:
89+
def on_new_connection(self, db_conn: "LoggingDatabaseConnection") -> None:
8490
...
8591

8692
@abc.abstractmethod
@@ -92,7 +98,7 @@ def is_connection_closed(self, conn: ConnectionType) -> bool:
9298
...
9399

94100
@abc.abstractmethod
95-
def lock_table(self, txn, table: str) -> None:
101+
def lock_table(self, txn: Cursor, table: str) -> None:
96102
...
97103

98104
@property
@@ -107,7 +113,7 @@ def in_transaction(self, conn: ConnectionType) -> bool:
107113
...
108114

109115
@abc.abstractmethod
110-
def attempt_to_set_autocommit(self, conn: ConnectionType, autocommit: bool):
116+
def attempt_to_set_autocommit(self, conn: ConnectionType, autocommit: bool) -> None:
111117
"""Attempt to set the connections autocommit mode.
112118
113119
When True queries are run outside of transactions.
@@ -120,7 +126,7 @@ def attempt_to_set_autocommit(self, conn: ConnectionType, autocommit: bool):
120126
@abc.abstractmethod
121127
def attempt_to_set_isolation_level(
122128
self, conn: ConnectionType, isolation_level: Optional[int]
123-
):
129+
) -> None:
124130
"""Attempt to set the connections isolation level.
125131
126132
Note: This has no effect on SQLite3, as transactions are SERIALIZABLE by default.

synapse/storage/engines/postgres.py

Lines changed: 31 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -13,18 +13,21 @@
1313
# limitations under the License.
1414

1515
import logging
16-
from typing import TYPE_CHECKING, Any, Mapping, Optional, cast
16+
from typing import TYPE_CHECKING, Any, Mapping, NoReturn, Optional, Tuple, cast
1717

1818
from synapse.storage.engines._base import (
1919
BaseDatabaseEngine,
2020
IncorrectDatabaseSetup,
2121
IsolationLevel,
2222
)
23-
from synapse.storage.types import Connection
23+
from synapse.storage.types import Cursor
2424

2525
if TYPE_CHECKING:
2626
import psycopg2 # noqa: F401
2727

28+
from synapse.storage.database import LoggingDatabaseConnection
29+
30+
2831
logger = logging.getLogger(__name__)
2932

3033

@@ -37,11 +40,11 @@ def __init__(self, database_config: Mapping[str, Any]):
3740

3841
# Disables passing `bytes` to txn.execute, c.f. #6186. If you do
3942
# actually want to use bytes than wrap it in `bytearray`.
40-
def _disable_bytes_adapter(_):
43+
def _disable_bytes_adapter(_: bytes) -> NoReturn:
4144
raise Exception("Passing bytes to DB is disabled.")
4245

4346
psycopg2.extensions.register_adapter(bytes, _disable_bytes_adapter)
44-
self.synchronous_commit = database_config.get("synchronous_commit", True)
47+
self.synchronous_commit: bool = database_config.get("synchronous_commit", True)
4548
self._version: Optional[int] = None # unknown as yet
4649

4750
self.isolation_level_map: Mapping[int, int] = {
@@ -58,14 +61,16 @@ def _disable_bytes_adapter(_):
5861
def single_threaded(self) -> bool:
5962
return False
6063

61-
def get_db_locale(self, txn):
64+
def get_db_locale(self, txn: Cursor) -> Tuple[str, str]:
6265
txn.execute(
6366
"SELECT datcollate, datctype FROM pg_database WHERE datname = current_database()"
6467
)
65-
collation, ctype = txn.fetchone()
68+
collation, ctype = cast(Tuple[str, str], txn.fetchone())
6669
return collation, ctype
6770

68-
def check_database(self, db_conn, allow_outdated_version: bool = False):
71+
def check_database(
72+
self, db_conn: "psycopg2.connection", allow_outdated_version: bool = False
73+
) -> None:
6974
# Get the version of PostgreSQL that we're using. As per the psycopg2
7075
# docs: The number is formed by converting the major, minor, and
7176
# revision numbers into two-decimal-digit numbers and appending them
@@ -113,7 +118,7 @@ def check_database(self, db_conn, allow_outdated_version: bool = False):
113118
ctype,
114119
)
115120

116-
def check_new_database(self, txn):
121+
def check_new_database(self, txn: Cursor) -> None:
117122
"""Gets called when setting up a brand new database. This allows us to
118123
apply stricter checks on new databases versus existing database.
119124
"""
@@ -134,10 +139,10 @@ def check_new_database(self, txn):
134139
"See docs/postgres.md for more information." % ("\n".join(errors))
135140
)
136141

137-
def convert_param_style(self, sql):
142+
def convert_param_style(self, sql: str) -> str:
138143
return sql.replace("?", "%s")
139144

140-
def on_new_connection(self, db_conn):
145+
def on_new_connection(self, db_conn: "LoggingDatabaseConnection") -> None:
141146
db_conn.set_isolation_level(self.default_isolation_level)
142147

143148
# Set the bytea output to escape, vs the default of hex
@@ -154,14 +159,14 @@ def on_new_connection(self, db_conn):
154159
db_conn.commit()
155160

156161
@property
157-
def can_native_upsert(self):
162+
def can_native_upsert(self) -> bool:
158163
"""
159164
Can we use native UPSERTs?
160165
"""
161166
return True
162167

163168
@property
164-
def supports_using_any_list(self):
169+
def supports_using_any_list(self) -> bool:
165170
"""Do we support using `a = ANY(?)` and passing a list"""
166171
return True
167172

@@ -170,7 +175,7 @@ def supports_returning(self) -> bool:
170175
"""Do we support the `RETURNING` clause in insert/update/delete?"""
171176
return True
172177

173-
def is_deadlock(self, error):
178+
def is_deadlock(self, error: Exception) -> bool:
174179
import psycopg2.extensions
175180

176181
if isinstance(error, psycopg2.DatabaseError):
@@ -180,19 +185,15 @@ def is_deadlock(self, error):
180185
return error.pgcode in ["40001", "40P01"]
181186
return False
182187

183-
def is_connection_closed(self, conn):
188+
def is_connection_closed(self, conn: "psycopg2.connection") -> bool:
184189
return bool(conn.closed)
185190

186-
def lock_table(self, txn, table):
191+
def lock_table(self, txn: Cursor, table: str) -> None:
187192
txn.execute("LOCK TABLE %s in EXCLUSIVE MODE" % (table,))
188193

189194
@property
190-
def server_version(self):
191-
"""Returns a string giving the server version. For example: '8.1.5'
192-
193-
Returns:
194-
string
195-
"""
195+
def server_version(self) -> str:
196+
"""Returns a string giving the server version. For example: '8.1.5'."""
196197
# note that this is a bit of a hack because it relies on check_database
197198
# having been called. Still, that should be a safe bet here.
198199
numver = self._version
@@ -204,19 +205,21 @@ def server_version(self):
204205
else:
205206
return "%i.%i.%i" % (numver / 10000, (numver % 10000) / 100, numver % 100)
206207

207-
def in_transaction(self, conn: Connection) -> bool:
208+
def in_transaction(self, conn: "psycopg2.connection") -> bool:
208209
import psycopg2.extensions
209210

210-
return conn.status != psycopg2.extensions.STATUS_READY # type: ignore
211+
return conn.status != psycopg2.extensions.STATUS_READY
211212

212-
def attempt_to_set_autocommit(self, conn: Connection, autocommit: bool):
213-
return conn.set_session(autocommit=autocommit) # type: ignore
213+
def attempt_to_set_autocommit(
214+
self, conn: "psycopg2.connection", autocommit: bool
215+
) -> None:
216+
return conn.set_session(autocommit=autocommit)
214217

215218
def attempt_to_set_isolation_level(
216-
self, conn: Connection, isolation_level: Optional[int]
217-
):
219+
self, conn: "psycopg2.connection", isolation_level: Optional[int]
220+
) -> None:
218221
if isolation_level is None:
219222
isolation_level = self.default_isolation_level
220223
else:
221224
isolation_level = self.isolation_level_map[isolation_level]
222-
return conn.set_isolation_level(isolation_level) # type: ignore
225+
return conn.set_isolation_level(isolation_level)

synapse/storage/engines/sqlite.py

Lines changed: 28 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,13 @@
1515
import sqlite3
1616
import struct
1717
import threading
18-
from typing import Any, Mapping, Optional
18+
from typing import TYPE_CHECKING, Any, List, Mapping, Optional
1919

2020
from synapse.storage.engines import BaseDatabaseEngine
21-
from synapse.storage.types import Connection
21+
from synapse.storage.types import Cursor
22+
23+
if TYPE_CHECKING:
24+
from synapse.storage.database import LoggingDatabaseConnection
2225

2326

2427
class Sqlite3Engine(BaseDatabaseEngine[sqlite3.Connection]):
@@ -46,15 +49,15 @@ def single_threaded(self) -> bool:
4649
return True
4750

4851
@property
49-
def can_native_upsert(self):
52+
def can_native_upsert(self) -> bool:
5053
"""
5154
Do we support native UPSERTs? This requires SQLite3 3.24+, plus some
5255
more work we haven't done yet to tell what was inserted vs updated.
5356
"""
5457
return sqlite3.sqlite_version_info >= (3, 24, 0)
5558

5659
@property
57-
def supports_using_any_list(self):
60+
def supports_using_any_list(self) -> bool:
5861
"""Do we support using `a = ANY(?)` and passing a list"""
5962
return False
6063

@@ -63,7 +66,9 @@ def supports_returning(self) -> bool:
6366
"""Do we support the `RETURNING` clause in insert/update/delete?"""
6467
return sqlite3.sqlite_version_info >= (3, 35, 0)
6568

66-
def check_database(self, db_conn, allow_outdated_version: bool = False):
69+
def check_database(
70+
self, db_conn: sqlite3.Connection, allow_outdated_version: bool = False
71+
) -> None:
6772
if not allow_outdated_version:
6873
version = sqlite3.sqlite_version_info
6974
# Synapse is untested against older SQLite versions, and we don't want
@@ -72,15 +77,15 @@ def check_database(self, db_conn, allow_outdated_version: bool = False):
7277
if version < (3, 22, 0):
7378
raise RuntimeError("Synapse requires sqlite 3.22 or above.")
7479

75-
def check_new_database(self, txn):
80+
def check_new_database(self, txn: Cursor) -> None:
7681
"""Gets called when setting up a brand new database. This allows us to
7782
apply stricter checks on new databases versus existing database.
7883
"""
7984

80-
def convert_param_style(self, sql):
85+
def convert_param_style(self, sql: str) -> str:
8186
return sql
8287

83-
def on_new_connection(self, db_conn):
88+
def on_new_connection(self, db_conn: "LoggingDatabaseConnection") -> None:
8489
# We need to import here to avoid an import loop.
8590
from synapse.storage.prepare_database import prepare_database
8691

@@ -94,48 +99,46 @@ def on_new_connection(self, db_conn):
9499
db_conn.execute("PRAGMA foreign_keys = ON;")
95100
db_conn.commit()
96101

97-
def is_deadlock(self, error):
102+
def is_deadlock(self, error: Exception) -> bool:
98103
return False
99104

100-
def is_connection_closed(self, conn):
105+
def is_connection_closed(self, conn: sqlite3.Connection) -> bool:
101106
return False
102107

103-
def lock_table(self, txn, table):
108+
def lock_table(self, txn: Cursor, table: str) -> None:
104109
return
105110

106111
@property
107-
def server_version(self):
108-
"""Gets a string giving the server version. For example: '3.22.0'
109-
110-
Returns:
111-
string
112-
"""
112+
def server_version(self) -> str:
113+
"""Gets a string giving the server version. For example: '3.22.0'."""
113114
return "%i.%i.%i" % sqlite3.sqlite_version_info
114115

115-
def in_transaction(self, conn: Connection) -> bool:
116-
return conn.in_transaction # type: ignore
116+
def in_transaction(self, conn: sqlite3.Connection) -> bool:
117+
return conn.in_transaction
117118

118-
def attempt_to_set_autocommit(self, conn: Connection, autocommit: bool):
119+
def attempt_to_set_autocommit(
120+
self, conn: sqlite3.Connection, autocommit: bool
121+
) -> None:
119122
# Twisted doesn't let us set attributes on the connections, so we can't
120123
# set the connection to autocommit mode.
121124
pass
122125

123126
def attempt_to_set_isolation_level(
124-
self, conn: Connection, isolation_level: Optional[int]
125-
):
126-
# All transactions are SERIALIZABLE by default in sqllite
127+
self, conn: sqlite3.Connection, isolation_level: Optional[int]
128+
) -> None:
129+
# All transactions are SERIALIZABLE by default in sqlite
127130
pass
128131

129132

130133
# Following functions taken from: https://github.com/coleifer/peewee
131134

132135

133-
def _parse_match_info(buf):
136+
def _parse_match_info(buf: bytes) -> List[int]:
134137
bufsize = len(buf)
135138
return [struct.unpack("@I", buf[i : i + 4])[0] for i in range(0, bufsize, 4)]
136139

137140

138-
def _rank(raw_match_info):
141+
def _rank(raw_match_info: bytes) -> float:
139142
"""Handle match_info called w/default args 'pcx' - based on the example rank
140143
function http://sqlite.org/fts3.html#appendix_a
141144
"""

0 commit comments

Comments
 (0)