Skip to content

Commit

Permalink
Change online cog to use upserts set to ignore conflicts.
Browse files Browse the repository at this point in the history
  • Loading branch information
Cobular committed May 14, 2020
1 parent 6b3e62e commit a1a785c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
21 changes: 11 additions & 10 deletions bot/cogs/online.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,18 @@ async def on_member_update(self, before, after):

# Try to insert the fact that the user is online. Date is autogenerated when this is run,
# so is the primary key. There is a unique constraint on userid + date, so it won't let
# this happen twice. Doesn't matter though, so we just let the error happen.
session = (
session_creator()
# this happen twice.
session = session_creator()
# Might need to optimize sessions more later, this isn't that efficient
# Looks like I needed to after all, sessions were not being closed when the add errored out.
insert_stmt = insert(Online_Table).values(
discord_user_id=after.id,
online=True
).on_conflict_do_nothing(
constraint="unique_user_per_day_constraint"
)
try:
# Might need to optimize sessions more later, this isn't that efficient
# Looks like I needed to after all, sessions were not being closed when the add errored out.
session.add(Online_Table(discord_user_id=after.id, online=True))
session.commit()
except IntegrityError:
logging.info(f"{after.name} changed state but was already logged, skipping.")
session.execute(insert_stmt)
session.commit()
session.close()


Expand Down
3 changes: 3 additions & 0 deletions database/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,6 @@ def as_dict(self):
def session_creator() -> Session:
session = sessionmaker(bind=engine)
return session()


global_session: Session = session_creator()

0 comments on commit a1a785c

Please sign in to comment.