2023-09-21

SQLAlchemy throws no exceptions

I am trying to append a child class to a parent class. The problem is even when I make mistakes on purpose, the code throws no exceptions but doesn't work. I have found no errors in IDE as I've tried multiple IDEs (Spyder, PyCharm, VSC) and none of them show exceptions. I've also tried to print the exceptions explicitly, and this doesn't work either (though it did work in some cases, which completely blows my mind). Moreover, the code doesn't even reach the print command I've set there. Here is what I have:

database_append_card.py:

async def append_all(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        new_card = CardBase(
            name=data['card_name'],
            front=data['front'],
            back=data['back'],
            )
    await add_child_to_db(
        child=new_card,
        column=str(message.from_user.id),
        parent_class=UserBase,
        my_async_session=async_session_maker)
    await bot.send_message(message.from_id, 'The card has been appended! ✅')

database_commands.py:

async def add_child_to_db(
    child,
    column,
    parent_class,
    my_async_session: AsyncSession):

    """ Adds a child class to parent class """

    async with my_async_session.begin() as session:
        try:
            parent = await session.execute(select(parent_class).where(parent_class.column==column))
            print(f'\n\n\n\n{parent}\n\n\n\n')
            parent.children.append(child)
        except SQLAlchemyError as exc:
            print(exc)
            raise
        finally:
            await session.close()

database_models.py:

class UserBase(Base):

    """ An account for storing and accessing multiple learning cards """

    __tablename__ = 'users'

    id = Column(Integer, primary_key=True, autoincrement=True)
    telegram_id = Column(String, unique=True)
    username = Column(String(100), unique=True)
    name = Column(String(200))
    surname = Column(String(200))
    my_cards: Mapped[list['CardBase']] = relationship()


class CardBase(Base):

    """ A learning card with front and back text bound to a specific user """

    __tablename__ = 'cards'

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    user_id: Mapped[int] = mapped_column(ForeignKey('users.id', ondelete='CASCADE'),
                             nullable=False)
    name = mapped_column(Text)
    front = mapped_column(Text)
    back = mapped_column(Text)

asyncpg==0.28.0
SQLAlchemy==2.0.19
Python 3.10.12


No comments:

Post a Comment