lite.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # sqlite db functionality
  2. import sqlite3 as lite
  3. class SqliteDB:
  4. def __init__(self, bot=None):
  5. self.bot = bot
  6. self._prepare_database()
  7. self.con.close()
  8. def _prepare_database(self):
  9. self._open()
  10. self.cur.execute('CREATE TABLE IF NOT EXISTS admins (id INTEGER PRIMARY KEY AUTOINCREMENT, username CHAR(32) DEFAULT NULL UNIQUE)')
  11. self.cur.execute('CREATE TABLE IF NOT EXISTS img (id INTEGER PRIMARY KEY, url CHAR(128) DEFAULT NULL, user CHAR(32) DEFAULT NULL, time DATETIME DEFAULT CURRENT_TIMESTAMP, channel CHAR(32) DEFAULT NULL)')
  12. self.cur.execute('CREATE TABLE IF NOT EXISTS lastfm (lastfm_username CHAR(64) NOT NULL, nick CHAR(32) NOT NULL)')
  13. self.cur.execute('CREATE TABLE IF NOT EXISTS qdb (id INTEGER PRIMARY KEY, quote TEXT NOT NULL, date DATETIME DEFAULT CURRENT_TIMESTAMP)')
  14. self.cur.execute('CREATE TABLE IF NOT EXISTS qdb_votes (vote_id PRIMARY KEY, quote_id INTEGER NOT NULL, votes INTEGER DEFAULT 0)')
  15. def _open(self):
  16. # perhaps TODO
  17. self.con = lite.connect(self.bot.conf.getNick(self.bot.network) + ".db", check_same_thread=False)
  18. self.cur = self.con.cursor()
  19. def e(self, sql):
  20. try:
  21. self._open()
  22. self.cur.execute(sql)
  23. if "INSERT" in sql or "REPLACE" in sql:
  24. self.con.commit()
  25. self.con.close()
  26. elif "SELECT" in sql:
  27. e = self.cur.fetchall()
  28. self.con.close()
  29. return e
  30. except Exception, e:
  31. print e
  32. self.con.rollback()
  33. self.con.close()
  34. return None
  35. def insertImg(self, user, url, channel):
  36. self._open()
  37. if user == "" or user == None:
  38. user = "nobody"
  39. self.cur.execute("INSERT INTO img (user, url, channel) VALUES (?, ?, ?)", (user, url, channel))
  40. self.con.commit()
  41. self.con.close()
  42. def getImgs(self):
  43. self._open()
  44. try:
  45. self.cur.execute("SELECT * FROM img ORDER BY time DESC")
  46. data = self.cur.fetchall()
  47. self.con.close()
  48. except:
  49. self.con.close()
  50. return None
  51. return data
  52. def isAdmin(self, username):
  53. self._open()
  54. try:
  55. self.cur.execute("SELECT * FROM admins WHERE username = ?",(username,))
  56. data = self.cur.fetchall()
  57. self.con.close()
  58. except Exception,e:
  59. self.con.close()
  60. return None
  61. return data