Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion src/egon/data/airflow/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,3 @@ services:
POSTGRES_PASSWORD: data
volumes:
- $HOME/docker/volumes/postgres/egon-data:/var/lib/postgresql/data
- ./entrypoints:/docker-entrypoint-initdb.d/

This file was deleted.

3 changes: 3 additions & 0 deletions src/egon/data/airflow/tasks.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import os.path
import subprocess

import egon.data


def initdb():
""" Initialize the local database used for data processing. """
subprocess.run(
["docker-compose", "up", "-d", "--build"],
cwd=os.path.dirname(__file__),
)
subprocess.run(["alembic", "upgrade", "head"], cwd=egon.data.__path__[0])
88 changes: 88 additions & 0 deletions src/egon/data/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts
script_location = alembic

# template used to generate migration files
file_template = %%(year)d-%%(month).2d-%%(day).2dT%%(hour).2d:%%(minute).2d.%%(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 = UTC

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

# 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/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 = driver://user:pass@localhost/dbname


[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 = fixup, isort, black, sequentialize
fixup.type = fixup
black.type = console_scripts
black.entrypoint = black
isort.type = console_scripts
isort.entrypoint = isort
sequentialize.type = sequentialize

# 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 src/egon/data/alembic/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration.
135 changes: 135 additions & 0 deletions src/egon/data/alembic/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
from fileinput import FileInput
from logging.config import fileConfig
from pathlib import Path
import re

from alembic import context
from alembic.script import ScriptDirectory, write_hooks

from egon.data.db import engine
from egon.data.orm.openstreetmap import metadata

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


@write_hooks.register("fixup")
def fix_minor_issues(filename, options):
"""Fix minor issues like grammar in comments or trailing whitespace."""
fixes = []
with FileInput(filename, inplace=True) as script:
for line in script:
if re.match(r"# revision identifiers, used by Alembic\.", line):
print("# Revision identifiers, used by Alembic.")
fixes.append('"# revision ..." -> "# Revision ..."')
else:
print(line, end="")
for fix in fixes:
print(f"Fixed: {fix}.")


def script(filename=None, revision=None):
"""Return the script object matching the parameters.

Either the script object having the given :py:obj:`filename` or having
the given :py:obj:`revision`, is returned. If both are given, both have
to match.

Supplying at least one is mandatory.
"""
assert filename is not None or revision is not None
scripts = ScriptDirectory.from_config(config)
return [
s
for s in scripts.walk_revisions()
if (filename is None or s.path == filename)
and (revision is None or s.revision == revision)
][0]


@write_hooks.register("sequentialize")
def assign_sequential_version_number(filename, options):
"""Prefix the migration script's name with a sequential version number.

The version number is generated by incrementing the version number of
the down revision by one. Since the intention is to get a sequential
ordering when sorting the migration scripts alphabetically, this
sequential number is right aligned and padded with zeroes to a length of
three characters.
"""

current = script(filename=filename)
path = Path(filename)
down = (
"-001." # Gets incremented to 0 in the line below.
if current.down_revision is None
else Path(script(revision=current.down_revision).path).name
)
version = int(re.match(r"^(-?\d{3})\..*", down)[1]) + 1
prefix = f"{version:0>3}."
path.rename(path.parent / (prefix + path.name))
print(f'Prefixed new migration script with "{prefix}".')


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,
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.

"""
connectable = engine()

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 src/egon/data/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"}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""Do nothing for the base migration

This migration intentionally does nothing. Downgrading to this revision
should reset the database to a clean state or at least undo everything
done via Alembic.

Revision ID: 9b9584efcefd
Revises:
Create Date: 2021-01-08 16:37:31.238609+00:00

"""

# Revision identifiers, used by Alembic.
revision = "9b9584efcefd"
down_revision = None
branch_labels = None
depends_on = None


def upgrade():
pass


def downgrade():
pass
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""Create the hstore and postgis database extensions

Revision ID: 79833aa6bc04
Revises: 9b9584efcefd
Create Date: 2021-01-08 18:50:07.951487+00:00

"""
from alembic import op

# Revision identifiers, used by Alembic.
revision = "79833aa6bc04"
down_revision = "9b9584efcefd"
branch_labels = None
depends_on = None


def upgrade():
op.execute("CREATE EXTENSION IF NOT EXISTS hstore;")
op.execute("CREATE EXTENSION IF NOT EXISTS postgis;")


def downgrade():
op.execute("DROP EXTENSION IF EXISTS postgis;")
op.execute("DROP EXTENSION IF EXISTS hstore;")
Loading