__init__.py 2.31 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
import setuptools
import sqlite3, pymysql, pymysql.cursors

SQLITE = 0
MYSQL = 1
MARIADB = MYSQL

MIN = 0
MAX = 1

class dbObject:

# --------------------------------------------- Initialization -------------------------------------------------

 def initMySQL(self, host, port, user, pwd, db):
  self.conn = pymysql.connect(host = host, port = port, user = user, password = pwd, db = db, charset = "utf8mb4", cursorclass = pymysql.cursors.DictCursor)
  self.cur = self.conn.cursor()
  self.dbtype = MYSQL
  self.host = host
  self.port = port
  self.user = user
  self.pwd = pwd
  self.db = db

 def initSQLite(self, path):
  self.conn = sqlite3.connect(path)
  self.cur = self.conn.cursor()
  self.dbtype = SQLITE
  self.path = path

 def __init__(self, dbtype = SQLITE, path = None, host = None, port = None, user = None, pwd = None, db = None):

  if dbtype == SQLITE:
   self.initSQLite(path or 'Database.db')

  elif dbtype == MYSQL:
   self.initMySQL(host or 'localhost', port or 3306, user, pwd, db)

  else:
   raise ValueError("Unknown database type %s." % str(dbtype))

# ---------------------------------------------- No more initialization ----------------------------------------

 def closeConnection(self):
  return self.conn.close()

 def commit(self):
  return self.conn.commit()

 def executeQuery(self, query):
  return self.cur.execute(query)

 def getAll(self):
  return self.cur.fetchall()

 def getNext(self):
  return self.cur.fetchone()

 def isInitialized(self):
  try:
   self.executeQuery("SELECT * FROM messages")
   return True
  except:
   return False

66 67 68 69 70
 def getLatestMessage(db, mode = 0, user = setuptools.user()):
  if mode == 0:
   db.executeQuery("SELECT max(id) FROM messages WHERE recipient_id='%s'" % user)
  else:
   db.executeQuery("SELECT max(id) FROM messages WHERE sender_id='%s'" % user)
71 72 73 74 75
  try:
   return int(db.getNext()[0])
  except:
   return 0

76 77 78 79 80 81 82 83
 def checkID(db, mid):
  db.executeQuery("SELECT * FROM messages WHERE id=%s" % mid)
  try:
   db.getNext()[0]
   return True
  except:
   return False

84 85 86 87 88 89 90
def dbHelper():
 if setuptools.dbtype() == SQLITE:
  return dbObject(dbtype=SQLITE, path=setuptools.dbpath())
 elif setuptools.dbtype() == MYSQL:
  return dbObject(dbtype=MYSQL, host=setuptools.dbhost(), user=setuptools.dbuser(), pwd=setuptools.dbpass(), db=setuptools.dbname())
 else:
  raise setuptools.SetupException()