PageRenderTime 43ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/libs/migrate/versioning/api.py

http://github.com/RuudBurger/CouchPotatoServer
Python | 384 lines | 335 code | 13 blank | 36 comment | 8 complexity | fe55537522fdee0d77e8c3aaab4da59e MD5 | raw file
Possible License(s): GPL-3.0
  1. """
  2. This module provides an external API to the versioning system.
  3. .. versionchanged:: 0.6.0
  4. :func:`migrate.versioning.api.test` and schema diff functions
  5. changed order of positional arguments so all accept `url` and `repository`
  6. as first arguments.
  7. .. versionchanged:: 0.5.4
  8. ``--preview_sql`` displays source file when using SQL scripts.
  9. If Python script is used, it runs the action with mocked engine and
  10. returns captured SQL statements.
  11. .. versionchanged:: 0.5.4
  12. Deprecated ``--echo`` parameter in favour of new
  13. :func:`migrate.versioning.util.construct_engine` behavior.
  14. """
  15. # Dear migrate developers,
  16. #
  17. # please do not comment this module using sphinx syntax because its
  18. # docstrings are presented as user help and most users cannot
  19. # interpret sphinx annotated ReStructuredText.
  20. #
  21. # Thanks,
  22. # Jan Dittberner
  23. import sys
  24. import inspect
  25. import logging
  26. from migrate import exceptions
  27. from migrate.versioning import (repository, schema, version,
  28. script as script_) # command name conflict
  29. from migrate.versioning.util import catch_known_errors, with_engine
  30. log = logging.getLogger(__name__)
  31. command_desc = {
  32. 'help': 'displays help on a given command',
  33. 'create': 'create an empty repository at the specified path',
  34. 'script': 'create an empty change Python script',
  35. 'script_sql': 'create empty change SQL scripts for given database',
  36. 'version': 'display the latest version available in a repository',
  37. 'db_version': 'show the current version of the repository under version control',
  38. 'source': 'display the Python code for a particular version in this repository',
  39. 'version_control': 'mark a database as under this repository\'s version control',
  40. 'upgrade': 'upgrade a database to a later version',
  41. 'downgrade': 'downgrade a database to an earlier version',
  42. 'drop_version_control': 'removes version control from a database',
  43. 'manage': 'creates a Python script that runs Migrate with a set of default values',
  44. 'test': 'performs the upgrade and downgrade command on the given database',
  45. 'compare_model_to_db': 'compare MetaData against the current database state',
  46. 'create_model': 'dump the current database as a Python model to stdout',
  47. 'make_update_script_for_model': 'create a script changing the old MetaData to the new (current) MetaData',
  48. 'update_db_from_model': 'modify the database to match the structure of the current MetaData',
  49. }
  50. __all__ = command_desc.keys()
  51. Repository = repository.Repository
  52. ControlledSchema = schema.ControlledSchema
  53. VerNum = version.VerNum
  54. PythonScript = script_.PythonScript
  55. SqlScript = script_.SqlScript
  56. # deprecated
  57. def help(cmd=None, **opts):
  58. """%prog help COMMAND
  59. Displays help on a given command.
  60. """
  61. if cmd is None:
  62. raise exceptions.UsageError(None)
  63. try:
  64. func = globals()[cmd]
  65. except:
  66. raise exceptions.UsageError(
  67. "'%s' isn't a valid command. Try 'help COMMAND'" % cmd)
  68. ret = func.__doc__
  69. if sys.argv[0]:
  70. ret = ret.replace('%prog', sys.argv[0])
  71. return ret
  72. @catch_known_errors
  73. def create(repository, name, **opts):
  74. """%prog create REPOSITORY_PATH NAME [--table=TABLE]
  75. Create an empty repository at the specified path.
  76. You can specify the version_table to be used; by default, it is
  77. 'migrate_version'. This table is created in all version-controlled
  78. databases.
  79. """
  80. repo_path = Repository.create(repository, name, **opts)
  81. @catch_known_errors
  82. def script(description, repository, **opts):
  83. """%prog script DESCRIPTION REPOSITORY_PATH
  84. Create an empty change script using the next unused version number
  85. appended with the given description.
  86. For instance, manage.py script "Add initial tables" creates:
  87. repository/versions/001_Add_initial_tables.py
  88. """
  89. repo = Repository(repository)
  90. repo.create_script(description, **opts)
  91. @catch_known_errors
  92. def script_sql(database, description, repository, **opts):
  93. """%prog script_sql DATABASE DESCRIPTION REPOSITORY_PATH
  94. Create empty change SQL scripts for given DATABASE, where DATABASE
  95. is either specific ('postgresql', 'mysql', 'oracle', 'sqlite', etc.)
  96. or generic ('default').
  97. For instance, manage.py script_sql postgresql description creates:
  98. repository/versions/001_description_postgresql_upgrade.sql and
  99. repository/versions/001_description_postgresql_downgrade.sql
  100. """
  101. repo = Repository(repository)
  102. repo.create_script_sql(database, description, **opts)
  103. def version(repository, **opts):
  104. """%prog version REPOSITORY_PATH
  105. Display the latest version available in a repository.
  106. """
  107. repo = Repository(repository)
  108. return repo.latest
  109. @with_engine
  110. def db_version(url, repository, **opts):
  111. """%prog db_version URL REPOSITORY_PATH
  112. Show the current version of the repository with the given
  113. connection string, under version control of the specified
  114. repository.
  115. The url should be any valid SQLAlchemy connection string.
  116. """
  117. engine = opts.pop('engine')
  118. schema = ControlledSchema(engine, repository)
  119. return schema.version
  120. def source(version, dest=None, repository=None, **opts):
  121. """%prog source VERSION [DESTINATION] --repository=REPOSITORY_PATH
  122. Display the Python code for a particular version in this
  123. repository. Save it to the file at DESTINATION or, if omitted,
  124. send to stdout.
  125. """
  126. if repository is None:
  127. raise exceptions.UsageError("A repository must be specified")
  128. repo = Repository(repository)
  129. ret = repo.version(version).script().source()
  130. if dest is not None:
  131. dest = open(dest, 'w')
  132. dest.write(ret)
  133. dest.close()
  134. ret = None
  135. return ret
  136. def upgrade(url, repository, version=None, **opts):
  137. """%prog upgrade URL REPOSITORY_PATH [VERSION] [--preview_py|--preview_sql]
  138. Upgrade a database to a later version.
  139. This runs the upgrade() function defined in your change scripts.
  140. By default, the database is updated to the latest available
  141. version. You may specify a version instead, if you wish.
  142. You may preview the Python or SQL code to be executed, rather than
  143. actually executing it, using the appropriate 'preview' option.
  144. """
  145. err = "Cannot upgrade a database of version %s to version %s. "\
  146. "Try 'downgrade' instead."
  147. return _migrate(url, repository, version, upgrade=True, err=err, **opts)
  148. def downgrade(url, repository, version, **opts):
  149. """%prog downgrade URL REPOSITORY_PATH VERSION [--preview_py|--preview_sql]
  150. Downgrade a database to an earlier version.
  151. This is the reverse of upgrade; this runs the downgrade() function
  152. defined in your change scripts.
  153. You may preview the Python or SQL code to be executed, rather than
  154. actually executing it, using the appropriate 'preview' option.
  155. """
  156. err = "Cannot downgrade a database of version %s to version %s. "\
  157. "Try 'upgrade' instead."
  158. return _migrate(url, repository, version, upgrade=False, err=err, **opts)
  159. @with_engine
  160. def test(url, repository, **opts):
  161. """%prog test URL REPOSITORY_PATH [VERSION]
  162. Performs the upgrade and downgrade option on the given
  163. database. This is not a real test and may leave the database in a
  164. bad state. You should therefore better run the test on a copy of
  165. your database.
  166. """
  167. engine = opts.pop('engine')
  168. repos = Repository(repository)
  169. # Upgrade
  170. log.info("Upgrading...")
  171. script = repos.version(None).script(engine.name, 'upgrade')
  172. script.run(engine, 1)
  173. log.info("done")
  174. log.info("Downgrading...")
  175. script = repos.version(None).script(engine.name, 'downgrade')
  176. script.run(engine, -1)
  177. log.info("done")
  178. log.info("Success")
  179. @with_engine
  180. def version_control(url, repository, version=None, **opts):
  181. """%prog version_control URL REPOSITORY_PATH [VERSION]
  182. Mark a database as under this repository's version control.
  183. Once a database is under version control, schema changes should
  184. only be done via change scripts in this repository.
  185. This creates the table version_table in the database.
  186. The url should be any valid SQLAlchemy connection string.
  187. By default, the database begins at version 0 and is assumed to be
  188. empty. If the database is not empty, you may specify a version at
  189. which to begin instead. No attempt is made to verify this
  190. version's correctness - the database schema is expected to be
  191. identical to what it would be if the database were created from
  192. scratch.
  193. """
  194. engine = opts.pop('engine')
  195. ControlledSchema.create(engine, repository, version)
  196. @with_engine
  197. def drop_version_control(url, repository, **opts):
  198. """%prog drop_version_control URL REPOSITORY_PATH
  199. Removes version control from a database.
  200. """
  201. engine = opts.pop('engine')
  202. schema = ControlledSchema(engine, repository)
  203. schema.drop()
  204. def manage(file, **opts):
  205. """%prog manage FILENAME [VARIABLES...]
  206. Creates a script that runs Migrate with a set of default values.
  207. For example::
  208. %prog manage manage.py --repository=/path/to/repository \
  209. --url=sqlite:///project.db
  210. would create the script manage.py. The following two commands
  211. would then have exactly the same results::
  212. python manage.py version
  213. %prog version --repository=/path/to/repository
  214. """
  215. Repository.create_manage_file(file, **opts)
  216. @with_engine
  217. def compare_model_to_db(url, repository, model, **opts):
  218. """%prog compare_model_to_db URL REPOSITORY_PATH MODEL
  219. Compare the current model (assumed to be a module level variable
  220. of type sqlalchemy.MetaData) against the current database.
  221. NOTE: This is EXPERIMENTAL.
  222. """ # TODO: get rid of EXPERIMENTAL label
  223. engine = opts.pop('engine')
  224. return ControlledSchema.compare_model_to_db(engine, model, repository)
  225. @with_engine
  226. def create_model(url, repository, **opts):
  227. """%prog create_model URL REPOSITORY_PATH [DECLERATIVE=True]
  228. Dump the current database as a Python model to stdout.
  229. NOTE: This is EXPERIMENTAL.
  230. """ # TODO: get rid of EXPERIMENTAL label
  231. engine = opts.pop('engine')
  232. declarative = opts.get('declarative', False)
  233. return ControlledSchema.create_model(engine, repository, declarative)
  234. @catch_known_errors
  235. @with_engine
  236. def make_update_script_for_model(url, repository, oldmodel, model, **opts):
  237. """%prog make_update_script_for_model URL OLDMODEL MODEL REPOSITORY_PATH
  238. Create a script changing the old Python model to the new (current)
  239. Python model, sending to stdout.
  240. NOTE: This is EXPERIMENTAL.
  241. """ # TODO: get rid of EXPERIMENTAL label
  242. engine = opts.pop('engine')
  243. return PythonScript.make_update_script_for_model(
  244. engine, oldmodel, model, repository, **opts)
  245. @with_engine
  246. def update_db_from_model(url, repository, model, **opts):
  247. """%prog update_db_from_model URL REPOSITORY_PATH MODEL
  248. Modify the database to match the structure of the current Python
  249. model. This also sets the db_version number to the latest in the
  250. repository.
  251. NOTE: This is EXPERIMENTAL.
  252. """ # TODO: get rid of EXPERIMENTAL label
  253. engine = opts.pop('engine')
  254. schema = ControlledSchema(engine, repository)
  255. schema.update_db_from_model(model)
  256. @with_engine
  257. def _migrate(url, repository, version, upgrade, err, **opts):
  258. engine = opts.pop('engine')
  259. url = str(engine.url)
  260. schema = ControlledSchema(engine, repository)
  261. version = _migrate_version(schema, version, upgrade, err)
  262. changeset = schema.changeset(version)
  263. for ver, change in changeset:
  264. nextver = ver + changeset.step
  265. log.info('%s -> %s... ', ver, nextver)
  266. if opts.get('preview_sql'):
  267. if isinstance(change, PythonScript):
  268. log.info(change.preview_sql(url, changeset.step, **opts))
  269. elif isinstance(change, SqlScript):
  270. log.info(change.source())
  271. elif opts.get('preview_py'):
  272. if not isinstance(change, PythonScript):
  273. raise exceptions.UsageError("Python source can be only displayed"
  274. " for python migration files")
  275. source_ver = max(ver, nextver)
  276. module = schema.repository.version(source_ver).script().module
  277. funcname = upgrade and "upgrade" or "downgrade"
  278. func = getattr(module, funcname)
  279. log.info(inspect.getsource(func))
  280. else:
  281. schema.runchange(ver, change, changeset.step)
  282. log.info('done')
  283. def _migrate_version(schema, version, upgrade, err):
  284. if version is None:
  285. return version
  286. # Version is specified: ensure we're upgrading in the right direction
  287. # (current version < target version for upgrading; reverse for down)
  288. version = VerNum(version)
  289. cur = schema.version
  290. if upgrade is not None:
  291. if upgrade:
  292. direction = cur <= version
  293. else:
  294. direction = cur >= version
  295. if not direction:
  296. raise exceptions.KnownError(err % (cur, version))
  297. return version