database.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-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 ._base import Config
  16. class DatabaseConfig(Config):
  17. def read_config(self, config):
  18. self.event_cache_size = self.parse_size(
  19. config.get("event_cache_size", "10K")
  20. )
  21. self.database_config = config.get("database")
  22. if self.database_config is None:
  23. self.database_config = {
  24. "name": "sqlite3",
  25. "args": {},
  26. }
  27. name = self.database_config.get("name", None)
  28. if name == "psycopg2":
  29. pass
  30. elif name == "sqlite3":
  31. self.database_config.setdefault("args", {}).update({
  32. "cp_min": 1,
  33. "cp_max": 1,
  34. "check_same_thread": False,
  35. })
  36. else:
  37. raise RuntimeError("Unsupported database type '%s'" % (name,))
  38. self.set_databasepath(config.get("database_path"))
  39. def default_config(self, **kwargs):
  40. database_path = self.abspath("homeserver.db")
  41. return """\
  42. # Database configuration
  43. database:
  44. # The database engine name
  45. name: "sqlite3"
  46. # Arguments to pass to the engine
  47. args:
  48. # Path to the database
  49. database: "%(database_path)s"
  50. # Number of events to cache in memory.
  51. event_cache_size: "10K"
  52. """ % locals()
  53. def read_arguments(self, args):
  54. self.set_databasepath(args.database_path)
  55. def set_databasepath(self, database_path):
  56. if database_path != ":memory:":
  57. database_path = self.abspath(database_path)
  58. if self.database_config.get("name", None) == "sqlite3":
  59. if database_path is not None:
  60. self.database_config["args"]["database"] = database_path
  61. def add_arguments(self, parser):
  62. db_group = parser.add_argument_group("database")
  63. db_group.add_argument(
  64. "-d", "--database-path", metavar="SQLITE_DATABASE_PATH",
  65. help="The path to a sqlite database to use."
  66. )