import pyngres as py

inp = py.IIAPI_INITPARM()
inp.in_timeout = -1
inp.in_version = py.IIAPI_VERSION

py.IIapi_initialize(inp)

status = inp.in_status
if status != py.IIAPI_ST_SUCCESS:
    print('could not initialize the OpenAPI')
    quit()

envHandle = inp.in_envHandle

wtp = py.IIAPI_WAITPARM()
wtp.wt_timeout = 0

# create a 'sandbox' database or substitute an existing database name below
dbname = 'sandbox'
target = dbname.encode()

cop = py.IIAPI_CONNPARM()
cop.co_target = target
cop.co_connHandle = envHandle
cop.co_type = py.IIAPI_CT_SQL
cop.co_timeout = -1

py.IIapi_connect(cop)
while not cop.co_genParm.gp_completed:
    py.IIapi_wait(wtp)

status = cop.co_genParm.gp_status
if status != py.IIAPI_ST_SUCCESS:
    print('could not connect to the database')
    quit()

connHandle = cop.co_connHandle

print('successfully connected')

dcp = py.IIAPI_DISCONNPARM()
dcp.dc_connHandle = connHandle

py.IIapi_disconnect(dcp)
while not dcp.dc_genParm.gp_completed:
    py.IIapi_wait(wtp)

rep = py.IIAPI_RELENVPARM()
rep.re_envHandle = envHandle
py.IIapi_releaseEnv(rep)

tmp = py.IIAPI_TERMPARM()
py.IIapi_terminate(tmp)

quit()



