postgres.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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 synapse.storage.engines._base import BaseDatabaseEngine, IncorrectDatabaseSetup
  16. from synapse.storage.types import Connection
  17. logger = logging.getLogger(__name__)
  18. class PostgresEngine(BaseDatabaseEngine):
  19. def __init__(self, database_module, database_config):
  20. super().__init__(database_module, database_config)
  21. self.module.extensions.register_type(self.module.extensions.UNICODE)
  22. # Disables passing `bytes` to txn.execute, c.f. #6186. If you do
  23. # actually want to use bytes than wrap it in `bytearray`.
  24. def _disable_bytes_adapter(_):
  25. raise Exception("Passing bytes to DB is disabled.")
  26. self.module.extensions.register_adapter(bytes, _disable_bytes_adapter)
  27. self.synchronous_commit = database_config.get("synchronous_commit", True)
  28. self._version = None # unknown as yet
  29. @property
  30. def single_threaded(self) -> bool:
  31. return False
  32. def check_database(self, db_conn, allow_outdated_version: bool = False):
  33. # Get the version of PostgreSQL that we're using. As per the psycopg2
  34. # docs: The number is formed by converting the major, minor, and
  35. # revision numbers into two-decimal-digit numbers and appending them
  36. # together. For example, version 8.1.5 will be returned as 80105
  37. self._version = db_conn.server_version
  38. # Are we on a supported PostgreSQL version?
  39. if not allow_outdated_version and self._version < 90600:
  40. raise RuntimeError("Synapse requires PostgreSQL 9.6 or above.")
  41. with db_conn.cursor() as txn:
  42. txn.execute("SHOW SERVER_ENCODING")
  43. rows = txn.fetchall()
  44. if rows and rows[0][0] != "UTF8":
  45. raise IncorrectDatabaseSetup(
  46. "Database has incorrect encoding: '%s' instead of 'UTF8'\n"
  47. "See docs/postgres.md for more information." % (rows[0][0],)
  48. )
  49. txn.execute(
  50. "SELECT datcollate, datctype FROM pg_database WHERE datname = current_database()"
  51. )
  52. collation, ctype = txn.fetchone()
  53. if collation != "C":
  54. logger.warning(
  55. "Database has incorrect collation of %r. Should be 'C'\n"
  56. "See docs/postgres.md for more information.",
  57. collation,
  58. )
  59. if ctype != "C":
  60. logger.warning(
  61. "Database has incorrect ctype of %r. Should be 'C'\n"
  62. "See docs/postgres.md for more information.",
  63. ctype,
  64. )
  65. def check_new_database(self, txn):
  66. """Gets called when setting up a brand new database. This allows us to
  67. apply stricter checks on new databases versus existing database.
  68. """
  69. txn.execute(
  70. "SELECT datcollate, datctype FROM pg_database WHERE datname = current_database()"
  71. )
  72. collation, ctype = txn.fetchone()
  73. errors = []
  74. if collation != "C":
  75. errors.append(" - 'COLLATE' is set to %r. Should be 'C'" % (collation,))
  76. if ctype != "C":
  77. errors.append(" - 'CTYPE' is set to %r. Should be 'C'" % (ctype,))
  78. if errors:
  79. raise IncorrectDatabaseSetup(
  80. "Database is incorrectly configured:\n\n%s\n\n"
  81. "See docs/postgres.md for more information." % ("\n".join(errors))
  82. )
  83. def convert_param_style(self, sql):
  84. return sql.replace("?", "%s")
  85. def on_new_connection(self, db_conn):
  86. db_conn.set_isolation_level(
  87. self.module.extensions.ISOLATION_LEVEL_REPEATABLE_READ
  88. )
  89. # Set the bytea output to escape, vs the default of hex
  90. cursor = db_conn.cursor()
  91. cursor.execute("SET bytea_output TO escape")
  92. # Asynchronous commit, don't wait for the server to call fsync before
  93. # ending the transaction.
  94. # https://www.postgresql.org/docs/current/static/wal-async-commit.html
  95. if not self.synchronous_commit:
  96. cursor.execute("SET synchronous_commit TO OFF")
  97. cursor.close()
  98. db_conn.commit()
  99. @property
  100. def can_native_upsert(self):
  101. """
  102. Can we use native UPSERTs?
  103. """
  104. return True
  105. @property
  106. def supports_using_any_list(self):
  107. """Do we support using `a = ANY(?)` and passing a list"""
  108. return True
  109. @property
  110. def supports_returning(self) -> bool:
  111. """Do we support the `RETURNING` clause in insert/update/delete?"""
  112. return True
  113. def is_deadlock(self, error):
  114. if isinstance(error, self.module.DatabaseError):
  115. # https://www.postgresql.org/docs/current/static/errcodes-appendix.html
  116. # "40001" serialization_failure
  117. # "40P01" deadlock_detected
  118. return error.pgcode in ["40001", "40P01"]
  119. return False
  120. def is_connection_closed(self, conn):
  121. return bool(conn.closed)
  122. def lock_table(self, txn, table):
  123. txn.execute("LOCK TABLE %s in EXCLUSIVE MODE" % (table,))
  124. @property
  125. def server_version(self):
  126. """Returns a string giving the server version. For example: '8.1.5'
  127. Returns:
  128. string
  129. """
  130. # note that this is a bit of a hack because it relies on check_database
  131. # having been called. Still, that should be a safe bet here.
  132. numver = self._version
  133. assert numver is not None
  134. # https://www.postgresql.org/docs/current/libpq-status.html#LIBPQ-PQSERVERVERSION
  135. if numver >= 100000:
  136. return "%i.%i" % (numver / 10000, numver % 10000)
  137. else:
  138. return "%i.%i.%i" % (numver / 10000, (numver % 10000) / 100, numver % 100)
  139. def in_transaction(self, conn: Connection) -> bool:
  140. return conn.status != self.module.extensions.STATUS_READY # type: ignore
  141. def attempt_to_set_autocommit(self, conn: Connection, autocommit: bool):
  142. return conn.set_session(autocommit=autocommit) # type: ignore