from MySQLdb import *
import MySQLdb as dbfunc
import _mysql_exceptions
class objectifier:
	def __repr__(self):
		stx = 'DB row:\n'
		for i in self.dict:
			stx += '   ' + str(i) + (' ' * (16 - len(str(i)))) + ': ' + str(self.dict[i]) + '\n'
		return stx
def objectify(x):
	m = objectifier()
	for i in x:
		try:
			setattr(m, i, x[i])
		except:
			raise
	m.dict = x
	return m
class ObjectCursor(cursors.DictCursor):
	def fetchone(self, *args, **kargs):
		fa = (cursors.DictCursor.fetchone(self, *args, **kargs))
		try:
			return objectify(fa)
		except:
			return fa
	def insert_id(self):
		self.execute('SELECT LAST_INSERT_ID() AS m')
		return self.fetchone().m
		
	def fetchall(self, *args, **kargs):
		fa = cursors.DictCursor.fetchall(self, *args, **kargs)
		try:
			return [objectify(i) for i in fa]
		except:
			return fa
cursors.ObjectCursor = ObjectCursor
def exeq(self, *args, **kargs):
	try:
		# EGGSECUTE!
		cursor = self.cursor (cursors.ObjectCursor)
		ar = cursor.execute (*args, **kargs)
		cursor.affected_rows = ar
		return cursor
	except _mysql_exceptions.OperationalError:
		print args
		print 'Op error'
		self.ping(True)
	except:
		print args
		raise
connect_info = None

def connect(*args, **kargs):
	connect_info = (args, kargs)
	return dbfunc.connect(*args, **kargs)
connections.Connection.exeq = exeq
def reconnect():
        global conn
        try:
                conn = dbfunc.connect (host = "192.168.1.175",
                                    user = "comex",
                                    passwd = "",
                                    db = "agora")
        except dbfunc.Error, e:
                print "Error %d: %s" % (e.args[0], e.args[1])
                sys.exit(1)
def ping():
        try:
                conn.ping(True)
        except:
                print '(reconnecting)'
                reconnect()
reconnect()
def exeq(*args, **kargs):
	return conn.exeq(*args, **kargs)				

