#!/usr/bin/env python

##
## FillData.py
##      -
##

# $Id: Database.py,v 1.1 2006/12/17 22:54:43 jarda Exp $


# import of required modules {{{
import adodb
# }}}


DRIVER = 'postgres'
#DRIVER = 'mysql'
HOST = '127.0.0.1'
PORT = '5432'
#PORT = '3306'
DB_NAME = 'benchmark'
#DBNAME = 'test'
#USER = 'testbench'
#PASSWORD = 'testbench'
USER = 'benchmark'
PASSWORD = 'benchmark'
OPTIONS = ''


#connectionString = "%(driver)s://%(user)s:%(password)s@%(host)s:%(port)s/%(dbName)s%(options)s" % {
connectionString = "host=%(host)s user=%(user)s password=%(password)s dbname=%(dbName)s port=%(port)s" % {
    'driver'    : DRIVER,
    'user'      : USER,
    'password'  : PASSWORD,
    'host'      : HOST,
    'port'      : PORT,
    'dbName'    : DB_NAME,
    'options'   : OPTIONS,
}
#print connectionString


CONNECTION = None


def getDatabaseConnection():
    # DOC {{{
    """Creates (if not created yet) and returns a database connection.
    """
    # }}}

    # CODE {{{
    global CONNECTION
    
    if (CONNECTION is None):
        CONNECTION = adodb.NewADOConnection(DRIVER)
        CONNECTION.Connect(connectionString)
        #CONNECTION.debug = 1
    
    # return the connection
    return CONNECTION
    # }}}


def assocGen(recordSet):
    # DOC {{{
    """Generates dictionaries for individual record set rows.
    """
    # }}}

    # CODE {{{
    while not recordSet.EOF:
        yield recordSet.GetRowAssoc(0)
        recordSet.MoveNext()
    # }}}


def genId(sequenceName):
    # DOC {{{
    """Generates a new ID for the specified sequence.

    Parameters

        sequenceName -- the sequence name
    """
    # }}}

    # CODE {{{
    db = getDatabaseConnection()
    recordSet = db.Execute("SELECT nextval('%s')" % (sequenceName,))
    
    if (not recordSet.RecordCount()):
        return None

    row = recordSet.GetRowAssoc(0)

    return row['nextval']
    # }}}
