event database migration
This commit is contained in:
141
server/alembic.ini
Normal file
141
server/alembic.ini
Normal file
@@ -0,0 +1,141 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts.
|
||||
# this is typically a path given in POSIX (e.g. forward slashes)
|
||||
# format, relative to the token %(here)s which refers to the location of this
|
||||
# ini file
|
||||
script_location = %(here)s/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. for multiple paths, the path separator
|
||||
# is defined by "path_separator" below.
|
||||
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 and tzdata 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 <script_location>/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 "path_separator"
|
||||
# below.
|
||||
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
|
||||
|
||||
# path_separator; This indicates what character is used to split lists of file
|
||||
# paths, including version_locations and prepend_sys_path within configparser
|
||||
# files such as alembic.ini.
|
||||
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
|
||||
# to provide os-dependent path splitting.
|
||||
#
|
||||
# Note that in order to support legacy alembic.ini files, this default does NOT
|
||||
# take place if path_separator is not present in alembic.ini. If this
|
||||
# option is omitted entirely, fallback logic is as follows:
|
||||
#
|
||||
# 1. Parsing of the version_locations option falls back to using the legacy
|
||||
# "version_path_separator" key, which if absent then falls back to the legacy
|
||||
# behavior of splitting on spaces and/or commas.
|
||||
# 2. Parsing of the prepend_sys_path option falls back to the legacy
|
||||
# behavior of splitting on spaces, commas, or colons.
|
||||
#
|
||||
# Valid values for path_separator are:
|
||||
#
|
||||
# path_separator = :
|
||||
# path_separator = ;
|
||||
# path_separator = space
|
||||
# path_separator = newline
|
||||
#
|
||||
# Use os.pathsep. Default configuration used for new projects.
|
||||
path_separator = os
|
||||
|
||||
# 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
|
||||
|
||||
# database URL. This is consumed by the user-maintained env.py script only.
|
||||
# other means of configuring database URLs may be customized within the env.py
|
||||
# file.
|
||||
# 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
|
||||
|
||||
# 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 = check --fix REVISION_SCRIPT_FILENAME
|
||||
|
||||
# Logging configuration. This is also consumed by the user-maintained
|
||||
# env.py script only.
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARNING
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARNING
|
||||
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
server/alembic/README
Normal file
1
server/alembic/README
Normal file
@@ -0,0 +1 @@
|
||||
Generic single-database configuration.
|
||||
104
server/alembic/env.py
Normal file
104
server/alembic/env.py
Normal file
@@ -0,0 +1,104 @@
|
||||
from logging.config import fileConfig
|
||||
|
||||
from sqlalchemy import engine_from_config
|
||||
from sqlalchemy import pool
|
||||
|
||||
from alembic import context
|
||||
|
||||
import sys
|
||||
sys.path.append('/workspace')
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
from server.models import Base
|
||||
|
||||
# .env laden (optional)
|
||||
env_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../.env'))
|
||||
print(f"Loading environment variables from: {env_path}")
|
||||
load_dotenv(env_path)
|
||||
|
||||
# Datenbank-Zugangsdaten aus .env
|
||||
DB_USER = os.getenv("DB_USER")
|
||||
DB_PASSWORD = os.getenv("DB_PASSWORD")
|
||||
DB_HOST = os.getenv("DB_HOST", "localhost")
|
||||
DB_PORT = os.getenv("DB_PORT", "3306")
|
||||
DB_NAME = os.getenv("DB_NAME")
|
||||
|
||||
# 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)
|
||||
|
||||
DATABASE_URL = (
|
||||
f"mysql+pymysql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
|
||||
)
|
||||
|
||||
print(f"Using DATABASE_URL: {DATABASE_URL}")
|
||||
|
||||
config.set_main_option("sqlalchemy.url", DATABASE_URL)
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
# from myapp import mymodel
|
||||
# target_metadata = mymodel.Base.metadata
|
||||
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:
|
||||
"""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()
|
||||
else:
|
||||
run_migrations_online()
|
||||
28
server/alembic/script.py.mako
Normal file
28
server/alembic/script.py.mako
Normal file
@@ -0,0 +1,28 @@
|
||||
"""${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:
|
||||
"""Upgrade schema."""
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
${downgrades if downgrades else "pass"}
|
||||
88
server/alembic/versions/c1178d5fa549_event_db.py
Normal file
88
server/alembic/versions/c1178d5fa549_event_db.py
Normal file
@@ -0,0 +1,88 @@
|
||||
"""event_db
|
||||
|
||||
Revision ID: c1178d5fa549
|
||||
Revises: f7dd3165f238
|
||||
Create Date: 2025-06-08 12:29:28.366231
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import mysql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = 'c1178d5fa549'
|
||||
down_revision: Union[str, None] = 'f7dd3165f238'
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('events',
|
||||
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column('client_uuid', sa.String(length=36), nullable=False),
|
||||
sa.Column('title', sa.String(length=100), nullable=False),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('start', sa.TIMESTAMP(timezone=True), nullable=False),
|
||||
sa.Column('end', sa.TIMESTAMP(timezone=True), nullable=False),
|
||||
sa.Column('event_type', sa.Enum('presentation', 'website', 'video', 'message', 'other', 'webuntis', name='eventtype'), nullable=False),
|
||||
sa.Column('created_at', sa.TIMESTAMP(timezone=True), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=True),
|
||||
sa.Column('updated_at', sa.TIMESTAMP(timezone=True), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=True),
|
||||
sa.Column('created_by', sa.Integer(), nullable=False),
|
||||
sa.Column('updated_by', sa.Integer(), nullable=True),
|
||||
sa.Column('is_active', sa.Boolean(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['client_uuid'], ['clients.uuid'], ),
|
||||
sa.ForeignKeyConstraint(['created_by'], ['users.id'], ),
|
||||
sa.ForeignKeyConstraint(['updated_by'], ['users.id'], ),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index(op.f('ix_events_client_uuid'), 'events', ['client_uuid'], unique=False)
|
||||
op.create_index(op.f('ix_events_end'), 'events', ['end'], unique=False)
|
||||
op.create_index(op.f('ix_events_start'), 'events', ['start'], unique=False)
|
||||
op.create_table('event_media',
|
||||
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column('event_id', sa.Integer(), nullable=False),
|
||||
sa.Column('media_type', sa.Enum('presentation', 'website', 'video', 'message', 'other', 'webuntis', name='eventtype'), nullable=False),
|
||||
sa.Column('url', sa.String(length=255), nullable=False),
|
||||
sa.Column('order', sa.Integer(), nullable=True),
|
||||
sa.Column('autoplay', sa.Boolean(), nullable=True),
|
||||
sa.Column('loop', sa.Boolean(), nullable=True),
|
||||
sa.Column('volume', sa.Float(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['event_id'], ['events.id'], ),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.add_column('clients', sa.Column('is_active', sa.Boolean(), nullable=False))
|
||||
op.create_index(op.f('ix_clients_hardware_hash'), 'clients', ['hardware_hash'], unique=False)
|
||||
op.create_index(op.f('ix_clients_ip_address'), 'clients', ['ip_address'], unique=False)
|
||||
op.add_column('users', sa.Column('is_active', sa.Boolean(), nullable=False))
|
||||
op.alter_column('users', 'password_hash',
|
||||
existing_type=mysql.VARCHAR(length=60),
|
||||
type_=sa.String(length=128),
|
||||
existing_nullable=False)
|
||||
op.drop_index(op.f('username'), table_name='users')
|
||||
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_index(op.f('ix_users_username'), table_name='users')
|
||||
op.create_index(op.f('username'), 'users', ['username'], unique=True)
|
||||
op.alter_column('users', 'password_hash',
|
||||
existing_type=sa.String(length=128),
|
||||
type_=mysql.VARCHAR(length=60),
|
||||
existing_nullable=False)
|
||||
op.drop_column('users', 'is_active')
|
||||
op.drop_index(op.f('ix_clients_ip_address'), table_name='clients')
|
||||
op.drop_index(op.f('ix_clients_hardware_hash'), table_name='clients')
|
||||
op.drop_column('clients', 'is_active')
|
||||
op.drop_table('event_media')
|
||||
op.drop_index(op.f('ix_events_start'), table_name='events')
|
||||
op.drop_index(op.f('ix_events_end'), table_name='events')
|
||||
op.drop_index(op.f('ix_events_client_uuid'), table_name='events')
|
||||
op.drop_table('events')
|
||||
# ### end Alembic commands ###
|
||||
32
server/alembic/versions/f7dd3165f238_initial.py
Normal file
32
server/alembic/versions/f7dd3165f238_initial.py
Normal file
@@ -0,0 +1,32 @@
|
||||
"""initial
|
||||
|
||||
Revision ID: f7dd3165f238
|
||||
Revises:
|
||||
Create Date: 2025-06-08 12:25:27.174339
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = 'f7dd3165f238'
|
||||
down_revision: Union[str, None] = None
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
pass
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
pass
|
||||
# ### end Alembic commands ###
|
||||
@@ -29,7 +29,7 @@ db_conn_str = f"mysql+pymysql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}/{DB_NAME}"
|
||||
engine = create_engine(db_conn_str, echo=True)
|
||||
|
||||
# Tabellen anlegen
|
||||
Base.metadata.create_all(engine)
|
||||
# Base.metadata.create_all(engine) # wird von alembic verwaltet
|
||||
|
||||
# Session erstellen
|
||||
Session = sessionmaker(bind=engine)
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
from sqlalchemy import Column, Integer, String, Enum, TIMESTAMP, func
|
||||
from sqlalchemy import (
|
||||
Column, Integer, String, Enum, TIMESTAMP, func, Boolean, ForeignKey, Float, Text, Index
|
||||
)
|
||||
from sqlalchemy.orm import declarative_base
|
||||
import enum
|
||||
|
||||
@@ -12,17 +14,55 @@ class UserRole(enum.Enum):
|
||||
class User(Base):
|
||||
__tablename__ = 'users'
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
username = Column(String(50), unique=True, nullable=False)
|
||||
password_hash = Column(String(60), nullable=False)
|
||||
username = Column(String(50), unique=True, nullable=False, index=True)
|
||||
password_hash = Column(String(128), nullable=False)
|
||||
role = Column(Enum(UserRole), nullable=False, default=UserRole.user)
|
||||
created_at = Column(TIMESTAMP, server_default=func.current_timestamp())
|
||||
updated_at = Column(TIMESTAMP, server_default=func.current_timestamp(), onupdate=func.current_timestamp())
|
||||
is_active = Column(Boolean, default=True, nullable=False)
|
||||
created_at = Column(TIMESTAMP(timezone=True), server_default=func.current_timestamp())
|
||||
updated_at = Column(TIMESTAMP(timezone=True), server_default=func.current_timestamp(), onupdate=func.current_timestamp())
|
||||
|
||||
class Client(Base):
|
||||
__tablename__ = 'clients'
|
||||
uuid = Column(String(36), primary_key=True, nullable=False)
|
||||
hardware_hash = Column(String(64), nullable=False)
|
||||
hardware_hash = Column(String(64), nullable=False, index=True)
|
||||
location = Column(String(100), nullable=True)
|
||||
ip_address = Column(String(45), nullable=True)
|
||||
registration_time = Column(TIMESTAMP, server_default=func.current_timestamp(), nullable=False)
|
||||
last_alive = Column(TIMESTAMP, server_default=func.current_timestamp(), onupdate=func.current_timestamp(), nullable=False)
|
||||
ip_address = Column(String(45), nullable=True, index=True)
|
||||
registration_time = Column(TIMESTAMP(timezone=True), server_default=func.current_timestamp(), nullable=False)
|
||||
last_alive = Column(TIMESTAMP(timezone=True), server_default=func.current_timestamp(), onupdate=func.current_timestamp(), nullable=False)
|
||||
is_active = Column(Boolean, default=True, nullable=False)
|
||||
|
||||
class EventType(enum.Enum):
|
||||
presentation = "presentation"
|
||||
website = "website"
|
||||
video = "video"
|
||||
message = "message"
|
||||
other = "other"
|
||||
webuntis = "webuntis"
|
||||
|
||||
class Event(Base):
|
||||
__tablename__ = 'events'
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
client_uuid = Column(String(36), ForeignKey('clients.uuid'), nullable=False, index=True)
|
||||
title = Column(String(100), nullable=False)
|
||||
description = Column(Text, nullable=True)
|
||||
start = Column(TIMESTAMP(timezone=True), nullable=False, index=True)
|
||||
end = Column(TIMESTAMP(timezone=True), nullable=False, index=True)
|
||||
event_type = Column(Enum(EventType), nullable=False)
|
||||
created_at = Column(TIMESTAMP(timezone=True), server_default=func.current_timestamp())
|
||||
updated_at = Column(TIMESTAMP(timezone=True), server_default=func.current_timestamp(), onupdate=func.current_timestamp())
|
||||
created_by = Column(Integer, ForeignKey('users.id'), nullable=False)
|
||||
updated_by = Column(Integer, ForeignKey('users.id'), nullable=True)
|
||||
is_active = Column(Boolean, default=True, nullable=False)
|
||||
|
||||
class EventMedia(Base):
|
||||
__tablename__ = 'event_media'
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
event_id = Column(Integer, ForeignKey('events.id'), nullable=False)
|
||||
media_type = Column(Enum(EventType), nullable=False)
|
||||
url = Column(String(255), nullable=False)
|
||||
order = Column(Integer, nullable=True)
|
||||
autoplay = Column(Boolean, nullable=True)
|
||||
loop = Column(Boolean, nullable=True)
|
||||
volume = Column(Float, nullable=True)
|
||||
|
||||
# Indizes für Performance (werden bei index=True automatisch gesetzt)
|
||||
|
||||
Reference in New Issue
Block a user