Skip to content

Instantly share code, notes, and snippets.

@jonathana
Created November 2, 2016 04:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathana/590533e89ecda60420d7e3368af7d82e to your computer and use it in GitHub Desktop.
Save jonathana/590533e89ecda60420d7e3368af7d82e to your computer and use it in GitHub Desktop.
Helper functions for the alembic database migration package
""" alembic_helper.py
Copyright (c) 2016 Jonathan M. Altman
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject
to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
``build_tables()`` and ``remove_tables()`` both take in an ordered dict where the key is a table to
create and the value is a tuple of sqlAlchemy Column definitions
Sample input for build_tables/remove_tables
``table_defs = OrderedDict((
('user', (
sa.Column(u'id', sa.BIGINT(), primary_key=True),
sa.Column(u'first_name', sa.TEXT(), nullable=False),
sa.Column(u'last_name', sa.TEXT(), nullable=False),
)),
('user_item', (
sa.Column(u'id', sa.BIGINT(), primary_key=True),
sa.Column(u'user_id', sa.BIGINT(), sa.ForeignKey(u'user.id'), nullable=False),
sa.Column(u'description', sa.TEXT(), nullable=False),
sa.Column(u'this_allows_nulls', sa.TEXT()),
)),
))``
Usage:
``build_tables(table_defs)`` to put the tables in in the order they appear in the ordered dict
``remove_tables(table_defs)`` to remove the tables in reverse order they appear in the ordered dict, to avoid FK issues
"""
from alembic import op
import sqlalchemy as sa
def build_tables(table_defs):
for table_name, column_defs in table_defs.iteritems():
op.create_table(table_name, *column_defs)
def remove_tables(table_defs):
for table_name in reversed(table_defs.keys()):
op.drop_table(table_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment