pyircbot/pyircbot/modules/MySQL.py

115 lines
3.5 KiB
Python
Raw Normal View History

2013-12-28 09:58:20 -08:00
#!/usr/bin/env python
2014-10-02 18:14:42 -07:00
"""
.. module:: MySQL
2015-11-01 18:03:11 -08:00
:synopsis: Module providing a mysql type service
2014-10-02 18:14:42 -07:00
.. moduleauthor:: Dave Pedu <dave@davepedu.com>
"""
2017-01-01 14:59:01 -08:00
from pyircbot.modulebase import ModuleBase
2013-12-28 09:58:20 -08:00
import sys
2017-12-02 23:48:44 -08:00
import pymysql as MySQLdb # python 3.x
2017-01-01 14:59:01 -08:00
2013-12-28 09:58:20 -08:00
class MySQL(ModuleBase):
2015-11-01 18:03:11 -08:00
def __init__(self, bot, moduleName):
2017-01-01 14:59:01 -08:00
ModuleBase.__init__(self, bot, moduleName)
self.services = ["mysql"]
2015-11-01 18:03:11 -08:00
self.connection = self.getConnection()
2017-01-01 14:59:01 -08:00
2015-11-01 18:03:11 -08:00
def getConnection(self):
return Connection(self)
2017-01-01 14:59:01 -08:00
2013-12-28 09:58:20 -08:00
class Connection:
2015-11-01 18:03:11 -08:00
def __init__(self, master):
self.config = master.config
self.log = master.log
self._connect()
2017-01-01 14:59:01 -08:00
2015-11-01 18:03:11 -08:00
# Check if the table requested exists
def tableExists(self, tablename):
c = self.getCursor()
c.execute("SHOW TABLES;")
tables = c.fetchall()
2017-01-01 14:59:01 -08:00
if len(tables) == 0:
return False
2015-11-01 18:03:11 -08:00
key = list(tables[0].keys())[0]
for table in tables:
2017-01-01 14:59:01 -08:00
if table[key] == tablename:
return True
2015-11-01 18:03:11 -08:00
return False
2017-01-01 14:59:01 -08:00
2015-11-01 18:03:11 -08:00
def query(self, queryText, args=()):
"""Execute a MySQL query and return the cursor
2017-01-01 14:59:01 -08:00
2015-11-01 18:03:11 -08:00
:param queryText: the mysql query as a string, using '%s' for token replacement
:type queryText: str
:param args: arguments to be escaped into the query
:type args: tuple
:returns: cursor -- the sql cursor"""
c = self.getCursor()
2017-01-01 14:59:01 -08:00
if len(args) == 0:
2015-11-01 18:03:11 -08:00
c.execute(queryText)
else:
c.execute(queryText, args)
return c
2017-01-01 14:59:01 -08:00
2015-11-01 18:03:11 -08:00
# Returns a cusor object, after checking for connectivity
def getCursor(self):
self.ensureConnected()
2017-01-01 14:59:01 -08:00
if sys.version_info > (3, 0):
2015-11-01 18:03:11 -08:00
c = self.connection.cursor(MySQLdb.cursors.DictCursor)
else:
c = self.connection.cursor(cursorclass=MySQLdb.cursors.DictCursor)
c.execute("USE `%s`;" % self.config["database"])
return c
2017-01-01 14:59:01 -08:00
2015-11-01 18:03:11 -08:00
def escape(self, s):
"""Escape a string using the mysql server
2017-01-01 14:59:01 -08:00
2015-11-01 18:03:11 -08:00
:param s: the string to escape
:type s: str
:returns: str -- the escaped string"""
self.ensureConnected()
return self.connection.escape_string(s)
2017-01-01 14:59:01 -08:00
2015-11-01 18:03:11 -08:00
def ensureConnected(self):
try:
self.connection.ping()
except:
try:
self.connection.close()
except:
pass
del self.connection
self._connect()
2017-01-01 14:59:01 -08:00
2015-11-01 18:03:11 -08:00
def ondisable(self):
self.connection.close()
2017-01-01 14:59:01 -08:00
2015-11-01 18:03:11 -08:00
# Connects to the database server, and selects a database (Or attempts to create it if it doesn't exist yet)
def _connect(self):
self.log.info("MySQL: Connecting to db host at %s" % self.config["host"])
2017-01-01 14:59:01 -08:00
self.connection = MySQLdb.connect(host=self.config["host"], user=self.config["username"],
passwd=self.config["password"])
2015-11-01 18:03:11 -08:00
self.log.info("MySQL: Connected.")
self.connection.autocommit(True)
c = None
2017-01-01 14:59:01 -08:00
if sys.version_info > (3, 0):
2015-11-01 18:03:11 -08:00
c = self.connection.cursor(MySQLdb.cursors.DictCursor)
else:
c = self.connection.cursor(cursorclass=MySQLdb.cursors.DictCursor)
2017-01-01 14:59:01 -08:00
2015-11-01 18:03:11 -08:00
c.execute("SHOW DATABASES")
dblist = c.fetchall()
found = False
for row in dblist:
2017-01-01 14:59:01 -08:00
if row["Database"] == self.config["database"]:
2015-11-01 18:03:11 -08:00
found = True
if not found:
c.execute("CREATE DATABASE `%s`;" % self.config["database"])
c.execute("USE `%s`;" % self.config["database"])
c.close()