#! /usr/bin/python
# -*- coding: iso-8859-1 -*-

#####################################################
#    Copyright (C) 2006 by Cesar Kallas   	
#    cesarkallas@soulivre.org   
#    http://cesarkallas.soulivre.org
#                                                                          
#    This program is free software; you can redistribute it and#or modify  
#    it under the terms of the GNU General Public License as published by 
#    the Free Software Foundation; either version 2 of the License, or     
#    (at your option) any later version.                                   
#                                                                          
#    This program is distributed in the hope that it will be useful,       
#    but WITHOUT ANY WARRANTY; without even the implied warranty of        
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         
#    GNU General Public License for more details.                          
#                                                                          
#    You should have received a copy of the GNU General Public License     
#    along with this program; if not, write to the                         
#    Free Software Foundation, Inc.,                                       
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             
#####################################################

from pysqlite2 import dbapi2 as sqlite
import Log, Opcoes

class BancoDados( object ):
	"""
	Classe que gerencia a conexao com o banco de dados SQLite
	Data: 04/09/2006
	"""
	global cursor
	
	def __init__(self):
		# Opcoes do banco de dados
		opcoes = Opcoes.Opcoes()
		try:
			op = opcoes.ler('BancoDados')
			self.arquivo = op["arquivo"]
			self.mode = int(op["mode"])
		except:
			log.error("BancoDados: ao buscar informacoes do banco de dados")
			raise
			return -1
		
		# Inicia Log do Banco De Dados
		self.log = Log.Log("BancoDados")
		self.log = self.log.get()

	def dict_factory(self, cursor, row):
		d = {}
		for idx, col in enumerate(cursor.description):
			d[col[0]] = str(row[idx])
		return d

	def conectar(self):
		"""
		Funcao que conecta na base de dados SQLite
		"""
		try:
			self.conn = sqlite.connect(self.arquivo, self.mode)
			self.conn.row_factory = self.dict_factory
			# Set isolation_level to "IMMEDIATE"
			#self.conn.isolation_level = "IMMEDIATE"
			#self.conn.row_factory = dict_factory
			self.cursor = self.conn.cursor()
			return self.conn, self.cursor
		except Exception:
			raise
			self.log.warn("BancoDados: falha ao conectar no banco de dados")
			return -1
			
	def desconectar(self):
		self.cursor.close()
		self.conn.close()

