Skip to content

Commit

Permalink
Merge pull request #58 from pboettch/alembic-integration
Browse files Browse the repository at this point in the history
Alembic integration
  • Loading branch information
jeandet authored May 24, 2024
2 parents 1629ca0 + 61e03dd commit 99f9a46
Show file tree
Hide file tree
Showing 12 changed files with 406 additions and 19 deletions.
14 changes: 0 additions & 14 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,3 @@ dynamic catalogues (filter-based).

* Free software: GNU General Public License v3
* Documentation: https://tscat.readthedocs.io.


Features
--------

* TODO

Credits
-------

This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template.

.. _Cookiecutter: https://github.com/audreyr/cookiecutter
.. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage
1 change: 1 addition & 0 deletions requirements_dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ appdirs
typing_extensions>=3.7
SQLAlchemy_Utils>=0.37.8
orjson
alembic
appdirs-stubs
mypy
pytest-timeout
Expand Down
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
history = history_file.read()

requirements = [
"alembic",
"typing_extensions>=3.7",
'sqlalchemy[mypy]<2',
"appdirs>=1.4.4 ",
Expand Down
Binary file added tests/migration-db-test.sqlite
Binary file not shown.
27 changes: 27 additions & 0 deletions tests/test_db_migration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import unittest
import tscat.orm_sqlalchemy
import os
import tscat
import datetime as dt


class DBMigration(unittest.TestCase):

def setUp(self) -> None:
if tscat.base._backend:
tscat.base._backend.close()
test_db_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'migration-db-test.sqlite')
tscat.base._backend = tscat.orm_sqlalchemy.Backend(testing=test_db_file)

def test_existing_event_now_has_rating_field(self):
existing, = tscat.get_events()
self.assertEqual(existing.rating, None)

def test_creating_event_with_rating(self):
tscat.create_event(dt.datetime.now(), dt.datetime.now() + dt.timedelta(days=1), "Patrick", rating=3)

_, e = tscat.get_events()
self.assertEqual(e.author, "Patrick")
self.assertEqual(e.rating, 3)

self.assertEqual(len(tscat.get_events()), 2)
34 changes: 29 additions & 5 deletions tscat/orm_sqlalchemy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

from sqlalchemy import create_engine, and_, or_, not_, event, func, cast, String
from sqlalchemy.orm import Session, Query
from sqlalchemy.pool.base import _ConnectionFairy

from operator import __eq__, __ne__, __ge__, __gt__, __le__, __lt__

Expand Down Expand Up @@ -126,20 +127,39 @@ def visit_predicate(self, pred: Predicate):


class Backend:
def __init__(self, testing=False):
if testing:
url = 'sqlite://' # memory database
def __init__(self, testing: Union[bool, str] = False):
if testing is True:
sqlite_filename = ""
elif isinstance(testing, str):
sqlite_filename = 'file:memdb1?mode=memory&cache=shared' # memory database

else: # pragma: no cover
db_file_path = user_data_dir('tscat')
if not os.path.exists(db_file_path):
os.makedirs(db_file_path)
url = f'sqlite:///{db_file_path}/backend.sqlite'
sqlite_filename = f'{db_file_path}/backend.sqlite'

# self.engine = create_engine(url, echo=True,
self.engine = create_engine(url,
self.engine = create_engine(f'sqlite:///{sqlite_filename}',
json_serializer=_serialize_json,
json_deserializer=_deserialize_json)

# copy testing database to memory
if isinstance(testing, str):
import sqlite3
source = sqlite3.connect(testing)
assert isinstance(self.engine.raw_connection(), _ConnectionFairy)
assert isinstance(self.engine.raw_connection().connection, sqlite3.Connection) # type: ignore
source.backup(self.engine.raw_connection().connection, pages=-1) # type: ignore

# tempt alembic migration of the database
from alembic.config import Config
from alembic import command
alembic_cfg = Config(os.path.join(os.path.dirname(__file__), 'alembic.ini'))
alembic_cfg.set_main_option("script_location", os.path.join(os.path.dirname(__file__), 'migrations'))
alembic_cfg.set_main_option("sqlalchemy.url", f'sqlite:///{sqlite_filename}')
command.upgrade(alembic_cfg, "head")

# use BEGIN EXCLUSIVE to lock database exclusively to one process
@event.listens_for(self.engine, "begin")
def do_begin(conn):
Expand All @@ -149,6 +169,10 @@ def do_begin(conn):

self.session = Session(bind=self.engine, autoflush=True)

def close(self):
self.session.close()
self.engine.dispose()

def _specialiced_serialization(self, key, value):
if key == "predicate":
return pickle.dumps(value, protocol=3)
Expand Down
116 changes: 116 additions & 0 deletions tscat/orm_sqlalchemy/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts
script_location = migrations

# 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>=3.9 or backports.zoneinfo library.
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
# string value is passed to ZoneInfo()
# 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 migrations/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:migrations/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.

# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false

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

sqlalchemy.url = sqlite:////home/pboettch/.local/share/tscat/backend.sqlite


[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

# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
# hooks = ruff
# ruff.type = exec
# ruff.executable = %(here)s/.venv/bin/ruff
# ruff.options = --fix 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
36 changes: 36 additions & 0 deletions tscat/orm_sqlalchemy/migrations/README
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
Alembic integration for database migrations
-------------------------------------------

This library uses alembic for database migrations. Alembic was added
later on when the database model was already created and used in production.

The goal is to use alembic to create migration scripts that can be used to
migrate production databases to the current state of the model after an
upgrade of tscat to a newer version by the user.

Initial steps that were taken starting from the 0.2.0-release (tag ``v0.2.0``):

1. Install alembic with ``pip install alembic``
2. Go to ``tscat/orm_sqlalchemy``
3. Create an alembic environment with ``alembic init migrations``. This creates
a directory called ``migrations``.
4. Edit the ``alembic.ini`` file to point to the database URL.
As in development we use a sqlite-database in its production location, we need to
resolve: e.g. with ``python -c "from appdirs import user_data_dir; print(user_data_dir('tscat'))"``
The URL is then the output of the above command with ``backend.sqlite`` appended.
As an example: (see the two extra forward slashes after sqlite://)

``sqlalchemy.url = sqlite:////home/pboettch/.local/share/tscat/backend.sqlite``

5. Edit the ``env.py`` file to point to the database model.
6. Remove the database file and create a new one corresponding to the orm of this tscat-version
7. Create the first migration with ``alembic revision --autogenerate -m "Initial migration"``.
8. Edit the create migration-script and empty out upgrade and downgrade functions. As we add alembic to
an existing production database we do not want to change the database, but only add the migration.
9. Run the migration with ``alembic upgrade head``. Now alembic should be in sync with the current
database model and later migrations are possible.

Steps 7 and 9 are to be repeated when the database model changes.



77 changes: 77 additions & 0 deletions tscat/orm_sqlalchemy/migrations/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
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.
if config.config_file_name is not None:
fileConfig(config.config_file_name)

# add your model's MetaData object here
# for 'autogenerate' support
from tscat.orm_sqlalchemy.orm import Base
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.


def run_migrations_offline() -> None: # pragma: no cover
"""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() -> None:
"""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() # pragma: no cover
else:
run_migrations_online()
26 changes: 26 additions & 0 deletions tscat/orm_sqlalchemy/migrations/script.py.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""${message}

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

"""
from typing import Sequence, Union

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

# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}


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


def downgrade() -> None:
${downgrades if downgrades else "pass"}
Loading

0 comments on commit 99f9a46

Please sign in to comment.