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.
 
 
 
 
 
 

166 lines
6.1 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 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, sqlite3.Cursor]):
  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 supports_using_any_list(self) -> bool:
  44. """Do we support using `a = ANY(?)` and passing a list"""
  45. return False
  46. @property
  47. def supports_returning(self) -> bool:
  48. """Do we support the `RETURNING` clause in insert/update/delete?"""
  49. return sqlite3.sqlite_version_info >= (3, 35, 0)
  50. def check_database(
  51. self, db_conn: sqlite3.Connection, allow_outdated_version: bool = False
  52. ) -> None:
  53. if not allow_outdated_version:
  54. # Synapse is untested against older SQLite versions, and we don't want
  55. # to let users upgrade to a version of Synapse with broken support for their
  56. # sqlite version, because it risks leaving them with a half-upgraded db.
  57. if sqlite3.sqlite_version_info < (3, 27, 0):
  58. raise RuntimeError("Synapse requires sqlite 3.27 or above.")
  59. def check_new_database(self, txn: Cursor) -> None:
  60. """Gets called when setting up a brand new database. This allows us to
  61. apply stricter checks on new databases versus existing database.
  62. """
  63. def convert_param_style(self, sql: str) -> str:
  64. return sql
  65. def on_new_connection(self, db_conn: "LoggingDatabaseConnection") -> None:
  66. # We need to import here to avoid an import loop.
  67. from synapse.storage.prepare_database import prepare_database
  68. if self._is_in_memory:
  69. # In memory databases need to be rebuilt each time. Ideally we'd
  70. # reuse the same connection as we do when starting up, but that
  71. # would involve using adbapi before we have started the reactor.
  72. prepare_database(db_conn, self, config=None)
  73. db_conn.create_function("rank", 1, _rank)
  74. db_conn.execute("PRAGMA foreign_keys = ON;")
  75. db_conn.commit()
  76. def is_deadlock(self, error: Exception) -> bool:
  77. return False
  78. def is_connection_closed(self, conn: sqlite3.Connection) -> bool:
  79. return False
  80. def lock_table(self, txn: Cursor, table: str) -> None:
  81. return
  82. @property
  83. def server_version(self) -> str:
  84. """Gets a string giving the server version. For example: '3.22.0'."""
  85. return "%i.%i.%i" % sqlite3.sqlite_version_info
  86. def in_transaction(self, conn: sqlite3.Connection) -> bool:
  87. return conn.in_transaction
  88. def attempt_to_set_autocommit(
  89. self, conn: sqlite3.Connection, autocommit: bool
  90. ) -> None:
  91. # Twisted doesn't let us set attributes on the connections, so we can't
  92. # set the connection to autocommit mode.
  93. pass
  94. def attempt_to_set_isolation_level(
  95. self, conn: sqlite3.Connection, isolation_level: Optional[int]
  96. ) -> None:
  97. # All transactions are SERIALIZABLE by default in sqlite
  98. pass
  99. @staticmethod
  100. def executescript(cursor: sqlite3.Cursor, script: str) -> None:
  101. """Execute a chunk of SQL containing multiple semicolon-delimited statements.
  102. Python's built-in SQLite driver does not allow you to do this with DBAPI2's
  103. `execute`:
  104. > execute() will only execute a single SQL statement. If you try to execute more
  105. > than one statement with it, it will raise a Warning. Use executescript() if
  106. > you want to execute multiple SQL statements with one call.
  107. Though the docs for `executescript` warn:
  108. > If there is a pending transaction, an implicit COMMIT statement is executed
  109. > first. No other implicit transaction control is performed; any transaction
  110. > control must be added to sql_script.
  111. """
  112. cursor.executescript(script)
  113. # Following functions taken from: https://github.com/coleifer/peewee
  114. def _parse_match_info(buf: bytes) -> List[int]:
  115. bufsize = len(buf)
  116. return [struct.unpack("@I", buf[i : i + 4])[0] for i in range(0, bufsize, 4)]
  117. def _rank(raw_match_info: bytes) -> float:
  118. """Handle match_info called w/default args 'pcx' - based on the example rank
  119. function http://sqlite.org/fts3.html#appendix_a
  120. """
  121. match_info = _parse_match_info(raw_match_info)
  122. score = 0.0
  123. p, c = match_info[:2]
  124. for phrase_num in range(p):
  125. phrase_info_idx = 2 + (phrase_num * c * 3)
  126. for col_num in range(c):
  127. col_idx = phrase_info_idx + (col_num * 3)
  128. x1, x2 = match_info[col_idx : col_idx + 2]
  129. if x1 > 0:
  130. score += float(x1) / x2
  131. return score