2017-06-30 11:25:56 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
import os
|
2020-03-16 21:51:32 +00:00
|
|
|
import contextlib
|
2017-06-30 11:25:56 +00:00
|
|
|
|
|
|
|
import psycopg2
|
|
|
|
from psycopg2.extras import DictCursor
|
|
|
|
|
2017-08-22 15:43:48 +00:00
|
|
|
from . import Plugin, Bot
|
2017-06-30 11:25:56 +00:00
|
|
|
|
2020-03-16 21:51:32 +00:00
|
|
|
class DBConn:
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self.args = args
|
|
|
|
self.kwargs = kwargs
|
|
|
|
self._reconnect()
|
|
|
|
|
|
|
|
def _reconnect(self):
|
|
|
|
self._con = psycopg2.connect(*self.args, **self.kwargs)
|
2020-03-16 22:04:29 +00:00
|
|
|
return self._con
|
2020-03-16 21:51:32 +00:00
|
|
|
|
|
|
|
def commit(self, *args, **kwargs):
|
|
|
|
try:
|
|
|
|
return self._con.commit(*args, **kwargs)
|
|
|
|
except psycopg2.InterfaceError:
|
2020-03-16 22:04:29 +00:00
|
|
|
return self._reconnect().commit(*args, **kwargs)
|
2020-03-16 21:51:32 +00:00
|
|
|
|
|
|
|
def rollback(self, *args, **kwargs):
|
|
|
|
try:
|
|
|
|
return self._con.rollback(*args, **kwargs)
|
|
|
|
except psycopg2.InterfaceError:
|
2020-03-16 22:04:29 +00:00
|
|
|
return self._reconnect().rollback(*args, **kwargs)
|
2020-03-16 21:51:32 +00:00
|
|
|
|
|
|
|
@contextlib.contextmanager
|
|
|
|
def cursor(self, *args, **kwargs):
|
|
|
|
try:
|
|
|
|
yield self._con.cursor(cursor_factory=DictCursor, *args, **kwargs)
|
|
|
|
except psycopg2.InterfaceError:
|
2020-03-16 22:04:29 +00:00
|
|
|
yield self._reconnect().cursor(cursor_factory=DictCursor, *args, **kwargs)
|
2020-03-16 21:51:32 +00:00
|
|
|
|
2017-06-30 11:25:56 +00:00
|
|
|
|
|
|
|
class Storage(Plugin):
|
2017-08-22 15:43:48 +00:00
|
|
|
def __init__(self, bot: Bot):
|
2017-06-30 11:25:56 +00:00
|
|
|
super().__init__(bot)
|
2017-08-22 15:43:48 +00:00
|
|
|
self.bot.sql = self
|
2020-03-16 21:51:32 +00:00
|
|
|
self.con = DBConn(os.environ['DATABASE_URI'])
|