new columns booked_by and booked_counter added, deleted unused migrations

This commit is contained in:
Dmitry 2024-08-09 15:32:32 +03:00
parent 56b72c8a62
commit c0229d6727
7 changed files with 76 additions and 66 deletions

View File

@ -139,11 +139,15 @@ async def change_book_status(data: pydantic_schemas.Book, current_user: Annotate
if not announcement_to_change: if not announcement_to_change:
raise HTTPException(status_code=404, detail="Item not found") raise HTTPException(status_code=404, detail="Item not found")
# Проверяем, что объявление бронирует не владелец # Проверяем, что объявление бронирует не владелец
if current_user.id == announcement_to_change.user_id: if announcement_to_change.booked_by.Comparator.contains(current_user.id):
raise HTTPException(status_code=403, detail="A user can't book his announcement") raise HTTPException(status_code=403, detail="A user can't book his announcement")
else: else:
# Инкрементируем поле booked_by на 1 # Инкрементируем поле booked_counter на 1
announcement_to_change.booked_by += 1 announcement_to_change.booked_counter += 1
# вставляем индекс забронировавшего пользователя в поле booked_by
await db.execute(mytable.insert(), data=[1,2,3])
announcement_to_change.booked_by
# фиксируем изменения в бд # фиксируем изменения в бд
await db.commit() await db.commit()
await db.refresh(announcement_to_change) await db.refresh(announcement_to_change)

View File

@ -1,9 +1,9 @@
from sqlalchemy import Column, Integer, String, Boolean, Float, Date, ForeignKey from sqlalchemy import Column, Integer, String, Boolean, Float, Date, ForeignKey
from sqlalchemy.orm import relationship from sqlalchemy.orm import relationship
from sqlalchemy.dialects import postgresql
from .db import Base, engine from .db import Base, engine
class User(Base):#класс пользователя class User(Base):#класс пользователя
__tablename__ = "users" __tablename__ = "users"
@ -36,8 +36,8 @@ class Announcement(Base): #класс объявления
src = Column(String, nullable=True) #изображение продукта в объявлении src = Column(String, nullable=True) #изображение продукта в объявлении
metro = Column(String) #ближайщее метро от адреса нахождения продукта metro = Column(String) #ближайщее метро от адреса нахождения продукта
trashId = Column(Integer, nullable=True) trashId = Column(Integer, nullable=True)
booked_by = Column(Integer) #количество забронировавших (0 - никто не забронировал) booked_by = postgresql.ARRAY(Integer, dimensions=2) #массив с id пользователей, забронировавших объявление
# state = Column(Enum(State), default=State.published) # состояние объявления (опубликовано, забронировано, устарело) booked_counter = Column(Integer) #количество забронировавших (0 - никто не забронировал)
obsolete = Column(Boolean, default=False) # состояние объявления (по-умолчанию считаем его актуальным) obsolete = Column(Boolean, default=False) # состояние объявления (по-умолчанию считаем его актуальным)
user = relationship("User", back_populates="announcements") user = relationship("User", back_populates="announcements")

View File

@ -20,7 +20,6 @@ def upgrade():
# ### commands auto generated by Alembic - please adjust! ### # ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('announcements', schema=None) as batch_op: with op.batch_alter_table('announcements', schema=None) as batch_op:
batch_op.add_column(sa.Column('user_id', sa.Integer(), nullable=True)) batch_op.add_column(sa.Column('user_id', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('state', sa.Enum('published', 'taken', 'obsolete', name='state'), nullable=True))
# batch_op.drop_constraint(None, type_='foreignkey') # batch_op.drop_constraint(None, type_='foreignkey')
batch_op.create_foreign_key('fk_users_id', 'users', ['user_id'], ['id']) batch_op.create_foreign_key('fk_users_id', 'users', ['user_id'], ['id'])
batch_op.drop_column('owner_id') batch_op.drop_column('owner_id')
@ -42,7 +41,6 @@ def downgrade():
batch_op.add_column(sa.Column('owner_id', sa.INTEGER(), nullable=True)) batch_op.add_column(sa.Column('owner_id', sa.INTEGER(), nullable=True))
# batch_op.drop_constraint('fk_users_id', type_='foreignkey') # batch_op.drop_constraint('fk_users_id', type_='foreignkey')
batch_op.create_foreign_key(None, 'users', ['owner_id'], ['id']) batch_op.create_foreign_key(None, 'users', ['owner_id'], ['id'])
batch_op.drop_column('state')
batch_op.drop_column('user_id') batch_op.drop_column('user_id')
# ### end Alembic commands ### # ### end Alembic commands ###

View File

@ -18,13 +18,6 @@ depends_on = None
def upgrade(): def upgrade():
# ### commands auto generated by Alembic - please adjust! ### # ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('poems', schema=None) as batch_op:
batch_op.add_column(sa.Column('title', sa.String(), nullable=True))
batch_op.add_column(sa.Column('text', sa.String(), nullable=True))
batch_op.add_column(sa.Column('author', sa.String(), nullable=True))
batch_op.drop_column('poem_name')
batch_op.drop_column('poem_text')
with op.batch_alter_table('trashboxes', schema=None) as batch_op: with op.batch_alter_table('trashboxes', schema=None) as batch_op:
batch_op.add_column(sa.Column('category', sa.String(), nullable=True)) batch_op.add_column(sa.Column('category', sa.String(), nullable=True))
batch_op.drop_column('categories') batch_op.drop_column('categories')
@ -37,12 +30,4 @@ def downgrade():
with op.batch_alter_table('trashboxes', schema=None) as batch_op: with op.batch_alter_table('trashboxes', schema=None) as batch_op:
batch_op.add_column(sa.Column('categories', sa.VARCHAR(), nullable=True)) batch_op.add_column(sa.Column('categories', sa.VARCHAR(), nullable=True))
batch_op.drop_column('category') batch_op.drop_column('category')
with op.batch_alter_table('poems', schema=None) as batch_op:
batch_op.add_column(sa.Column('poem_text', sa.VARCHAR(), nullable=True))
batch_op.add_column(sa.Column('poem_name', sa.VARCHAR(), nullable=True))
batch_op.drop_column('author')
batch_op.drop_column('text')
batch_op.drop_column('title')
# ### end Alembic commands ### # ### end Alembic commands ###

View File

@ -0,0 +1,66 @@
"""Added booked_by column which contains id of users who booked the announcement old booked_by renamed to booked_counter
Revision ID: 5a8105ac1a4f
Revises: 547f860f21a7
Create Date: 2024-08-09 15:07:51.386406
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '5a8105ac1a4f'
down_revision: Union[str, None] = '547f860f21a7'
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.add_column('announcements', sa.Column('booked_counter', sa.Integer(), nullable=True))
op.alter_column('announcements', 'longtitude',
existing_type=sa.INTEGER(),
type_=sa.Float(),
existing_nullable=True)
op.alter_column('announcements', 'latitude',
existing_type=sa.INTEGER(),
type_=sa.Float(),
existing_nullable=True)
op.drop_column('announcements', 'booked_by')
op.alter_column('trashboxes', 'latitude',
existing_type=sa.INTEGER(),
type_=sa.Float(),
existing_nullable=True)
op.alter_column('trashboxes', 'longtitude',
existing_type=sa.INTEGER(),
type_=sa.Float(),
existing_nullable=True)
op.create_foreign_key(None, 'trashboxes', 'users', ['user_id'], ['id'])
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'trashboxes', type_='foreignkey')
op.alter_column('trashboxes', 'longtitude',
existing_type=sa.Float(),
type_=sa.INTEGER(),
existing_nullable=True)
op.alter_column('trashboxes', 'latitude',
existing_type=sa.Float(),
type_=sa.INTEGER(),
existing_nullable=True)
op.add_column('announcements', sa.Column('booked_by', sa.INTEGER(), autoincrement=False, nullable=True))
op.alter_column('announcements', 'latitude',
existing_type=sa.Float(),
type_=sa.INTEGER(),
existing_nullable=True)
op.alter_column('announcements', 'longtitude',
existing_type=sa.Float(),
type_=sa.INTEGER(),
existing_nullable=True)
op.drop_column('announcements', 'booked_counter')
# ### end Alembic commands ###

View File

@ -1,30 +0,0 @@
"""lazy=selectin added to user table relationships
Revision ID: 8e631a2fe6b8
Revises:
Create Date: 2023-09-02 23:45:08.799366
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = '8e631a2fe6b8'
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! ###
pass
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###

View File

@ -18,10 +18,8 @@ depends_on = None
def upgrade(): def upgrade():
# ### commands auto generated by Alembic - please adjust! ### # ### commands auto generated by Alembic - please adjust! ###
op.drop_table('_alembic_tmp_users')
with op.batch_alter_table('announcements', schema=None) as batch_op: with op.batch_alter_table('announcements', schema=None) as batch_op:
batch_op.add_column(sa.Column('obsolete', sa.Boolean(), nullable=True)) batch_op.add_column(sa.Column('obsolete', sa.Boolean(), nullable=True))
batch_op.drop_column('state')
with op.batch_alter_table('poems', schema=None) as batch_op: with op.batch_alter_table('poems', schema=None) as batch_op:
batch_op.add_column(sa.Column('title', sa.String(), nullable=True)) batch_op.add_column(sa.Column('title', sa.String(), nullable=True))
@ -49,16 +47,5 @@ def downgrade():
batch_op.drop_column('title') batch_op.drop_column('title')
with op.batch_alter_table('announcements', schema=None) as batch_op: with op.batch_alter_table('announcements', schema=None) as batch_op:
batch_op.add_column(sa.Column('state', sa.VARCHAR(length=9), nullable=True))
batch_op.drop_column('obsolete') batch_op.drop_column('obsolete')
op.create_table('_alembic_tmp_users',
sa.Column('id', sa.INTEGER(), nullable=False),
sa.Column('email', sa.VARCHAR(), nullable=True),
sa.Column('hashed_password', sa.VARCHAR(), nullable=True),
sa.Column('name', sa.VARCHAR(), nullable=True),
sa.Column('surname', sa.VARCHAR(), nullable=True),
sa.Column('disabled', sa.BOOLEAN(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ### # ### end Alembic commands ###