Completed
Push — master ( 257ced...98bfd2 )
by Matt
41s
created
1
from logger import Logger
2
try:
3
  import MySQLdb as mdb
4
except ImportError:
5
  import sys
6
  imported = False
7
  if "lite" not in sys.modules:
8
    print "Could not find MySQLdb and lite is not imported! Erroring out!"
9
    sys.exit(1)
10
11
from datetime import datetime,timedelta
12
13
class DB:
14
  """
15
  Handles connecting to the database and reading and writing data.
16
  Currently supports only MySQL/mariadb, and that probably needs to change.
17
  """
18
  age = datetime.now()
19
20
  def __init__(self, bot=None):
21
    self.bot = bot
22
    self.dry_run = False
23
    
24
  def _open(self):
25
    if self.bot is not None:
26
      dbusername = self.bot.conf.getDBUsername(self.bot.network)
27
      password = self.bot.conf.getDBPass(self.bot.network)
28
      dbname = self.bot.conf.getDBName(self.bot.network)
29
    else:
30
      dbusername = "pybot"
31
      password = "1q2w3e4r"
32
      dbname = "pybot"
33
34
    try:
35
      self.con = mdb.connect("localhost",dbusername,password,dbname)
36
    except mdb.OperationalError as e:
37
      self.dry_run = True
38
      self.bot.logger(Logger.WARNING, e)
39
      print e
40
      return
41
42
    self.cur = self.con.cursor()
43
  
44
  def _close(self):
45
    self.con = None
46
    if not self.dry_run:
47
      self.cur.close()
48
49
  # should prevent mysql has gone away errors.. ideally
50
  def _handle(self):
51
    global cur
52
    global age
53
    now = datetime.now()
54
    if now - self.age > timedelta(minutes=5):
55
      self.cur.close()
56
      self.con = mdb.connect("localhost","pybot","1q2w3e4r","pybot")
57
      self.cur = self.con.cursor()
58
59
  def select(self, where, what):
60
    try:
61
      self._open()
62
      self.cur.execute("""SELECT %s FROM %s""")
63
      data = self.cur.fetchall()
64
      self._close()
65
    except:
66
      self._close()
67
      return None
68
69
    return data
70
71
  def replace(self, where, which, what):
72
    try:
73
      self._open()
74
      self.cur.execute("""REPLACE INTO %s (%s) VALUES (%s)""",(where, which, what)) 
75
      self._close()
76
    except:
77
      self._close()
78
      return None
79 View Code Duplication
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
80
  def e(self, sql):
81
    try:
82
      self._open()
83
      self.cur.execute(sql) 
84
      if "INSERT" in sql or "REPLACE" in sql:
85
        self.con.commit()
86
        self._close()
87
      elif "SELECT" in sql:
88
        e = self.cur.fetchall()
89
        self._close()
90
        return e
91
    except Exception, e:
92
      print e
93
      self.con.rollback()
94
      self._close()
95
      return None
96
97
  def insert(self, where, which, what):
98
    try:
99
      self._open()
100
      self.cur.execute("""INSERT INTO %s (%s) VALUES (%s)""",(where, which, what)) 
101
      self._close()
102
    except:
103
      self._close()
104
      return None
105
106
  def updateSeen(self,who,statement,event):
107
    self._open()
108
    #print "executing REPLACE INTO seen (user_name, statement, event) VALUES ( " + str(who) + " " + str(statement) + " " + str(event) + ")"
109
    self.cur.execute("REPLACE INTO seen (user_name, statement, event) VALUES (%s, %s, %s)", (who, statement, event))
110
    self._close()
111
112
  def getSeen(self, who):
113
    self._open()
114
    if who != "":
115
      self.cur.execute("SELECT user_name, date, statement, event FROM seen WHERE user_name = %s", who)
116
      data = self.cur.fetchone()
117
      return data;
118
      self._close()
119
    else:
120
      self._close()
121
      return None 
122
123
  def insertImg(self, user, url, channel):
124
    self._open()
125
    if user == "" or user == None:
126
      user = "nobody"
127
    try:
128
      self.cur.execute("""INSERT INTO img (user, url, channel) VALUES (%s, %s, %s)""", (user, url, channel))
129
      if not self.dry_run:
130
        self.con.commit()
131
    except:
132
      self.bot.logger(Logger.WARNING, 'failed to insert ' + url)
133
      print "failure"
134
      print "Unexpected error:", sys.exc_info()[0]
135
      if not self.dry_run:
136
        self.con.rollback()
137
138
    self._close()
139
140
  def getImgs(self):
141
    self._open()
142
    try:
143
      self.cur.execute("""SELECT * FROM img ORDER BY time DESC""")
144
      data = self.cur.fetchall()
145
      self._close()
146
    except:
147
      self._close()
148
      return None
149
150
    return data
151
152
  def isAdmin(self, username):
153
    self._open()
154
    try:
155
      self.cur.execute("""SELECT * FROM admins WHERE username = %s""",[username])
156
      data = self.cur.fetchall()
157
      self._close()
158
    except Exception, e:
159
      print  e
160
      self._close()
161
      return None
162
163
    return data
164