« ^ »

YAMLでER図を作図してSphinxに描画する拡張sphinx_erdiagramを使う

所要時間: 約 5分

データベースのテーブルとカラムとそれらの関係を図で示したものがER図です。 設計資料としてよく用いられます。 ER図の作図には色々なものがありますが、今回はSphinxのsphinx_erdiagramを用いての作図を試します。

Sphinxについては http://www.sphinx-doc.org/en/stable/ をご覧ください。

sphinx_erdiagram

sphinx_erdiagram1はER図を書くためのSphinx拡張です。 要素と関係はYAMLで表現し、それをGraphvizを使って描画しています。 今回はドキュメントの作成からとりあえずのER図の生成までします。

各種ツールのインストール

HemebrewでGraphvizをインストールします。

brew reinstall graphviz --with-pango

Sphinxをインストールします。

pip install sphinx

sphinx_erdiagramをインストールします。

pip install sphinx_erdiagram

Sphinxのドキュメントの作成

sphinx-quickstartを使ってスキャフォールディングします。設定項目をあれこれ聞いてきますが、大抵のものはデフォルト値が設定されているのでENTERを押すだけ進んでいきます。 入力が必要なのはProject、Author、Versionです。

sphinx-quickstart
Welcome to the Sphinx 1.5.1 quickstart utility.

Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).

Enter the root path for documentation.
> Root path for the documentation [.]:

You have two options for placing the build directory for Sphinx output.
Either, you use a directory "_build" within the root path, or you separate
"source" and "build" directories within the root path.
> Separate source and build directories (y/n) [n]:

Inside the root directory, two more directories will be created; "_templates"
for custom HTML templates and "_static" for custom stylesheets and other static
files. You can enter another prefix (such as ".") to replace the underscore.
> Name prefix for templates and static dir [_]:

The project name will occur in several places in the built documentation.
> Project name: Sphinx ER Diagram Document
> Author name(s): TakesxiSximada

Sphinx has the notion of a "version" and a "release" for the
software. Each version can have multiple releases. For example, for
Python the version is something like 2.5 or 3.0, while the release is
something like 2.5.1 or 3.0a1.  If you don't need this dual structure,
just set both to the same value.
> Project version []:
> Project release []: 1.0.0

If the documents are to be written in a language other than English,
you can select a language here by its language code. Sphinx will then
translate text that it generates into that language.

For a list of supported codes, see
http://sphinx-doc.org/config.html#confval-language.
> Project language [en]:

The file name suffix for source files. Commonly, this is either ".txt"
or ".rst".  Only files with this suffix are considered documents.
> Source file suffix [.rst]:

One document is special in that it is considered the top node of the
"contents tree", that is, it is the root of the hierarchical structure
of the documents. Normally, this is "index", but if your "index"
document is a custom template, you can also set this to another filename.
> Name of your master document (without suffix) [index]:

Sphinx can also add configuration for epub output:
> Do you want to use the epub builder (y/n) [n]:

Please indicate if you want to use one of the following Sphinx extensions:
> autodoc: automatically insert docstrings from modules (y/n) [n]:
> doctest: automatically test code snippets in doctest blocks (y/n) [n]:
> intersphinx: link between Sphinx documentation of different projects (y/n) [n]:
> todo: write "todo" entries that can be shown or hidden on build (y/n) [n]:
> coverage: checks for documentation coverage (y/n) [n]:
> imgmath: include math, rendered as PNG or SVG images (y/n) [n]:
> mathjax: include math, rendered in the browser by MathJax (y/n) [n]:
> ifconfig: conditional inclusion of content based on config values (y/n) [n]:
> viewcode: include links to the source code of documented Python objects (y/n) [n]:
> githubpages: create .nojekyll file to publish the document on GitHub pages (y/n) [n]:

A Makefile and a Windows command file can be generated for you so that you
only have to run e.g. `make html' instead of invoking sphinx-build
directly.
> Create Makefile? (y/n) [y]:
> Create Windows command file? (y/n) [y]:

Creating file ./conf.py.
Creating file ./index.rst.
Creating file ./Makefile.
Creating file ./make.bat.

Finished: An initial directory structure has been created.

You should now populate your master file ./index.rst and create other documentation
source files. Use the Makefile to build the docs, like so:
   make builder
where "builder" is one of the supported builders, e.g. html, latex or linkcheck.

sphinx_erdiagramの有効化

sphinx_erdiagramを有効にするためにconf.pyを編集します。

vi conf.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Sphinx ER Diagram Document documentation build configuration file, created by
# sphinx-quickstart on Sat Feb 25 13:50:23 2017.
#
# 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.

# 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.
#
# import os
# import sys
# 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.

# [DGRAM_CONF_START]
extensions = [
    'myasuda.sphinx.erdiagram',
]
graphviz_output_format = 'png'
# [DGRAM_CONF_END]

# 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 master toctree document.
master_doc = 'index'

# General information about the project.
project = 'Sphinx ER Diagram Document'
copyright = '2017, TakesxiSximada'
author = 'TakesxiSximada'

# 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 = ''
# The full version, including alpha/beta/rc tags.
release = '1.0.0'

# 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

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# 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 = {}

# 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']


# -- Options for HTMLHelp output ------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = 'SphinxERDiagramDocumentdoc'


# -- 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, 'SphinxERDiagramDocument.tex', 'Sphinx ER Diagram Document Documentation',
     'TakesxiSximada', 'manual'),
]


# -- 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, 'sphinxerdiagramdocument', 'Sphinx ER Diagram Document Documentation',
     [author], 1)
]


# -- 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, 'SphinxERDiagramDocument', 'Sphinx ER Diagram Document Documentation',
     author, 'SphinxERDiagramDocument', 'One line description of project.',
     'Miscellaneous'),
]

ER図の作図

ER図をYAML形式で記述します。

entities:
  user:
    columns:
      - id: { label: integer, notnull: true, pk: true }
      - name: { label: string, notnull: true }
      - created_at: {label: datetime, notnull: true}
      - updated_at: {label: datetime}

  item:
    columns:
      - id: {label: integer, notnull: true, pk: true}
      - name: {label: string, notnull: true}
      - price: {label: decimal, notnull: true}
      - created_at: {label: datetime, notnull: true}
      - updated_at: {label: datetime}

  stock:
    columns:
      - id: {label: integer, notnull: true, pk: true}
      - code: {label: uuid, notnull: true}
      - item_id: {label: integer, fk: true}
      - reservation_id: {label: unique(reservation.id), fk: true}
      - created_at: {label: datetime, notnull: true}
      - updated_at: {label: datetime}

  reservation:
    columns:
      - id: {label: integer, notnull: true, pk: true}
      - code: {label: uuid, notnull: true}
      - price: {label: decimal, notnull: true}
      - stock_id: {label: stock.id, notnull: true, fk: true}
      - user_id: {label: user.id, notnull: true, fk: true}

      - created_at: {label: datetime, notnull: true}
      - updated_at: {label: datetime}
      - reserved_at: {label: datetime}
      - canceled_at: {label: datetime}

relations:
  user 1--* reservation:
  item 1--* stock:
  stock 1--* reservation:

作成したER.ymlをindex.rstに取り込みます。 取り込むにはer-diagramディレクティブを使います。

.. Sphinx ER Diagram Document documentation master file, created by
   sphinx-quickstart on Sat Feb 25 13:50:23 2017.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to Sphinx ER Diagram Document's documentation!
======================================================

.. ER_INCLUDE_START

.. er-diagram:: ER.yml

.. ER_INCLUDE_END

.. toctree::
   :maxdepth: 2
   :caption: Contents:


Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

ドキュメントの生成

ビルドして表示を確認します。

make html

生成されたER図を見てみましょう。

https://res.cloudinary.com/symdon/image/upload/v1641980130/blog.symdon.info/ERDiagram-3750e0c81af10a88382652f200a4537fe5df5a30_vkk5lw.png

uniqueとかの表現がなさそうなのと、fk(foreign key)の表現が図ではとてもわかりにくいのが辛いけど、それ以外は良かった。

実行環境

  • macOS 10.12.1(16B2657)
  • Python 3.6.0 |Continuum Analytics, Inc.| (default, Dec 23 2016, 13:19:00)
  • Homebrew 1.1.10-249-g2a45dfd
  • Homebrew/homebrew-core (git revision 3a73e; last commit 2017-02-24)

参考

脚注