# start by importing pyngres

import pyngres as py

# initialize the OpenAPI to use the latest version

inp = py.IIAPI_INITPARM()
inp.in_timeout = -1
inp.in_version = py.IIAPI_VERSION
status = inp.in_status
if status != py.IIAPI_ST_SUCCESS:
    print('could not initialize the OpenAPI')
    quit()

# note the envHandle for future use

envHandle = inp.in_envHandle

# allocate a control block for IIapi_wait(), which will be called
# in a loop after asynchronous OpenAPI functions are invoked
# (such as Iiapi_connect()). The loop terminates when the requested
# asynchronous operation is completed

wtp = py.IIAPI_WAITPARM()
wtp.wt_timeout = 0

# define the connection target

dbname = 'loathing::sandbox'

# construct the target name as a NUL-terminated array of bytes 
# (i.e. a C string) by encoding dbname (which is a Python str and 
# hence meaningless to the OpenAPI). The database name in this
# example includes a *vnode* name target = dbname.encode()

target = dbname.encode()

# Allocate a control block for IIapi_connect(). Initialize it 
# with the database target name; the previously noted envHandle; the 
# py.IIAPI_CT_SQL constant to indicate this will be an SQL 
# session, and set the timeout to -1 so the OpenAPI will wait 
# indefinitely for the connection to be established (or refused)

cop = py.IIAPI_CONNPARM()
cop.co_target = target
cop.co_connHandle = envHandle
cop.co_type = py.IIAPI_CT_SQL
cop.co_timeout = -1

# invoke IIapi_connect() then loop until the gp_completed flag indicates 
# the database connection request has finished

py.IIapi_connect(cop)
while not cop.co_genParm.gp_completed:
    py.IIapi_wait(wtp)

# the request can be completed successfully or it might fail for some
# reason, such as an invalid database name

# ************************************************************************
# IMPORTANT: the status is returned only when the operation is complete; 
# do not test it before completion
# ************************************************************************

status = cop.co_status
if status != py.IIAPI_ST_SUCCESS:
    print('could not connect to the database')
    quit()

# when the connection is successfully established the returned 
# connection handle must be noted for future use in other OpenAPI 
# function invokations. The OpenAPI uses connection handles to allows it 
# to interact correctly with multiple simultaneous database 
# connections in the same application

connHandle = cop.co_connHandle

# once the connection is established the application can start sending
# SQL statements to be executed, fetching query results, and controlling
# the session behaviour (e.g. committing transactions, setting lockmodes,
# changing display formats.)

...
