Skip to content

Commit

Permalink
Alembic beginnings
Browse files Browse the repository at this point in the history
  • Loading branch information
nicfit committed Jan 22, 2017
1 parent 8fe9f51 commit 17add76
Show file tree
Hide file tree
Showing 6 changed files with 214 additions and 9 deletions.
68 changes: 68 additions & 0 deletions mishmash/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

sqlalchemy.url = sqlite:///testdb.sql


# 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
1 change: 1 addition & 0 deletions mishmash/alembic/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration.
70 changes: 70 additions & 0 deletions mishmash/alembic/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
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
target_metadata = None

# 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, literal_binds=True)

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.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section),
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 mishmash/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"}
24 changes: 24 additions & 0 deletions mishmash/alembic/versions/ae1461b8a01f_initial_empty_rev.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""initial/empty rev
Revision ID: ae1461b8a01f
Revises:
Create Date: 2017-01-22 00:14:12.583177
"""
from alembic import op
import sqlalchemy as sa


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


def upgrade():
pass


def downgrade():
pass
36 changes: 27 additions & 9 deletions mishmash/database.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import os
from pathlib import Path
import nicfit
from sqlalchemy import create_engine, or_
from sqlalchemy.orm import sessionmaker

from sqlalchemy_utils.functions import (database_exists,
create_database,
drop_database)
from alembic import command
from alembic.config import Config

from .orm import TYPES, TABLES
from .orm import Base, Artist, Track, Album
Expand All @@ -20,16 +24,16 @@


def init(config, engine_args=None, session_args=None, trans_mgr=None):
url = config.db_url
db_url = config.db_url

log.debug("Checking for database '%s'" % url)
if not database_exists(url):
log.info("Creating database '%s'" % url)
create_database(url, template="template0")
log.debug("Checking for database '%s'" % db_url)
if not database_exists(db_url):
log.info("Creating database '%s'" % db_url)
create_database(db_url, template="template0")

log.debug("Connecting to database '%s'" % url)
log.debug("Connecting to database '%s'" % db_url)
args = engine_args or DEFAULT_ENGINE_ARGS
engine = create_engine(url, **args)
engine = create_engine(db_url, **args)
engine.connect()

args = session_args or DEFAULT_SESSION_ARGS
Expand All @@ -42,17 +46,20 @@ def init(config, engine_args=None, session_args=None, trans_mgr=None):
T.metadata.bind = engine

session = SessionMaker()
alembic_init = False
try:
try:
log.debug("Checking database schema '%s'" % url)
log.debug("Checking database schema '%s'" % db_url)
checkSchema(engine)
except MissingSchemaException as ex:
log.info("Creating database schema '%s'" % url)
log.info("Creating database schema '%s'" % db_url)
Base.metadata.create_all(engine)
for T in TYPES:
# Run extra table initialization
T.initTable(session, config)

alembic_init = True

if trans_mgr:
transaction.commit()
else:
Expand All @@ -66,6 +73,17 @@ def init(config, engine_args=None, session_args=None, trans_mgr=None):
finally:
session.close()

if alembic_init:
alembic_d = Path(__file__).parent
alembic_cfg = Config(str(alembic_d / "alembic.ini"))
alembic_cfg.set_main_option("sqlalchemy.url", db_url)
cwd = os.getcwd()
try:
os.chdir(str(alembic_d))
command.stamp(alembic_cfg, "head")
finally:
os.chdir(cwd)

return engine, SessionMaker


Expand Down

0 comments on commit 17add76

Please sign in to comment.