# -*- coding: utf8 -*-
'''DB MODULE - PSYCO-POSTGRESQL
*******************************
***  DB MODULE - PSYCO-POSTGRESQL
*******************************
$RCSfile: dbmod_psycopg.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 psycopg 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.4 using psycopg ?'
	__dbmod__	= u'Psycopg2 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 %s" %(self.psfObj.encoding))
		#c = None


	# _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
	def createDBconnection(self):
		try:
			import psycopg2
		except:
			raise DbModuleMissingError('psycopg')
		self.__class__.__version__ = self.__class__.__version__[:-1]+psycopg2.__version__
		try:
			if len(self.psfObj.password) > 0:
				loginParas = "host=%s user=%s password=%s dbname=%s" % (self.psfObj.dbIP, self.psfObj.user, self.psfObj.password, self.psfObj.database )
				return psycopg2.connect(loginParas)
			else:
				loginParas = "host=%s user=%s dbname=%s" % (self.psfObj.dbIP, self.psfObj.user, self.psfObj.database )
				return psycopg2.connect(loginParas)
		except:
			raise ConnectionError()
			

	
