sqlite.py 5.1 KB

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