File: types.py

package info (click to toggle)
matrix-synapse 1.146.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 79,992 kB
  • sloc: python: 261,671; javascript: 7,230; sql: 4,758; sh: 1,302; perl: 626; makefile: 207
file content (183 lines) | stat: -rw-r--r-- 6,401 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
#
# This file is licensed under the Affero General Public License (AGPL) version 3.
#
# Copyright 2020 The Matrix.org Foundation C.I.C.
# Copyright (C) 2023 New Vector, Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# See the GNU Affero General Public License for more details:
# <https://www.gnu.org/licenses/agpl-3.0.html>.
#
# Originally licensed under the Apache License, Version 2.0:
# <http://www.apache.org/licenses/LICENSE-2.0>.
#
# [This file includes modifications made by New Vector Limited]
#
#
from types import TracebackType
from typing import (
    Any,
    Callable,
    Iterator,
    Mapping,
    Protocol,
    Sequence,
)

"""
Some very basic protocol definitions for the DB-API2 classes specified in PEP-249
"""

SQLQueryParameters = Sequence[Any] | Mapping[str, Any]


class Cursor(Protocol):
    def execute(self, sql: str, parameters: SQLQueryParameters = ...) -> Any: ...

    def executemany(
        self, sql: str, parameters: Sequence[SQLQueryParameters]
    ) -> Any: ...

    def fetchone(self) -> tuple | None: ...

    def fetchmany(self, size: int | None = ...) -> list[tuple]: ...

    def fetchall(self) -> list[tuple]: ...

    @property
    def description(
        self,
    ) -> Sequence[Any] | None:
        # At the time of writing, Synapse only assumes that `column[0]: str` for each
        # `column in description`. Since this is hard to express in the type system, and
        # as this is rarely used in Synapse, we deem `column: Any` good enough.
        ...

    @property
    def rowcount(self) -> int:
        return 0

    def __iter__(self) -> Iterator[tuple]: ...

    def close(self) -> None: ...


class Connection(Protocol):
    def cursor(self) -> Cursor: ...

    def close(self) -> None: ...

    def commit(self) -> None: ...

    def rollback(self) -> None: ...

    def __enter__(self) -> "Connection": ...

    def __exit__(
        self,
        exc_type: type[BaseException] | None,
        exc_value: BaseException | None,
        traceback: TracebackType | None,
    ) -> bool | None: ...


class DBAPI2Module(Protocol):
    """The module-level attributes that we use from PEP 249.

    This is NOT a comprehensive stub for the entire DBAPI2."""

    __name__: str

    # Exceptions. See https://peps.python.org/pep-0249/#exceptions

    # For our specific drivers:
    # - Python's sqlite3 module doesn't contains the same descriptions as the
    #   DBAPI2 spec, see https://docs.python.org/3/library/sqlite3.html#exceptions
    # - Psycopg2 maps every Postgres error code onto a unique exception class which
    #   extends from this hierarchy. See
    #     https://docs.python.org/3/library/sqlite3.html?highlight=sqlite3#exceptions
    #     https://www.postgresql.org/docs/current/errcodes-appendix.html#ERRCODES-TABLE
    #
    # Note: rather than
    #     x: T
    # we write
    #     @property
    #     def x(self) -> T: ...
    # which expresses that the protocol attribute `x` is read-only. The mypy docs
    #     https://mypy.readthedocs.io/en/latest/common_issues.html#covariant-subtyping-of-mutable-protocol-members-is-rejected
    # explain why this is necessary for safety. TL;DR: we shouldn't be able to write
    # to `x`, only read from it. See also https://github.com/python/mypy/issues/6002 .
    @property
    def Warning(self) -> type[Exception]: ...

    @property
    def Error(self) -> type[Exception]: ...

    # Errors are divided into `InterfaceError`s (something went wrong in the database
    # driver) and `DatabaseError`s (something went wrong in the database). These are
    # both subclasses of `Error`, but we can't currently express this in type
    # annotations due to https://github.com/python/mypy/issues/8397
    @property
    def InterfaceError(self) -> type[Exception]: ...

    @property
    def DatabaseError(self) -> type[Exception]: ...

    # Everything below is a subclass of `DatabaseError`.

    # Roughly: the database rejected a nonsensical value. Examples:
    # - An integer was too big for its data type.
    # - An invalid date time was provided.
    # - A string contained a null code point.
    @property
    def DataError(self) -> type[Exception]: ...

    # Roughly: something went wrong in the database, but it's not within the application
    # programmer's control. Examples:
    # - We failed to establish a connection to the database.
    # - The connection to the database was lost.
    # - A deadlock was detected.
    # - A serialisation failure occurred.
    # - The database ran out of resources, such as storage, memory, connections, etc.
    # - The database encountered an error from the operating system.
    @property
    def OperationalError(self) -> type[Exception]: ...

    # Roughly: we've given the database data which breaks a rule we asked it to enforce.
    # Examples:
    # - Stop, criminal scum! You violated the foreign key constraint
    # - Also check constraints, non-null constraints, etc.
    @property
    def IntegrityError(self) -> type[Exception]: ...

    # Roughly: something went wrong within the database server itself.
    @property
    def InternalError(self) -> type[Exception]: ...

    # Roughly: the application did something silly that needs to be fixed. Examples:
    # - We don't have permissions to do something.
    # - We tried to create a table with duplicate column names.
    # - We tried to use a reserved name.
    # - We referred to a column that doesn't exist.
    @property
    def ProgrammingError(self) -> type[Exception]: ...

    # Roughly: we've tried to do something that this database doesn't support.
    @property
    def NotSupportedError(self) -> type[Exception]: ...

    # We originally wrote
    # def connect(self, *args, **kwargs) -> Connection: ...
    # But mypy doesn't seem to like that because sqlite3.connect takes a mandatory
    # positional argument. We can't make that part of the signature though, because
    # psycopg2.connect doesn't have a mandatory positional argument. Instead, we use
    # the following slightly unusual workaround.
    @property
    def connect(self) -> Callable[..., Connection]: ...


__all__ = ["Cursor", "Connection", "DBAPI2Module"]