Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add database migrations with alembic #3

Merged
merged 1 commit into from
Aug 27, 2022
Merged
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: 1 addition & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
.git/
.github/
.pytest_cache/
.mypy_cache/
.venv/
.env
5 changes: 5 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,8 @@ repos:
hooks:
- id: flake8
args: ["--max-line-length=110", "--ignore=E203,E501,W503"]

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.971
hooks:
- id: mypy
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,4 @@ USER fastqueue

# Set entrypoint and cmd
ENTRYPOINT ["/usr/bin/tini", "--"]
CMD ["python", "/app/fastqueue/main.py"]
CMD ["python", "/app/fastqueue/main.py", "server"]
7 changes: 5 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ build-image:
docker build --rm -t fastqueue .

run-server:
poetry run python fastqueue/main.py
poetry run python fastqueue/main.py server

.PHONY: test lint run-db rm-db build-image run-server
run-db-migrate:
poetry run python fastqueue/main.py db-migrate

.PHONY: test lint run-db rm-db build-image run-server run-db-migrate
105 changes: 105 additions & 0 deletions alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts
script_location = alembic

# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s

# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .

# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python-dateutil library that can be
# installed by adding `alembic[tz]` to the pip requirements
# 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 = 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.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions

# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.

# 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 = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME

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

from sqlalchemy import create_engine

from alembic import context
from fastqueue.config import settings

# 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.
if config.config_file_name is not None:
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() -> None:
"""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=settings.database_url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
compare_type=True,
)

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


def run_migrations_online() -> None:
"""Run migrations in 'online' mode.

In this scenario we need to create an Engine
and associate a connection with the context.

"""
connectable = create_engine(settings.database_url)
with connectable.connect() as connection:
context.configure(connection=connection, target_metadata=target_metadata, compare_type=True)

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 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() -> None:
${upgrades if upgrades else "pass"}


def downgrade() -> None:
${downgrades if downgrades else "pass"}
10 changes: 9 additions & 1 deletion env.sample
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
fastqueue_log_formatter='asctime=%(asctime)s level=%(levelname)s pathname=%(pathname)s line=%(lineno)s message=%(message)s'
fastqueue_log_level='debug'
fastqueue_log_json='false'

fastqueue_debug='true'
fastqueue_server_host='127.0.0.1'
fastqueue_server_port='8000'
fastqueue_server_reload='true'
fastqueue_server_num_workers='1'
fastqueue_log_level='info'

fastqueue_postgresql_host='localhost'
fastqueue_postgresql_dbname='fastqueue'
fastqueue_postgresql_user='fastqueue'
fastqueue_postgresql_password='fastqueue'
23 changes: 23 additions & 0 deletions fastqueue/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import uvicorn
from fastapi import FastAPI

from fastqueue.config import settings

app = FastAPI(debug=settings.debug)


@app.get("/")
def read_root():
return {"Hello": "World"}


def run_server():
uvicorn.run(
"fastqueue.api:app",
debug=settings.debug,
host=settings.server_host,
port=settings.server_port,
log_level=settings.log_level.lower(),
reload=settings.server_reload,
workers=settings.server_num_workers,
)
30 changes: 29 additions & 1 deletion fastqueue/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,45 @@


class Settings(BaseSettings):
# log settings
log_formatter: str = (
"asctime=%(asctime)s level=%(levelname)s pathname=%(pathname)s line=%(lineno)s message=%(message)s"
)
log_level: str = "info"
log_json: bool = True

# fastapi settings
debug: bool = False
server_host: str = "0.0.0.0"
server_port: int = 8000
server_reload: bool = False
server_num_workers: int = 1
log_level: str = "info"

# postgresql settings
postgresql_host: str
postgresql_dbname: str
postgresql_user: str
postgresql_password: str

class Config:
env_file = ".env"
env_file_encoding = "utf-8"
env_prefix = "fastqueue_"

def _create_database_url(self, prefix: str) -> str:
user = self.postgresql_user
password = self.postgresql_password
host = self.postgresql_host
dbname = self.postgresql_dbname
return f"{prefix}://{user}:{password}@{host}/{dbname}"

@property
def database_url(self) -> str:
return self._create_database_url("postgresql+psycopg2")

@property
def async_database_url(self) -> str:
return self._create_database_url("postgresql+asyncpg")


settings = Settings()
21 changes: 21 additions & 0 deletions fastqueue/database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from pathlib import Path

from alembic import command
from alembic.config import Config
from fastqueue.config import settings
from fastqueue.logger import get_logger

logger = get_logger(__name__)


def run_migrations() -> None:
parent_path = Path(__file__).parents[1]
script_location = parent_path.joinpath(Path("alembic"))
ini_location = parent_path.joinpath(Path("alembic.ini"))
logger.info(
"running db migrations", extra=dict(ini_location=ini_location, script_location=script_location)
)
alembic_cfg = Config(ini_location)
alembic_cfg.set_main_option("script_location", str(script_location))
alembic_cfg.set_main_option("sqlalchemy.url", settings.database_url)
command.upgrade(alembic_cfg, "head")
29 changes: 29 additions & 0 deletions fastqueue/logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import logging

from pythonjsonlogger import jsonlogger

from fastqueue.config import settings


def get_log_level(level: str) -> int:
return getattr(logging, level.upper())


def get_console_handler() -> logging.StreamHandler:
if settings.log_json:
formatter = jsonlogger.JsonFormatter(settings.log_formatter)
else:
formatter = logging.Formatter(settings.log_formatter)
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
return console_handler


def get_logger(name: str) -> logging.Logger:
logger = logging.getLogger(name)
log_level = get_log_level(settings.log_level)
logger.setLevel(log_level)
logger.addHandler(get_console_handler())
# with this pattern, it's rarely necessary to propagate the error up to parent
logger.propagate = False
return logger
Loading