#
# Sample program used for analysing the trac db pool behavior
#

import os
import sys
import time

import pysqlite2.dbapi2 as sqlite

from trac.env import Environment

try:
    import threading
except ImportError:
    import dummy_threading as threading
    threading._get_ident = lambda: 0


def main(args=sys.argv):
    path = len(args) > 1 and args[1]
    n = len(args) > 2 and int(args[2]) or 3
    env = Environment(path)

    try:
        cnx = env.get_db_cnx()
        cursor = cnx.cursor()
        cursor.execute("CREATE TABLE test(value integer)")
        cursor.executemany("INSERT INTO test (value) VALUES (%s)",
                           [(1,)]*10000)
        cnx.commit()
    except:
        print 'table exists'

    threads = [None]*n
    while True:
        for i in range(0, n):
            t = threads[i]
            if t and t.isAlive():
                t.join(0.1)
            else:
                t = threading.Thread(target=run, args=(i, env,))
                print 'start', t.start()
                threads[i] = t


def run(i, env):
    sum = 0
    r = None
    for loop in range(0, 5):
        # acquire resource
        try:
            # -- test interference with repository cache
            print
            print i, 'implicit acquire - repos...',
            repos = env.get_repository()
            print repos.youngest_rev
            # -- (program works fine without the above block)

            print i, 'acquiring...',
            cnx = env.get_db_cnx()
            print i, 'acquired'

            # -- do some stuff with the connection
            cursor = cnx.cursor()
            cursor.execute("SELECT * FROM test")
            for v, in cursor:
                sum += v
            print '[select query', i, '=>', sum, ']'

            cursor.execute("INSERT INTO test (value) VALUES (%s)", (333,))
            print '[insert query]', i
            cnx.commit()
            print '[commit]', i
            print
            print
            # release resource
#            if cnx:
#                del cnx
        except Exception, e:
            print e
            print i, '*'*40, 'oops, timeout reached...'
        # sleep a while
        time.sleep(0.1)
    print '==='*10, 'done with', i
    env.shutdown(threading._get_ident())


if __name__ == '__main__':
    main()

