docs, 1.0 version bump

This commit is contained in:
Robert Lechte 2017-03-19 16:56:51 +11:00
parent 36e40ba8bc
commit 2ddb10ce89
11 changed files with 866 additions and 2 deletions

2
.gitignore vendored
View File

@ -37,3 +37,5 @@ nosetests.xml
.pydevproject
.cache
docs/_build

View File

@ -7,6 +7,11 @@ But schemas are actually good. Enforcing data consistency and structure is a goo
**Migra supports PostgreSQL >= 9.4.** Known issues exist with earlier versions.
Full documentation
------------------
Official documentation is at `migra.readthedocs.io <https://csvx.readthedocs.io/en/latest/>`_
How it Works
------------

192
docs/Makefile Normal file
View File

@ -0,0 +1,192 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " applehelp to make an Apple Help Book"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
@echo " coverage to run coverage check of the documentation (if enabled)"
clean:
rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/migra.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/migra.qhc"
applehelp:
$(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp
@echo
@echo "Build finished. The help book is in $(BUILDDIR)/applehelp."
@echo "N.B. You won't be able to view it unless you put it in" \
"~/Library/Documentation/Help or install it in your application" \
"bundle."
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/migra"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/migra"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
coverage:
$(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
@echo "Testing of coverage in the sources finished, look at the " \
"results in $(BUILDDIR)/coverage/python.txt."
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."

56
docs/_static/custom.css vendored Normal file
View File

@ -0,0 +1,56 @@
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/K88pR3goAWT7BTt32Z01mxJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/RjgO7rYTmqiVp7vzi-Q5URJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/LWCjsQkB6EMdfHrEVqA1KRJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/xozscpT2726on7jbcb_pAhJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/59ZRklaO5bWGqF5A9baEERJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+0102-0103, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/u-WUoqrET9fUeobQW7jkRRJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/cJZKeOuBrn4kERxqtaUH3VtXRa8TVwTICgirnJhmVJw.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;
}

BIN
docs/_static/migration.jpg vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

13
docs/_templates/sidebartop.html vendored Normal file
View File

@ -0,0 +1,13 @@
<a href="#"><img src="_static/migration.jpg" /></a>
<p><strong>migra</strong> is a python library and command line tool for working with PostgreSQL schemas. If you've always found database migrations frustrating and annoying, this may be the tool for you.</p>
<p>
<iframe src="https://ghbtns.com/github-btn.html?user={{ theme_github_user }}&repo={{ theme_github_repo }}&type={{ theme_github_type }}&count={{ theme_github_count }}&size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="200px" height="35px"></iframe>
</p>
<p>Written by <a href="https://github.com/djrobstep">djrobstep</a> (takes a tool to build a tool), <strong>migra</strong> recently had its 1.0 release, and is in production use by the Australian government.</p>
If you like <strong>migra</strong>, check out djrobstep's other projects: <a href="https://github.com/djrobstep/sqlakeyset">sqlakeyset</a>, <a href="https://github.com/djrobstep/autovenv">autovenv</a>, and <a href="https://github.com/djrobstep/csvx">csvx</a>.
</p>

301
docs/conf.py Normal file
View File

@ -0,0 +1,301 @@
# -*- coding: utf-8 -*-
#
# migra documentation build configuration file, created by
# sphinx-quickstart on Sun Sep 6 18:17:50 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('..'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.coverage',
'sphinx.ext.napoleon',
'sphinxcontrib.fulltoc'
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'migra'
copyright = ''
author = u'Robert Lechte'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
'font_family': 'Open Sans',
'head_font_family': 'Open Sans',
'github_user': 'djrobstep',
'github_repo': 'migra',
'github_banner': True,
'logo': 'migration.jpg'
}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
html_sidebars = {
'index': ['sidebartop.html', 'localtoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html'],
'**': ['sidebartop.html', 'localtoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html']
}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
html_show_copyright = False
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'migradoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'migra.tex', u'migra Documentation',
u'Robert Lechte', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'migra', u'migra Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'migra', u'migra Documentation',
author, 'migra', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False

171
docs/howto.rst Normal file
View File

@ -0,0 +1,171 @@
HOWTO: Do migrations
====================
Sample app
----------
The techniques discussed below are also demonstrated in a sample flask application available here:
`https://githug.com/djrobstep/bookapp <https://csvx.readthedocs.io/en/latest/>`_
Two scenarios
-------------
There's usually two stages to working with databases:
- Developing locally and figuring out what intended database state you want.
- Deploying your intended database state to production.
Local development and prototyping
---------------------------------
Usually you'll have an intended state in mind for your database. This is often defined with ORM models or perhaps just a simple setup script.
As your app and database develop and evolve, you'll want to keep your local database in sync with your intended state, without dropping everything and recreating each time. Ideally we would have a single command to do this.
Using ``migra`` and ``sqlbag`` (a library created alongside SQL bag to do things like database connections with less boilerplate), we can achieve that simple command with not too much fuss.
Let's break it down:
.. code-block:: python
from migra import Migration
from sqlbag import S, \
temporary_database, \
load_sql_from_file
def setup_intended_db_state(temp_db_url):
with S(temp_db_url) as s:
load_sql_from_file(s, 'db_setup.sql')
# if instead you're using app models
# with eg the SQLAlchemy ORM, you'd
# use something like models.create_all
# here to load your tables
def main():
with temporary_database() as temp_db_url:
setup_intended_db_state(temp_db_url)
with S(local_db_url) as s0, \ S(temp_db_url) as s1:
m = Migration(s0, s1)
m.set_safety(False)
m.add_all_changes()
if m.statements:
print('The following changes are required:')
print(m.sql)
if prompt('Apply these changes?'):
m.apply()
else:
print('DB already synced, no changes required.')
if __name__ == '__main__':
main()
Preparing a production migration
--------------------------------
To determine the changes we need to apply to our production database, we want to load our intended state (much as we did above) and compare that to the actual current production state.
You could do this through a schema dump, or directly through a read-only connection.
The following pg_dump command is useful for generating a suitable schema dump:
.. code-block:: shell
pg_dump --schema-only --no-owner --no-privileges --column-inserts -f out.dump.sql postgresql://productiondatabase
Generating a (preliminary) migration script then works very similarly:
.. code-block:: python
from migra import Migration
from sqlbag import S, \
temporary_database, \
load_sql_from_file
import io
def setup_intended_db_state(temp_db_url):
with S(temp_db_url) as s:
load_sql_from_file(s, 'out.dump.sql')
def setup_intended_db_state(temp_db_url):
with S(temp_db_url) as s:
load_sql_from_file(s, 'db_setup.sql')
def main():
with \
temporary_database() as temp_prod, \
temporary_database() as temp_target:
setup_current_production_state(temp_prod)
setup_intended_db_state(temp_target)
with S(local_db_url) as s0, \ S(temp_db_url) as s1:
m = Migration(s0, s1)
m.set_safety(False)
m.add_all_changes()
with io.open('pending.sql', 'w') as f:
f.write(m.sql)
if __name__ == '__main__':
main()
Review time!
------------
Always review the output migra generates before applying it, particularly for production migrations.
Often the migra-generated output will be all you need. But often it won't.
You'll often need to move data around as part of your migration.
Also, there are situations that are impossible for migra to detect, that you'll need to handle manually. For instance, migra can't tell that you've renamed a column rather and simply dropping an old one and adding a new one. So if you want to do a rename, you'll need to do that manually.
There are also performance considerations if your production database is large. Some schema operations can take a long time to apply.
Ideally, test your prepared, edited, and reviewed migration script against real production data before applying it for real.
The best way to do this is to make migration testing part of your application test suite!
Making migrations testable
--------------------------
When developing an app, we'd ideally like to verify that our app will work correctly with the database both before and after the migration is applied. Otherwise, interruptions and downtime could result.
If we define methods to load each of these two conditions, then we can configure our tests to run twice if there is a pending migration to be applied.
Using python's pytest library, this is fairly straightforward.
.. code-block: python
from migrations import load_pre_migration, load_post_migration
with io.open('MIGRATIONS/pending.sql') as f:
pending_contents = f.read()
if pending_contents.strip():
DATABASE_SETUPS_TO_TEST = [
load_pre_migration,
load_post_migration
]
else:
DATABASE_SETUPS_TO_TEST = [
load_post_migration
]
@pytest.fixture(params=DATABASE_SETUPS_TO_TEST)
def db(request):
with temporary_database() as test_db_url:
setup_method = request.param
setup_method(test_db_url)
yield test_db_url
Now, each test that uses the ``db`` fixture gets run twice when necessary.
This makes migrations much more testable and reliable.
Setting up these test conditions will again require the use of a production schema dump that accurately reflects the current database production state. How you make this accessible to your test suite for use in test setup will depend on the operational specifics of your particular app and database setup.

116
docs/index.rst Normal file
View File

@ -0,0 +1,116 @@
migra: PostgreSQL migrations made almost painless
=================================================
Schema migrations are without doubt the most cumbersome and annoying part of working with SQL databases. So much so that some people think that schemas themselves are bad!
But schemas are actually good. Enforcing data consistency and structure is a good thing. Its the migration tooling that is bad, because its harder to use than it should be. ``migra`` is an attempt to change that, and make migrations easy, safe, and reliable instead of something to dread.
**Migra supports PostgreSQL >= 9.4.** Known issues exist with earlier versions.
Think of `migra` as a diff tool for schemas
-------------------------------------------
Suppose database A and database B have similar but slightly different schemas. `migra` will detect the differences and output the SQL needed to transform A to B.
This includes changes to tables, views, functions, indexes, constraints, enums, sequences, and installed extensions.
You can use ``migra`` as a library to build your own migration scripts, tools, etc. Installing migra also installs the ``migra`` command, so you can use it as follows:
.. code-block:: shell
$ migra postgresql:///a postgresql:///b
alter table "public"."products" add column newcolumn text;
alter table "public"."products" add constraint "x" CHECK ((price > (0)::numeric));
If *b* is the target schema, then a new column and constraint needs to be applied to *a* to make it match *b*'s schema. Once we've reviewed the autogenerated SQL and we're happy with it, we can apply these changes as easily as:
.. code-block:: shell
$ migra --unsafe postgresql:///a postgresql:///b > migration_script.sql
# Then after careful review (obviously)...
$ psql a --single-transaction -f migration_script.sql
Migration complete!
IMPORTANT: Practice safe migrations
-----------------------------------
**Migrations can never be fully automatic**. As noted above **ALWAYS REVIEW MIGRATION SCRIPTS CAREFULLY, ESPECIALLY WHEN DROPPING TABLES IS INVOLVED**.
Best practice is to run your migrations against a copy of your production database first. This helps verify correctness and spot any performance issues before they cause interruptions and downtime on your production database.
`migra` will deliberately throw an error if any generated statements feature the word "drop". This safety feature is by no means idiot-proof, but might prevent a few obvious blunders.
If you want to generate "drop ..." statements, you need to use the ``--unsafe`` flag if using the command, or if using the python package directly, ``set_safety(`` to false on your `Migration` object.
Python Code
-----------
Here's how the migra command is implemented under the hood (with a few irrelevant lines removed).
As you can see, it's pretty simple (`S` here is a context manager that creates a database session from a database URL).
.. code-block:: python
from migra import Migration
from sqlbag import S
with S(args.dburl_from) as s0, S(args.dburl_target) as s1:
m = Migration(s0, s1)
if args.unsafe:
m.set_safety(False)
m.add_all_changes()
print(m.sql)
Here the code just opens connections to both databases for the Migration object to analyse. ``m.add_all_changes()`` generates the SQL statements for the changes required, and adds to the migration object's list of pending changes. The necessary SQL is now available as a property.
Features and Limitations
------------------------
``migra`` plays nicely with extensions. Schema contents belonging to extensions will be ignored and left to the extension to manage.
Only SQL/PLPGSQL functions are confirmed to work so far. ``migra`` ignores functions that use other languages.
Installation
------------
Assuming you have `pip <https://pip.pypa.io>`_ installed, all you need to do is install as follows:
.. code-block:: shell
$ pip install migra
If you don't have psycopg2 (the PostgreSQL driver) installed yet, you can install this at the same time with:
.. code-block:: shell
$ pip install migra[pg]
Table of contents
-----------------
.. toctree::
:maxdepth: 3
howto.rst
API/Interface Details
---------------------
* :ref:`genindex`
Useful Links
------------
Source Code: `github.com/djrobstep/migra <https://github.com/djrobstep/migra>`_
PyPI package info: `migra@PyPI <https://pypi.python.org/pypi/migra>`_

View File

@ -20,3 +20,4 @@ pep8
wheel
sphinx
sphinxcontrib-fulltoc

View File

@ -8,7 +8,7 @@ readme = io.open('README.rst').read()
setup(
name='migra',
version='0.1.1470919406',
version='1.0.1489900901',
url='https://github.com/djrobstep/migra',
description='Like diff but for PostgreSQL schemas',
long_description=readme,
@ -22,7 +22,14 @@ setup(
zip_safe=False,
packages=find_packages(),
classifiers=[
'Development Status :: 3 - Alpha'
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
],
entry_points={
'console_scripts': [