prepare_database.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. import fnmatch
  16. import imp
  17. import logging
  18. import os
  19. import re
  20. logger = logging.getLogger(__name__)
  21. # Remember to update this number every time a change is made to database
  22. # schema files, so the users will be informed on server restarts.
  23. SCHEMA_VERSION = 32
  24. dir_path = os.path.abspath(os.path.dirname(__file__))
  25. class PrepareDatabaseException(Exception):
  26. pass
  27. class UpgradeDatabaseException(PrepareDatabaseException):
  28. pass
  29. def prepare_database(db_conn, database_engine, config):
  30. """Prepares a database for usage. Will either create all necessary tables
  31. or upgrade from an older schema version.
  32. If `config` is None then prepare_database will assert that no upgrade is
  33. necessary, *or* will create a fresh database if the database is empty.
  34. """
  35. try:
  36. cur = db_conn.cursor()
  37. version_info = _get_or_create_schema_state(cur, database_engine)
  38. if version_info:
  39. user_version, delta_files, upgraded = version_info
  40. if config is None:
  41. if user_version != SCHEMA_VERSION:
  42. # If we don't pass in a config file then we are expecting to
  43. # have already upgraded the DB.
  44. raise UpgradeDatabaseException("Database needs to be upgraded")
  45. else:
  46. _upgrade_existing_database(
  47. cur, user_version, delta_files, upgraded, database_engine, config
  48. )
  49. else:
  50. _setup_new_database(cur, database_engine)
  51. cur.close()
  52. db_conn.commit()
  53. except:
  54. db_conn.rollback()
  55. raise
  56. def _setup_new_database(cur, database_engine):
  57. """Sets up the database by finding a base set of "full schemas" and then
  58. applying any necessary deltas.
  59. The "full_schemas" directory has subdirectories named after versions. This
  60. function searches for the highest version less than or equal to
  61. `SCHEMA_VERSION` and executes all .sql files in that directory.
  62. The function will then apply all deltas for all versions after the base
  63. version.
  64. Example directory structure:
  65. schema/
  66. delta/
  67. ...
  68. full_schemas/
  69. 3/
  70. test.sql
  71. ...
  72. 11/
  73. foo.sql
  74. bar.sql
  75. ...
  76. In the example foo.sql and bar.sql would be run, and then any delta files
  77. for versions strictly greater than 11.
  78. """
  79. current_dir = os.path.join(dir_path, "schema", "full_schemas")
  80. directory_entries = os.listdir(current_dir)
  81. valid_dirs = []
  82. pattern = re.compile(r"^\d+(\.sql)?$")
  83. for filename in directory_entries:
  84. match = pattern.match(filename)
  85. abs_path = os.path.join(current_dir, filename)
  86. if match and os.path.isdir(abs_path):
  87. ver = int(match.group(0))
  88. if ver <= SCHEMA_VERSION:
  89. valid_dirs.append((ver, abs_path))
  90. else:
  91. logger.warn("Unexpected entry in 'full_schemas': %s", filename)
  92. if not valid_dirs:
  93. raise PrepareDatabaseException(
  94. "Could not find a suitable base set of full schemas"
  95. )
  96. max_current_ver, sql_dir = max(valid_dirs, key=lambda x: x[0])
  97. logger.debug("Initialising schema v%d", max_current_ver)
  98. directory_entries = os.listdir(sql_dir)
  99. for filename in fnmatch.filter(directory_entries, "*.sql"):
  100. sql_loc = os.path.join(sql_dir, filename)
  101. logger.debug("Applying schema %s", sql_loc)
  102. executescript(cur, sql_loc)
  103. cur.execute(
  104. database_engine.convert_param_style(
  105. "INSERT INTO schema_version (version, upgraded)"
  106. " VALUES (?,?)"
  107. ),
  108. (max_current_ver, False,)
  109. )
  110. _upgrade_existing_database(
  111. cur,
  112. current_version=max_current_ver,
  113. applied_delta_files=[],
  114. upgraded=False,
  115. database_engine=database_engine,
  116. config=None,
  117. is_empty=True,
  118. )
  119. def _upgrade_existing_database(cur, current_version, applied_delta_files,
  120. upgraded, database_engine, config, is_empty=False):
  121. """Upgrades an existing database.
  122. Delta files can either be SQL stored in *.sql files, or python modules
  123. in *.py.
  124. There can be multiple delta files per version. Synapse will keep track of
  125. which delta files have been applied, and will apply any that haven't been
  126. even if there has been no version bump. This is useful for development
  127. where orthogonal schema changes may happen on separate branches.
  128. Different delta files for the same version *must* be orthogonal and give
  129. the same result when applied in any order. No guarantees are made on the
  130. order of execution of these scripts.
  131. This is a no-op of current_version == SCHEMA_VERSION.
  132. Example directory structure:
  133. schema/
  134. delta/
  135. 11/
  136. foo.sql
  137. ...
  138. 12/
  139. foo.sql
  140. bar.py
  141. ...
  142. full_schemas/
  143. ...
  144. In the example, if current_version is 11, then foo.sql will be run if and
  145. only if `upgraded` is True. Then `foo.sql` and `bar.py` would be run in
  146. some arbitrary order.
  147. Args:
  148. cur (Cursor)
  149. current_version (int): The current version of the schema.
  150. applied_delta_files (list): A list of deltas that have already been
  151. applied.
  152. upgraded (bool): Whether the current version was generated by having
  153. applied deltas or from full schema file. If `True` the function
  154. will never apply delta files for the given `current_version`, since
  155. the current_version wasn't generated by applying those delta files.
  156. """
  157. if current_version > SCHEMA_VERSION:
  158. raise ValueError(
  159. "Cannot use this database as it is too " +
  160. "new for the server to understand"
  161. )
  162. start_ver = current_version
  163. if not upgraded:
  164. start_ver += 1
  165. logger.debug("applied_delta_files: %s", applied_delta_files)
  166. for v in range(start_ver, SCHEMA_VERSION + 1):
  167. logger.info("Upgrading schema to v%d", v)
  168. delta_dir = os.path.join(dir_path, "schema", "delta", str(v))
  169. try:
  170. directory_entries = os.listdir(delta_dir)
  171. except OSError:
  172. logger.exception("Could not open delta dir for version %d", v)
  173. raise UpgradeDatabaseException(
  174. "Could not open delta dir for version %d" % (v,)
  175. )
  176. directory_entries.sort()
  177. for file_name in directory_entries:
  178. relative_path = os.path.join(str(v), file_name)
  179. logger.debug("Found file: %s", relative_path)
  180. if relative_path in applied_delta_files:
  181. continue
  182. absolute_path = os.path.join(
  183. dir_path, "schema", "delta", relative_path,
  184. )
  185. root_name, ext = os.path.splitext(file_name)
  186. if ext == ".py":
  187. # This is a python upgrade module. We need to import into some
  188. # package and then execute its `run_upgrade` function.
  189. module_name = "synapse.storage.v%d_%s" % (
  190. v, root_name
  191. )
  192. with open(absolute_path) as python_file:
  193. module = imp.load_source(
  194. module_name, absolute_path, python_file
  195. )
  196. logger.debug("Running script %s", relative_path)
  197. module.run_create(cur, database_engine)
  198. if not is_empty:
  199. module.run_upgrade(cur, database_engine, config=config)
  200. elif ext == ".pyc":
  201. # Sometimes .pyc files turn up anyway even though we've
  202. # disabled their generation; e.g. from distribution package
  203. # installers. Silently skip it
  204. pass
  205. elif ext == ".sql":
  206. # A plain old .sql file, just read and execute it
  207. logger.debug("Applying schema %s", relative_path)
  208. executescript(cur, absolute_path)
  209. else:
  210. # Not a valid delta file.
  211. logger.warn(
  212. "Found directory entry that did not end in .py or"
  213. " .sql: %s",
  214. relative_path,
  215. )
  216. continue
  217. # Mark as done.
  218. cur.execute(
  219. database_engine.convert_param_style(
  220. "INSERT INTO applied_schema_deltas (version, file)"
  221. " VALUES (?,?)",
  222. ),
  223. (v, relative_path)
  224. )
  225. cur.execute("DELETE FROM schema_version")
  226. cur.execute(
  227. database_engine.convert_param_style(
  228. "INSERT INTO schema_version (version, upgraded)"
  229. " VALUES (?,?)",
  230. ),
  231. (v, True)
  232. )
  233. def get_statements(f):
  234. statement_buffer = ""
  235. in_comment = False # If we're in a /* ... */ style comment
  236. for line in f:
  237. line = line.strip()
  238. if in_comment:
  239. # Check if this line contains an end to the comment
  240. comments = line.split("*/", 1)
  241. if len(comments) == 1:
  242. continue
  243. line = comments[1]
  244. in_comment = False
  245. # Remove inline block comments
  246. line = re.sub(r"/\*.*\*/", " ", line)
  247. # Does this line start a comment?
  248. comments = line.split("/*", 1)
  249. if len(comments) > 1:
  250. line = comments[0]
  251. in_comment = True
  252. # Deal with line comments
  253. line = line.split("--", 1)[0]
  254. line = line.split("//", 1)[0]
  255. # Find *all* semicolons. We need to treat first and last entry
  256. # specially.
  257. statements = line.split(";")
  258. # We must prepend statement_buffer to the first statement
  259. first_statement = "%s %s" % (
  260. statement_buffer.strip(),
  261. statements[0].strip()
  262. )
  263. statements[0] = first_statement
  264. # Every entry, except the last, is a full statement
  265. for statement in statements[:-1]:
  266. yield statement.strip()
  267. # The last entry did *not* end in a semicolon, so we store it for the
  268. # next semicolon we find
  269. statement_buffer = statements[-1].strip()
  270. def executescript(txn, schema_path):
  271. with open(schema_path, 'r') as f:
  272. for statement in get_statements(f):
  273. txn.execute(statement)
  274. def _get_or_create_schema_state(txn, database_engine):
  275. # Bluntly try creating the schema_version tables.
  276. schema_path = os.path.join(
  277. dir_path, "schema", "schema_version.sql",
  278. )
  279. executescript(txn, schema_path)
  280. txn.execute("SELECT version, upgraded FROM schema_version")
  281. row = txn.fetchone()
  282. current_version = int(row[0]) if row else None
  283. upgraded = bool(row[1]) if row else None
  284. if current_version:
  285. txn.execute(
  286. database_engine.convert_param_style(
  287. "SELECT file FROM applied_schema_deltas WHERE version >= ?"
  288. ),
  289. (current_version,)
  290. )
  291. applied_deltas = [d for d, in txn.fetchall()]
  292. return current_version, applied_deltas, upgraded
  293. return None