Beispiel #1
0
 void Datetime::ociDescriptorAlloc()
 {
   log_debug("OCIDescriptorAlloc(OCI_DTYPE_TIMESTAMP)");
   sword ret = OCIDescriptorAlloc(conn->getEnvHandle(),
     reinterpret_cast<void**>(&datetime), OCI_DTYPE_TIMESTAMP, 0, 0);
   conn->checkError(ret, "OCIDescriptorAlloc(OCI_DTYPE_TIMESTAMP)");
 }
Beispiel #2
0
/*
 * @overload initialize(conn, directory = nil, filename = nil)
 *
 *  Creates a BFILE object.
 *  This is correspond to {BFILENAME}[https://docs.oracle.com/database/121/SQLRF/functions020.htm].
 *
 *  @param [OCI8] conn
 *  @param [String] directory  a directory object created by
 *    {"CREATE DIRECTORY"}[http://docs.oracle.com/database/121/SQLRF/statements_5008.htm].
 *  @param [String] filename
 *  @return [OCI8::BFILE]
 */
static VALUE oci8_bfile_initialize(int argc, VALUE *argv, VALUE self)
{
    oci8_lob_t *lob = TO_LOB(self);
    VALUE svc;
    VALUE dir_alias;
    VALUE filename;
    oci8_svcctx_t *svcctx;
    int rv;

    rb_scan_args(argc, argv, "12", &svc, &dir_alias, &filename);
    svcctx = oci8_get_svcctx(svc);
    rv = OCIDescriptorAlloc(oci8_envhp, &lob->base.hp.ptr, OCI_DTYPE_LOB, 0, NULL);
    if (rv != OCI_SUCCESS) {
        oci8_env_raise(oci8_envhp, rv);
    }
    lob->base.type = OCI_DTYPE_LOB;
    lob->pos = 0;
    lob->csfrm = SQLCS_IMPLICIT;
    lob->lobtype = OCI_TEMP_BLOB;
    lob->state = S_BFILE_CLOSE;
    if (argc != 1) {
        OCI8SafeStringValue(dir_alias);
        OCI8SafeStringValue(filename);
        oci8_bfile_set_name(self, dir_alias, filename);
    }
    oci8_link_to_parent(&lob->base, &svcctx->base);
    lob->svcctx = svcctx;
    return Qnil;
}
Beispiel #3
0
 void Blob::ociDescriptorAlloc()
 {
   log_debug("OCIDescriptorAlloc(OCI_DTYPE_LOB)");
   sword ret = OCIDescriptorAlloc(conn->getEnvHandle(),
     reinterpret_cast<void**>(&lob), OCI_DTYPE_LOB, 0, 0);
   conn->checkError(ret, "OCIDescriptorAlloc(OCI_DTYPE_LOB)");
 }
Beispiel #4
0
static VALUE get_rowid_attr(rowid_arg_t *arg)
{
    oci8_base_t *base = arg->base;
    ub4 attrtype = arg->attrtype;
    char buf[MAX_ROWID_LEN];
    ub2 buflen;
    sword rv;

    /* get a rowid descriptor from OCIHandle */
    rv = OCIDescriptorAlloc(oci8_envhp, (dvoid*)&arg->ridp, OCI_DTYPE_ROWID, 0, NULL);
    if (rv != OCI_SUCCESS)
        oci8_env_raise(oci8_envhp, rv);
    rv = OCIAttrGet(base->hp.ptr, base->type, arg->ridp, 0, attrtype, oci8_errhp);
    if (rv != OCI_SUCCESS) {
        oci8_raise(oci8_errhp, rv, NULL);
    }
    /* convert the rowid descriptor to a string. */
    if (have_OCIRowidToChar) {
        /* If OCIRowidToChar is available, use it. */
        buflen = MAX_ROWID_LEN;
        rv = OCIRowidToChar(arg->ridp, TO_ORATEXT(buf), &buflen, oci8_errhp);
        if (rv != OCI_SUCCESS) {
            oci8_raise(oci8_errhp, rv, NULL);
        }
    } else {
        /* If OCIRowidToChar is not available, convert it on
         * Oracle Server.
         */
        oci8_base_t *svc;
        oci8_exec_sql_var_t define_var;
        oci8_exec_sql_var_t bind_var;

        /* search a connection from the handle */
        svc = base;
        while (svc->type != OCI_HTYPE_SVCCTX) {
            svc = svc->parent;
            if (svc == NULL) {
                rb_raise(rb_eRuntimeError, "No connection is found!!");
            }
        }
        /* :strval */
        define_var.valuep = buf;
        define_var.value_sz = sizeof(buf);
        define_var.dty = SQLT_CHR;
        define_var.indp = NULL;
        define_var.alenp = &buflen;
        /* :rowid */
        bind_var.valuep = &arg->ridp;
        bind_var.value_sz = sizeof(void *);
        bind_var.dty = SQLT_RDD;
        bind_var.indp = NULL;
        bind_var.alenp = NULL;
        /* convert the rowid descriptor to a string value by querying Oracle server. */
        oci8_exec_sql((oci8_svcctx_t*)svc, "SELECT :rid FROM dual", 1, &define_var, 1, &bind_var, 1);
        if (buflen == 0) {
            return Qnil;
        }
    }
    return rb_external_str_new_with_enc(buf, buflen, rb_usascii_encoding());
}
Beispiel #5
0
static VALUE oci8_lob_do_initialize(int argc, VALUE *argv, VALUE self, ub1 csfrm, ub1 lobtype)
{
    oci8_lob_t *lob = DATA_PTR(self);
    VALUE svc;
    VALUE val;
    sword rv;

    rb_scan_args(argc, argv, "11", &svc, &val);
    TO_SVCCTX(svc); /* check argument type */
    rv = OCIDescriptorAlloc(oci8_envhp, &lob->base.hp.ptr, OCI_DTYPE_LOB, 0, NULL);
    if (rv != OCI_SUCCESS)
        oci8_env_raise(oci8_envhp, rv);
    lob->base.type = OCI_DTYPE_LOB;
    lob->svc = svc;
    lob->svchp = NULL;
    lob->pos = 0;
    lob->char_width = 1;
    lob->csfrm = csfrm;
    lob->lobtype = lobtype;
    lob->state = S_NO_OPEN_CLOSE;
    oci8_link_to_parent((oci8_base_t*)lob, (oci8_base_t*)DATA_PTR(svc));
    if (!NIL_P(val)) {
        if (have_OCILobCreateTemporary_nb) {
            oci8_svcctx_t *svcctx = oci8_get_svcctx(svc);
            OCI8StringValue(val);
            oci_lc(OCILobCreateTemporary_nb(svcctx, svcctx->base.hp.svc, oci8_errhp, lob->base.hp.lob, 0, csfrm, lobtype, TRUE, OCI_DURATION_SESSION));
            lob->svchp = oci8_get_oci_svcctx(svc);
            oci8_lob_write(self, val);
        } else {
            rb_raise(rb_eRuntimeError, "creating a temporary lob is not supported on this Oracle version");
        }
    }
    return Qnil;
}
Beispiel #6
0
static VALUE oci8_bfile_initialize(int argc, VALUE *argv, VALUE self)
{
    oci8_lob_t *lob = DATA_PTR(self);
    VALUE svc;
    VALUE dir_alias;
    VALUE filename;

    rb_scan_args(argc, argv, "12", &svc, &dir_alias, &filename);
    TO_SVCCTX(svc); /* check argument type */
    oci_lc(OCIDescriptorAlloc(oci8_envhp, &lob->base.hp.ptr, OCI_DTYPE_LOB, 0, NULL));
    lob->base.type = OCI_DTYPE_LOB;
    lob->svc = svc;
    lob->pos = 0;
    lob->char_width = 1;
    lob->csfrm = SQLCS_IMPLICIT;
    lob->lobtype = OCI_TEMP_BLOB;
    lob->state = S_BFILE_CLOSE;
    if (argc != 1) {
        OCI8SafeStringValue(dir_alias);
        OCI8SafeStringValue(filename);
        oci8_bfile_set_name(self, dir_alias, filename);
    }
    oci8_link_to_parent((oci8_base_t*)lob, (oci8_base_t*)DATA_PTR(svc));
    return Qnil;
}
Beispiel #7
0
void OWStatement::Define( OCILobLocator** pphLocator )
{
    OCIDefine*  hDefine = NULL;

    nNextCol++;

    CheckError( OCIDescriptorAlloc(
        poConnection->hEnv,
        (void**) pphLocator,
        OCI_DTYPE_LOB,
        0,
        0),
        hError );

    CheckError( OCIDefineByPos(
        hStmt,
        &hDefine,
        hError,
        (ub4) nNextCol,
        (dvoid*) pphLocator,
        (sb4) 0,
        (ub2) SQLT_BLOB,
        (void*) NULL,
        (ub2*) NULL,
        (ub2*) NULL,
        (ub4) OCI_DEFAULT ),
        hError );
}
Beispiel #8
0
void OWStatement::BindName( const char* pszName, OCILobLocator** pphLocator )
{
    OCIBind* hBind = NULL;

    CheckError( OCIDescriptorAlloc(
        poConnection->hEnv,
        (void**) pphLocator,
        OCI_DTYPE_LOB,
        0,
        0),
        hError );

    CheckError( OCIBindByName(
        (OCIStmt*) hStmt,
        (OCIBind**) &hBind,
        (OCIError*) hError,
        (text*) pszName,
        (sb4) -1,
        (dvoid*) pphLocator,
        (sb4) -1,
        (ub2) SQLT_CLOB,
        (dvoid*) NULL,
        (ub2*) NULL,
        (ub2*) NULL,
        (ub4) 0,
        (ub4*) NULL,
        (ub4) OCI_DEFAULT ),
        hError );
}
Beispiel #9
0
void OWStatement::Define( OCILobLocator** pphLocator, long nIterations )
{
    OCIDefine* hDefine = NULL;

    nNextCol++;

    long i;

    for (i = 0; i < nIterations; i++)
    {
        OCIDescriptorAlloc(
            poConnection->hEnv,
            (void**) &pphLocator[i],
            OCI_DTYPE_LOB, (size_t) 0, (void**) 0);
    }

    CheckError( OCIDefineByPos( hStmt,
        &hDefine,
        hError,
        (ub4) nNextCol,
        (dvoid*) pphLocator,
        (sb4) -1,
        (ub2) SQLT_BLOB,
        (void*) 0,
        (ub2*) 0,
        (ub2*) 0,
        (ub4) OCI_DEFAULT ), hError );
}
Beispiel #10
0
static VALUE oci8_lob_do_initialize(int argc, VALUE *argv, VALUE self, ub1 csfrm, ub1 lobtype)
{
    oci8_lob_t *lob = TO_LOB(self);
    VALUE svc;
    VALUE val;
    oci8_svcctx_t *svcctx;
    sword rv;

    rb_scan_args(argc, argv, "11", &svc, &val);
    svcctx = oci8_get_svcctx(svc);
    rv = OCIDescriptorAlloc(oci8_envhp, &lob->base.hp.ptr, OCI_DTYPE_LOB, 0, NULL);
    if (rv != OCI_SUCCESS)
        oci8_env_raise(oci8_envhp, rv);
    lob->base.type = OCI_DTYPE_LOB;
    lob->pos = 0;
    lob->csfrm = csfrm;
    lob->lobtype = lobtype;
    lob->state = S_NO_OPEN_CLOSE;
    oci8_link_to_parent(&lob->base, &svcctx->base);
    lob->svcctx = svcctx;
    RB_OBJ_WRITTEN(self, Qundef, svc);
    if (!NIL_P(val)) {
        OCI8StringValue(val);
        chker2(OCILobCreateTemporary_nb(svcctx, svcctx->base.hp.svc, oci8_errhp, lob->base.hp.lob, 0, csfrm, lobtype, TRUE, OCI_DURATION_SESSION),
               &svcctx->base);
        oci8_lob_write(self, val);
        lob->pos = 0; /* reset the position */
    }
    return Qnil;
}
Beispiel #11
0
void BindParLob::descAlloc(void) //TODO OCI_DTYPE_FILE for BFILE, CFILE
{
	for(unsigned i=0; i<_cnt; ++i)
	{
		sword res = OCICALL(OCIDescriptorAlloc(_env, &((void**)valuep)[i], OCI_DTYPE_LOB, 0, NULL));
		oci_check_error(__TROTL_HERE__, _env, res);
	}
}
Beispiel #12
0
Descriptor * EnvImpl::allocDescriptor(DescriptorType descriptorType)
{
  void *descriptor = NULL;

  ociCallEnv(OCIDescriptorAlloc(envh_, &descriptor, descriptorType,
                                0, NULL), envh_);

  return (Descriptor *)descriptor;
}
Beispiel #13
0
void locatorIsEqual_proc(OCILobLocator *Lob_loc1, OCILobLocator *Lob_loc2,
                         OCIEnv *envhp, OCIError *errhp, OCISvcCtx *svchp, 
                         OCIStmt *stmthp)
{
  boolean       isEqual;
  OCILobLocator *Lob_loc3;
  
  printf ("----------- OCILobIsEqual Demo --------------\n");


  /* Call OCI to see if the two locators are Equal: */
  printf (" check if Lob1 and Lob2 are Equal.\n");
  checkerr (errhp, OCILobIsEqual(envhp, Lob_loc1, Lob_loc2, &isEqual));

  if (isEqual)
  {
    /* ... The LOB locators are Equal: */
    printf(" Lob Locators are equal.\n");
  }
  else
  {
    /* ... The LOB locators are not Equal: */
    printf(" Lob Locators are NOT Equal.\n");
  }

  (void)OCIDescriptorAlloc((void *) envhp, (void **) &Lob_loc3,
                             (ub4)OCI_DTYPE_LOB, (size_t) 0, (void **) 0);

  /* Assign Lob_loc1 to Lob_loc2 thereby saving a copy of the value of the LOB
     at this point in time: */
  printf(" assign the src locator to dest locator\n");
  checkerr (errhp, OCILobLocatorAssign(svchp, errhp, Lob_loc1, &Lob_loc3)); 

  /* When you write some data to the LOB through Lob_loc1, Lob_loc2 will not
     see the newly written data whereas Lob_loc1 will see the new data: */

  /* Call OCI to see if the two locators are Equal: */
  printf (" check if Lob1 and Lob3 are Equal.\n");
  checkerr (errhp, OCILobIsEqual(envhp, Lob_loc1, Lob_loc3, &isEqual));

  if (isEqual)
  {
    /* ... The LOB locators are Equal: */
    printf(" Lob Locators are equal.\n");
  }
  else
  {
    /* ... The LOB locators are not Equal: */
    printf(" Lob Locators are NOT Equal.\n");
  }

  OCIDescriptorFree((void *)Lob_loc3, (ub4)OCI_DTYPE_LOB); 
  
  return;
}
Beispiel #14
0
static void bind_init_elem_common(oci8_bind_t *obind, VALUE svc, ub4 type)
{
    ub4 idx = 0;
    sword rv;

    do {
        rv = OCIDescriptorAlloc(oci8_envhp, (dvoid*)((dvoid**)obind->valuep + idx), type, 0, 0);
        if (rv != OCI_SUCCESS)
            oci8_env_raise(oci8_envhp, rv);
    } while (++idx < obind->maxar_sz);
}
Beispiel #15
0
boolean OCI_DescriptorAlloc
(
    CONST dvoid *parenth,
    dvoid      **descpp,
    CONST ub4    type
 )
{
    sword ret = OCIDescriptorAlloc(parenth, descpp, type, 0, NULL);

    if (OCI_SUCCESSFUL(ret))
    {
        OCI_MUTEXED_CALL(OCILib.nb_descp++)
    }

    return OCI_SUCCESSFUL(ret);
}
Beispiel #16
0
void BindParRid::descAlloc(void)
{
	for(unsigned i=0; i<_cnt; ++i)
	{
		//sword res = OCICALL(OCIDescriptorAlloc(_env, &((void**)valuep)[i], OCI_DTYPE_ROWID, 0, NULL));
		sword res = OCICALL(OCIDescriptorAlloc(_env, &valuep[i], OCI_DTYPE_ROWID, 0, NULL));
		oci_check_error(__TROTL_HERE__, _env, res);
	}
	// sword res = OCICALL(OCIArrayDescriptorAlloc(
	// 					    (void *)_env,
	// 					    (void **)&valuep,
	// 					    OCI_DTYPE_ROWID,
	// 					    _cnt,
	// 					    0,
	// 					    (void **)0));	
	// oci_check_error(__TROTL_HERE__, _env, res);
}
Beispiel #17
0
//-----------------------------------------------------------------------------
// TimestampVar_Initialize()
//   Initialize the variable.
//-----------------------------------------------------------------------------
static int TimestampVar_Initialize(
    udt_TimestampVar *var,              // variable to initialize
    udt_Cursor *cursor)                 // cursor variable associated with
{
    sword status;
    ub4 i;

    // initialize the LOB locators
    for (i = 0; i < var->allocatedElements; i++) {
        status = OCIDescriptorAlloc(var->environment->handle,
                (dvoid**) &var->data[i], OCI_DTYPE_TIMESTAMP, 0, 0);
        if (Environment_CheckForError(var->environment, status,
                "TimestampVar_Initialize()") < 0)
            return -1;
    }

    return 0;
}
Beispiel #18
0
sword OCI_DescriptorAlloc
(
    CONST dvoid *parenth,
    dvoid      **descpp,
    CONST ub4    type,
    CONST size_t xtramem_sz,
    dvoid      **usrmempp
)
{
    sword ret = OCIDescriptorAlloc(parenth, descpp, type, xtramem_sz, usrmempp);

    if (OCI_SUCCESSFUL(ret))
    {
        OCI_MUTEXED_CALL(OCILib.nb_descp++)
    }

    return ret;
}
void OraclePreparedStatement_setTimestamp(T P, int parameterIndex, time_t time) {
        assert(P);
        struct tm ts = {.tm_isdst = -1};
        ub4   valid;
        int i = checkAndSetParameterIndex(parameterIndex, P->paramCount);

        P->lastError = OCIDescriptorAlloc((dvoid *)P->env, (dvoid **) &(P->params[i].type.date),
                                          (ub4) OCI_DTYPE_TIMESTAMP,
                                          (size_t) 0, (dvoid **) 0);
        if (P->lastError != OCI_SUCCESS && P->lastError != OCI_SUCCESS_WITH_INFO)
                THROW(SQLException, "%s", OraclePreparedStatement_getLastError(P->lastError, P->err));

        gmtime_r(&time, &ts);

        OCIDateTimeConstruct(P->usr,
                             P->err,
                             P->params[i].type.date, //OCIDateTime   *datetime,
                             ts.tm_year+1900, ts.tm_mon+1, ts.tm_mday, ts.tm_hour, ts.tm_min, ts.tm_sec, 0/*fsec*/,
                             (OraText*)0, 0);
        
        if (OCI_SUCCESS != OCIDateTimeCheck(P->usr, P->err, P->params[i].type.date, &valid) || valid != 0)
        {
                THROW(SQLException, "Invalid date/time value");
        }

        P->params[i].length = sizeof(OCIDateTime *);

        P->lastError = OCIBindByPos(P->stmt, &P->params[i].bind, P->err, parameterIndex, &P->params[i].type.date, 
                                    P->params[i].length, SQLT_TIMESTAMP, 0, 0, 0, 0, 0, OCI_DEFAULT);
        if (P->lastError != OCI_SUCCESS && P->lastError != OCI_SUCCESS_WITH_INFO)
                THROW(SQLException, "%s", OraclePreparedStatement_getLastError(P->lastError, P->err));
}


void OraclePreparedStatement_setInt(T P, int parameterIndex, int x) {
        assert(P);
        int i = checkAndSetParameterIndex(parameterIndex, P->paramCount);
        P->params[i].type.integer = x;
        P->params[i].length = sizeof(x);
        P->lastError = OCIBindByPos(P->stmt, &P->params[i].bind, P->err, parameterIndex, &P->params[i].type.integer,
                                    (int)P->params[i].length, SQLT_INT, 0, 0, 0, 0, 0, OCI_DEFAULT);
        if (P->lastError != OCI_SUCCESS && P->lastError != OCI_SUCCESS_WITH_INFO)
                THROW(SQLException, "%s", OraclePreparedStatement_getLastError(P->lastError, P->err));
}
Beispiel #20
0
void OWStatement::WriteCLob( OCILobLocator** pphLocator, char* pszData )
{
    nNextCol++;

    CheckError( OCIDescriptorAlloc(
        poConnection->hEnv,
        (void**) pphLocator,
        OCI_DTYPE_LOB,
        (size_t) 0,
        (dvoid **) 0),
        hError );

    CheckError( OCILobCreateTemporary( 
        poConnection->hSvcCtx,
        poConnection->hError,
        (OCILobLocator*) *pphLocator,
        (ub4) OCI_DEFAULT,
        (ub1) OCI_DEFAULT,
        (ub1) OCI_TEMP_CLOB,
        false,
        OCI_DURATION_SESSION ),
        hError );

    ub4 nAmont = (ub4) strlen(pszData);

    CheckError( OCILobWrite(
        poConnection->hSvcCtx,
        hError,
        *pphLocator,
        (ub4*) &nAmont,
        (ub4) 1,
        (dvoid*) pszData,
        (ub4) strlen(pszData),
        (ub1) OCI_ONE_PIECE,
        (dvoid*) NULL,
        NULL,
        (ub2) 0,
        (ub1) SQLCS_IMPLICIT ),
        hError );
}
Beispiel #21
0
//-----------------------------------------------------------------------------
// LobVar_Initialize()
//   Initialize the variable.
//-----------------------------------------------------------------------------
static int LobVar_Initialize(
    udt_LobVar *var,                    // variable to initialize
    udt_Cursor *cursor)                 // cursor created by
{
    sword status;
    ub4 i;
    ub4 length;

    // initialize members
    Py_INCREF(cursor->connection);
    var->connection = cursor->connection;
    var->isFile = (var->type == &vt_BFILE);

    // initialize the LOB locators
    for (i = 0; i < var->allocatedElements; i++) {
        status = OCIDescriptorAlloc(var->environment->handle,
                (dvoid**) &var->data[i], OCI_DTYPE_LOB, 0, 0);
        if (Environment_CheckForError(var->environment, status,
                "LobVar_Initialize()") < 0)
            return -1;
        PySys_WriteStderr("LobVar_Initialize(env=%p, i=%d, lob=%p)\n",
                var->environment->handle, i, var->data[i]);

        /*
        Py_BEGIN_ALLOW_THREADS
        status = OCILobGetLength(var->connection->handle,
                var->environment->errorHandle,
                var->data[i], &length);
        Py_END_ALLOW_THREADS
        if (Environment_CheckForError(var->environment, status,
                "LobVar_InternalSize()") < 0)
            return -1;

        PySys_WriteStderr("LobVar_Initialize(lob=%p length=%d)\n",
                var->data[i], length);
        */
    }

    return 0;
}
Beispiel #22
0
sword OCI_DescriptorArrayAlloc
(
    CONST dvoid *parenth,
    dvoid      **descpp,
    CONST ub4    type,
    ub4          nb_elem,
    CONST size_t xtramem_sz,
    dvoid      **usrmempp
)
{
    sword ret = OCI_SUCCESS;

#if OCI_VERSION_COMPILE >= OCI_11_1

    if (OCILib.version_runtime >= OCI_11_1)
    {
        ret = OCIArrayDescriptorAlloc(parenth, descpp, type, nb_elem, xtramem_sz, usrmempp);

    }
    else

#endif

    {
        ub4 i;

        for (i = 0; (i < nb_elem) && (OCI_SUCCESS == ret); i++)
        {
            ret = OCIDescriptorAlloc(parenth, &descpp[i], type, xtramem_sz, usrmempp);
        }
    }

    if (OCI_SUCCESSFUL(ret))
    {
        OCI_MUTEXED_CALL(OCILib.nb_descp += nb_elem)
    }

    return ret;
}
Beispiel #23
0
sword
decriptorAllocSlice(
	OCIEnv *env,
	void *dest,
	ub4 elem_size,
	ub4 type,
	size_t length
) {
	sword rc;
	int i;
	for(i=0; i < length; i++) {
		rc = OCIDescriptorAlloc(
			env,             //CONST dvoid   *parenth,
			dest + i * elem_size, //dvoid         **descpp,
			type,                                 //ub4           type,
			0,   //size_t        xtramem_sz,
			0); //dvoid         **usrmempp);
		if(rc == OCI_ERROR) {
			return rc;
	    }
	}
	return OCI_SUCCESS;
}
Beispiel #24
0
//-----------------------------------------------------------------------------
// LobVar_Initialize()
//   Initialize the variable.
//-----------------------------------------------------------------------------
static int LobVar_Initialize(
    udt_LobVar *var,                    // variable to initialize
    udt_Cursor *cursor)                 // cursor created by
{
    sword status;
    ub4 i;

    // initialize members
    Py_INCREF(cursor->connection);
    var->connection = cursor->connection;
    var->isFile = (var->type == &vt_BFILE);

    // initialize the LOB locators
    for (i = 0; i < var->allocatedElements; i++) {
        status = OCIDescriptorAlloc(var->environment->handle,
                (dvoid**) &var->data[i], OCI_DTYPE_LOB, 0, 0);
        if (Environment_CheckForError(var->environment, status,
                "LobVar_Initialize()") < 0)
            return -1;
    }

    return 0;
}
Beispiel #25
0
void DownloadFileWithCompression(struct ORACLEALLINONE *oraAllInOne, char* pDirectory,
                                 int compressionLevel, char* pRemoteFile, char* pLocalFile,
                                 int isKeepPartial, int isResume)
{
	FILE *fp;
	sword ociResult;
	ub4 vCompressionLevel;
	ub8 vSkipBytes;
	char blobBuffer[ORA_BLOB_BUFFER_SIZE];
	oraub8 vSize;
	int zRet;
	z_stream zStrm;
	unsigned char zOut[ORA_BLOB_BUFFER_SIZE];
#ifndef _WIN32
	int showProgress;
	char progressLine[MAX_FMT_SIZE];
#endif
	int isStdUsed;
	off_t cnt;
	off_t sourceSize;
        struct stat fileStat;

	struct BINDVARIABLE oraBindsDownload[] =
	{
		{ 0, SQLT_STR,  ":directory",         pDirectory,         ORA_IDENTIFIER_SIZE + 1   },
		{ 0, SQLT_INT,  ":compression_level", &vCompressionLevel, sizeof(vCompressionLevel) },
		{ 0, SQLT_STR,  ":filename",          pRemoteFile,        MAX_FMT_SIZE              },
		{ 0, SQLT_BLOB, ":blob",              &oraAllInOne->blob, sizeof(oraAllInOne->blob) },
		{ 0, SQLT_INT,  ":skipbytes",         &vSkipBytes,        sizeof(vSkipBytes)        },
		{ 0 }
	};

	struct ORACLESTATEMENT oraStmtDownload = {
#include "downloadcompr.text"
,
		0, oraBindsDownload, NO_ORACLE_DEFINES };

	vCompressionLevel = compressionLevel;
	isStdUsed = !strcmp(pLocalFile, "-");
	if (isStdUsed)
	{
		isResume = 0;
		isKeepPartial = 1;
	}

	SetSessionAction(oraAllInOne, "GZIP_AND_DOWNLOAD: GZIP");
	if (OCIDescriptorAlloc(oraAllInOne->envhp, (void**)&oraAllInOne->blob, OCI_DTYPE_LOB, 0, 0))
	{
		ExitWithError(oraAllInOne, RET_OCIINIT, ERROR_NONE, "Failed to allocate BLOB\n");
	}

	cnt = 0;
	vSkipBytes = 0;
	if (isResume)
	{
		if (!stat(pLocalFile, &fileStat))
			vSkipBytes = cnt = fileStat.st_size;
		if (!cnt)
			isResume = 0;
	}

#ifndef _WIN32
	showProgress = 1;
	if (!isatty(STDOUT_FILENO) || isStdUsed)
		showProgress = 0;

	if (showProgress)
		start_longops_meter(oraAllInOne, 0, 1);
#endif

	PrepareStmtAndBind(oraAllInOne, &oraStmtDownload);
	ociResult = ExecuteStmt(oraAllInOne);
#ifndef _WIN32
	if (showProgress)
		stop_longops_meter();
#endif

	if (ociResult)
		ExitWithError(oraAllInOne, RET_ORA, ERROR_OCI, "Failed to compress file in oracle directory\n");

#ifndef _WIN32
	if (showProgress)
	{
		if (OCILobGetLength2(oraAllInOne->svchp[0], oraAllInOne->errhp, oraAllInOne->blob, (oraub8*)&sourceSize))
			ExitWithError(oraAllInOne, RET_ORA, ERROR_OCI, "Error getting BLOB length\n");
		strcpy(progressLine, "TRANSFER & GUNZIP: ");
		strncat(progressLine, basename(pLocalFile), MAX_FMT_SIZE - 1 - strlen(progressLine));
		start_progress_meter(progressLine, sourceSize, &cnt);
	}
#endif

	SetSessionAction(oraAllInOne, "GZIP_AND_DOWNLOAD: DOWNLOAD");
	if (!isStdUsed && (fp = fopen(pLocalFile, isResume ? "ab" : "wb")) == NULL)
	{
		ExitWithError(oraAllInOne, RET_FS, ERROR_OS, "Error opening a local file for writing\n");
	}
	if (isStdUsed)
		fp = stdout;

	zStrm.zalloc = Z_NULL;
	zStrm.zfree = Z_NULL;
	zStrm.opaque = Z_NULL;
	zStrm.avail_in = 0;
	zStrm.next_in = Z_NULL;
	zRet = inflateInit2(&zStrm, 16+MAX_WBITS);
	if (zRet != Z_OK)
	{
		if (!isStdUsed)
			fclose(fp);
		ExitWithError(oraAllInOne, RET_ZLIB, ERROR_NONE, "ZLIB initialization failed\n");
	}

	vSize = 0;
	ociResult = OCILobRead2(oraAllInOne->svchp[0], oraAllInOne->errhp, oraAllInOne->blob, &vSize, 0, 1, blobBuffer, ORA_BLOB_BUFFER_SIZE, OCI_FIRST_PIECE, 0, 0, 0, 0);
	while (ociResult == OCI_NEED_DATA || ociResult == OCI_SUCCESS)
	{
		cnt += vSize;
		zStrm.avail_in = vSize;
		zStrm.next_in = blobBuffer;
		do
		{
			zStrm.avail_out = ORA_BLOB_BUFFER_SIZE;
			zStrm.next_out = zOut;
			zRet = inflate(&zStrm, Z_NO_FLUSH);
			switch (zRet)
			{
            case Z_STREAM_ERROR:
			case Z_NEED_DICT:
			case Z_DATA_ERROR:
			case Z_MEM_ERROR:
				(void)inflateEnd(&zStrm);
				if (!isStdUsed)
					fclose(fp);
				ExitWithError(oraAllInOne, RET_ZLIB, ERROR_NONE, "ZLIB inflate failed: %d, size %d\n", zRet, vSize);
			}

			fwrite(zOut, sizeof(unsigned char), ORA_BLOB_BUFFER_SIZE - zStrm.avail_out, fp);
			if (ferror(fp))
			{
				(void)inflateEnd(&zStrm);
				if (!isStdUsed)
					fclose(fp);
				ExitWithError(oraAllInOne, RET_DONOTEXIT, ERROR_OS, "Error writing to a local file\n");
				if (!isKeepPartial)
				{
					if (unlink(pLocalFile))
						ExitWithError(oraAllInOne, RET_FS, ERROR_OS, "Could not remove partial file %s\n", pLocalFile);
				}
				ExitWithError(oraAllInOne, RET_FS, ERROR_NONE, 0);
			}
		}
		while (zStrm.avail_out == 0);

		if (ociResult == OCI_SUCCESS)
			break;
		ociResult = OCILobRead2(oraAllInOne->svchp[0], oraAllInOne->errhp, oraAllInOne->blob, &vSize, 0, 1, blobBuffer, ORA_BLOB_BUFFER_SIZE, OCI_NEXT_PIECE, 0, 0, 0, 0);
	}

#ifndef _WIN32
	if (showProgress)
		stop_progress_meter();
#endif
	inflateEnd(&zStrm);
	if (!isStdUsed)
		fclose(fp);

	if (ociResult != OCI_SUCCESS)
	{
		ExitWithError(oraAllInOne, RET_ORA, ERROR_OCI, "Error reading BLOB\n");
	}

	ReleaseStmt(oraAllInOne);
	SetSessionAction(oraAllInOne, 0);

	OCILobFreeTemporary(oraAllInOne->svchp[0], oraAllInOne->errhp, oraAllInOne->blob);

	if (OCIDescriptorFree(oraAllInOne->blob, OCI_DTYPE_LOB))
	{
		ExitWithError(oraAllInOne, RET_OCIINIT, ERROR_NONE, "Failed to free BLOB\n");
	}
	oraAllInOne->blob = 0;
}

void UploadFileWithCompression(struct ORACLEALLINONE *oraAllInOne, char* pDirectory,
                               int compressionLevel, char* pRemoteFile, char* pLocalFile,
                               int isKeepPartial, int isResume)
{
	FILE *fp;
	sword ociResult;
	char blobBuffer[ORA_BLOB_BUFFER_SIZE];
	oraub8 vSize;
	ub8 vSkippedBytes;
	char vOpenMode[3];
	ub1 piece;
	int zRet, zFlush;
	z_stream zStrm;
	unsigned char zIn[ORA_BLOB_BUFFER_SIZE];
#ifndef _WIN32
	int showProgress;
	char progressLine[MAX_FMT_SIZE];
#endif
	int isStdUsed;
	off_t cnt;
	off_t sourceSize;
	struct stat fileStat;
	int isError;
	struct ORACLEFILEATTR oracleFileAttr;

	struct BINDVARIABLE oraBindsUpload[] =
	{
		{ 0, SQLT_STR,  ":directory", pDirectory,         ORA_IDENTIFIER_SIZE + 1   },
		{ 0, SQLT_STR,  ":filename",  pRemoteFile,        MAX_FMT_SIZE              },
		{ 0, SQLT_STR,  ":openmode",  vOpenMode,          sizeof(vOpenMode)         },
		{ 0, SQLT_INT,  ":file_size", &sourceSize,        sizeof(sourceSize)        },
		{ 0, SQLT_INT,  ":skipped",   &vSkippedBytes,     sizeof(vSkippedBytes)     },
		{ 0, SQLT_BLOB, ":blob",      &oraAllInOne->blob, sizeof(oraAllInOne->blob) },
		{ 0 }
	};

	struct ORACLESTATEMENT oraStmtUpload = {
#include "uploadcompr.text"
,
		0, oraBindsUpload, NO_ORACLE_DEFINES };

	isStdUsed = !strcmp(pLocalFile, "-");
	if (isStdUsed)
		isResume = 0;

	SetSessionAction(oraAllInOne, "UPLOAD_AND_GUNZIP: UPLOAD");
	if (OCIDescriptorAlloc(oraAllInOne->envhp, (void**)&oraAllInOne->blob, OCI_DTYPE_LOB, 0, 0))
	{
		ExitWithError(oraAllInOne, RET_OCIINIT, ERROR_NONE, "Failed to allocate BLOB\n");
	}

	if (OCILobCreateTemporary(oraAllInOne->svchp[0], oraAllInOne->errhp, oraAllInOne->blob, OCI_DEFAULT, 0, OCI_TEMP_BLOB, TRUE/*cache*/, OCI_DURATION_SESSION))
	{
		ExitWithError(oraAllInOne, RET_ORA, ERROR_OCI, "Failed to create temporary BLOB\n");
	}

	piece = OCI_FIRST_PIECE;

#ifndef _WIN32
	showProgress = 1;
	if (!isatty(STDOUT_FILENO) || isStdUsed)
		showProgress = 0;
#endif

	cnt = vSkippedBytes = 0;
	if (isResume)
	{
		GetOracleFileAttr(oraAllInOne, pDirectory, pRemoteFile, &oracleFileAttr);
		if (oracleFileAttr.bExists)
			cnt = vSkippedBytes = oracleFileAttr.length;
		if (!cnt)
			isResume = 0;
	}

#ifndef _WIN32
	if (showProgress)
	{
		stat(pLocalFile, &fileStat);
		sourceSize = fileStat.st_size;
		strcpy(progressLine, "GZIP & TRANSFER: ");
		strncat(progressLine, basename(pLocalFile), MAX_FMT_SIZE - 1 - strlen(progressLine));
		start_progress_meter(progressLine, sourceSize, &cnt);
	}
#endif

	if (!isStdUsed && (fp = fopen(pLocalFile, "rb")) == NULL)
	{
		ExitWithError(oraAllInOne, RET_FS, ERROR_OS, "Error opening a local file for reading\n");
	}
	if (isStdUsed)
		fp = stdin;

	if (cnt > 0)
	{
		if (fseek(fp, cnt, SEEK_SET))
		{
			fclose(fp);
			ExitWithError(oraAllInOne, RET_FS, ERROR_OS, "Error setting reading position in a local file\n");
		}
	}

	zStrm.zalloc = Z_NULL;
	zStrm.zfree = Z_NULL;
	zStrm.opaque = Z_NULL;

	zRet = deflateInit2(&zStrm, compressionLevel ? compressionLevel : Z_DEFAULT_COMPRESSION, Z_DEFLATED, 16+MAX_WBITS, 8, Z_DEFAULT_STRATEGY);
	if (zRet != Z_OK)
	{
		if (!isStdUsed)
			fclose(fp);
		ExitWithError(oraAllInOne, RET_ZLIB, ERROR_NONE, "ZLIB initialization failed\n");
	}

	while (!feof(fp))
	{
		zStrm.avail_in = fread(zIn, sizeof(unsigned char), sizeof(zIn), fp);
		cnt += zStrm.avail_in;
		if (ferror(fp))
		{
			(void)deflateEnd(&zStrm);
			if (!isStdUsed)
				fclose(fp);
			ExitWithError(oraAllInOne, RET_FS, ERROR_OS, "Error reading from a local file\n");
		}

		zFlush = feof(fp) ? Z_FINISH : Z_NO_FLUSH;
		zStrm.next_in = zIn;

		do
		{
			zStrm.avail_out = ORA_BLOB_BUFFER_SIZE;
			zStrm.next_out = blobBuffer;
			zRet = deflate(&zStrm, zFlush);
			if (zRet != Z_OK && zRet != Z_STREAM_END && zRet != Z_BUF_ERROR)
			{
				(void)deflateEnd(&zStrm);
				if (!isStdUsed)
					fclose(fp);
				ExitWithError(oraAllInOne, RET_ZLIB, ERROR_NONE, "ZLIB deflate failed: %d, size %d\n", zRet, zStrm.avail_in);
			}

			if (zRet == Z_STREAM_END)
				piece = (piece == OCI_FIRST_PIECE) ? OCI_ONE_PIECE : OCI_LAST_PIECE;

			vSize = (piece == OCI_ONE_PIECE) ? ORA_BLOB_BUFFER_SIZE - zStrm.avail_out : 0;
			if (zStrm.avail_out == ORA_BLOB_BUFFER_SIZE)
				continue;
			ociResult = OCILobWrite2(oraAllInOne->svchp[0], oraAllInOne->errhp, oraAllInOne->blob, &vSize, 0, 1, blobBuffer, ORA_BLOB_BUFFER_SIZE - zStrm.avail_out, piece, 0, 0, 0, 0);
			if (ociResult != OCI_NEED_DATA && ociResult)
			{
				(void)deflateEnd(&zStrm);
				if (!isStdUsed)
					fclose(fp);
				ExitWithError(oraAllInOne, RET_ORA, ERROR_OCI, "Error writing to BLOB\n");
			}
			if (piece == OCI_FIRST_PIECE)
				piece = OCI_NEXT_PIECE;
		}
		while (zStrm.avail_out == 0);
	}

#ifndef _WIN32
	if (showProgress)
		stop_progress_meter();
#endif
	deflateEnd(&zStrm);
	if (!isStdUsed)
		fclose(fp);

	isError = 0;
        strcpy(vOpenMode, isResume ? "ab" : "wb");
	SetSessionAction(oraAllInOne, "UPLOAD_AND_GUNZIP: GUNZIP");

#ifndef _WIN32
	if (showProgress)
		start_longops_meter(oraAllInOne, 0, 1);
#endif

	PrepareStmtAndBind(oraAllInOne, &oraStmtUpload);
	ociResult = ExecuteStmt(oraAllInOne);
#ifndef _WIN32
	if (showProgress)
		stop_longops_meter();
#endif
	if (ociResult)
	{
		ExitWithError(oraAllInOne, RET_DONOTEXIT, ERROR_OCI, "Failed to decompress file in oracle directory\n");
		isError = 1;
	}
	else
		ReleaseStmt(oraAllInOne);
	SetSessionAction(oraAllInOne, 0);

	OCILobFreeTemporary(oraAllInOne->svchp[0], oraAllInOne->errhp, oraAllInOne->blob);

	if (OCIDescriptorFree(oraAllInOne->blob, OCI_DTYPE_LOB))
	{
		if (!isError)
			ExitWithError(oraAllInOne, RET_DONOTEXIT, ERROR_NONE, "Failed to free BLOB\n");
		isError = 1;
	}
	oraAllInOne->blob = 0;

	if (isError)
	{
		if (!isKeepPartial)
			Rm(oraAllInOne, pDirectory, pRemoteFile);
		ExitWithError(oraAllInOne, RET_ORA, ERROR_NONE, 0);
	}
}
Beispiel #26
0
/******************************************************************************
 *                                                                            *
 * Function: zbx_db_vselect                                                   *
 *                                                                            *
 * Purpose: execute a select statement                                        *
 *                                                                            *
 * Return value: data, NULL (on error) or (DB_RESULT)ZBX_DB_DOWN              *
 *                                                                            *
 ******************************************************************************/
DB_RESULT	zbx_db_vselect(const char *fmt, va_list args)
{
	char		*sql = NULL;
	DB_RESULT	result = NULL;
	double		sec = 0;

#if defined(HAVE_IBM_DB2)
	int		i;
	SQLRETURN	ret = SQL_SUCCESS;
#elif defined(HAVE_ORACLE)
	sword		err = OCI_SUCCESS;
	ub4		prefetch_rows = 200, counter;
#elif defined(HAVE_POSTGRESQL)
	char		*error = NULL;
#elif defined(HAVE_SQLITE3)
	int		ret = FAIL;
	char		*error = NULL;
#endif

	if (0 != CONFIG_LOG_SLOW_QUERIES)
		sec = zbx_time();

	sql = zbx_dvsprintf(sql, fmt, args);

	if (1 == txn_error)
	{
		zabbix_log(LOG_LEVEL_DEBUG, "ignoring query [txnlev:%d] [%s] within failed transaction", txn_level, sql);
		goto clean;
	}

	zabbix_log(LOG_LEVEL_DEBUG, "query [txnlev:%d] [%s]", txn_level, sql);

#if defined(HAVE_IBM_DB2)
	result = zbx_malloc(result, sizeof(ZBX_IBM_DB2_RESULT));
	memset(result, 0, sizeof(ZBX_IBM_DB2_RESULT));

	/* allocate a statement handle */
	if (SUCCEED != zbx_ibm_db2_success(ret = SQLAllocHandle(SQL_HANDLE_STMT, ibm_db2.hdbc, &result->hstmt)))
		goto error;

	/* directly execute the statement */
	if (SUCCEED != zbx_ibm_db2_success(ret = SQLExecDirect(result->hstmt, (SQLCHAR *)sql, SQL_NTS)))
		goto error;

	/* identify the number of output columns */
	if (SUCCEED != zbx_ibm_db2_success(ret = SQLNumResultCols(result->hstmt, &result->ncolumn)))
		goto error;

	if (0 == result->ncolumn)
		goto error;

	result->nalloc = 0;
	result->values = zbx_malloc(result->values, sizeof(char *) * result->ncolumn);
	result->values_cli = zbx_malloc(result->values_cli, sizeof(char *) * result->ncolumn);
	result->values_len = zbx_malloc(result->values_len, sizeof(SQLINTEGER) * result->ncolumn);

	for (i = 0; i < result->ncolumn; i++)
	{
		/* get the display size for a column */
		if (SUCCEED != zbx_ibm_db2_success(ret = SQLColAttribute(result->hstmt, (SQLSMALLINT)(i + 1),
				SQL_DESC_DISPLAY_SIZE, NULL, 0, NULL, &result->values_len[i])))
		{
			goto error;
		}

		result->values_len[i] += 1; /* '\0'; */

		/* allocate memory to bind a column */
		result->values_cli[i] = zbx_malloc(NULL, result->values_len[i]);
		result->nalloc++;

		/* bind columns to program variables, converting all types to CHAR */
		if (SUCCEED != zbx_ibm_db2_success(ret = SQLBindCol(result->hstmt, (SQLSMALLINT)(i + 1),
				SQL_C_CHAR, result->values_cli[i], result->values_len[i], &result->values_len[i])))
		{
			goto error;
		}
	}
error:
	if (SUCCEED != zbx_ibm_db2_success(ret) || 0 == result->ncolumn)
	{
		zbx_ibm_db2_log_errors(SQL_HANDLE_DBC, ibm_db2.hdbc);
		zbx_ibm_db2_log_errors(SQL_HANDLE_STMT, result->hstmt);

		IBM_DB2free_result(result);

		result = (SQL_CD_TRUE == IBM_DB2server_status() ? NULL : (DB_RESULT)ZBX_DB_DOWN);
	}
#elif defined(HAVE_MYSQL)
	if (NULL == conn)
	{
		zabbix_errlog(ERR_Z3003);
		result = NULL;
	}
	else
	{
		if (0 != mysql_query(conn, sql))
		{
			zabbix_errlog(ERR_Z3005, mysql_errno(conn), mysql_error(conn), sql);
			switch (mysql_errno(conn))
			{
				case CR_CONN_HOST_ERROR:
				case CR_SERVER_GONE_ERROR:
				case CR_CONNECTION_ERROR:
				case CR_SERVER_LOST:
				case ER_SERVER_SHUTDOWN:
				case ER_ACCESS_DENIED_ERROR: /* wrong user or password */
				case ER_ILLEGAL_GRANT_FOR_TABLE: /* user without any privileges */
				case ER_TABLEACCESS_DENIED_ERROR:/* user without some privilege */
				case ER_UNKNOWN_ERROR:
					result = (DB_RESULT)ZBX_DB_DOWN;
					break;
				default:
					result = NULL;
					break;
			}
		}
		else
			result = mysql_store_result(conn);
	}
#elif defined(HAVE_ORACLE)
	result = zbx_malloc(NULL, sizeof(ZBX_OCI_DB_RESULT));
	memset(result, 0, sizeof(ZBX_OCI_DB_RESULT));

	err = OCIHandleAlloc((dvoid *)oracle.envhp, (dvoid **)&result->stmthp, OCI_HTYPE_STMT, (size_t)0, (dvoid **)0);

	/* Prefetching when working with Oracle is needed because otherwise it fetches only 1 row at a time when doing */
	/* selects (default behavior). There are 2 ways to do prefetching: memory based and rows based. Based on the   */
	/* study optimal (speed-wise) memory based prefetch is 2 MB. But in case of many subsequent selects CPU usage  */
	/* jumps up to 100 %. Using rows prefetch with up to 200 rows does not affect CPU usage, it is the same as     */
	/* without prefetching at all. See ZBX-5920, ZBX-6493 for details.                                             */
	/*                                                                                                             */
	/* Tested on Oracle 11gR2.                                                                                     */
	/*                                                                                                             */
	/* Oracle info: docs.oracle.com/cd/B28359_01/appdev.111/b28395/oci04sql.htm                                    */

	if (OCI_SUCCESS == err)
	{
		err = OCIAttrSet(result->stmthp, OCI_HTYPE_STMT, &prefetch_rows, sizeof(prefetch_rows),
				OCI_ATTR_PREFETCH_ROWS, oracle.errhp);
	}

	if (OCI_SUCCESS == err)
	{
		err = OCIStmtPrepare(result->stmthp, oracle.errhp, (text *)sql, (ub4)strlen((char *)sql),
				(ub4)OCI_NTV_SYNTAX, (ub4)OCI_DEFAULT);
	}

	if (OCI_SUCCESS == err)
	{
		err = OCIStmtExecute(oracle.svchp, result->stmthp, oracle.errhp, (ub4)0, (ub4)0,
				(CONST OCISnapshot *)NULL, (OCISnapshot *)NULL,
				0 == txn_level ? OCI_COMMIT_ON_SUCCESS : OCI_DEFAULT);
	}

	if (OCI_SUCCESS == err)
	{
		/* get the number of columns in the query */
		err = OCIAttrGet((void *)result->stmthp, OCI_HTYPE_STMT, (void *)&result->ncolumn,
				  (ub4 *)0, OCI_ATTR_PARAM_COUNT, oracle.errhp);
	}

	if (OCI_SUCCESS != err)
		goto error;

	assert(0 < result->ncolumn);

	result->values = zbx_malloc(NULL, result->ncolumn * sizeof(char *));
	result->clobs = zbx_malloc(NULL, result->ncolumn * sizeof(OCILobLocator *));
	result->values_alloc = zbx_malloc(NULL, result->ncolumn * sizeof(ub4));
	memset(result->values, 0, result->ncolumn * sizeof(char *));
	memset(result->clobs, 0, result->ncolumn * sizeof(OCILobLocator *));
	memset(result->values_alloc, 0, result->ncolumn * sizeof(ub4));

	for (counter = 1; OCI_SUCCESS == err && counter <= result->ncolumn; counter++)
	{
		OCIParam	*parmdp = NULL;
		OCIDefine	*defnp = NULL;
		ub4		char_semantics;
		ub2		col_width = 0, data_type;

		/* request a parameter descriptor in the select-list */
		err = OCIParamGet((void *)result->stmthp, OCI_HTYPE_STMT, oracle.errhp, (void **)&parmdp, (ub4)counter);

		if (OCI_SUCCESS == err)
		{
			/* retrieve the data type for the column */
			err = OCIAttrGet((void *)parmdp, OCI_DTYPE_PARAM, (dvoid *)&data_type, (ub4 *)NULL,
					(ub4)OCI_ATTR_DATA_TYPE, (OCIError *)oracle.errhp);
		}

		if (SQLT_CLOB == data_type)
		{
			if (ZBX_DB_OK == err)
			{
				/* allocate the lob locator variable */
				err = OCIDescriptorAlloc((dvoid *)oracle.envhp, (dvoid **)&result->clobs[counter - 1],
						OCI_DTYPE_LOB, (size_t)0, (dvoid **)0);
			}

			if (OCI_SUCCESS == err)
			{
				/* associate clob var with its define handle */
				err = OCIDefineByPos((void *)result->stmthp, &defnp, (OCIError *)oracle.errhp,
						(ub4)counter, (dvoid *)&result->clobs[counter - 1], (sb4)-1,
						data_type, (dvoid *)0, (ub2 *)0, (ub2 *)0, (ub4)OCI_DEFAULT);
			}
		}
		else
		{
			if (OCI_SUCCESS == err)
			{
				/* retrieve the length semantics for the column */
				char_semantics = 0;
				err = OCIAttrGet((void *)parmdp, (ub4)OCI_DTYPE_PARAM, (void *)&char_semantics,
						(ub4 *)NULL, (ub4)OCI_ATTR_CHAR_USED, (OCIError *)oracle.errhp);
			}

			if (OCI_SUCCESS == err)
			{
				if (0 != char_semantics)
				{
					/* retrieve the column width in characters */
					err = OCIAttrGet((void *)parmdp, (ub4)OCI_DTYPE_PARAM, (void *)&col_width,
							(ub4 *)NULL, (ub4)OCI_ATTR_CHAR_SIZE, (OCIError *)oracle.errhp);
				}
				else
				{
					/* retrieve the column width in bytes */
					err = OCIAttrGet((void *)parmdp, (ub4)OCI_DTYPE_PARAM, (void *)&col_width,
							(ub4 *)NULL, (ub4)OCI_ATTR_DATA_SIZE, (OCIError *)oracle.errhp);
				}
			}
			col_width++;	/* add 1 byte for terminating '\0' */

			result->values_alloc[counter - 1] = col_width;
			result->values[counter - 1] = zbx_malloc(NULL, col_width);
			*result->values[counter - 1] = '\0';

			if (OCI_SUCCESS == err)
			{
				/* represent any data as characters */
				err = OCIDefineByPos(result->stmthp, &defnp, oracle.errhp, counter,
						(dvoid *)result->values[counter - 1], col_width, SQLT_STR,
						(dvoid *)0, (ub2 *)0, (ub2 *)0, OCI_DEFAULT);
			}
		}

		/* free cell descriptor */
		OCIDescriptorFree(parmdp, OCI_DTYPE_PARAM);
		parmdp = NULL;
	}

error:
	if (OCI_SUCCESS != err)
	{
		zabbix_errlog(ERR_Z3005, err, zbx_oci_error(err), sql);

		OCI_DBfree_result(result);

		result = (OCI_SERVER_NORMAL == OCI_DBserver_status() ? NULL : (DB_RESULT)ZBX_DB_DOWN);
	}
#elif defined(HAVE_POSTGRESQL)
	result = zbx_malloc(NULL, sizeof(ZBX_PG_DB_RESULT));
	result->pg_result = PQexec(conn, sql);
	result->values = NULL;
	result->cursor = 0;
	result->row_num = 0;

	if (NULL == result->pg_result)
		zabbix_errlog(ERR_Z3005, 0, "result is NULL", sql);

	if (PGRES_TUPLES_OK != PQresultStatus(result->pg_result))
	{
		error = zbx_dsprintf(error, "%s:%s",
				PQresStatus(PQresultStatus(result->pg_result)),
				PQresultErrorMessage(result->pg_result));
		zabbix_errlog(ERR_Z3005, 0, error, sql);
		zbx_free(error);

		PG_DBfree_result(result);
		result = (CONNECTION_OK == PQstatus(conn) ? NULL : (DB_RESULT)ZBX_DB_DOWN);
	}
	else	/* init rownum */
		result->row_num = PQntuples(result->pg_result);
#elif defined(HAVE_SQLITE3)
	if (0 == txn_level && PHP_MUTEX_OK != php_sem_acquire(&sqlite_access))
	{
		zabbix_log(LOG_LEVEL_CRIT, "ERROR: cannot create lock on SQLite3 database");
		exit(FAIL);
	}

	result = zbx_malloc(NULL, sizeof(ZBX_SQ_DB_RESULT));
	result->curow = 0;

lbl_get_table:
	if (SQLITE_OK != (ret = sqlite3_get_table(conn,sql, &result->data, &result->nrow, &result->ncolumn, &error)))
	{
		if (SQLITE_BUSY == ret)
			goto lbl_get_table;

		zabbix_errlog(ERR_Z3005, 0, error, sql);
		sqlite3_free(error);

		SQ_DBfree_result(result);

		switch (ret)
		{
			case SQLITE_ERROR:	/* SQL error or missing database; assuming SQL error, because if we
						   are this far into execution, zbx_db_connect() was successful */
			case SQLITE_NOMEM:	/* a malloc() failed */
			case SQLITE_MISMATCH:	/* data type mismatch */
				result = NULL;
				break;
			default:
				result = (DB_RESULT)ZBX_DB_DOWN;
				break;
		}
	}

	if (0 == txn_level)
		php_sem_release(&sqlite_access);
#endif	/* HAVE_SQLITE3 */

	if (0 != CONFIG_LOG_SLOW_QUERIES)
	{
		sec = zbx_time() - sec;
		if (sec > (double)CONFIG_LOG_SLOW_QUERIES / 1000.0)
			zabbix_log(LOG_LEVEL_WARNING, "slow query: " ZBX_FS_DBL " sec, \"%s\"", sec, sql);
	}

	if (NULL == result && 0 < txn_level)
	{
		zabbix_log(LOG_LEVEL_DEBUG, "query [%s] failed, setting transaction as failed", sql);
		txn_error = 1;
	}
clean:
	zbx_free(sql);

	return result;
}
Beispiel #27
0
int _ora_connect(database *db,char *srvname,char *username,char *password) {
t_ora * o; void *p;
//printf("Connecting???\n");
// Создаем симпле-ора, ошибки памяти не проверяем...
o = malloc( sizeof(t_ora) );
if (!o) { sprintf(db->error,"vora - no memory"); return 0;}
memset(o,0,sizeof(t_ora)); db->h = o;
db->disconnect = ora_disconnect;
db->compile = ora_compile;
db->exec = ora_exec;
db->commit = ora_commit;
db->rollback = ora_rollback;
db->open = ora_open;
db->fetch = ora_fetch;
db->bind = ora_bind;
o->envhp=env; // Copy It
// Инициализиреум envhp - "сессионный набор" (для дальнейшего ЮЗА)

OCIEnvInit( (OCIEnv **) &o->envhp, OCI_DEFAULT, (size_t) 0,(dvoid **) 0 );

debugf(" ..try connect to oracle {user:'******',pass:'******',server:'%s',env:0x%p}\n",username,password,srvname,o->envhp);
// Инитим обьект типа ошибка Оракл
OCIHandleAlloc( (dvoid *) o->envhp, (dvoid **) &o->errhp, OCI_HTYPE_ERROR,(size_t) 0, (dvoid **) 0);
debugf(".. OCIHandleAlloc errhp:0x%p\n", o->errhp);
//printf("ErrHP=%d\n",o->errhp);
// Инитим "серверОракл"
OCIHandleAlloc( (dvoid *) o->envhp, (dvoid **) &o->srvhp, OCI_HTYPE_SERVER,(size_t) 0, (dvoid **) 0);
debugf(".. OCUHandleAlloc srvhp:0x%p, attaching\n", o->srvhp);
// Следующие две команды совершенно непонятны...
if (OCI_SUCCESS!=OCIServerAttach( o->srvhp, o->errhp, (text *)srvname, strlen(srvname), OCI_DEFAULT)) {
 debugf(" -- failed Server Attach");
 ora_error(db);
 ora_disconnect(db);
 return 0;
 }

debugf(".. Server Attached... srvhp:0x%p\n", o->srvhp);

//return ora_disconnect(db);

OCIHandleAlloc( (dvoid *) o->envhp, (dvoid **) &o->svchp, OCI_HTYPE_SVCCTX,(size_t) 0, (dvoid **) 0);


// Забираем с сервера настройки для нашей сессии
OCIAttrSet( (dvoid *) o->svchp, OCI_HTYPE_SVCCTX, (dvoid *)o->srvhp,(ub4) 0, OCI_ATTR_SERVER, (OCIError *) o->errhp);
// Создаем обьет "авторизованность"
OCIHandleAlloc((dvoid *) o->envhp, (dvoid **)&o->authp,(ub4) OCI_HTYPE_SESSION, (size_t) 0, (dvoid **) 0);
// Записыавем имя пользователя
OCIAttrSet((dvoid *) o->authp, (ub4) OCI_HTYPE_SESSION,(dvoid *) username, (ub4) strlen((char *)username),
                 (ub4) OCI_ATTR_USERNAME, o->errhp);
// Записываем пароль
OCIAttrSet((dvoid *) o->authp, (ub4) OCI_HTYPE_SESSION,
       (dvoid *) password, (ub4) strlen((char *)password), (ub4) OCI_ATTR_PASSWORD, o->errhp);

// Compile statement...
OCIHandleAlloc( (dvoid *) o->envhp, (dvoid **) &o->stmt, OCI_HTYPE_STMT, (size_t) 0, (dvoid **) 0);

// Это для получения "describe" от SELECT
OCIHandleAlloc((dvoid *) o->envhp, (dvoid **) &o->dschp,
                        (ub4) OCI_HTYPE_DESCRIBE,(size_t) 0, (dvoid **) 0);

// Для блобчика готовим...
OCIDescriptorAlloc((dvoid *) o->envhp, (dvoid **) &o->blob,
                           (ub4) OCI_DTYPE_LOB, (size_t) 0, (dvoid **) 0);

OCIAttrSet((dvoid *) o->blob, (ub4) OCI_DTYPE_LOB,
       0,0, (ub4) OCI_ATTR_LOBEMPTY, o->errhp);

//OCIDescriptorAlloc((dvoid *) o->envhp, (dvoid **) &o->blob_read,
  //                         (ub4) OCI_DTYPE_LOB, (size_t) 0, (dvoid **) 0);

//OCIAttrSet((dvoid *) o->blob_read, (ub4) OCI_HTYPE_SESSION,
   //    0,0, (ub4) 0 /*OCI_ATTR_LOBEMPTY*/, o->errhp);


debugf(" initing OCISessionBegin {svchp:%p,errhp:%p,authp:%p}\n",o->svchp,o->errhp,o->authp);
if (OCI_SUCCESS!=OCISessionBegin (o->svchp,o->errhp,o->authp, OCI_CRED_RDBMS,(ub4) OCI_DEFAULT)) {
 ora_error(db);
 ora_disconnect(db);
 return 0;
 }
debugf(" ora_session inited, set some attributes\n");

//return 1;
// Его (blob) еще нужно создавать... интересно, что это за действо?
//OCILobCreateTemporary(o->svchp,o->errhp,o->blob,
   //    OCI_DEFAULT,OCI_DEFAULT,OCI_TEMP_BLOB,FALSE,OCI_DURATION_SESSION);

//OCILobCreateTemporary(o->svchp,o->errhp,o->blob_read,
   //    OCI_DEFAULT,OCI_DEFAULT,OCI_TEMP_BLOB,FALSE,OCI_DURATION_SESSION);



// Нужное какое-то подсоединение...
OCIAttrSet((dvoid *) o->svchp, (ub4) OCI_HTYPE_SVCCTX,
                   (dvoid *) o->authp, (ub4) 0,
                   (ub4) OCI_ATTR_SESSION, o->errhp);
if (0) { // Как установить аттрибут???
ub1 yes = 1;
int res;
res = OCIAttrSet((dvoid *) o->stmt, (ub4) OCI_PTYPE_DATABASE,
                   (dvoid *) &yes, (ub4) 1,
                   (ub4) OCI_ATTR_AUTOCOMMIT_DDL, o->errhp);
printf("\n ------------- Autocommit set result=%d, ok=%d\n",res, OCI_SUCCESS);
if (res) {
   {
 ora_error(db);
 ora_disconnect(db);
 return 0;
 }
  }
}


debugf(" ok, oracle sever connected\n");
return 1; // Connected OK!
}
Beispiel #28
0
// Вызывается перед первым эхеком...
int ora_check_bind(database *db) {
  int typ,len,i;
  db_col *c; void *val;
  t_ora *o = db->h;
  if(db->in.count==0) return 1; // Нету переменных, OK.
  for(i=0,c=db->in.cols; i<db->in.count; i++,c++)   {
    val=(void*)c->value; c->dbvalue = c->value; // by default -)))
    switch (c->type)
    {
      case dbInt:     typ=INT_TYPE;    len=sizeof(int); break;
      case dbDouble:  typ=SQLT_FLT;  len=sizeof(double); break;
      case dbChar:    typ=STRING_TYPE; len=c->len+1; break;
      case dbDate:    typ=DATE_TYPE; // Придется декодировать...
                      len=7; val=c->dbvalue; //c->value=(void*)c->dbtype;
                      break;
      case dbBlob:    val = c->name[0]!=':'?&o->blob_read:&o->blob;
                      if (1) { int code; ub4 lobEmpty = 0;
//                             if (o->blob) { OCIDescriptorFree(o->blob, (ub4) OCI_DTYPE_LOB); o->blob=0;}
                             if (o->blob) { OCIDescriptorFree(o->blob, (ub4) OCI_DTYPE_LOB); o->blob=0;}
                      OCIDescriptorAlloc((dvoid *) o->envhp, (dvoid **) &o->blob,
                           (ub4) OCI_DTYPE_LOB, (size_t) 0, (dvoid **) 0);
                      OCILobCreateTemporary(o->svchp,o->errhp,o->blob,
                        OCI_DEFAULT,OCI_DEFAULT,OCI_TEMP_BLOB,FALSE,OCI_DURATION_SESSION);
                            //if( code=OCILobCreateTemporary(o->svchp, o->errhp, o->blob,
                           //(ub2)0, SQLCS_IMPLICIT,
                           //OCI_TEMP_BLOB, OCI_ATTR_NOCACHE,
                           //OCI_DURATION_SESSION) )
  //{
    // (void) printf("FAILED: CreateTemporary() code=%d \n",code);
    // return 0;
  //}
                           //   code=OCIDescriptorAlloc((dvoid *) o->envhp, (dvoid **) &o->blob,
                                    //     (ub4) OCI_DTYPE_LOB, (size_t) 0, (dvoid **) 0);
                            //  printf("Created with code=%d\n",code);
                             // code=OCIAttrSet((dvoid *) o->blob, (ub4) OCI_DTYPE_LOB,
                              //    &lobEmpty, sizeof(lobEmpty),
                               //  (ub4) OCI_ATTR_LOBEMPTY, o->errhp);
                              //if (o->blob)
                              len = 0; typ = SQLT_BLOB;
                              //printf("init oblob=%d code=%d\n",o->blob,code);
                              code = OCILobTrim(o->svchp, o->errhp, o->blob,0);
  //printf("LobTrimmed %d  code=%d!\n",o->blob,code);

                      }
                       len = 0; typ = SQLT_BLOB;
                      break;
      default:        sprintf(db->error,"VORA-bind: unknown type %d pos=%d",c->type,i);
                      return 0;
    }
  //rintf("Start bind var %s\n",c->name);
  if (!ora_ok(db->err_code = OCIBindByName(o->stmt,&o->defs[db->out.count+i],
         o->errhp, (text *) c->name, -1,
              val, len, typ,  (short*)&c->null,
             (ub2 *) 0, (ub2 *) 0, (ub4) 0, (ub4 *) 0, OCI_DEFAULT)))
  {
	  ora_error(db);
	  strcat(db->error," on bind ");
	  strcat(db->error,c->name);
	  return 0;
   }
  //rintf("End bind %s\n",c->name);
  }
  return 1;
}
Beispiel #29
0
void
_gda_oracle_set_value (GValue *value, 
		       GdaOracleValue *ora_value,
		       GdaConnection *cnc)
{
	GdaTime gtime;
	GdaTimestamp timestamp;
	sb2 year;
	ub1 month;
	ub1 day;
	ub1 hour;
	ub1 min;
	ub1 sec;

	if (ora_value->indicator == -1) {
		gda_value_set_null (value);
		return;
	}

	gda_value_reset_with_type (value, ora_value->g_type);
	switch (ora_value->s_type) {
	case GDA_STYPE_INT:
		g_value_set_int (value, *((gint *) ora_value->value));
		break;
	case GDA_STYPE_STRING: {
		gchar *string_buffer, *tmp;
		
		string_buffer = (gchar *) ora_value->value;
		string_buffer [ora_value->rlen] = '\0';
		g_strchomp (string_buffer);
		//tmp = g_locale_to_utf8 (string_buffer, -1, NULL, NULL, NULL);
		//g_value_take_string (value, tmp);
		g_value_set_string (value, string_buffer);
		if (ora_value->use_callback) {
			g_free (string_buffer);
			ora_value->value = NULL;
		}
		break;
	}
	case GDA_STYPE_BOOLEAN:
		g_value_set_boolean (value, (*((gint *) ora_value->value)) ? TRUE: FALSE);
		break;
	case GDA_STYPE_DATE: {
		GDate *date;
		OCIDateGetDate ((CONST OCIDate *) ora_value->value,
				(sb2 *) &year,
				(ub1 *) &month,
				(ub1 *) &day);
		date = g_date_new_dmy (day, month, year);
		g_value_take_boxed (value, date);
		break;
	}
	case GDA_STYPE_TIME: {
		OCIDateGetTime ((CONST OCIDate *) ora_value->value,
				(ub1 *) &hour,
				(ub1 *) &min,
				(ub1 *) &sec);
		gtime.hour = hour;
		gtime.minute = min;
		gtime.second = sec;
		gda_value_set_time (value, &gtime);
		break;
	}
	case GDA_STYPE_TIMESTAMP: {
		OCIDateGetDate ((CONST OCIDate *) ora_value->value,
				(sb2 *) &year,
				(ub1 *) &month,
				(ub1 *) &day);
		OCIDateGetTime ((CONST OCIDate *) ora_value->value,
				(ub1 *) &hour,
				(ub1 *) &min,
				(ub1 *) &sec);
		timestamp.year = year;
		timestamp.month = month;
		timestamp.day = day;
		timestamp.hour = hour;
		timestamp.minute = min;
		timestamp.second = sec;
		timestamp.fraction = 0;
		timestamp.timezone = 0;
		gda_value_set_timestamp(value, &timestamp);
		break;
	}
	case GDA_STYPE_INT64:
		TO_IMPLEMENT; /* test that value fits in */
		g_value_set_int64 (value, atoll (ora_value->value));
		break;
	case GDA_STYPE_UINT64:
		TO_IMPLEMENT; /* test that value fits in */
		g_value_set_uint64 (value, atoll (ora_value->value));
		break;
	case GDA_STYPE_UINT:
		TO_IMPLEMENT; /* test that value fits in */
		g_value_set_uint (value, *((guint*) ora_value->value));
		break;
	case GDA_STYPE_FLOAT:
		g_value_set_float (value, *((gfloat*) ora_value->value));
		break;
	case GDA_STYPE_DOUBLE:
		g_value_set_double (value, *((gdouble*) ora_value->value));
		break;
	case GDA_STYPE_LONG:
		TO_IMPLEMENT;
		break;
	case GDA_STYPE_ULONG:
		TO_IMPLEMENT;
		break;
	case GDA_STYPE_NUMERIC: {
		GdaNumeric *numeric;
		gchar *tmp;
		g_assert (!ora_value->use_callback);
		
		tmp = g_malloc0 (ora_value->defined_size);
		memcpy (tmp, ora_value->value, ora_value->defined_size);
		tmp [ora_value->rlen] = '\0';
		g_strchomp (tmp);

		numeric = gda_numeric_new ();
		gda_numeric_set_from_string (numeric, tmp);
		g_free (tmp);
		gda_numeric_set_precision (numeric, ora_value->precision);
		gda_numeric_set_width (numeric, ora_value->scale);
		g_value_take_boxed (value, numeric);
		break;
	}
	case GDA_STYPE_BINARY: {
		GdaBinary *bin;

		bin = g_new0 (GdaBinary, 1);
		if (ora_value->use_callback) {		
			bin->data = ora_value->value;
			ora_value->value = NULL;
		}
		else {
			bin->data = g_new (guchar, ora_value->rlen);
			memcpy (bin->data, ora_value->value, ora_value->rlen);
		}
		bin->binary_length = ora_value->rlen;
		gda_value_take_binary (value, bin);
		break;
	}
	case GDA_STYPE_BLOB: {
		GdaBlob *blob;
		GdaBlobOp *op;
		OCILobLocator *lobloc;
		OracleConnectionData *cdata;
		gint result;

		/* REM: we need to make a "copy" of the lob locator to give to the GdaOracleblobOp object */
		cdata = (OracleConnectionData*) gda_connection_internal_get_provider_data_error (cnc, NULL);
		if (!cdata) {
			gda_connection_add_event_string (cnc, _("Invalid Oracle handle"));
			gda_value_set_null (value);
			return;
		}

		result = OCIDescriptorAlloc ((dvoid *) cdata->henv, (dvoid **) &lobloc, 
					     (ub4) gda_oracle_blob_type (ora_value->sql_type), (size_t) 0, (dvoid **) 0);
		if (gda_oracle_check_result (result, cnc, cdata, OCI_HTYPE_ERROR,
					     _("Could not allocate Lob locator"))) {
			gda_value_set_null (value);
			return;
		}

		result = OCILobAssign ((dvoid *) cdata->henv, (dvoid *) cdata->herr, ora_value->value, &lobloc);
		if (gda_oracle_check_result (result, cnc, cdata, OCI_HTYPE_ERROR,
					     _("Could not copy Lob locator"))) {
			gda_value_set_null (value);
			return;
		}

		blob = g_new0 (GdaBlob, 1);
		op = gda_oracle_blob_op_new (cnc, lobloc);
		gda_blob_set_op (blob, op);
		g_object_unref (op);

		gda_value_take_blob (value, blob);
		break;
	}
	case GDA_STYPE_CHAR: {
		TO_IMPLEMENT; /* test that value fits in */
		g_value_set_schar (value, *((gint8*) ora_value->value));
		break;
	}
	case GDA_STYPE_SHORT: {
		TO_IMPLEMENT; /* test that value fits in */
		gda_value_set_short (value, *((gint*) ora_value->value));
		break;
	}
	case GDA_STYPE_GTYPE:
		TO_IMPLEMENT;
		break;
	case GDA_STYPE_GEOMETRIC_POINT:
		TO_IMPLEMENT;
		break;
	case GDA_STYPE_NULL:
		gda_value_set_null (value);
		break;
	default:
		g_assert_not_reached ();
	}
}
int main(int argc, char *argv[])
{

  ub1 *LobReadBuf=NULL;
  ub4 *KeysValueBuf=NULL;
  OCIStmt *stmtsellochp = 0;
  OCIBind *bndv1 = 0;
  OCIDefine *defv1 = 0;
  OCILobLocator *lobloc=0;
  static text *stmt_sellocstr = (text *)"SELECT DOCUMENT FROM FOO WHERE PKEY = :MYPKEY";

  int i, j, q;                  /* loop variables */
  sword orc;                    /* Return value */
  ub4 LobSize = 0;              /* Size of Lob to be selected */
  ub4 Iter=1;                   /* How many times to repeat before exiting */
  ub4 NumRows=0;                /* Num of Rows to select in each iteration */
  ub4 trace_flag=0;             /* 0 is default, means no sql_trace */
  int UserNum=1;                /* used in multiuser tests */

  ub4 KeyStartValue=0;          /* primary key generator, derived from USERKEYRANGE * UserNum */
  ub4 KeyMaxValue=0;            /* derived from StartValue + NumRows*Iter */
  sb8 KeyValue=0;               /* random number between StartValue and MaxValue */
  int LobType;                  /* to check Lobtype = BASICFILE or SECUREFILE */
  int ReqTime;                  /* argument to GetDbTime function ReqTime=1 elasped, ReqTime=0 cpu time */

  ub4 StartTimeTot;
  ub4 StartTime;
  ub4 StartCpu;

  ub4 EndTimeTot;
  ub4 EndTime;
  ub4 EndCpu;

  ub4 ElapsedTimeTot;
  ub4 ElapsedTime;
  ub4 ElapsedCpu;

  ub4 AvgElapsed;
  ub4 AvgCpu;
  float AvgRate;



  if (argc <= 5) {
    printf("Usage: %s <uid> <pwd> <LobSize(bytes)> <NumRows> <Iteration> <UserNum> trace_flag(1|0>\n\r", argv[0]);
    exit(-1);
  }

  /* process command line args */
  LobSize=atoi(argv[3]);
  NumRows=atoi(argv[4]);
  Iter=atoi(argv[5]);

  if (argc > 6 )
    UserNum=atoi(argv[6]);                  /* Used in multiuser run, to make unique pkeys */

  if (argc > 7 )
    trace_flag=atoi(argv[7]);

  /* Allocate OCI handles */
  if (AllocateHandles(0)) {
    printf("AllocateHandles failed \n");
    exit(-1);
  }

  /* Login using argv[1] and argv[2] */
  if ( (ConnectToDb(argv[1], argv[2])) != OCI_SUCCESS ) { 
    printf("ConnectToDb failed \n");
    CheckErr(errhp, orc);
    exit(-1);
  }

  srand48(LobSize);

  printf("Using LobSize=%d bytes, NumRows=%d, calculated total memorysize=%d bytes\r\n", LobSize, NumRows, LobSize*NumRows);

  if((LobSize==0)||(NumRows<1))
  {
   printf("Parameter error\r\n");
   exit(-1);
  }

  /* Memory allocation section */
  if ( (LobReadBuf=(ub1 *)malloc(LobSize)) == NULL ) {
    printf("Error allocating memory for LobReadBuf\r\n");
    exit(-1);
  }

  /* Initialize allocated memory and setup Read buffer as 0000000 */
  memset(LobReadBuf,0,LobSize);                 /* setup Lob read buffer as 0 */

  KeyStartValue=UserNum*USERKEYRANGE;           /* Value is set as per UserNum */
  KeyMaxValue = KeyStartValue + (NumRows*Iter);


  /* SQL_TRACE section */
  if (trace_flag == 1) { 
    printf("Begin tracing...\n");
    TurnOnSqlTrace();
  }  
 
  printf("Trying to Select %d Rows with Lob size of %d Bytes)\r\n", NumRows, LobSize);
  printf("Selecting data.....please wait\r\n");

  /* allocate a statement handle for SELECT OF LOB LOCATOR  and prepare it */
  CheckErr(errhp, OCIHandleAlloc(envhp, (dvoid **) &stmtsellochp, OCI_HTYPE_STMT,
                                     (size_t) 0, (dvoid **) 0));
 
  CheckErr(errhp, OCIStmtPrepare(stmtsellochp, errhp, (CONST text *) stmt_sellocstr,
                                     strlen((char *) stmt_sellocstr), OCI_NTV_SYNTAX, OCI_DEFAULT));
 
  /* Allocate Lob Locator descriptor */ 
  CheckErr(errhp, OCIDescriptorAlloc(envhp, (dvoid **)&lobloc, (ub4) OCI_DTYPE_LOB, (size_t) 0, (dvoid **) 0)) ;
  
  CheckErr(errhp, OCIBindByName(stmtsellochp, (OCIBind **) &bndv1, errhp,
                  (text *)":MYPKEY", (sb4) 7, &KeyValue, (sb4) sizeof(ub4), SQLT_INT,
                  (dvoid *) 0, (ub2 *) 0, (ub2 *) 0, (ub4) 0, (ub4 *) 0, OCI_DEFAULT));

  CheckErr(errhp, OCIDefineByPos (stmtsellochp, (OCIDefine **) &defv1, errhp,
                  1, &lobloc, 0 , SQLT_BLOB,
                  (dvoid *)0, (ub2 *)0, (ub2 *)0, OCI_DEFAULT));

  /* Allocate and Prepare statement to get cpu and elapsed time using dbms_utility */
  PrepareDbTime();

  for (q = 0 ; q < Iter ; q ++ ) { 
     
     StartTime = GetDbTime(1);

     if ( q == 1)  {                       /* Discard q=0 as warm up */
       StartTimeTot = StartTime;
       StartCpu = GetDbTime(0);
     }

     for (i=0; i < NumRows; i++) {

         KeyValue=(lrand48 () % (KeyMaxValue-KeyStartValue)) + KeyStartValue ;

         CheckErr(errhp, OCIStmtExecute(svchp, stmtsellochp, errhp, (ub4) 1, (ub4) 0,
                         (CONST OCISnapshot *) 0, (OCISnapshot *) 0, OCI_DEFAULT));

         /*
         CheckErr(errhp, OCILobGetLength(svchp, errhp, lobloc, &LobReadLen));
         printf ("Length of the lob to read %d \n", LobReadLen);
         */

         /* Got the Locator, now start Reading data using it */
         CheckErr(errhp, OCILobRead(svchp, errhp, lobloc, &LobSize, 
                         1, &LobReadBuf[0], (ub4) LobSize, 
                         (dvoid *)0, NULL, (ub2) 0, (ub1) SQLCS_IMPLICIT));

     }

     EndTime = GetDbTime(1);

     ElapsedTime = (EndTime - StartTime)*10 ;

     printf("Elapsed time for Iter %d Select (%d rows) in msecs: %ld\n", q+1, NumRows, ElapsedTime);

  }    /* end of Iteration 'for' loop */

  EndTimeTot = EndTime;
  ElapsedTimeTot = (EndTimeTot-StartTimeTot)*10;
  
  EndCpu = GetDbTime(0);
  /* cpu time is centisecond, x10 to report in msec, not accurate, doing it for consistency */
  ElapsedCpu = (EndCpu - StartCpu) * 10;

  printf ("--------------------------------------------------------------------------- \n");
  printf("Total Elapsed time for select (%d rows) in msecs (excluding Iter 1) : %ld\n", (NumRows*(Iter-1)), ElapsedTimeTot);

  if (Iter > 1) {
    AvgElapsed=ElapsedTimeTot/(Iter-1);
    AvgCpu=ElapsedCpu/(Iter-1);
    printf("Avg Elapsed time for a Iteration (%d rows) in msecs (excluding Iter 1) : %ld\n", NumRows, AvgElapsed );
    printf("Avg CPU time for a Iteration  (%d rows) in msecs (excluding Iter 1) : %ld\n", NumRows, AvgCpu );

    /* x1000 to report in seconds from mseconds */
    AvgRate=((float)LobSize*(float)NumRows*1000)/((float)AvgElapsed*1024*1024);
    printf("Avg Read Rate for (%d rows) (excluding Iter 1) : %0.2f (Mb/sec)\n", NumRows,  AvgRate);
  }

  LobType=CheckLobType();

  if (LobType == 1)
    printf ("SECUREFILE Lob Read Test Finished (Using OCILobRead API)\n");
  else
    printf ("BASICFILE Lob Read Test Finished (Using OCILobRead API)\n");
 
  printf("Selected LobSize=%d bytes, NumRows=%d, Iter=%d \r\n", LobSize, NumRows, Iter );
  printf ("--------------------------------------------------------------------------- \n");
 
  return(0);
  
}  /* end of Main */