When to use SQLAlchemy listen events

Loris Bennett loris.bennett at fu-berlin.de
Mon Feb 28 03:41:55 EST 2022


"Loris Bennett" <loris.bennett at fu-berlin.de> writes:

> Hi,
>
> I am wondering whether SQLAlchemy listen events are appropriate for the
> following situation:
>
> I have a table containing users and a table for events related to users
>
>   class User(Base):
>       __tablename__ = "users"
>
>       uid = Column('uid', String(64), primary_key=True)
>       gid = Column('gid', String(64), ForeignKey('groups.gid'), nullable=False)
>       lang = Column('lang', String(2))
>
>
>   class UserEvent(Base):
>       __tablename__ = "user_events"
>
>       id = Column('id', Integer, primary_key=True)
>       date = Column('date', Date, nullable=False)
>       uid = Column('gid', String(64), ForeignKey('users.uid'), nullable=False)
>       comment = Column('comment', String(256))
>
> (There are also analogous tables for groups and group events).
>
> The functions provided by the interface are things like the following
>
>   add_user(user, group, lang)
>   move_user(user, group)
>   delete_user(user)
>   warn_user(user, reason)
>
> Whereas 'add/move/delete_user' result in changes to the table 'users',
> 'warn_user' does not.  All should produce entries in the table
> 'user_events'. 
>
> There could be more functions similar to 'warn_user' that only create an
> entry in 'user_events'.  Potentially there could be a lot more of
> these than the 'user'-table-changing type.
>
> It seems like for the first three functions, capturing the resulting
> database changes in the table 'user_events' would be a standard use-case
> for listen event.  However, the 'warn_user' function is different.
>
> So can/should I shoehorn the 'warn_user' function to being like the
> others three and use listen events, or should I just come up with my own
> mechanism which will allow any function just to add an entry to the
> events table?

So I just ended up writing my own decorator.  That seems more
appropriate and flexible in this instance.

-- 
This signature is currently under construction.


More information about the Python-list mailing list