# -*- coding: utf8 -*-
'''
DB MODULE - mySQL
*******************************
***  DB MODULE - mySQL
*******************************
$RCSfile: dbmod_mysql.py,v $
$Revision: 939 $
$Author: markus $
$Date: 2008-11-17 22:33:56 +0100 (Mo, 17. Nov 2008) $

The biocase.wrapper database module to access mySQL databases.
You will need the mxODBC module to connect to a MS SQL Server DB via ODBC.
'''

from string                                import join
from biocase.wrapper.errorclasses         import *
from biocase.wrapper.sql.base             import sqlBase
from biocase.wrapper.dbmod.base_dbmod   import DBBasemodule

import logging
log=logging.getLogger("pywrapper.dbmod.mysql")
# uses inherited ANSI SQL.

        

# ---------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------
class DBmodule(DBBasemodule):
    __version__ = '0.51 using MySQLdb ?'
    __dbmod__    = u'mySQL DB module'

    # _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    def __init__(self, psfObj):
                # call createDBconnection method
        DBBasemodule.__init__(self, psfObj)
        # dont use parameters but integrate all parameters into SQL strings:
        self.trans.integrateParametersInSQLString()
        # read DB 8bit encoding
        log.debug("8bit DB Encoding: %s"%(psfObj.encoding))
        self.conn.encoding = psfObj.encoding
    

    # _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    def createDBconnection(self):
        try:
            import MySQLdb
        except:
            raise DbModuleMissingError('MySQLdb')
        self.__class__.__version__ = self.__class__.__version__[:-1] +MySQLdb.__version__
        try:
            #log.debug("Host=%s, DB=%s, User=%s, Passwd=%s" % (self.psfObj.dbIP, self.psfObj.database, self.psfObj.user ,self.psfObj.password ))
            return MySQLdb.connect( host=self.psfObj.dbIP, db=self.psfObj.database, user=self.psfObj.user, passwd=self.psfObj.password )
        except:
            raise ConnectionError
            

    # _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    def execSQL(self, sql, paras=None):
        # create cursor:
        self.c = self.conn.cursor()
        # execute SQL statement and return result
        log.debug("start DB query")
        try:
            sql = sql.encode(self.psfObj.encoding)
            log.info("Executing SQL: '%s'" %(sql))
        except:
            self.c.close()
            raise SQLunicodeGenerationError()
        # execute this SQL always before executing SQL statements:
        constantSQL = 'SET SQL_BIG_SELECTS = 1'
        self.c.execute(constantSQL)
        # execute dynamic SQL:
        try:
            self.c.execute(sql)
        except:
            raise SQLError(sql)
        tmp = self.c.fetchall()
        log.debug("end DB query")
        log.info("Hits: "+str(len(tmp)))
        if log.isEnabledFor(logging.DEBUG):
            try:
                if type(tmp) == type('a'):
                    rsString = unicode(tmp, self.psfObj.encoding)
                else:
                    rsString = unicode(tmp)
                log.debug("Resulting Recordset:  "+rsString )
            except:
                log.debug("The Recordset Result could not be converted to a string")
        self.c.close()
        return tmp
    
