Skip to content

Commit

Permalink
Add initial alembic migration (#209)
Browse files Browse the repository at this point in the history
* Add initial alembic migration

* Filter out alembic files from coverage

* Bump version
  • Loading branch information
pbylicki authored Apr 2, 2020
1 parent 81a95c2 commit 3c05da2
Show file tree
Hide file tree
Showing 15 changed files with 306 additions and 18 deletions.
3 changes: 3 additions & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[run]
omit =
rfhub2/alembic/*
10 changes: 10 additions & 0 deletions DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,13 @@ black -t py36 rfhub2 tests

You can consider adding a git hook or integrating it with your IDE for automated execution.

### Database migrations
When you introduce any changes to database schema, you should prepare Alembic revision reflecting these changes.

To autogenerate revision file, make sure that SQLALCHEMY_DB_URI variable in config points to existing database instance
containing database state from previous revision and execute

```
PYTHONPATH=. alembic -c rfhub2/alembic.ini revision --autogenerate -m "Your revision name"
```
Before commit, inspect generated file to make sure that revision contains only relevant changes to the schema.
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
alembic==1.4.2
aiofiles==0.4.0
Click==7.1.1
dataclasses==0.6
Expand Down
82 changes: 82 additions & 0 deletions rfhub2/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts
script_location = %(here)s/alembic

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

# timezone to use when rendering the date
# within the migration file as well as the filename.
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =

# 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 = true

# 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/alembic/versions

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

[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples

# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks=black
# black.type=console_scripts
# black.entrypoint=black
# black.options=-l 79

# 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
75 changes: 75 additions & 0 deletions rfhub2/alembic/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool

from alembic import context

# 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 rfhub2.db.base import *

target_metadata = Base.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.
from rfhub2.config import SQLALCHEMY_DB_URI


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.
"""
context.configure(
url=SQLALCHEMY_DB_URI,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)

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.
"""
configuration = config.get_section(config.config_ini_section)
configuration["sqlalchemy.url"] = SQLALCHEMY_DB_URI
connectable = engine_from_config(
configuration, prefix="sqlalchemy.", poolclass=pool.NullPool
)

with connectable.connect() as connection:
context.configure(connection=connection, target_metadata=target_metadata)

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


if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
24 changes: 24 additions & 0 deletions rfhub2/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}

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

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


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


def downgrade():
${downgrades if downgrades else "pass"}
69 changes: 69 additions & 0 deletions rfhub2/alembic/versions/c54a916ec6c8_initial_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
"""Initial model
Revision ID: c54a916ec6c8
Revises:
Create Date: 2020-04-01 21:02:20.117380
"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = "c54a916ec6c8"
down_revision = None
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"collection",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("name", sa.Text(), nullable=True),
sa.Column("type", sa.Text(), nullable=True),
sa.Column("version", sa.Text(), nullable=True),
sa.Column("scope", sa.Text(), nullable=True),
sa.Column("named_args", sa.Text(), nullable=True),
sa.Column("path", sa.Text(), nullable=True),
sa.Column("doc", sa.Text(), nullable=True),
sa.Column("doc_format", sa.Text(), nullable=True),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_collection_name"), "collection", ["name"], unique=False)
op.create_table(
"keywordstatistics",
sa.Column("collection", sa.Text(), nullable=False),
sa.Column("keyword", sa.Text(), nullable=False),
sa.Column("execution_time", sa.DateTime(timezone=True), nullable=False),
sa.Column("times_used", sa.Integer(), nullable=True),
sa.Column("total_elapsed", sa.Integer(), nullable=True),
sa.Column("min_elapsed", sa.Integer(), nullable=True),
sa.Column("max_elapsed", sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint("collection", "keyword", "execution_time"),
)
op.create_table(
"keyword",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("name", sa.Text(), nullable=True),
sa.Column("doc", sa.Text(), nullable=True),
sa.Column("args", sa.Text(), nullable=True),
sa.Column("collection_id", sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(
["collection_id"], ["collection.id"], ondelete="CASCADE"
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_keyword_name"), "keyword", ["name"], unique=False)
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f("ix_keyword_name"), table_name="keyword")
op.drop_table("keyword")
op.drop_table("keywordstatistics")
op.drop_index(op.f("ix_collection_name"), table_name="collection")
op.drop_table("collection")
# ### end Alembic commands ###
7 changes: 0 additions & 7 deletions rfhub2/db/init_db.py

This file was deleted.

27 changes: 27 additions & 0 deletions rfhub2/db/migrate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from alembic.config import Config
from alembic.runtime.migration import MigrationContext
from alembic import command
from sqlalchemy.engine import Connection, Engine
from sqlalchemy.engine.reflection import Inspector


def has_tables(connection: Connection) -> bool:
inspector = Inspector(connection)
tables = inspector.get_table_names()
return len(tables) > 0


def has_revision(connection: Connection) -> bool:
context = MigrationContext.configure(connection)
current_rev = context.get_current_revision()
return current_rev is not None


def migrate_db(engine: Engine) -> None:
alembic_cfg = Config("rfhub2/alembic.ini")
with engine.begin() as connection:
# check if database has not been migrated yet with alembic
if has_tables(connection) and not has_revision(connection):
# stamp database with the initial revision id, representing pre-alembic database schema
command.stamp(alembic_cfg, "c54a916ec6c8")
command.upgrade(alembic_cfg, "head")
6 changes: 3 additions & 3 deletions rfhub2/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from rfhub2.app import create_app
from rfhub2.db.init_db import init_db
from rfhub2.db.session import db_session
from rfhub2.db.migrate import migrate_db
from rfhub2.db.session import engine

init_db(db_session)
migrate_db(engine)
app = create_app()
2 changes: 1 addition & 1 deletion rfhub2/version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
version = "0.15"
version = "0.16"
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
zip_safe=True,
include_package_data=True,
install_requires=[
'alembic>=1.2.0',
'aiofiles>=0.4.0',
'Click>=7.0',
'fastapi>=0.46.0',
Expand Down
11 changes: 7 additions & 4 deletions tests/unit/api/endpoints/base_endpoint_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@

from rfhub2 import config
from rfhub2.app import create_app
from rfhub2.db.init_db import init_db
from rfhub2.db.sample_data import recreate_data
from rfhub2.db.session import db_session
from rfhub2.db.migrate import migrate_db
from rfhub2.db.session import db_session, engine
from tests.unit.sample_data import recreate_data


class BaseApiEndpointTest(unittest.TestCase):
Expand Down Expand Up @@ -234,10 +234,13 @@ class BaseApiEndpointTest(unittest.TestCase):
"max_elapsed": 1000,
}

@classmethod
def setUpClass(cls) -> None:
migrate_db(engine)

def setUp(self) -> None:
self.app = create_app()
db_session.rollback()
init_db(db_session)
recreate_data(db_session)
self.client: TestClient = TestClient(self.app)
self.auth_client: TestClient = TestClient(self.app)
Expand Down
6 changes: 3 additions & 3 deletions tests/unit/db/base_repo_tests.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import unittest

from rfhub2.db.base import Collection, Keyword
from rfhub2.db.init_db import init_db
from rfhub2.db.migrate import migrate_db
from rfhub2.db.repository.collection_repository import CollectionRepository
from rfhub2.db.repository.keyword_repository import KeywordRepository
from rfhub2.db.session import db_session
from rfhub2.db.session import db_session, engine


class BaseRepositoryTest(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
init_db(db_session)
migrate_db(engine)

def setUp(self) -> None:
db_session.rollback()
Expand Down
File renamed without changes.

0 comments on commit 3c05da2

Please sign in to comment.