db.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. 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.Logger.WARNING, e)
  34. return
  35. self.cur = self.con.cursor()
  36. def _close(self):
  37. self.con = None
  38. if not self.dry_run:
  39. self.cur.close()
  40. # should prevent mysql has gone away errors.. ideally
  41. def _handle(self):
  42. global cur
  43. global age
  44. now = datetime.now()
  45. if now - self.age > timedelta(minutes=5):
  46. self.cur.close()
  47. self.con = mdb.connect("localhost","pybot","1q2w3e4r","pybot")
  48. self.cur = self.con.cursor()
  49. def select(self, where, what):
  50. try:
  51. self._open()
  52. self.cur.execute("""SELECT %s FROM %s""")
  53. data = self.cur.fetchall()
  54. self._close()
  55. except:
  56. self._close()
  57. return None
  58. return data
  59. def replace(self, where, which, what):
  60. try:
  61. self._open()
  62. self.cur.execute("""REPLACE INTO %s (%s) VALUES (%s)""",(where, which, what))
  63. self._close()
  64. except:
  65. self._close()
  66. return None
  67. def e(self, sql):
  68. try:
  69. self._open()
  70. self.cur.execute(sql)
  71. if "INSERT" in sql or "REPLACE" in sql:
  72. self.con.commit()
  73. self._close()
  74. elif "SELECT" in sql:
  75. e = self.cur.fetchall()
  76. self._close()
  77. return e
  78. except Exception, e:
  79. print e
  80. self.con.rollback()
  81. self._close()
  82. return None
  83. def insert(self, where, which, what):
  84. try:
  85. self._open()
  86. self.cur.execute("""INSERT INTO %s (%s) VALUES (%s)""",(where, which, what))
  87. self._close()
  88. except:
  89. self._close()
  90. return None
  91. def updateSeen(self,who,statement,event):
  92. self._open()
  93. #print "executing REPLACE INTO seen (user_name, statement, event) VALUES ( " + str(who) + " " + str(statement) + " " + str(event) + ")"
  94. self.cur.execute("REPLACE INTO seen (user_name, statement, event) VALUES (%s, %s, %s)", (who, statement, event))
  95. self._close()
  96. def getSeen(self, who):
  97. self._open()
  98. if who != "":
  99. self.cur.execute("SELECT user_name, date, statement, event FROM seen WHERE user_name = %s", who)
  100. data = self.cur.fetchone()
  101. return data;
  102. self._close()
  103. else:
  104. self._close()
  105. return None
  106. def insertImg(self, user, url, channel):
  107. self._open()
  108. if user == "" or user == None:
  109. user = "nobody"
  110. try:
  111. self.cur.execute("""INSERT INTO img (user, url, channel) VALUES (%s, %s, %s)""", (user, url, channel))
  112. if not self.dry_run:
  113. self.con.commit()
  114. except:
  115. self.bot.logger(logger.Logger.WARNING, 'failed to insert ' + url)
  116. print "failure"
  117. print "Unexpected error:", sys.exc_info()[0]
  118. if not self.dry_run:
  119. self.con.rollback()
  120. self._close()
  121. def getImgs(self):
  122. self._open()
  123. try:
  124. self.cur.execute("""SELECT * FROM img ORDER BY time DESC""")
  125. data = self.cur.fetchall()
  126. self._close()
  127. except:
  128. self._close()
  129. return None
  130. return data
  131. def isAdmin(self, username):
  132. self._open()
  133. try:
  134. self.cur.execute("""SELECT * FROM admins WHERE username = %s""",[username])
  135. data = self.cur.fetchall()
  136. self._close()
  137. except Exception, e:
  138. print e
  139. self._close()
  140. return None
  141. return data