# -*- coding: utf8 -*-
'''
DB MODULE - Firebird
*******************************
***  DB MODULE - Firebird
*******************************
$RCSfile: dbmod_firebird.py,v $
$Revision: 875 $
$Author: markus $
$Date: 2008-04-24 02:23:32 +0200 (Do, 24. Apr 2008) $

The biocase.wrapper database module to access Firebird/Interbase databases.
You will need the kinterbasdb python module to run this dbmodule.
'''


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

import logging
log = logging.getLogger("pywrapper.dbmod")


# no alias tag
sqlBase.templates['alias'] = '#1  #2'

# OFFSET: SELECT FIRST x SKIP y * FROM
sqlBase.templates['select-limit'] = 'SELECT FIRST #3 DISTINCT #1 FROM #2'
#sqlBase.templates['select-limit'] = None

# ---------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------
class DBmodule(DBBasemodule):
    __version__ = '0.3 using kinterbasedb ?'
    __dbmod__    = u'Firebird module'
    
    # _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    def __init__(self, psfObj):
                # call createDBconnection method
        DBBasemodule.__init__(self, psfObj)

        # read DB 8bit encoding
        log.debug("8bit DB Encoding: %s"%(psfObj.encoding))
        self.conn.encoding = psfObj.encoding

    # _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
    def createDBconnection(self):
        try:
            import kinterbasdb
            # This translator configuration, which is intended for use with Python 2.3 and later, represents date/time values via the standard library module datetime  and fixed point values via the third-party fixedpoint  module.
            # Unicode values are encoded and decoded automatically (see this FAQ for more info).
            # Implemented by the kinterbasdb.typeconv_23plus module. 
            #kinterbasdb.init(type_conv=100)
        except:
            raise DbModuleMissingError('kinterbasdb')
        self.__class__.__version__ = self.__class__.__version__[:-1]+ join([str(x) for x in kinterbasdb.__version__], ".")
        #
        # connect
        try:
            if self.psfObj.dbIP is not None and len(self.psfObj.dbIP.strip() ) > 2:
                host = self.psfObj.dbIP 
            else:
                host = None
            if len(self.psfObj.password) > 0:
                #return kinterbasdb.connect(database='localhost:d:/plantlore.fdb', user='SYSDBA', password='masterkey')
                return kinterbasdb.connect(host=None, user=str(self.psfObj.user), database=str(self.psfObj.database), password=str(self.psfObj.password) )
            else:
                return kinterbasdb.connect(host=host, user=str(self.psfObj.user), database=str(self.psfObj.database) )
        except:
            log.error("ConnectionError()")
            raise ConnectionError()

    
    def execSQL(self, sql, paras=None):
        if paras is not None:
            # only allow strings as parameters
            p_tmp = []
            for p in paras:
                if type(p)==UnicodeType:
                    p = p.encode(self.conn.encoding)
                p_tmp.append( p )
            paras=p_tmp
        # call base method
        return DBBasemodule.execSQL(self, sql, paras)
    
