postgres.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. # Copyright 2015, 2016 OpenMarket Ltd
  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. import abc
  15. import logging
  16. from typing import TYPE_CHECKING, Any, Mapping, Optional, Tuple, Type, cast, Generic
  17. from synapse.storage.engines._base import (
  18. BaseDatabaseEngine,
  19. ConnectionType,
  20. CursorType,
  21. IncorrectDatabaseSetup,
  22. IsolationLevelType,
  23. )
  24. from synapse.storage.types import Cursor, DBAPI2Module
  25. if TYPE_CHECKING:
  26. from synapse.storage.database import LoggingDatabaseConnection
  27. logger = logging.getLogger(__name__)
  28. class PostgresEngine(
  29. Generic[ConnectionType, CursorType, IsolationLevelType],
  30. BaseDatabaseEngine[ConnectionType, CursorType, IsolationLevelType],
  31. metaclass=abc.ABCMeta,
  32. ):
  33. isolation_level_map: Mapping[int, IsolationLevelType]
  34. default_isolation_level: IsolationLevelType
  35. def __init__(self, module: DBAPI2Module, database_config: Mapping[str, Any]):
  36. super().__init__(module, database_config)
  37. self.synchronous_commit: bool = database_config.get("synchronous_commit", True)
  38. # Set the statement timeout to 1 hour by default.
  39. # Any query taking more than 1 hour should probably be considered a bug;
  40. # most of the time this is a sign that work needs to be split up or that
  41. # some degenerate query plan has been created and the client has probably
  42. # timed out/walked off anyway.
  43. # This is in milliseconds.
  44. self.statement_timeout: Optional[int] = database_config.get(
  45. "statement_timeout", 60 * 60 * 1000
  46. )
  47. self._version: Optional[int] = None # unknown as yet
  48. self.config = database_config
  49. @abc.abstractmethod
  50. def get_server_version(self, db_conn: ConnectionType) -> int:
  51. """Gets called when setting up a brand new database. This allows us to
  52. apply stricter checks on new databases versus existing database.
  53. """
  54. ...
  55. @property
  56. def single_threaded(self) -> bool:
  57. return False
  58. def get_db_locale(self, txn: Cursor) -> Tuple[str, str]:
  59. txn.execute(
  60. "SELECT datcollate, datctype FROM pg_database WHERE datname = current_database()"
  61. )
  62. collation, ctype = cast(Tuple[str, str], txn.fetchone())
  63. return collation, ctype
  64. def check_database(
  65. self,
  66. db_conn: ConnectionType,
  67. allow_outdated_version: bool = False,
  68. ) -> None:
  69. # Get the version of PostgreSQL that we're using. As per the psycopg2
  70. # docs: The number is formed by converting the major, minor, and
  71. # revision numbers into two-decimal-digit numbers and appending them
  72. # together. For example, version 8.1.5 will be returned as 80105
  73. self._version = self.get_server_version(db_conn)
  74. allow_unsafe_locale = self.config.get("allow_unsafe_locale", False)
  75. # Are we on a supported PostgreSQL version?
  76. if not allow_outdated_version and self._version < 110000:
  77. raise RuntimeError("Synapse requires PostgreSQL 11 or above.")
  78. # psycopg and psycopg2 both support using cursors as context managers.
  79. with db_conn.cursor() as txn: # type: ignore[attr-defined]
  80. txn.execute("SHOW SERVER_ENCODING")
  81. rows = txn.fetchall()
  82. if rows and rows[0][0] != "UTF8":
  83. raise IncorrectDatabaseSetup(
  84. "Database has incorrect encoding: '%s' instead of 'UTF8'\n"
  85. "See docs/postgres.md for more information." % (rows[0][0],)
  86. )
  87. collation, ctype = self.get_db_locale(txn)
  88. if collation != "C":
  89. logger.warning(
  90. "Database has incorrect collation of %r. Should be 'C'",
  91. collation,
  92. )
  93. if not allow_unsafe_locale:
  94. raise IncorrectDatabaseSetup(
  95. "Database has incorrect collation of %r. Should be 'C'\n"
  96. "See docs/postgres.md for more information. You can override this check by"
  97. "setting 'allow_unsafe_locale' to true in the database config.",
  98. collation,
  99. )
  100. if ctype != "C":
  101. if not allow_unsafe_locale:
  102. logger.warning(
  103. "Database has incorrect ctype of %r. Should be 'C'",
  104. ctype,
  105. )
  106. raise IncorrectDatabaseSetup(
  107. "Database has incorrect ctype of %r. Should be 'C'\n"
  108. "See docs/postgres.md for more information. You can override this check by"
  109. "setting 'allow_unsafe_locale' to true in the database config.",
  110. ctype,
  111. )
  112. def check_new_database(self, txn: Cursor) -> None:
  113. """Gets called when setting up a brand new database. This allows us to
  114. apply stricter checks on new databases versus existing database.
  115. """
  116. collation, ctype = self.get_db_locale(txn)
  117. errors = []
  118. if collation != "C":
  119. errors.append(" - 'COLLATE' is set to %r. Should be 'C'" % (collation,))
  120. if ctype != "C":
  121. errors.append(" - 'CTYPE' is set to %r. Should be 'C'" % (ctype,))
  122. if errors:
  123. raise IncorrectDatabaseSetup(
  124. "Database is incorrectly configured:\n\n%s\n\n"
  125. "See docs/postgres.md for more information." % ("\n".join(errors))
  126. )
  127. def convert_param_style(self, sql: str) -> str:
  128. return sql.replace("?", "%s")
  129. def on_new_connection(self, db_conn: "LoggingDatabaseConnection") -> None:
  130. # mypy doesn't realize that ConnectionType matches the Connection protocol.
  131. self.attempt_to_set_isolation_level(db_conn.conn, self.default_isolation_level) # type: ignore[arg-type]
  132. # Set the bytea output to escape, vs the default of hex
  133. cursor = db_conn.cursor()
  134. cursor.execute("SET bytea_output TO escape")
  135. # Asynchronous commit, don't wait for the server to call fsync before
  136. # ending the transaction.
  137. # https://www.postgresql.org/docs/current/static/wal-async-commit.html
  138. if not self.synchronous_commit:
  139. cursor.execute("SET synchronous_commit TO OFF")
  140. # Abort really long-running statements and turn them into errors.
  141. if self.statement_timeout is not None:
  142. # TODO Avoid a circular import, this needs to be abstracted.
  143. if self.__class__.__name__ == "Psycopg2Engine":
  144. cursor.execute("SET statement_timeout TO ?", (self.statement_timeout,))
  145. else:
  146. cursor.execute(
  147. sql.SQL("SET statement_timeout TO {}").format(
  148. self.statement_timeout
  149. )
  150. )
  151. cursor.close()
  152. db_conn.commit()
  153. @property
  154. def supports_using_any_list(self) -> bool:
  155. """Do we support using `a = ANY(?)` and passing a list"""
  156. return True
  157. @property
  158. def supports_returning(self) -> bool:
  159. """Do we support the `RETURNING` clause in insert/update/delete?"""
  160. return True
  161. def is_connection_closed(self, conn: ConnectionType) -> bool:
  162. # Both psycopg and psycopg2 connections have a closed attributed.
  163. return bool(conn.closed) # type: ignore[attr-defined]
  164. def lock_table(self, txn: Cursor, table: str) -> None:
  165. txn.execute("LOCK TABLE %s in EXCLUSIVE MODE" % (table,))
  166. @property
  167. def server_version(self) -> str:
  168. """Returns a string giving the server version. For example: '8.1.5'."""
  169. # note that this is a bit of a hack because it relies on check_database
  170. # having been called. Still, that should be a safe bet here.
  171. numver = self._version
  172. assert numver is not None
  173. # https://www.postgresql.org/docs/current/libpq-status.html#LIBPQ-PQSERVERVERSION
  174. if numver >= 100000:
  175. return "%i.%i" % (numver / 10000, numver % 10000)
  176. else:
  177. return "%i.%i.%i" % (numver / 10000, (numver % 10000) / 100, numver % 100)
  178. @property
  179. def row_id_name(self) -> str:
  180. return "ctid"
  181. @staticmethod
  182. def executescript(cursor: CursorType, script: str) -> None:
  183. """Execute a chunk of SQL containing multiple semicolon-delimited statements.
  184. Psycopg2 seems happy to do this in DBAPI2's `execute()` function.
  185. For consistency with SQLite, any ongoing transaction is committed before
  186. executing the script in its own transaction. The script transaction is
  187. left open and it is the responsibility of the caller to commit it.
  188. """
  189. cursor.execute(f"COMMIT; BEGIN TRANSACTION; {script}")