sqlite3.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from synapse.storage.prepare_database import (
  16. prepare_database, prepare_sqlite3_database
  17. )
  18. import struct
  19. class Sqlite3Engine(object):
  20. single_threaded = True
  21. def __init__(self, database_module, config):
  22. self.module = database_module
  23. self.config = config
  24. def check_database(self, txn):
  25. pass
  26. def convert_param_style(self, sql):
  27. return sql
  28. def on_new_connection(self, db_conn):
  29. self.prepare_database(db_conn)
  30. db_conn.create_function("rank", 1, _rank)
  31. def prepare_database(self, db_conn):
  32. prepare_sqlite3_database(db_conn)
  33. prepare_database(db_conn, self, config=self.config)
  34. def is_deadlock(self, error):
  35. return False
  36. def is_connection_closed(self, conn):
  37. return False
  38. def lock_table(self, txn, table):
  39. return
  40. # Following functions taken from: https://github.com/coleifer/peewee
  41. def _parse_match_info(buf):
  42. bufsize = len(buf)
  43. return [struct.unpack('@I', buf[i:i + 4])[0] for i in range(0, bufsize, 4)]
  44. def _rank(raw_match_info):
  45. """Handle match_info called w/default args 'pcx' - based on the example rank
  46. function http://sqlite.org/fts3.html#appendix_a
  47. """
  48. match_info = _parse_match_info(raw_match_info)
  49. score = 0.0
  50. p, c = match_info[:2]
  51. for phrase_num in range(p):
  52. phrase_info_idx = 2 + (phrase_num * c * 3)
  53. for col_num in range(c):
  54. col_idx = phrase_info_idx + (col_num * 3)
  55. x1, x2 = match_info[col_idx:col_idx + 2]
  56. if x1 > 0:
  57. score += float(x1) / x2
  58. return score