init commit

This commit is contained in:
2025-08-20 21:10:31 +09:00
parent 36a9382cb6
commit 745046c638
31 changed files with 1074 additions and 1 deletions

1
app/migrations/README Normal file
View File

@@ -0,0 +1 @@
Alembic migrations

72
app/migrations/env.py Normal file
View File

@@ -0,0 +1,72 @@
from __future__ import annotations
import os
import sys
from logging.config import fileConfig
from sqlalchemy import engine_from_config, pool
from alembic import context
# Сделаем проект импортируемым при запуске alembic из корня
sys.path.append(os.getcwd())
from app.db.base import Base # noqa
from app.db import models # noqa: F401 # важно импортировать, чтобы metadata увидела модели
# Alembic Config
config = context.config
# Логирование из alembic.ini
if config.config_file_name is not None:
fileConfig(config.config_file_name)
target_metadata = Base.metadata
def get_url() -> str:
"""Берём URL БД из env или собираем из DB_* переменных."""
url = os.getenv("DATABASE_URL", "").strip()
if url:
return url
host = os.getenv("DB_HOST", "db")
port = os.getenv("DB_PORT", "5432")
name = os.getenv("DB_NAME", "tg_poster")
user = os.getenv("DB_USER", "postgres")
pwd = os.getenv("DB_PASSWORD", "postgres")
return f"postgresql+psycopg://{user}:{pwd}@{host}:{port}/{name}"
def run_migrations_offline() -> None:
"""Запуск миграций в оффлайн-режиме (генерация SQL)."""
url = get_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:
"""Запуск миграций в онлайн-режиме с активным соединением."""
configuration = config.get_section(config.config_ini_section) or {}
# ВАЖНО: используем ключ sqlalchemy.url и prefix="sqlalchemy."
configuration["sqlalchemy.url"] = get_url()
connectable = engine_from_config(
configuration,
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()

View File

@@ -0,0 +1,20 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}

View File

@@ -0,0 +1,60 @@
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0001_init'
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table('users',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('tg_id', sa.BigInteger(), nullable=False, unique=True, index=True),
sa.Column('name', sa.String(length=255)),
sa.Column('created_at', sa.DateTime(), nullable=False),
)
op.create_table('chats',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('chat_id', sa.BigInteger(), nullable=False, unique=True, index=True),
sa.Column('type', sa.String(length=32)),
sa.Column('title', sa.String(length=255)),
sa.Column('owner_user_id', sa.Integer(), sa.ForeignKey('users.id'), index=True),
sa.Column('can_post', sa.Boolean(), nullable=False, server_default=sa.text('false')),
sa.Column('created_at', sa.DateTime(), nullable=False),
)
op.create_table('drafts',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('user_id', sa.Integer(), sa.ForeignKey('users.id'), index=True),
sa.Column('text', sa.Text()),
sa.Column('status', sa.String(length=16), index=True, server_default='editing'),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
)
op.create_table('draft_media',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('draft_id', sa.Integer(), sa.ForeignKey('drafts.id'), index=True),
sa.Column('kind', sa.String(length=16)),
sa.Column('file_id', sa.String(length=255)),
sa.Column('order', sa.Integer(), server_default='0'),
)
op.create_table('deliveries',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('draft_id', sa.Integer(), sa.ForeignKey('drafts.id'), index=True),
sa.Column('chat_id', sa.BigInteger(), index=True),
sa.Column('status', sa.String(length=16), index=True, server_default='new'),
sa.Column('error', sa.Text()),
sa.Column('message_ids', sa.Text()),
sa.Column('created_at', sa.DateTime(), nullable=False),
)
def downgrade() -> None:
op.drop_table('deliveries')
op.drop_table('draft_media')
op.drop_table('drafts')
op.drop_table('chats')
op.drop_table('users')