-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add alembic + first test migrations #1
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
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| [alembic] | ||
| script_location = .\app\core\database\migrations | ||
| file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s | ||
|
|
||
| prepend_sys_path = . | ||
| version_path_separator = os | ||
|
|
||
| [post_write_hooks] | ||
| hooks = ruff_format, ruff_fix | ||
|
|
||
| ruff_format.type = exec | ||
| ruff_format.executable = ruff | ||
| ruff_format.options = format REVISION_SCRIPT_FILENAME | ||
|
|
||
| ruff_fix.type = exec | ||
| ruff_fix.executable = ruff | ||
| ruff_fix.options = check --fix REVISION_SCRIPT_FILENAME | ||
|
|
||
| [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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,30 +1,46 @@ | ||
| import typing | ||
| from pathlib import Path | ||
| from functools import cached_property | ||
|
|
||
| from pydantic import BaseModel, Field | ||
| from pydantic import BaseModel | ||
| from pydantic_settings import BaseSettings, SettingsConfigDict | ||
| from sqlalchemy.engine.url import URL | ||
|
|
||
| if typing.TYPE_CHECKING: | ||
| from app.app.app import Application | ||
|
|
||
|
|
||
| class BotConfig(BaseModel): | ||
| token: str = Field("...", validation_alias="BOT__TOKEN") | ||
| token: str = "..." | ||
|
|
||
|
|
||
| class DatabaseConfig(BaseModel): | ||
| host: str = Field("localhost", validation_alias="DATABASE__HOST") | ||
| port: int = Field(5432, validation_alias="DATABASE__PORT") | ||
| user: str = Field("postgres", validation_alias="DATABASE__USER") | ||
| password: str = Field("postgres", validation_alias="DATABASE__PASSWORD") | ||
| database: str = Field("project", validation_alias="DATABASE__DATABASE") | ||
| host: str = "localhost" | ||
| port: int = 5432 | ||
| user: str = "postgres" | ||
| password: str = "postgres" | ||
| database: str = "project" | ||
|
|
||
| @cached_property | ||
| def url(self) -> URL: | ||
| return URL.create( | ||
| drivername="postgresql+asyncpg", | ||
| username=self.user, | ||
| password=self.password, | ||
| host=self.host, | ||
| port=self.port, | ||
| database=self.database, | ||
| ) | ||
|
|
||
|
|
||
| class Config(BaseSettings): | ||
| bot: BotConfig | None = None | ||
| database: DatabaseConfig | None = None | ||
| model_config = SettingsConfigDict(env_file=".env", env_nested_delimiter='__') | ||
|
|
||
| model_config = SettingsConfigDict( | ||
| env_file=(".env", "../../../../.env"), # Если main / если миграции | ||
| env_nested_delimiter="__", | ||
| ) | ||
|
|
||
| def setup_config(app: "Application", config_path: Path) -> None: | ||
| app.config = Config(_env_file=config_path) | ||
|
|
||
| def setup_config(app: "Application") -> None: | ||
| app.config = Config() |
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| import asyncio | ||
| import importlib | ||
| import pkgutil | ||
| from logging.config import fileConfig | ||
|
|
||
| from alembic import context | ||
| from sqlalchemy import pool | ||
| from sqlalchemy.engine import Connection | ||
| from sqlalchemy.ext.asyncio import async_engine_from_config | ||
|
|
||
| import app | ||
| from app.app.app import app as application, setup_app | ||
| from app.core.database.sqlalchemy_base import BaseModel | ||
|
|
||
| setup_app() | ||
| config = context.config | ||
|
|
||
| for module_info in pkgutil.walk_packages(app.__path__, prefix=app.__name__ + "."): | ||
| importlib.import_module(module_info.name) | ||
|
|
||
| if config.config_file_name is not None: | ||
| fileConfig(config.config_file_name) | ||
|
|
||
| if application.config is None or application.config.database is None: | ||
| raise ValueError("No configuration file provided") | ||
|
|
||
| config.set_main_option( | ||
| "sqlalchemy.url", | ||
| application.config.database.url.render_as_string(hide_password=False), | ||
| ) | ||
|
|
||
| target_metadata = BaseModel.metadata | ||
|
|
||
|
|
||
| def run_migrations_offline() -> None: | ||
| 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 do_run_migrations(connection: Connection) -> None: | ||
| context.configure(connection=connection, target_metadata=target_metadata) | ||
|
|
||
| with context.begin_transaction(): | ||
| context.run_migrations() | ||
|
|
||
|
|
||
| async def run_async_migrations() -> None: | ||
| connectable = async_engine_from_config( | ||
| config.get_section(config.config_ini_section, {}), | ||
| prefix="sqlalchemy.", | ||
| poolclass=pool.NullPool, | ||
| ) | ||
|
|
||
| async with connectable.connect() as connection: | ||
| await connection.run_sync(do_run_migrations) | ||
|
|
||
| await connectable.dispose() | ||
|
|
||
|
|
||
| def run_migrations_online() -> None: | ||
| asyncio.run(run_async_migrations()) | ||
|
|
||
|
|
||
| if context.is_offline_mode(): | ||
| run_migrations_offline() | ||
| else: | ||
| run_migrations_online() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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"} |
42 changes: 42 additions & 0 deletions
42
app/core/database/migrations/versions/2025_04_14_1524-32d5607c5cc0_.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| """empty message | ||
|
|
||
| Revision ID: 32d5607c5cc0 | ||
| Revises: | ||
| Create Date: 2025-04-14 15:24:41.833280 | ||
|
|
||
| """ | ||
|
|
||
| from collections.abc import Sequence | ||
|
|
||
| import sqlalchemy as sa | ||
| from alembic import op | ||
|
|
||
| # revision identifiers, used by Alembic. | ||
| revision: str = "32d5607c5cc0" | ||
| down_revision: str | None = None | ||
| branch_labels: str | Sequence[str] | None = None | ||
| depends_on: str | Sequence[str] | None = None | ||
|
|
||
|
|
||
| def upgrade() -> None: | ||
| """Upgrade schema.""" | ||
| # ### commands auto generated by Alembic - please adjust! ### | ||
| op.create_table( | ||
| "telegram_user", | ||
| sa.Column("username", sa.String(length=64), nullable=False), | ||
| sa.Column("score", sa.Integer(), nullable=False), | ||
| sa.Column("win_count", sa.Integer(), nullable=False), | ||
| sa.Column("loss_count", sa.Integer(), nullable=False), | ||
| sa.Column("id", sa.BigInteger(), nullable=False), | ||
| sa.CheckConstraint("loss_count >= 0", name="loss_count_non_negative"), | ||
| sa.CheckConstraint("win_count >= 0", name="win_count_non_negative"), | ||
| sa.PrimaryKeyConstraint("id"), | ||
| ) | ||
| # ### end Alembic commands ### | ||
|
|
||
|
|
||
| def downgrade() -> None: | ||
| """Downgrade schema.""" | ||
| # ### commands auto generated by Alembic - please adjust! ### | ||
| op.drop_table("telegram_user") | ||
| # ### end Alembic commands ### |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| from sqlalchemy import BigInteger | ||
| from sqlalchemy.orm import Mapped, mapped_column | ||
|
|
||
|
|
||
| class IDMixin: | ||
| id: Mapped[int] = mapped_column(BigInteger, primary_key=True) | ||
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| from sqlalchemy import CheckConstraint, String | ||
| from sqlalchemy.orm import Mapped, mapped_column | ||
|
|
||
| from app.core.database.mixins import IDMixin | ||
| from app.core.database.sqlalchemy_base import BaseModel | ||
|
|
||
|
|
||
| class TelegramUserModel(IDMixin, BaseModel): | ||
|
Gray-Advantage marked this conversation as resolved.
|
||
| __tablename__ = "telegram_user" | ||
|
|
||
| __table_args__ = ( | ||
| CheckConstraint("win_count >= 0", name="win_count_non_negative"), | ||
| CheckConstraint("loss_count >= 0", name="loss_count_non_negative"), | ||
| ) | ||
|
|
||
| username: Mapped[str] = mapped_column(String(64)) | ||
| score: Mapped[int] = mapped_column(default=0) | ||
| win_count: Mapped[int] = mapped_column(default=0) | ||
| loss_count: Mapped[int] = mapped_column(default=0) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| services: | ||
| postgres: | ||
| image: postgres:17.4-alpine | ||
| ports: | ||
| - ${DATABASE__PORT}:${DATABASE__PORT} | ||
|
Gray-Advantage marked this conversation as resolved.
|
||
| env_file: | ||
| - .env | ||
| environment: | ||
| - POSTGRES_USER=${DATABASE__USER} | ||
| - POSTGRES_PASSWORD=${DATABASE__PASSWORD} | ||
| - POSTGRES_DB=${DATABASE__DATABASE} | ||
| healthcheck: | ||
| test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"] | ||
| interval: 2s | ||
| timeout: 5s | ||
| retries: 10 | ||
| command: -p ${DATABASE__PORT} | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,8 +1,6 @@ | ||
| from pathlib import Path | ||
|
|
||
| from aiohttp.web import run_app | ||
|
|
||
| from app.app.app import setup_app | ||
|
|
||
| if __name__ == "__main__": | ||
| run_app(setup_app(Path(__file__).resolve().parent / ".env")) | ||
| run_app(setup_app()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.