sqlite.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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 platform
  15. import sqlite3
  16. import struct
  17. import threading
  18. from typing import TYPE_CHECKING, Any, List, Mapping, Optional
  19. from synapse.storage.engines import BaseDatabaseEngine
  20. from synapse.storage.types import Cursor
  21. if TYPE_CHECKING:
  22. from synapse.storage.database import LoggingDatabaseConnection
  23. class Sqlite3Engine(BaseDatabaseEngine[sqlite3.Connection]):
  24. def __init__(self, database_config: Mapping[str, Any]):
  25. super().__init__(sqlite3, database_config)
  26. database = database_config.get("args", {}).get("database")
  27. self._is_in_memory = database in (
  28. None,
  29. ":memory:",
  30. )
  31. if platform.python_implementation() == "PyPy":
  32. # pypy's sqlite3 module doesn't handle bytearrays, convert them
  33. # back to bytes.
  34. sqlite3.register_adapter(bytearray, lambda array: bytes(array))
  35. # The current max state_group, or None if we haven't looked
  36. # in the DB yet.
  37. self._current_state_group_id = None
  38. self._current_state_group_id_lock = threading.Lock()
  39. @property
  40. def single_threaded(self) -> bool:
  41. return True
  42. @property
  43. def can_native_upsert(self) -> bool:
  44. """
  45. Do we support native UPSERTs? This requires SQLite3 3.24+, plus some
  46. more work we haven't done yet to tell what was inserted vs updated.
  47. """
  48. return sqlite3.sqlite_version_info >= (3, 24, 0)
  49. @property
  50. def supports_using_any_list(self) -> bool:
  51. """Do we support using `a = ANY(?)` and passing a list"""
  52. return False
  53. @property
  54. def supports_returning(self) -> bool:
  55. """Do we support the `RETURNING` clause in insert/update/delete?"""
  56. return sqlite3.sqlite_version_info >= (3, 35, 0)
  57. def check_database(
  58. self, db_conn: sqlite3.Connection, allow_outdated_version: bool = False
  59. ) -> None:
  60. if not allow_outdated_version:
  61. version = sqlite3.sqlite_version_info
  62. # Synapse is untested against older SQLite versions, and we don't want
  63. # to let users upgrade to a version of Synapse with broken support for their
  64. # sqlite version, because it risks leaving them with a half-upgraded db.
  65. if version < (3, 22, 0):
  66. raise RuntimeError("Synapse requires sqlite 3.22 or above.")
  67. def check_new_database(self, txn: Cursor) -> None:
  68. """Gets called when setting up a brand new database. This allows us to
  69. apply stricter checks on new databases versus existing database.
  70. """
  71. def convert_param_style(self, sql: str) -> str:
  72. return sql
  73. def on_new_connection(self, db_conn: "LoggingDatabaseConnection") -> None:
  74. # We need to import here to avoid an import loop.
  75. from synapse.storage.prepare_database import prepare_database
  76. if self._is_in_memory:
  77. # In memory databases need to be rebuilt each time. Ideally we'd
  78. # reuse the same connection as we do when starting up, but that
  79. # would involve using adbapi before we have started the reactor.
  80. prepare_database(db_conn, self, config=None)
  81. db_conn.create_function("rank", 1, _rank)
  82. db_conn.execute("PRAGMA foreign_keys = ON;")
  83. db_conn.commit()
  84. def is_deadlock(self, error: Exception) -> bool:
  85. return False
  86. def is_connection_closed(self, conn: sqlite3.Connection) -> bool:
  87. return False
  88. def lock_table(self, txn: Cursor, table: str) -> None:
  89. return
  90. @property
  91. def server_version(self) -> str:
  92. """Gets a string giving the server version. For example: '3.22.0'."""
  93. return "%i.%i.%i" % sqlite3.sqlite_version_info
  94. def in_transaction(self, conn: sqlite3.Connection) -> bool:
  95. return conn.in_transaction
  96. def attempt_to_set_autocommit(
  97. self, conn: sqlite3.Connection, autocommit: bool
  98. ) -> None:
  99. # Twisted doesn't let us set attributes on the connections, so we can't
  100. # set the connection to autocommit mode.
  101. pass
  102. def attempt_to_set_isolation_level(
  103. self, conn: sqlite3.Connection, isolation_level: Optional[int]
  104. ) -> None:
  105. # All transactions are SERIALIZABLE by default in sqlite
  106. pass
  107. # Following functions taken from: https://github.com/coleifer/peewee
  108. def _parse_match_info(buf: bytes) -> List[int]:
  109. bufsize = len(buf)
  110. return [struct.unpack("@I", buf[i : i + 4])[0] for i in range(0, bufsize, 4)]
  111. def _rank(raw_match_info: bytes) -> float:
  112. """Handle match_info called w/default args 'pcx' - based on the example rank
  113. function http://sqlite.org/fts3.html#appendix_a
  114. """
  115. match_info = _parse_match_info(raw_match_info)
  116. score = 0.0
  117. p, c = match_info[:2]
  118. for phrase_num in range(p):
  119. phrase_info_idx = 2 + (phrase_num * c * 3)
  120. for col_num in range(c):
  121. col_idx = phrase_info_idx + (col_num * 3)
  122. x1, x2 = match_info[col_idx : col_idx + 2]
  123. if x1 > 0:
  124. score += float(x1) / x2
  125. return score