Skip to content

Commit

Permalink
Setup Alembic
Browse files Browse the repository at this point in the history
Added initial alembic config and schema
Changed Enums to String with validator since
    Alembic doesn't handle SA's Enum type
  • Loading branch information
gmjosack committed Jan 17, 2015
1 parent de79149 commit d596042
Show file tree
Hide file tree
Showing 6 changed files with 320 additions and 3 deletions.
68 changes: 68 additions & 0 deletions alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts
script_location = alembic

# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s

# max length of characters to apply to the
# "slug" field
#truncate_slug_length = 40

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false

# version location specification; this defaults
# to alembic/versions. When using multiple version
# directories, initial revisions must be specified with --version-path
# version_locations = %(here)s/bar %(here)s/bat alembic/versions

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

# TODO(gary): Update to work off existing config
sqlalchemy.url = sqlite:///nsot.sqlite

# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
73 changes: 73 additions & 0 deletions alembic/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
from __future__ import with_statement
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)

# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from nsot.models import Model
target_metadata = Model.metadata

# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.


def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(url=url, target_metadata=target_metadata)

with context.begin_transaction():
context.run_migrations()


def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
engine = engine_from_config(
config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool)

connection = engine.connect()
context.configure(
connection=connection,
target_metadata=target_metadata
)

try:
with context.begin_transaction():
context.run_migrations()
finally:
connection.close()

if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
24 changes: 24 additions & 0 deletions alembic/script.py.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""${message}

Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}

"""

# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}

from alembic import op
import sqlalchemy as sa
${imports if imports else ""}

def upgrade():
${upgrades if upgrades else "pass"}


def downgrade():
${downgrades if downgrades else "pass"}
138 changes: 138 additions & 0 deletions alembic/versions/e3cd3d62ff_.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
"""empty message
Revision ID: e3cd3d62ff
Revises:
Create Date: 2015-01-17 03:51:06.190157
"""

# revision identifiers, used by Alembic.
revision = 'e3cd3d62ff'
down_revision = None
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa


def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('sites',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=255), nullable=False),
sa.Column('description', sa.Text(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
op.create_table('counters',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=64), nullable=False),
sa.Column('count', sa.Integer(), nullable=False),
sa.Column('last_modified', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
)
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('email', sa.String(length=255), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('email')
)
op.create_table('permissions',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('site_id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('permissions_flag', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['site_id'], [u'sites.id'], ondelete=u'CASCADE'),
sa.ForeignKeyConstraint(['user_id'], [u'users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index('site_user_idx', 'permissions', ['site_id', 'user_id'], unique=True)
op.create_table('networks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('site_id', sa.Integer(), nullable=False),
sa.Column('ip_version', sa.String(length=1), nullable=False),
sa.Column('parent_id', sa.Integer(), nullable=True),
sa.Column('network_address', sa.VARBINARY(length=16), nullable=False),
sa.Column('broadcast_address', sa.VARBINARY(length=16), nullable=False),
sa.Column('prefix_length', sa.Integer(), nullable=False),
sa.Column('is_ip', sa.Boolean(), nullable=False),
sa.Column('attributes', sa.Text(), nullable=True),
sa.ForeignKeyConstraint(['parent_id'], [u'networks.id'], ),
sa.ForeignKeyConstraint(['site_id'], [u'sites.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index('cidr_idx', 'networks', ['site_id', 'ip_version', 'network_address', 'prefix_length'], unique=True)
op.create_index(op.f('ix_networks_broadcast_address'), 'networks', ['broadcast_address'], unique=False)
op.create_index(op.f('ix_networks_ip_version'), 'networks', ['ip_version'], unique=False)
op.create_index(op.f('ix_networks_is_ip'), 'networks', ['is_ip'], unique=False)
op.create_index(op.f('ix_networks_network_address'), 'networks', ['network_address'], unique=False)
op.create_index(op.f('ix_networks_prefix_length'), 'networks', ['prefix_length'], unique=False)
op.create_index(op.f('ix_networks_site_id'), 'networks', ['site_id'], unique=False)
op.create_table('network_attributes',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('site_id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=64), nullable=False),
sa.Column('description', sa.Text(), nullable=False),
sa.Column('required', sa.Boolean(), nullable=False),
sa.ForeignKeyConstraint(['site_id'], [u'sites.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index('name_idx', 'network_attributes', ['site_id', 'name'], unique=True)
op.create_table('changes',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('site_id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('change_at', sa.DateTime(), nullable=False),
sa.Column('event', sa.String(length=10), nullable=False),
sa.Column('resource_type', sa.Integer(), nullable=False),
sa.Column('resource_id', sa.Integer(), nullable=False),
sa.Column('resource', sa.Text(), nullable=False),
sa.ForeignKeyConstraint(['site_id'], [u'sites.id'], ondelete=u'CASCADE'),
sa.ForeignKeyConstraint(['user_id'], [u'users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_changes_site_id'), 'changes', ['site_id'], unique=False)
op.create_index(op.f('ix_changes_user_id'), 'changes', ['user_id'], unique=False)
op.create_table('network_attribute_index',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=64), nullable=False),
sa.Column('value', sa.String(length=255), nullable=False),
sa.Column('network_id', sa.Integer(), nullable=False),
sa.Column('attribute_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['attribute_id'], [u'network_attributes.id'], ),
sa.ForeignKeyConstraint(['network_id'], [u'networks.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_network_attribute_index_name'), 'network_attribute_index', ['name'], unique=False)
op.create_index(op.f('ix_network_attribute_index_value'), 'network_attribute_index', ['value'], unique=False)
op.create_index('single_attr_idx', 'network_attribute_index', ['network_id', 'attribute_id'], unique=True)
### end Alembic commands ###


def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_index('single_attr_idx', table_name='network_attribute_index')
op.drop_index(op.f('ix_network_attribute_index_value'), table_name='network_attribute_index')
op.drop_index(op.f('ix_network_attribute_index_name'), table_name='network_attribute_index')
op.drop_table('network_attribute_index')
op.drop_index(op.f('ix_changes_user_id'), table_name='changes')
op.drop_index(op.f('ix_changes_site_id'), table_name='changes')
op.drop_table('changes')
op.drop_index('name_idx', table_name='network_attributes')
op.drop_table('network_attributes')
op.drop_index(op.f('ix_networks_site_id'), table_name='networks')
op.drop_index(op.f('ix_networks_prefix_length'), table_name='networks')
op.drop_index(op.f('ix_networks_network_address'), table_name='networks')
op.drop_index(op.f('ix_networks_is_ip'), table_name='networks')
op.drop_index(op.f('ix_networks_ip_version'), table_name='networks')
op.drop_index(op.f('ix_networks_broadcast_address'), table_name='networks')
op.drop_index('cidr_idx', table_name='networks')
op.drop_table('networks')
op.drop_index('site_user_idx', table_name='permissions')
op.drop_table('permissions')
op.drop_table('users')
op.drop_table('counters')
op.drop_table('sites')
### end Alembic commands ###
19 changes: 16 additions & 3 deletions nsot/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@
obj_type: idx
for idx, obj_type in enumerate(RESOURCE_BY_IDX)
}

CHANGE_EVENTS = ("Create", "Update", "Delete")
IP_VERSIONS = ("4", "6")


class Session(_Session):
Expand Down Expand Up @@ -379,7 +381,7 @@ class Network(Model):
id = Column(Integer, primary_key=True)
site_id = Column(Integer, ForeignKey("sites.id"), nullable=False, index=True)

ip_version = Column(Enum("4", "6"), nullable=False, index=True)
ip_version = Column(String(1), nullable=False, index=True)

# Root networks will be NULL while other networks will point to
# their supernet.
Expand All @@ -399,6 +401,12 @@ class Network(Model):
# is done against an Inverted Index table
_attributes = Column("attributes", Text)

@validates("ip_version")
def validate_ip_version(self, key, value):
if value not in IP_VERSIONS:
raise exc.ValidationError("Invalid IP Version.")
return value

def to_dict(self):
network_address = ipaddress.ip_address(self.network_address)

Expand Down Expand Up @@ -671,7 +679,6 @@ def validate_name(self, key, value):

return value


@classmethod
def all_by_name(cls, session):
return {
Expand Down Expand Up @@ -704,13 +711,19 @@ class Change(Model):

change_at = Column(DateTime, default=datetime.utcnow, nullable=False)

event = Column(Enum(*CHANGE_EVENTS), nullable=False)
event = Column(String(10), nullable=False)

resource_type = Column(Integer, nullable=False)
resource_id = Column(Integer, nullable=False)

_resource = Column("resource", Text, nullable=False)

@validates("event")
def validate_event(self, key, value):
if value not in CHANGE_EVENTS:
raise exc.ValidationError("Invalid Change Event.")
return value

@property
def resource(self):
return json.loads(self._resource)
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ tornado==4.0.2
wsgiref==0.1.2
bittle==0.2.1
Werkzeug==0.9.6
alembic==0.7.4

0 comments on commit d596042

Please sign in to comment.