Skip to content

Commit 2f27a19

Browse files
committed
feat: добавить миграции Alembic для users tasks tags
Что сделано: - настроен Alembic для асинхронного SQLAlchemy проекта - добавлены миграции создания users и tasks - добавлены миграции создания tags и связующей таблицы task_tags
1 parent 355f5fb commit 2f27a19

6 files changed

Lines changed: 374 additions & 0 deletions

File tree

alembic.ini

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
# A generic, single database configuration.
2+
3+
[alembic]
4+
# path to migration scripts.
5+
# this is typically a path given in POSIX (e.g. forward slashes)
6+
# format, relative to the token %(here)s which refers to the location of this
7+
# ini file
8+
script_location = %(here)s/alembic
9+
10+
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
11+
# Uncomment the line below if you want the files to be prepended with date and time
12+
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
13+
# for all available tokens
14+
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
15+
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
16+
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
17+
18+
# sys.path path, will be prepended to sys.path if present.
19+
# defaults to the current working directory. for multiple paths, the path separator
20+
# is defined by "path_separator" below.
21+
prepend_sys_path = .
22+
23+
# timezone to use when rendering the date within the migration file
24+
# as well as the filename.
25+
# If specified, requires the tzdata library which can be installed by adding
26+
# `alembic[tz]` to the pip requirements.
27+
# string value is passed to ZoneInfo()
28+
# leave blank for localtime
29+
# timezone =
30+
31+
# max length of characters to apply to the "slug" field
32+
# truncate_slug_length = 40
33+
34+
# set to 'true' to run the environment during
35+
# the 'revision' command, regardless of autogenerate
36+
# revision_environment = false
37+
38+
# set to 'true' to allow .pyc and .pyo files without
39+
# a source .py file to be detected as revisions in the
40+
# versions/ directory
41+
# sourceless = false
42+
43+
# version location specification; This defaults
44+
# to <script_location>/versions. When using multiple version
45+
# directories, initial revisions must be specified with --version-path.
46+
# The path separator used here should be the separator specified by "path_separator"
47+
# below.
48+
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
49+
50+
# path_separator; This indicates what character is used to split lists of file
51+
# paths, including version_locations and prepend_sys_path within configparser
52+
# files such as alembic.ini.
53+
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
54+
# to provide os-dependent path splitting.
55+
#
56+
# Note that in order to support legacy alembic.ini files, this default does NOT
57+
# take place if path_separator is not present in alembic.ini. If this
58+
# option is omitted entirely, fallback logic is as follows:
59+
#
60+
# 1. Parsing of the version_locations option falls back to using the legacy
61+
# "version_path_separator" key, which if absent then falls back to the legacy
62+
# behavior of splitting on spaces and/or commas.
63+
# 2. Parsing of the prepend_sys_path option falls back to the legacy
64+
# behavior of splitting on spaces, commas, or colons.
65+
#
66+
# Valid values for path_separator are:
67+
#
68+
# path_separator = :
69+
# path_separator = ;
70+
# path_separator = space
71+
# path_separator = newline
72+
#
73+
# Use os.pathsep. Default configuration used for new projects.
74+
path_separator = os
75+
76+
77+
# set to 'true' to search source files recursively
78+
# in each "version_locations" directory
79+
# new in Alembic version 1.10
80+
# recursive_version_locations = false
81+
82+
# the output encoding used when revision files
83+
# are written from script.py.mako
84+
# output_encoding = utf-8
85+
86+
# database URL. This is consumed by the user-maintained env.py script only.
87+
# other means of configuring database URLs may be customized within the env.py
88+
# file.
89+
# URL берётся из .env через env.py, не хардкодим здесь
90+
# sqlalchemy.url = driver://user:pass@localhost/dbname
91+
92+
93+
[post_write_hooks]
94+
# post_write_hooks defines scripts or Python functions that are run
95+
# on newly generated revision scripts. See the documentation for further
96+
# detail and examples
97+
98+
# format using "black" - use the console_scripts runner, against the "black" entrypoint
99+
# hooks = black
100+
# black.type = console_scripts
101+
# black.entrypoint = black
102+
# black.options = -l 79 REVISION_SCRIPT_FILENAME
103+
104+
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
105+
# hooks = ruff
106+
# ruff.type = module
107+
# ruff.module = ruff
108+
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
109+
110+
# Alternatively, use the exec runner to execute a binary found on your PATH
111+
# hooks = ruff
112+
# ruff.type = exec
113+
# ruff.executable = ruff
114+
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
115+
116+
# Logging configuration. This is also consumed by the user-maintained
117+
# env.py script only.
118+
[loggers]
119+
keys = root,sqlalchemy,alembic
120+
121+
[handlers]
122+
keys = console
123+
124+
[formatters]
125+
keys = generic
126+
127+
[logger_root]
128+
level = WARNING
129+
handlers = console
130+
qualname =
131+
132+
[logger_sqlalchemy]
133+
level = WARNING
134+
handlers =
135+
qualname = sqlalchemy.engine
136+
137+
[logger_alembic]
138+
level = INFO
139+
handlers =
140+
qualname = alembic
141+
142+
[handler_console]
143+
class = StreamHandler
144+
args = (sys.stderr,)
145+
level = NOTSET
146+
formatter = generic
147+
148+
[formatter_generic]
149+
format = %(levelname)-5.5s [%(name)s] %(message)s
150+
datefmt = %H:%M:%S

alembic/README

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Generic single-database configuration with an async dbapi.

alembic/env.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import asyncio
2+
from logging.config import fileConfig
3+
4+
from alembic import context
5+
from sqlalchemy import pool
6+
from sqlalchemy.engine import Connection
7+
from sqlalchemy.ext.asyncio import async_engine_from_config
8+
9+
from app.config import settings
10+
from app.database import Base
11+
12+
# импортируем модели чтобы Alembic видел таблицы при autogenerate
13+
import app.models.user # noqa: F401
14+
import app.models.task # noqa: F401
15+
import app.models.tag # noqa: F401
16+
17+
config = context.config
18+
19+
if config.config_file_name is not None:
20+
fileConfig(config.config_file_name)
21+
22+
# подключаем наши метаданные для autogenerate
23+
target_metadata = Base.metadata
24+
25+
# подставляем URL из .env вместо alembic.ini
26+
config.set_main_option("sqlalchemy.url", settings.DATABASE_URL)
27+
28+
29+
def run_migrations_offline() -> None:
30+
url = config.get_main_option("sqlalchemy.url")
31+
context.configure(
32+
url=url,
33+
target_metadata=target_metadata,
34+
literal_binds=True,
35+
dialect_opts={"paramstyle": "named"},
36+
)
37+
with context.begin_transaction():
38+
context.run_migrations()
39+
40+
41+
def do_run_migrations(connection: Connection) -> None:
42+
context.configure(connection=connection, target_metadata=target_metadata)
43+
with context.begin_transaction():
44+
context.run_migrations()
45+
46+
47+
async def run_async_migrations() -> None:
48+
connectable = async_engine_from_config(
49+
config.get_section(config.config_ini_section, {}),
50+
prefix="sqlalchemy.",
51+
poolclass=pool.NullPool,
52+
)
53+
async with connectable.connect() as connection:
54+
await connection.run_sync(do_run_migrations)
55+
await connectable.dispose()
56+
57+
58+
def run_migrations_online() -> None:
59+
asyncio.run(run_async_migrations())
60+
61+
62+
if context.is_offline_mode():
63+
run_migrations_offline()
64+
else:
65+
run_migrations_online()

alembic/script.py.mako

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""${message}
2+
3+
Revision ID: ${up_revision}
4+
Revises: ${down_revision | comma,n}
5+
Create Date: ${create_date}
6+
7+
"""
8+
from typing import Sequence, Union
9+
10+
from alembic import op
11+
import sqlalchemy as sa
12+
${imports if imports else ""}
13+
14+
# revision identifiers, used by Alembic.
15+
revision: str = ${repr(up_revision)}
16+
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
17+
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
18+
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
19+
20+
21+
def upgrade() -> None:
22+
"""Upgrade schema."""
23+
${upgrades if upgrades else "pass"}
24+
25+
26+
def downgrade() -> None:
27+
"""Downgrade schema."""
28+
${downgrades if downgrades else "pass"}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""create tags and task_tags
2+
3+
Revision ID: 6392a705d4e1
4+
Revises: d3360cd6d7ff
5+
Create Date: 2026-03-08 18:15:33.531165
6+
7+
"""
8+
9+
from typing import Sequence, Union
10+
11+
from alembic import op
12+
import sqlalchemy as sa
13+
14+
15+
# revision identifiers, used by Alembic.
16+
revision: str = "6392a705d4e1"
17+
down_revision: Union[str, Sequence[str], None] = "d3360cd6d7ff"
18+
branch_labels: Union[str, Sequence[str], None] = None
19+
depends_on: Union[str, Sequence[str], None] = None
20+
21+
22+
def upgrade() -> None:
23+
"""Upgrade schema."""
24+
# ### commands auto generated by Alembic - please adjust! ###
25+
op.create_table(
26+
"tags",
27+
sa.Column("id", sa.UUID(), nullable=False),
28+
sa.Column("name", sa.String(length=50), nullable=False),
29+
sa.Column("color", sa.String(length=7), nullable=False),
30+
sa.Column(
31+
"created_at",
32+
sa.DateTime(timezone=True),
33+
server_default=sa.text("timezone('utc', now())"),
34+
nullable=False,
35+
),
36+
sa.PrimaryKeyConstraint("id"),
37+
sa.UniqueConstraint("name"),
38+
)
39+
op.create_table(
40+
"task_tags",
41+
sa.Column("task_id", sa.UUID(), nullable=False),
42+
sa.Column("tag_id", sa.UUID(), nullable=False),
43+
sa.ForeignKeyConstraint(["tag_id"], ["tags.id"], ondelete="CASCADE"),
44+
sa.ForeignKeyConstraint(["task_id"], ["tasks.id"], ondelete="CASCADE"),
45+
sa.PrimaryKeyConstraint("task_id", "tag_id"),
46+
)
47+
# ### end Alembic commands ###
48+
49+
50+
def downgrade() -> None:
51+
"""Downgrade schema."""
52+
# ### commands auto generated by Alembic - please adjust! ###
53+
op.drop_table("task_tags")
54+
op.drop_table("tags")
55+
# ### end Alembic commands ###
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
"""create users and tasks
2+
3+
Revision ID: d3360cd6d7ff
4+
Revises:
5+
Create Date: 2026-03-08 16:13:37.899287
6+
7+
"""
8+
9+
from typing import Sequence, Union
10+
11+
from alembic import op
12+
import sqlalchemy as sa
13+
14+
15+
# revision identifiers, used by Alembic.
16+
revision: str = "d3360cd6d7ff"
17+
down_revision: Union[str, Sequence[str], None] = None
18+
branch_labels: Union[str, Sequence[str], None] = None
19+
depends_on: Union[str, Sequence[str], None] = None
20+
21+
22+
def upgrade() -> None:
23+
"""Upgrade schema."""
24+
# ### commands auto generated by Alembic - please adjust! ###
25+
op.create_table(
26+
"users",
27+
sa.Column("id", sa.UUID(), nullable=False),
28+
sa.Column("email", sa.String(length=254), nullable=False),
29+
sa.Column("hashed_password", sa.String(length=255), nullable=False),
30+
sa.Column(
31+
"is_active", sa.Boolean(), server_default=sa.text("true"), nullable=False
32+
),
33+
sa.Column(
34+
"updated_at",
35+
sa.DateTime(timezone=True),
36+
server_default=sa.text("timezone('utc', now())"),
37+
nullable=False,
38+
),
39+
sa.Column(
40+
"created_at",
41+
sa.DateTime(timezone=True),
42+
server_default=sa.text("timezone('utc', now())"),
43+
nullable=False,
44+
),
45+
sa.PrimaryKeyConstraint("id"),
46+
)
47+
op.create_index(op.f("ix_users_email"), "users", ["email"], unique=True)
48+
op.create_table(
49+
"tasks",
50+
sa.Column("id", sa.UUID(), nullable=False),
51+
sa.Column("title", sa.String(length=255), nullable=False),
52+
sa.Column("description", sa.Text(), nullable=True),
53+
sa.Column("status", sa.String(length=20), nullable=False),
54+
sa.Column("priority", sa.String(length=10), nullable=False),
55+
sa.Column("due_date", sa.Date(), nullable=True),
56+
sa.Column("user_id", sa.UUID(), nullable=False),
57+
sa.Column(
58+
"created_at",
59+
sa.DateTime(timezone=True),
60+
server_default=sa.text("timezone('utc', now())"),
61+
nullable=False,
62+
),
63+
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
64+
sa.PrimaryKeyConstraint("id"),
65+
)
66+
# ### end Alembic commands ###
67+
68+
69+
def downgrade() -> None:
70+
"""Downgrade schema."""
71+
# ### commands auto generated by Alembic - please adjust! ###
72+
op.drop_table("tasks")
73+
op.drop_index(op.f("ix_users_email"), table_name="users")
74+
op.drop_table("users")
75+
# ### end Alembic commands ###

0 commit comments

Comments
 (0)