сделал миграции для базы данных

This commit is contained in:
Андрей Дувакин 2025-02-09 12:53:26 +05:00
parent 1d8b569d3e
commit 3ae2b72563
6 changed files with 434 additions and 1 deletions

119
API/alembic.ini Normal file
View File

@ -0,0 +1,119 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
# Use forward slashes (/) also on windows to provide an os agnostic path
script_location = app/database/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 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 app/database/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:app/database/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 = newline
#
# Use os.pathsep. Default configuration used for new projects.
version_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
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 = --fix REVISION_SCRIPT_FILENAME
# Logging configuration
[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

View File

@ -0,0 +1 @@
Generic single-database configuration.

View File

@ -0,0 +1,44 @@
from logging.config import fileConfig
from sqlalchemy import create_engine, pool
from alembic import context
from app.domain.models import Base
from app.settings import settings
config = context.config
target_metadata = Base.metadata
if config.config_file_name is not None:
fileConfig(config.config_file_name)
def get_url():
return settings.DATABASE_URL
def run_migrations_offline() -> None:
context.configure(
url=get_url(),
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
connectable = create_engine(get_url(), 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()

View File

@ -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"}

View File

@ -0,0 +1,222 @@
"""initial migration
Revision ID: d7d8af88f58b
Revises:
Create Date: 2025-02-09 12:52:46.145611
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = 'd7d8af88f58b'
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:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('appeals_topics',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('title', sa.VARCHAR(length=500), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_table('categories',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('title', sa.VARCHAR(length=200), nullable=False),
sa.Column('description', sa.String(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_table('notification_types',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('title', sa.VARCHAR(length=100), nullable=False),
sa.Column('description', sa.String(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_table('roles',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('title', sa.VARCHAR(length=100), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_table('step_types',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('title', sa.VARCHAR(length=200), nullable=False),
sa.Column('description', sa.String(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_table('task_types',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('title', sa.VARCHAR(length=200), nullable=False),
sa.Column('description', sa.String(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_table('users',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('first_name', sa.VARCHAR(length=150), nullable=False),
sa.Column('last_name', sa.VARCHAR(length=150), nullable=False),
sa.Column('patronymic', sa.VARCHAR(length=150), nullable=True),
sa.Column('gender', sa.Enum('MALE', 'FEMALE', 'NOTHING', name='usergenderenum'), nullable=False),
sa.Column('birthday', sa.Date(), nullable=False),
sa.Column('registration_date', sa.DateTime(), nullable=False),
sa.Column('login', sa.VARCHAR(length=150), nullable=False),
sa.Column('password', sa.String(), nullable=False),
sa.Column('email', sa.VARCHAR(length=200), nullable=False),
sa.Column('role_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['role_id'], ['roles.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('login')
)
op.create_table('appeals',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('message', sa.String(), nullable=False),
sa.Column('created_date', sa.DateTime(), nullable=False),
sa.Column('status', sa.Enum('NEW', 'IN_PROGRESS', 'WAITING_FOR_USER_RESPONSE', 'WAITING_FOR_SPECIALIST_RESPONSE', 'RESOLVED', 'CLOSED', 'REJECTED', name='appealstatusenum'), nullable=False),
sa.Column('topic_id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['topic_id'], ['appeals_topics.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('courses',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('title', sa.VARCHAR(length=200), nullable=False),
sa.Column('description', sa.String(), nullable=False),
sa.Column('category_id', sa.Integer(), nullable=False),
sa.Column('owner_user_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['category_id'], ['categories.id'], ),
sa.ForeignKeyConstraint(['owner_user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('course_students',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('enrollment_date', sa.Date(), nullable=False),
sa.Column('is_finished', sa.Boolean(), nullable=False),
sa.Column('course_id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['course_id'], ['courses.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('lessons',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('title', sa.VARCHAR(length=200), nullable=False),
sa.Column('description', sa.String(), nullable=False),
sa.Column('course_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['course_id'], ['courses.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('notifications',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('text', sa.String(), nullable=False),
sa.Column('datetime_notification', sa.DateTime(), nullable=False),
sa.Column('is_read', sa.Boolean(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('type_id', sa.Integer(), nullable=False),
sa.Column('course_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['course_id'], ['courses.id'], ),
sa.ForeignKeyConstraint(['type_id'], ['notification_types.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('steps',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('title', sa.VARCHAR(length=200), nullable=True),
sa.Column('lesson_id', sa.Integer(), nullable=False),
sa.Column('type_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['lesson_id'], ['lessons.id'], ),
sa.ForeignKeyConstraint(['type_id'], ['step_types.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('lectures',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('text', sa.String(), nullable=False),
sa.Column('image', sa.String(), nullable=True),
sa.Column('number', sa.Integer(), nullable=False),
sa.Column('step_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['step_id'], ['steps.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('step_tasks',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('text', sa.String(), nullable=False),
sa.Column('step_id', sa.Integer(), nullable=False),
sa.Column('type_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['step_id'], ['steps.id'], ),
sa.ForeignKeyConstraint(['type_id'], ['task_types.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('answer_options',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('answer', sa.String(), nullable=False),
sa.Column('is_current', sa.Boolean(), nullable=False),
sa.Column('task_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['task_id'], ['step_tasks.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('task_answers',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('answer_date', sa.DateTime(), nullable=False),
sa.Column('text', sa.String(), nullable=False),
sa.Column('is_current', sa.Boolean(), nullable=True),
sa.Column('comment', sa.String(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('task_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['task_id'], ['step_tasks.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('task_files',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('file_path', sa.String(), nullable=False),
sa.Column('file_title', sa.String(), nullable=False),
sa.Column('task_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['task_id'], ['step_tasks.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('answer_files',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('file_path', sa.String(), nullable=False),
sa.Column('file_title', sa.String(), nullable=False),
sa.Column('answer_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['answer_id'], ['task_answers.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('test_answers',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('answer_date', sa.DateTime(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('answer_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['answer_id'], ['answer_options.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('test_answers')
op.drop_table('answer_files')
op.drop_table('task_files')
op.drop_table('task_answers')
op.drop_table('answer_options')
op.drop_table('step_tasks')
op.drop_table('lectures')
op.drop_table('steps')
op.drop_table('notifications')
op.drop_table('lessons')
op.drop_table('course_students')
op.drop_table('courses')
op.drop_table('appeals')
op.drop_table('users')
op.drop_table('task_types')
op.drop_table('step_types')
op.drop_table('roles')
op.drop_table('notification_types')
op.drop_table('categories')
op.drop_table('appeals_topics')
# ### end Alembic commands ###

View File

@ -1,3 +1,24 @@
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
Base = declarative_base()
import app.domain.models.answer_files
import app.domain.models.answer_options
import app.domain.models.appeals
import app.domain.models.appeals_topics
import app.domain.models.categories
import app.domain.models.courses
import app.domain.models.course_students
import app.domain.models.lectures
import app.domain.models.lessons
import app.domain.models.notification_types
import app.domain.models.notifications
import app.domain.models.roles
import app.domain.models.steps
import app.domain.models.step_tasks
import app.domain.models.step_types
import app.domain.models.task_answers
import app.domain.models.task_files
import app.domain.models.task_types
import app.domain.models.test_answers
import app.domain.models.users