ЛР2: PostgreSQL, сессии (Basic + Bearer), Compose, миграции
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-10-16 11:11:00 +03:00
parent 65003b6119
commit 4937d6d4e8
56 changed files with 1969 additions and 26 deletions
+52
View File
@@ -0,0 +1,52 @@
from logging.config import fileConfig
from alembic import context
from sqlalchemy import create_engine, pool, text
from core.config import settings
from core.db import build_url
from models import Base
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
target_metadata = Base.metadata
# Ключ advisory lock: параллельные запуски миграций выполнятся по очереди.
MIGRATION_LOCK_KEY = 2_026_002
def run_migrations_offline() -> None:
context.configure(
url=build_url(),
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
engine = create_engine(
build_url(),
poolclass=pool.NullPool,
connect_args={"connect_timeout": settings.db.connect_timeout},
)
with engine.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
compare_server_default=True,
)
with context.begin_transaction():
connection.execute(text("SELECT pg_advisory_xact_lock(:key)"), {"key": MIGRATION_LOCK_KEY})
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+28
View 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, Sequence[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"}
@@ -0,0 +1,85 @@
"""initial schema
Revision ID: 0001
Revises:
Create Date: 2026-10-15 17:30:37.825446
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '0001'
down_revision: Union[str, Sequence[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! ###
op.create_table('chats',
sa.Column('id', sa.Uuid(), server_default=sa.text('gen_random_uuid()'), nullable=False),
sa.Column('title', sa.Text(), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('clock_timestamp()'), nullable=False),
sa.CheckConstraint('char_length(title) BETWEEN 1 AND 100', name=op.f('chats_title_len')),
sa.PrimaryKeyConstraint('id', name=op.f('chats_pkey'))
)
op.create_table('users',
sa.Column('id', sa.Uuid(), server_default=sa.text('gen_random_uuid()'), nullable=False),
sa.Column('username', sa.Text(), nullable=False),
sa.Column('display_name', sa.Text(), nullable=False),
sa.Column('password_hash', sa.Text(), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('clock_timestamp()'), nullable=False),
sa.CheckConstraint("username ~ '^[a-z0-9_]{3,32}$'", name=op.f('users_username_format')),
sa.CheckConstraint('char_length(display_name) BETWEEN 1 AND 100', name=op.f('users_display_name_len')),
sa.PrimaryKeyConstraint('id', name=op.f('users_pkey')),
sa.UniqueConstraint('username', name=op.f('users_username_key'))
)
op.create_table('chat_members',
sa.Column('chat_id', sa.Uuid(), nullable=False),
sa.Column('user_id', sa.Uuid(), nullable=False),
sa.ForeignKeyConstraint(['chat_id'], ['chats.id'], name=op.f('chat_members_chat_id_fkey')),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], name=op.f('chat_members_user_id_fkey')),
sa.PrimaryKeyConstraint('chat_id', 'user_id', name=op.f('chat_members_pkey'))
)
op.create_index(op.f('chat_members_user_id_chat_id_idx'), 'chat_members', ['user_id', 'chat_id'], unique=False)
op.create_table('sessions',
sa.Column('token_hash', sa.LargeBinary(), nullable=False),
sa.Column('user_id', sa.Uuid(), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('clock_timestamp()'), nullable=False),
sa.Column('expires_at', sa.DateTime(timezone=True), nullable=False),
sa.CheckConstraint('expires_at > created_at', name=op.f('sessions_expiry_after_creation')),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], name=op.f('sessions_user_id_fkey'), ondelete='CASCADE'),
sa.PrimaryKeyConstraint('token_hash', name=op.f('sessions_pkey'))
)
op.create_index(op.f('sessions_expires_at_idx'), 'sessions', ['expires_at'], unique=False)
op.create_table('messages',
sa.Column('id', sa.Uuid(), server_default=sa.text('gen_random_uuid()'), nullable=False),
sa.Column('chat_id', sa.Uuid(), nullable=False),
sa.Column('sender_id', sa.Uuid(), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('clock_timestamp()'), nullable=False),
sa.Column('text', sa.Text(), nullable=False),
sa.CheckConstraint('char_length(text) BETWEEN 1 AND 4000', name=op.f('messages_text_len')),
sa.ForeignKeyConstraint(['chat_id', 'sender_id'], ['chat_members.chat_id', 'chat_members.user_id'], name='messages_sender_is_member'),
sa.PrimaryKeyConstraint('id', name=op.f('messages_pkey'))
)
op.create_index('messages_chat_history_idx', 'messages', ['chat_id', 'created_at', 'id'], unique=False)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index('messages_chat_history_idx', table_name='messages')
op.drop_table('messages')
op.drop_index(op.f('sessions_expires_at_idx'), table_name='sessions')
op.drop_table('sessions')
op.drop_index(op.f('chat_members_user_id_chat_id_idx'), table_name='chat_members')
op.drop_table('chat_members')
op.drop_table('users')
op.drop_table('chats')
# ### end Alembic commands ###