You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

247 lines
9.9 KiB

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