# -*- coding: utf8 -*-
'''DB MODULE - POSTGRESQL
*******************************
***  DB MODULE - POSTGRESQL
*******************************
$RCSfile: dbmod_postgres.py,v $
$Revision: 911 $
$Author: markus $
$Date: 2008-04-30 23:52:39 +0200 (Mi, 30. Apr 2008) $

The biocase.wrapper database module to access PostgreSQL databases.
You will need the pg module to connect to a PostgreSQL DB.
'''

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.postgres")


#############################################
#
# CUSTOMIZATION for PostgreSQL
#
# OVERLOAD BASE CLASSES AND OTHER METHODS
#
#############################################

# uses inherited ANSI SQL apart from the following.
sqlBase.templates['attribute'] = '"#1"."#2"'
sqlBase.templates['table'] = '"#1"'
sqlBase.binaryCOP['like'] = "ILIKE"

        
# ---------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------
class DBmodule(DBBasemodule):
    __version__ = '0.91 using pyPgSQL ?'
    __dbmod__    = u'PostgreSQL DB module'
    
    # _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    def __init__(self, psfObj):
        # setting the psfObj reference to self.psfObj
        # call createDBconnection method
        DBBasemodule.__init__(self, psfObj)
        # dont use parameters but integrate all parameters into SQL strings:
        self.trans.integrateParametersInSQLString()
        # set unicode encoding to true
        c = self.conn.cursor()
        c.execute("set client_encoding to unicode")
        c = None


    # _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    def createDBconnection(self):
        try:
            from  pyPgSQL import PgSQL, __version__ as pyPgSQLversion
        except:
            log.warn("The pyPgSQL module is not properly installed on your system. You need this module to connect to PostgreSQL sources.")
            raise DbModuleMissingError('pyPgSQL')
        self.__class__.__version__ = self.__class__.__version__[:-1]+pyPgSQLversion
        try:
            if len(self.psfObj.password) > 0:
                loginParas = "Host=%s, User=%s, Passwd=%s, DB=%s" % (self.psfObj.dbIP, self.psfObj.user, self.psfObj.password, self.psfObj.database )
                return PgSQL.connect(host=self.psfObj.dbIP, user=self.psfObj.user, password=self.psfObj.password, database=self.psfObj.database, client_encoding='utf-8', unicode_results=1)
            else:
                loginParas = "Host=%s, User=%s, DB=%s" % (self.psfObj.dbIP, self.psfObj.user, self.psfObj.database )
                return PgSQL.connect(host=self.psfObj.dbIP, user=self.psfObj.user, database=self.psfObj.database, client_encoding='utf-8', unicode_results=1)
        except:
            raise ConnectionError()
            

    # _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    def execSQL(self, sql, paras=None):
        self.c = self.conn.cursor()
        # execute SQL statement and return result
        log.debug("start DB query")
        try:
            log.info("Executing SQL: '%s'" %sql )
        except:
            log.info("Couldnt log SQL to be executed")
        #EXECUTE
        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


