nxy/bot/seen.py
jkhsjdhjs e03f5d0a43 add auto reconnect for postgres
This only works on the second database interaction, since psycopg2 only notices that
the connection is gone, when a query is executed.

So in the common case reconnect works as follows:
- some bot method calls a cursor function like .execute(), .fetchone(), etc.
  - this raises an error if the connection is broken
  - if following code then requests a new cursor, this will also fail since psycopg2
    now knows that the connection is gone
  - the error is caught in storage.DBConn.cursor(), a new connection will be set up
    of which a new cursor is yielded
If the error happens in connection.commit() or .rollback() instead we can instantly
reconnect since these methods are wrapped.

So why not wrap the cursor methods as well?
Consider the following example:
A query is the last thing that was executed on a cursor.
The database connection is lost.
Now .fetchone() is called on the cursor.
We could wrap .fetchone() and reconnect, but we'd have to use a new cursor since
cursors are linked to connections. And on this new cursor .fetchone() wouldn't
make any sense, since we haven't executed a query on this cursor.
2020-03-16 21:51:32 +00:00

67 lines
1.9 KiB
Python

# -*- coding: utf-8 -*-
import re
import irc3
from docopt import Dict
from irc3.plugins.command import command
from irc3.utils import IrcString
from . import DatabasePlugin
class Seen(DatabasePlugin):
@command
def seen(self, mask: IrcString, target: IrcString, args: Dict):
"""Get last seen date and message for a nick
%%seen [<nick>]
"""
nick = args.get('<nick>', mask.nick)
# Don't be stupid
if nick == mask.nick:
return '{}, look in the mirror faggot!'.format(nick)
# Fetch seen from database
with self.con.cursor() as cur:
cur.execute('''
SELECT
seen_at, message, channel
FROM
seens
WHERE
nick = lower(%s)
''', [nick])
seen = cur.fetchone()
# No result
if not seen:
return 'I\'ve never seen {}'.format(nick)
# Return result
return '{nick} was last seen {delta} in {channel} saying: {message}'.format(
nick=nick,
# TODO: relative string delta?
delta=seen['seen_at'],
channel=seen['channel'],
message=re.sub(r'\x01ACTION (.*)\x01', r'/me \1', seen['message']),
)
@irc3.event(r'(?i)^:(?P<mask>\S+) PRIVMSG (?P<target>\S+) :(?P<msg>.*)')
def save(self, mask: str, target: str, msg: str):
mask = IrcString(mask)
with self.con.cursor() as cur:
cur.execute('''
INSERT INTO
seens (nick, host, channel, message)
VALUES
(lower(%s), %s, %s, %s)
ON CONFLICT (nick) DO UPDATE SET
host = excluded.host,
channel = excluded.channel,
seen_at = now(),
message = excluded.message
''', [mask.nick, mask.host, target, msg])
self.con.commit()