Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

205 rindas
6.4 KiB

  1. # Copyright 2020 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from types import TracebackType
  15. from typing import (
  16. Any,
  17. Callable,
  18. Iterator,
  19. List,
  20. Mapping,
  21. Optional,
  22. Sequence,
  23. Tuple,
  24. Type,
  25. Union,
  26. )
  27. from typing_extensions import Protocol
  28. """
  29. Some very basic protocol definitions for the DB-API2 classes specified in PEP-249
  30. """
  31. SQLQueryParameters = Union[Sequence[Any], Mapping[str, Any]]
  32. class Cursor(Protocol):
  33. def execute(self, sql: str, parameters: SQLQueryParameters = ...) -> Any:
  34. ...
  35. def executemany(self, sql: str, parameters: Sequence[SQLQueryParameters]) -> Any:
  36. ...
  37. def fetchone(self) -> Optional[Tuple]:
  38. ...
  39. def fetchmany(self, size: Optional[int] = ...) -> List[Tuple]:
  40. ...
  41. def fetchall(self) -> List[Tuple]:
  42. ...
  43. @property
  44. def description(
  45. self,
  46. ) -> Optional[Sequence[Any]]:
  47. # At the time of writing, Synapse only assumes that `column[0]: str` for each
  48. # `column in description`. Since this is hard to express in the type system, and
  49. # as this is rarely used in Synapse, we deem `column: Any` good enough.
  50. ...
  51. @property
  52. def rowcount(self) -> int:
  53. return 0
  54. def __iter__(self) -> Iterator[Tuple]:
  55. ...
  56. def close(self) -> None:
  57. ...
  58. class Connection(Protocol):
  59. def cursor(self) -> Cursor:
  60. ...
  61. def close(self) -> None:
  62. ...
  63. def commit(self) -> None:
  64. ...
  65. def rollback(self) -> None:
  66. ...
  67. def __enter__(self) -> "Connection":
  68. ...
  69. def __exit__(
  70. self,
  71. exc_type: Optional[Type[BaseException]],
  72. exc_value: Optional[BaseException],
  73. traceback: Optional[TracebackType],
  74. ) -> Optional[bool]:
  75. ...
  76. class DBAPI2Module(Protocol):
  77. """The module-level attributes that we use from PEP 249.
  78. This is NOT a comprehensive stub for the entire DBAPI2."""
  79. __name__: str
  80. # Exceptions. See https://peps.python.org/pep-0249/#exceptions
  81. # For our specific drivers:
  82. # - Python's sqlite3 module doesn't contains the same descriptions as the
  83. # DBAPI2 spec, see https://docs.python.org/3/library/sqlite3.html#exceptions
  84. # - Psycopg2 maps every Postgres error code onto a unique exception class which
  85. # extends from this hierarchy. See
  86. # https://docs.python.org/3/library/sqlite3.html?highlight=sqlite3#exceptions
  87. # https://www.postgresql.org/docs/current/errcodes-appendix.html#ERRCODES-TABLE
  88. #
  89. # Note: rather than
  90. # x: T
  91. # we write
  92. # @property
  93. # def x(self) -> T: ...
  94. # which expresses that the protocol attribute `x` is read-only. The mypy docs
  95. # https://mypy.readthedocs.io/en/latest/common_issues.html#covariant-subtyping-of-mutable-protocol-members-is-rejected
  96. # explain why this is necessary for safety. TL;DR: we shouldn't be able to write
  97. # to `x`, only read from it. See also https://github.com/python/mypy/issues/6002 .
  98. @property
  99. def Warning(self) -> Type[Exception]:
  100. ...
  101. @property
  102. def Error(self) -> Type[Exception]:
  103. ...
  104. # Errors are divided into `InterfaceError`s (something went wrong in the database
  105. # driver) and `DatabaseError`s (something went wrong in the database). These are
  106. # both subclasses of `Error`, but we can't currently express this in type
  107. # annotations due to https://github.com/python/mypy/issues/8397
  108. @property
  109. def InterfaceError(self) -> Type[Exception]:
  110. ...
  111. @property
  112. def DatabaseError(self) -> Type[Exception]:
  113. ...
  114. # Everything below is a subclass of `DatabaseError`.
  115. # Roughly: the database rejected a nonsensical value. Examples:
  116. # - An integer was too big for its data type.
  117. # - An invalid date time was provided.
  118. # - A string contained a null code point.
  119. @property
  120. def DataError(self) -> Type[Exception]:
  121. ...
  122. # Roughly: something went wrong in the database, but it's not within the application
  123. # programmer's control. Examples:
  124. # - We failed to establish a connection to the database.
  125. # - The connection to the database was lost.
  126. # - A deadlock was detected.
  127. # - A serialisation failure occurred.
  128. # - The database ran out of resources, such as storage, memory, connections, etc.
  129. # - The database encountered an error from the operating system.
  130. @property
  131. def OperationalError(self) -> Type[Exception]:
  132. ...
  133. # Roughly: we've given the database data which breaks a rule we asked it to enforce.
  134. # Examples:
  135. # - Stop, criminal scum! You violated the foreign key constraint
  136. # - Also check constraints, non-null constraints, etc.
  137. @property
  138. def IntegrityError(self) -> Type[Exception]:
  139. ...
  140. # Roughly: something went wrong within the database server itself.
  141. @property
  142. def InternalError(self) -> Type[Exception]:
  143. ...
  144. # Roughly: the application did something silly that needs to be fixed. Examples:
  145. # - We don't have permissions to do something.
  146. # - We tried to create a table with duplicate column names.
  147. # - We tried to use a reserved name.
  148. # - We referred to a column that doesn't exist.
  149. @property
  150. def ProgrammingError(self) -> Type[Exception]:
  151. ...
  152. # Roughly: we've tried to do something that this database doesn't support.
  153. @property
  154. def NotSupportedError(self) -> Type[Exception]:
  155. ...
  156. # We originally wrote
  157. # def connect(self, *args, **kwargs) -> Connection: ...
  158. # But mypy doesn't seem to like that because sqlite3.connect takes a mandatory
  159. # positional argument. We can't make that part of the signature though, because
  160. # psycopg2.connect doesn't have a mandatory positional argument. Instead, we use
  161. # the following slightly unusual workaround.
  162. @property
  163. def connect(self) -> Callable[..., Connection]:
  164. ...
  165. __all__ = ["Cursor", "Connection", "DBAPI2Module"]