from sqlobject import *
import sys, os

connectionURI = "mysql://user:password@localhost:3306/test?init_command=set%20table_type=\"InnoDB\"&autoCommit="
my_connection = mysql.builder().connectionFromURI( connectionURI )
my_connection.autocommit = False
my_connection.debug = True
my_connection.debugOutput = True

sqlhub.processConnection = my_connection

class BaseSQLObject(SQLObject):
	class sqlmeta:
		cacheValues = False

class Aggregates(BaseSQLObject):
	total = IntCol()

class MyValues(BaseSQLObject):
	value = IntCol()

Aggregates.createTable( ifNotExists=True )
MyValues.createTable( ifNotExists=True )

## OK, init done

print "starting"

t = my_connection.transaction()

for i in xrange(100):
	print i

	try:
		agg = Aggregates.select(connection = t, forUpdate = True).getOne()
	except:
		agg = Aggregates(total = 0, connection = t)

	newVal = i % 10 + 1
	#print "updating total"
	agg.total = agg.total + newVal
	#print "adding value"
	newValue = MyValues(value = newVal, connection = t)
	#print "doing commit"
	t.commit()

