sqlite3.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 prepare_database
  16. import struct
  17. class Sqlite3Engine(object):
  18. single_threaded = True
  19. def __init__(self, database_module):
  20. self.module = database_module
  21. def check_database(self, txn):
  22. pass
  23. def convert_param_style(self, sql):
  24. return sql
  25. def on_new_connection(self, db_conn):
  26. prepare_database(db_conn, self, config=None)
  27. db_conn.create_function("rank", 1, _rank)
  28. def is_deadlock(self, error):
  29. return False
  30. def is_connection_closed(self, conn):
  31. return False
  32. def lock_table(self, txn, table):
  33. return
  34. # Following functions taken from: https://github.com/coleifer/peewee
  35. def _parse_match_info(buf):
  36. bufsize = len(buf)
  37. return [struct.unpack('@I', buf[i:i + 4])[0] for i in range(0, bufsize, 4)]
  38. def _rank(raw_match_info):
  39. """Handle match_info called w/default args 'pcx' - based on the example rank
  40. function http://sqlite.org/fts3.html#appendix_a
  41. """
  42. match_info = _parse_match_info(raw_match_info)
  43. score = 0.0
  44. p, c = match_info[:2]
  45. for phrase_num in range(p):
  46. phrase_info_idx = 2 + (phrase_num * c * 3)
  47. for col_num in range(c):
  48. col_idx = phrase_info_idx + (col_num * 3)
  49. x1, x2 = match_info[col_idx:col_idx + 2]
  50. if x1 > 0:
  51. score += float(x1) / x2
  52. return score