from __future__ import absolute_import
import logging

logger = logging.getLogger(__name__)       

class DatabaseWrapper():
	def __init__(self, connection_cursor):
		self.conn = connection_cursor

	def execute(self, sql):
		logger.debug(u"Execute sql: '%s'." % sql)
		self.conn.execute(sql)

	def fetchall(self):
		result = self.conn.fetchall()
		return self._filter_result(result, [])

	def fetchmany(self):
		result = self.conn.fetchmany()
		return self._filter_result(result, [])

	def fetchone(self):
		result = self.conn.fetchone()
		return self._filter_result(result)

	def rowcount(self):
		result = self.conn.rowcount
		logger.debug(u"Sql rowcount result: '%s'." % result)
		return result

	def close(self):
		self.conn.close()

	# Decodes result of the query to utf-8
	def _filter_result(self, raw_result, empty_result = None):
		new_result = []
		if raw_result is not None:
			for item in xrange(len(raw_result)):
				if type(raw_result[item]) is str:
					new_result.append(raw_result[item].decode('utf-8'))
				else:
					new_result.append(raw_result[item])
		if new_result is not None:
			logger.debug(u"Sql query result: '%s'." % ' '.join(map(unicode, new_result)))
		return new_result if len(new_result) != 0 else empty_result
