db.py 4.1 KB

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