static int _doConnect(T C, URL_T url, char**  error) {
#undef ERROR
#define ERROR(e) do {*error = Str_dup(e); return false;} while (0)
#define ORAERROR(e) do{ *error = Str_dup(OracleConnection_getLastError(e)); return false;} while(0)
        const char *database, *username, *password;
        const char *host = URL_getHost(url);
        int port = URL_getPort(url);
        if (! (username = URL_getUser(url)))
                if (! (username = URL_getParameter(url, "user")))
                        ERROR("no username specified in URL");
        if (! (password = URL_getPassword(url)))
                if (! (password = URL_getParameter(url, "password")))
                        ERROR("no password specified in URL");
        if (! (database = URL_getPath(url)))
                ERROR("no database specified in URL");
        ++database;
        /* Create a thread-safe OCI environment with N' substitution turned on. */
        if (OCIEnvCreate(&C->env, OCI_THREADED | OCI_OBJECT | OCI_NCHAR_LITERAL_REPLACE_ON, 0, 0, 0, 0, 0, 0))
                ERROR("Create a OCI environment failed");
        /* allocate an error handle */
        if (OCI_SUCCESS != OCIHandleAlloc(C->env, (dvoid**)&C->err, OCI_HTYPE_ERROR, 0, 0))
                ERROR("Allocating error handler failed");
        /* server contexts */
        if (OCI_SUCCESS != OCIHandleAlloc(C->env, (dvoid**)&C->srv, OCI_HTYPE_SERVER, 0, 0))
                ERROR("Allocating server context failed");
        /* allocate a service handle */
        if (OCI_SUCCESS != OCIHandleAlloc(C->env, (dvoid**)&C->svc, OCI_HTYPE_SVCCTX, 0, 0))
                ERROR("Allocating service handle failed");
        StringBuffer_clear(C->sb);
        /* Oracle connect string is on the form: //host[:port]/service name */
        if (host) {
                StringBuffer_append(C->sb, "//%s", host);
                if (port > 0)
                        StringBuffer_append(C->sb, ":%d", port);
                StringBuffer_append(C->sb, "/%s", database);
        } else /* Or just service name */
                StringBuffer_append(C->sb, "%s", database);
        /* Create a server context */
        C->lastError = OCIServerAttach(C->srv, C->err, StringBuffer_toString(C->sb), StringBuffer_length(C->sb), 0);
        if (C->lastError != OCI_SUCCESS && C->lastError != OCI_SUCCESS_WITH_INFO)
                ORAERROR(C);
        /* Set attribute server context in the service context */
        C->lastError = OCIAttrSet(C->svc, OCI_HTYPE_SVCCTX, C->srv, 0, OCI_ATTR_SERVER, C->err);
        if (C->lastError != OCI_SUCCESS && C->lastError != OCI_SUCCESS_WITH_INFO)
                ORAERROR(C);
        C->lastError = OCIHandleAlloc(C->env, (void**)&C->usr, OCI_HTYPE_SESSION, 0, NULL);
        if (C->lastError != OCI_SUCCESS && C->lastError != OCI_SUCCESS_WITH_INFO)
                ORAERROR(C);
        C->lastError = OCIAttrSet(C->usr, OCI_HTYPE_SESSION, (dvoid *)username, (int)strlen(username), OCI_ATTR_USERNAME, C->err);
        if (C->lastError != OCI_SUCCESS && C->lastError != OCI_SUCCESS_WITH_INFO)
                ORAERROR(C);
        C->lastError = OCIAttrSet(C->usr, OCI_HTYPE_SESSION, (dvoid *)password, (int)strlen(password), OCI_ATTR_PASSWORD, C->err);
        if (C->lastError != OCI_SUCCESS && C->lastError != OCI_SUCCESS_WITH_INFO)
                ORAERROR(C);
        C->lastError = OCISessionBegin(C->svc, C->err, C->usr, OCI_CRED_RDBMS, OCI_DEFAULT);
        if (C->lastError != OCI_SUCCESS && C->lastError != OCI_SUCCESS_WITH_INFO)
                ORAERROR(C);
        OCIAttrSet(C->svc, OCI_HTYPE_SVCCTX, C->usr, 0, OCI_ATTR_SESSION, C->err);
        return true;
}
Exemple #2
0
static int o_init (void) /* {{{ */
{
  int status;

  if (oci_env != NULL)
    return (0);

  status = OCIEnvCreate (&oci_env,
      /* mode = */ OCI_THREADED,
      /* context        = */ NULL,
      /* malloc         = */ NULL,
      /* realloc        = */ NULL,
      /* free           = */ NULL,
      /* user_data_size = */ 0,
      /* user_data_ptr  = */ NULL);
  if (status != 0)
  {
    ERROR ("oracle plugin: OCIEnvCreate failed with status %i.", status);
    return (-1);
  }

  status = OCIHandleAlloc (oci_env, (void *) &oci_error, OCI_HTYPE_ERROR,
      /* user_data_size = */ 0, /* user_data = */ NULL);
  if (status != OCI_SUCCESS)
  {
    ERROR ("oracle plugin: OCIHandleAlloc (OCI_HTYPE_ERROR) failed "
        "with status %i.", status);
    return (-1);
  }

  return (0);
} /* }}} int o_init */
sword AllocateHandles(ub1 mymem)
{

    if (OCIEnvCreate(&envhp,
                         (ub4) OCI_DEFAULT,
                         (dvoid *)0,
                         (dvoid * (*)(dvoid *, size_t)) 0,
                         (dvoid * (*)(dvoid *, dvoid *, size_t))0,
                         (void (*)(dvoid *, dvoid *)) 0,
                         0,
                         (dvoid **) 0) != OCI_SUCCESS) {
            return OCI_ERROR;
    }
 
    /* allocate an error handle withtin the environment */
    if (OCIHandleAlloc((dvoid *) envhp, (dvoid **) &errhp,
                       (ub4) OCI_HTYPE_ERROR, (size_t) 0, (dvoid **) 0)) {
        printf("OCIHandleAlloc failed for errhp\n");
        return OCI_ERROR;
    }
    
    /* allocate a service context handle within the environment */
    if (OCIHandleAlloc((dvoid *) envhp, (dvoid **) &svchp ,
                       (ub4) OCI_HTYPE_SVCCTX, (size_t) 0, (dvoid **) 0)) {
        printf("OCIHandleAlloc failed for context\n");
        return OCI_ERROR;
    }
    
    return OCI_SUCCESS;
}
Exemple #4
0
int main(int argc, char *argv[])
{
  OCIError *errhp = NULL;

  printf("stage4: Demonstrating OCI statement caching \n");

  /* parse command line options */
  parse_options(argc, argv);
  
  checkenv(envhp, OCIEnvCreate(&envhp,                /* returned env handle */
                               OCI_THREADED,         /* initialization modes */
                               NULL, NULL, NULL, NULL, /* callbacks, context */
                               (size_t) 0,    /* extra memory size: optional */
                               (void **) NULL));    /* returned extra memory */

  /* allocate error handle
   * note: for OCIHandleAlloc(), we always check error on environment handle
   */
  checkenv(envhp, OCIHandleAlloc(envhp,                /* environment handle */
                                 (void **) &errhp,    /* returned err handle */
                                 OCI_HTYPE_ERROR,/*type of handle to allocate*/
                                 (size_t) 0,  /* extra memory size: optional */
                                 (void **) NULL));  /* returned extra memory */

  create_session_pool(envhp, errhp, &poolName, &poolNameLen);

  /* allocate auth handle
   * note: for OCIHandleAlloc(), we check error on environment handle
   */
  checkenv(envhp, OCIHandleAlloc(envhp,
                          (void **) &authp, OCI_HTYPE_AUTHINFO,
                          (size_t) 0, (void **) NULL));

  /* setup username and password */
  checkerr(errhp, OCIAttrSet(authp, OCI_HTYPE_AUTHINFO,
                             (void *) username, strlen((char *)username),
                             OCI_ATTR_USERNAME, errhp));

  checkerr(errhp, OCIAttrSet(authp, OCI_HTYPE_AUTHINFO,
                            apppassword, strlen((char *) apppassword),
                            OCI_ATTR_PASSWORD, errhp));

  spawn_threads(envhp, errhp, &thread_function);
  
  /* Destroy the session pool */
  OCISessionPoolDestroy(spoolhp, errhp, OCI_DEFAULT);

  /* clean up */
  if (authp)
    OCIHandleFree(authp, OCI_HTYPE_AUTHINFO);
  if (spoolhp)
    OCIHandleFree(spoolhp, OCI_HTYPE_SPOOL); 
  if (errhp)
    OCIHandleFree(errhp, OCI_HTYPE_ERROR);
  if (envhp)
    OCIHandleFree(envhp, OCI_HTYPE_ENV);
  
  return 0;
}
Exemple #5
0
void InitHandles() {
	if (OCIEnvCreate(&henv, OCI_DEFAULT, NULL, NULL, NULL, NULL, 0, NULL) ||
		OCIHandleAlloc(henv, (dvoid*)&hser, OCI_HTYPE_SERVER, 0, NULL) ||
		OCIHandleAlloc(henv, (dvoid*)&herr, OCI_HTYPE_ERROR, 0, NULL) ||
		OCIHandleAlloc(henv, (dvoid*)&husr, OCI_HTYPE_SESSION, 0, NULL) ||
		OCIHandleAlloc(henv, (dvoid*)&hsvc, OCI_HTYPE_SVCCTX, 0, NULL) ||
		OCIHandleAlloc(henv, (dvoid*)&hsql, OCI_HTYPE_STMT, 0, NULL)) {
		Log("initialize handles failed");
		exit(2);
	}
}
Exemple #6
0
/*************************************************************************
 *
 *	Function: sql_init_socket
 *
 *	Purpose: Establish connection to the db
 *
 *************************************************************************/
static int sql_init_socket(SQLSOCK *sqlsocket, SQL_CONFIG *config) {

	rlm_sql_oracle_sock *oracle_sock;

	if (!sqlsocket->conn) {
		sqlsocket->conn = (rlm_sql_oracle_sock *)rad_malloc(sizeof(rlm_sql_oracle_sock));
		if (!sqlsocket->conn) {
			return -1;
		}
	}
	memset(sqlsocket->conn,0,sizeof(rlm_sql_oracle_sock));

	oracle_sock = sqlsocket->conn;

	if (OCIEnvCreate(&oracle_sock->env, OCI_DEFAULT|OCI_THREADED, (dvoid *)0,
		(dvoid * (*)(dvoid *, size_t)) 0,
		(dvoid * (*)(dvoid *, dvoid *, size_t))0,
		(void (*)(dvoid *, dvoid *)) 0,
		0, (dvoid **)0 )) {
		radlog(L_ERR,"rlm_sql_oracle: Couldn't init Oracle OCI environment (OCIEnvCreate())");
		return -1;
	}

	if (OCIHandleAlloc((dvoid *) oracle_sock->env, (dvoid **) &oracle_sock->errHandle,
		(ub4) OCI_HTYPE_ERROR, (size_t) 0, (dvoid **) 0))
	{
		radlog(L_ERR,"rlm_sql_oracle: Couldn't init Oracle ERROR handle (OCIHandleAlloc())");
		return -1;
	}

	/* Allocate handles for select and update queries */
	if (OCIHandleAlloc((dvoid *)oracle_sock->env, (dvoid **) &oracle_sock->queryHandle,
				(ub4)OCI_HTYPE_STMT, (CONST size_t) 0, (dvoid **) 0))
	{
		radlog(L_ERR,"rlm_sql_oracle: Couldn't init Oracle query handles: %s",
			sql_error(sqlsocket, config));
		return -1;
	}


	if (OCILogon(oracle_sock->env, oracle_sock->errHandle, &oracle_sock->conn,
			config->sql_login, strlen(config->sql_login),
			config->sql_password,  strlen(config->sql_password),
			config->sql_db, strlen(config->sql_db)))
	{
		radlog(L_ERR,"rlm_sql_oracle: Oracle logon failed: '%s'", sql_error(sqlsocket, config));
		sql_close(sqlsocket,config);
		return -1;
	}

	return 0;
}
Exemple #7
0
void oci_init(void)
{
	function_success = SUCCESS;
    checkenv(envhp, OCIEnvCreate(&envhp,				/* returned env handle */
                                 OCI_DEFAULT,			/* initilization modes */
                                 NULL, NULL, NULL, NULL,/* callbacks, context */
                                 (size_t) 0,			/* optional extra memory size: optional */
                                 (void**) NULL));		/* returned extra memeory */

    checkenv(envhp, OCIHandleAlloc(envhp,				/* environment handle */
                                   (void **) &errhp,	/* returned err handle */
                                   OCI_HTYPE_ERROR,		/* typ of handle to allocate */
                                   (size_t) 0,			/* optional extra memory size */
                                   (void **) NULL));	/* returned extra memeory */

    if(function_success != SUCCESS)
        exit(1);
}
Exemple #8
0
char *prefix(int version)  {
if (!ora_mutex)
 { int cnt=0; int mode = /*OCI_DEFAULT*/OCI_THREADED;
 //return 0;
  ora_mutex = mutex_create();
 //printf("mutex created!\n");
   // Без этой штуки Oracle не хочет работать в потоках!
 if(1) (void) OCIInitialize((ub4)mode, (dvoid *)0,
                       (dvoid * (*)(dvoid *, size_t)) 0,
                      (dvoid * (*)(dvoid *, dvoid *, size_t))0,
                     (void (*)(dvoid *, dvoid *)) 0 );
                     //OCI_UTF16ID
 //OCIEnvNlsCreate(&env, mode , 0 , 0,0,0,0,0,OCI_UTF16ID,OCI_UTF16ID);  //my_malloc,my_realloc,	my_free,0,0); //&o->p);
 OCIEnvCreate(&env, mode , 0 , 0,0,0,0,0); //,OCI_UTF16ID,OCI_UTF16ID);  //my_malloc,my_realloc,	my_free,0,0); //&o->p);
 debugf(" created OCI:{env:0x%p,mode:%d,prefix:'_ora'\n",env,mode);
 }
return "ora_";
}
/*************************************************************************
 *
 *	Function: sql_socket_init
 *
 *	Purpose: Establish connection to the db
 *
 *************************************************************************/
static int sql_socket_init(rlm_sql_handle_t *handle, rlm_sql_config_t *config) {

	rlm_sql_oracle_conn_t *conn;

	MEM(conn = handle->conn = talloc_zero(handle, rlm_sql_oracle_conn_t));
	talloc_set_destructor((void *) conn, sql_socket_destructor);

	if (OCIEnvCreate(&conn->env, OCI_DEFAULT|OCI_THREADED, (dvoid *)0,
		(dvoid * (*)(dvoid *, size_t)) 0,
		(dvoid * (*)(dvoid *, dvoid *, size_t))0,
		(void (*)(dvoid *, dvoid *)) 0,
		0, (dvoid **)0 )) {
		radlog(L_ERR,"rlm_sql_oracle: Couldn't init Oracle OCI environment (OCIEnvCreate())");
		return -1;
	}

	if (OCIHandleAlloc((dvoid *) conn->env, (dvoid **) &conn->errHandle,
		(ub4) OCI_HTYPE_ERROR, (size_t) 0, (dvoid **) 0))
	{
		radlog(L_ERR,"rlm_sql_oracle: Couldn't init Oracle ERROR handle (OCIHandleAlloc())");
		return -1;
	}

	/* Allocate handles for select and update queries */
	if (OCIHandleAlloc((dvoid *)conn->env, (dvoid **) &conn->queryHandle,
				(ub4)OCI_HTYPE_STMT, (CONST size_t) 0, (dvoid **) 0))
	{
		radlog(L_ERR,"rlm_sql_oracle: Couldn't init Oracle query handles: %s",
			sql_error(handle, config));
		return -1;
	}


	if (OCILogon(conn->env, conn->errHandle, &conn->ctx,
			config->sql_login, strlen(config->sql_login),
			config->sql_password,  strlen(config->sql_password),
			config->sql_db, strlen(config->sql_db)))
	{
		radlog(L_ERR,"rlm_sql_oracle: Oracle logon failed: '%s'", sql_error(handle, config));
		return -1;
	}

	return 0;
}
Exemple #10
0
void ocisession::init(void)
{
	intf_ret r;
 	r.fn_ret = SUCCESS;

	if(envhp == NULL) {
		sword ret = 0;
		ret = OCIEnvCreate((OCIEnv**)&envhp,		/* returned env handle */
						   OCI_THREADED,			/* initilization modes */
						   NULL, NULL, NULL, NULL,	/* callbacks, context */
						   (size_t) 0,				/* optional extra memory size: optional */
						   (void**) NULL);			/* returned extra memeory */

		r.handle = envhp;
		checkenv(&r, ret);
		if(r.fn_ret != SUCCESS)
        throw r;
	}
}
Exemple #11
0
/*
   Allocate the environment structure for use by the SQL routines.
*/
int
cllOpenEnv( icatSessionStruct *icss ) {
    int             stat;

    OCIEnv           *p_env;
    OCISvcCtx        *p_svc;

    stat = OCIEnvCreate( ( OCIEnv ** )&p_env,
                         ( ub4 )OCI_DEFAULT,
                         ( dvoid * )0, ( dvoid * ( * )( dvoid *, size_t ) )0,
                         ( dvoid * ( * )( dvoid *, dvoid *, size_t ) )0,
                         ( void ( * )( dvoid *, dvoid * ) )0,
                         ( size_t )0, ( dvoid ** )0 );
    if ( stat != OCI_SUCCESS ) {
        rodsLog( LOG_ERROR, "cllOpenEnv: OCIEnvCreate failed" );
        return CAT_ENV_ERR;
    }

    /* Initialize handles */
    stat = OCIHandleAlloc( ( dvoid * ) p_env, ( dvoid ** ) &p_err, OCI_HTYPE_ERROR,
                           ( size_t ) 0, ( dvoid ** ) 0 );

    if ( stat != OCI_SUCCESS ) {
        rodsLog( LOG_ERROR, "cllOpenEnv: OCIHandleAlloc failed" );
        return CAT_ENV_ERR;
    }

    stat = OCIHandleAlloc( ( dvoid * ) p_env, ( dvoid ** ) &p_svc, OCI_HTYPE_SVCCTX,
                           ( size_t ) 0, ( dvoid ** ) 0 );

    if ( stat != OCI_SUCCESS ) {
        rodsLog( LOG_ERROR, "cllOpenEnv: OCIHandleAlloc failed" );
        return CAT_ENV_ERR;
    }

    icss->connectPtr = p_svc;
    icss->environPtr = p_env;

    return 0;
}
Exemple #12
0
/*
** Creates an Environment and returns it.
*/
static int create_environment (lua_State *L) {
	env_data *env = (env_data *)lua_newuserdata(L, sizeof(env_data));
	luasql_setmeta (L, LUASQL_ENVIRONMENT_OCI8);
	/* fill in structure */
	env->closed = 0;
	env->conn_counter = 0;
	env->envhp = NULL;
	env->errhp = NULL;
/* maybe OCI_SHARED and OCI_THREADED ??? */
	if (OCIEnvCreate ( &(env->envhp), (ub4)OCI_DEFAULT, (dvoid *)0,
			(dvoid * (*)(dvoid *, size_t)) 0,
			(dvoid * (*)(dvoid *, dvoid *, size_t)) 0,
			(void (*)(dvoid *, dvoid *)) 0,
			(size_t) 0,
			(dvoid **) 0))
		luasql_faildirect (L, "couldn't create environment");
	/* error handler */
	ASSERT (L, OCIHandleAlloc((dvoid *) env->envhp,
		(dvoid **) &(env->errhp), /* !!! */
		(ub4) OCI_HTYPE_ERROR, (size_t) 0, (dvoid **) 0), env->errhp);
	return 1;
}
Exemple #13
0
int db_init(char *servername, char *username, char *passwd)
{
    OCIEnvCreate(&myenvhp, OCI_THREADED|OCI_OBJECT, (dvoid *)0, 0, 0, 0,
                 (size_t)0, (dvoid **)0);
    OCIHandleAlloc((dvoid *)myenvhp, (dvoid **)&mysrvhp, OCI_HTYPE_SERVER, 0,
                   (dvoid **)0);
    OCIHandleAlloc((dvoid *)myenvhp, (dvoid **)&myerrhp, OCI_HTYPE_ERROR, 0,
                   (dvoid **)0);
    /* 服务名 */
    status = OCIServerAttach(mysrvhp, myerrhp, (const OraText*)servername,
                             strlen(servername), OCI_DEFAULT);
    if (status != OCI_SUCCESS && status != OCI_SUCCESS_WITH_INFO) {
        checkerr(status, myerrhp);
        OCIServerDetach(mysrvhp, myerrhp, OCI_DEFAULT);
        return -1;
    }
    OCIHandleAlloc((dvoid *)myenvhp, (dvoid **)&mysvchp, OCI_HTYPE_SVCCTX, 0,
                   (dvoid **)0);
    OCIAttrSet((dvoid *)mysvchp, OCI_HTYPE_SVCCTX, (dvoid *)mysrvhp, (ub4)0,
               OCI_ATTR_SERVER, myerrhp);
    OCIHandleAlloc((dvoid *)myenvhp, (dvoid **)&myusrhp, OCI_HTYPE_SESSION, 0,
                   (dvoid **)0);
    OCIAttrSet((dvoid *)myusrhp, OCI_HTYPE_SESSION, (dvoid *)username,
               (ub4)strlen(username), OCI_ATTR_USERNAME, myerrhp);
    OCIAttrSet((dvoid *)myusrhp, OCI_HTYPE_SESSION, (dvoid *)passwd,
               (ub4)strlen(passwd), OCI_ATTR_PASSWORD, myerrhp);

    if(OCISessionBegin((dvoid *)mysvchp, myerrhp, myusrhp, OCI_CRED_RDBMS,
                       OCI_DEFAULT) != OCI_SUCCESS) {
        DEBUG("Build the talking fail!\n");
        OCIHandleFree((void *)myenvhp, OCI_HTYPE_ENV);
        return -1;
    }
    OCIAttrSet((dvoid *)mysvchp, OCI_HTYPE_SVCCTX, (dvoid *)myusrhp, (ub4)0,
               OCI_ATTR_SESSION, myerrhp);
    INFO("Oracle connect successful!\n");
    return 0;
}
Exemple #14
0
OWConnection::OWConnection( const char* pszUserIn,
                            const char* pszPasswordIn,
                            const char* pszServerIn )
{
    pszUser         = CPLStrdup( pszUserIn );
    pszPassword     = CPLStrdup( pszPasswordIn );
    pszServer       = CPLStrdup( pszServerIn );
    hEnv            = NULL;
    hError          = NULL;
    hSvcCtx         = NULL;
    hDescribe       = NULL;
    hNumArrayTDO    = NULL;
    hGeometryTDO    = NULL;
    hGeoRasterTDO   = NULL;
    hElemArrayTDO   = NULL;
    hOrdnArrayTDO   = NULL;
    bSuceeeded      = false;
    nCharSize       = 1;

    // ------------------------------------------------------
    //  Operational Systems's authentication option
    // ------------------------------------------------------

    const char* pszUserId = "/";

    ub4 eCred = OCI_CRED_RDBMS;

    if( EQUAL(pszServer, "") &&
        EQUAL(pszPassword, "") &&
        EQUAL(pszUser, "") )
    {
        eCred = OCI_CRED_EXT;
    }
    else
    {
        pszUserId = pszUser;
    }

    // ------------------------------------------------------
    //  Initialize Environment handler
    // ------------------------------------------------------

    if( OCIEnvCreate( &hEnv,
        (ub4) ( OCI_DEFAULT | OCI_OBJECT | OCI_THREADED ),
        (dvoid *) 0, (dvoid * (*)(dvoid *, size_t)) 0,
        (dvoid * (*)(dvoid *, dvoid *, size_t)) 0,
        (void (*)(dvoid *, dvoid *)) 0, (size_t) 0,
        (dvoid **) 0), NULL )
    {
        return;
    }

    // ------------------------------------------------------
    //  Initialize Error handler
    // ------------------------------------------------------

    if( CheckError( OCIHandleAlloc( (dvoid *) hEnv, (dvoid **) &hError,
        OCI_HTYPE_ERROR, (size_t) 0, (dvoid **) 0), NULL ) )
    {
        return;
    }

    // ------------------------------------------------------
    //  Initialize Server Context
    // ------------------------------------------------------

    if( CheckError( OCIHandleAlloc( (dvoid *) hEnv, (dvoid **) &hSvcCtx,
        OCI_HTYPE_SVCCTX, (size_t) 0, (dvoid **) 0), hError ) )
    {
        return;
    }

    // ------------------------------------------------------
    //  Allocate Server and Authentication (Session) handler
    // ------------------------------------------------------

    if( CheckError( OCIHandleAlloc( (dvoid *) hEnv, (dvoid **) &hServer,
        (ub4) OCI_HTYPE_SERVER, (size_t) 0, (dvoid **) 0), hError ) )
    {
        return;
    }

    if( CheckError( OCIHandleAlloc((dvoid *) hEnv, (dvoid **)&hSession,
        (ub4) OCI_HTYPE_SESSION, (size_t) 0, (dvoid **) 0), hError ) )
    {
        return;
    }

    // ------------------------------------------------------
    //  Attach to the server
    // ------------------------------------------------------

    if( CheckError( OCIServerAttach( hServer, hError, (text*) pszServer,
        strlen((char*) pszServer), 0), hError ) )
    {
        return;
    }

    if( CheckError( OCIAttrSet((dvoid *) hSession, (ub4) OCI_HTYPE_SESSION,
        (dvoid *) pszUserId, (ub4) strlen( pszUserId),
        (ub4) OCI_ATTR_USERNAME, hError), hError ) )
    {
        return;
    }

    if( CheckError( OCIAttrSet((dvoid *) hSession, (ub4) OCI_HTYPE_SESSION,
        (dvoid *) pszPassword, (ub4) strlen((char *) pszPassword),
        (ub4) OCI_ATTR_PASSWORD, hError), hError ) )
    {
        return;
    }

    if( CheckError( OCIAttrSet( (dvoid *) hSvcCtx, OCI_HTYPE_SVCCTX, (dvoid *)hServer,
        (ub4) 0, OCI_ATTR_SERVER, (OCIError *) hError), hError ) )
    {
        return;
    }

    // ------------------------------------------------------
    //  Initialize Session
    // ------------------------------------------------------

    if( CheckError( OCISessionBegin(hSvcCtx, hError, hSession, eCred,
        (ub4) OCI_DEFAULT), hError ) )
    {
        return;
    }

    // ------------------------------------------------------
    //  Initialize Service
    // ------------------------------------------------------

    if( CheckError( OCIAttrSet((dvoid *) hSvcCtx, (ub4) OCI_HTYPE_SVCCTX,
        (dvoid *) hSession, (ub4) 0,
        (ub4) OCI_ATTR_SESSION, hError), hError ) )
    {
        return;
    }

    bSuceeeded = true;

    // ------------------------------------------------------
    //  Get Character Size based on current Locale
    // ------------------------------------------------------

    OCINlsNumericInfoGet( hEnv, hError,
        &nCharSize, OCI_NLS_CHARSET_MAXBYTESZ );

    // ------------------------------------------------------
    //  Get Server Version
    // ------------------------------------------------------

    char szVersionTxt[OWTEXT];

    OCIServerVersion (
        hSvcCtx,
        hError,
        (text*) szVersionTxt,
        (ub4) OWTEXT,
        (ub1) OCI_HTYPE_SVCCTX );

    nVersion = OWParseServerVersion( szVersionTxt );

    // ------------------------------------------------------
    //  Initialize/Describe types
    // ------------------------------------------------------

    CheckError( OCIHandleAlloc(
        (dvoid*) hEnv,
        (dvoid**) (dvoid*) &hDescribe,
        (ub4) OCI_HTYPE_DESCRIBE,
        (size_t) 0,
        (dvoid**) NULL ), hError );

    hNumArrayTDO    = DescribeType( SDO_NUMBER_ARRAY );
    hGeometryTDO    = DescribeType( SDO_GEOMETRY );
    hGeoRasterTDO   = DescribeType( SDO_GEORASTER );
    hElemArrayTDO   = DescribeType( SDO_ELEM_INFO_ARRAY);
    hOrdnArrayTDO   = DescribeType( SDO_ORDINATE_ARRAY);

    if( nVersion > 10 )
    {
        hPCTDO      = DescribeType( SDO_PC );
    }
}
Exemple #15
0
// open a connection to the database
void open_db_connection (TM_CONN_HNDL *conn_hndl)
{
	int		ret_val;
	TM_CONNECTION	**conn;

	// Allocate memory for the connection handle object.
	conn = (TM_CONNECTION **) conn_hndl;
	
	*conn = (TM_CONNECTION *) tman_malloc(sizeof(TM_CONNECTION));
	
	/* Initialize the environment */
	ret_val = OCIEnvCreate( &(*(TM_CONNECTION **) conn)->envhp, OCI_THREADED | OCI_OBJECT, NULL, NULL, NULL, NULL, 0, NULL);
	
	if( ret_val != OCI_SUCCESS )
	{
		printf("Internal Error: Could not create environment to open a connection to the DBMS. ");
		printf("Please contact Velara Technical Support. Shutting down...\n");
		exit(EXIT_FAILURE);
	}

	// allocate the neccessary handles to open and maintain a connection to the database
	OCIHandleAlloc ( (*conn)->envhp, &((*conn)->errhp), OCI_HTYPE_ERROR, 0, NULL);
	OCIHandleAlloc ( (*conn)->envhp, &((*conn)->svchp), OCI_HTYPE_SVCCTX, 0, NULL);
	OCIHandleAlloc ( (*conn)->envhp, &((*conn)->srvhp), OCI_HTYPE_SERVER, 0, NULL);
	OCIHandleAlloc ( (*conn)->envhp, &((*conn)->authp), OCI_HTYPE_SESSION, 0, NULL);
	
	ASSERT((*conn)->errhp);
	ASSERT((*conn)->svchp);
	ASSERT((*conn)->srvhp);
	ASSERT((*conn)->authp);

	// initialize the service context handle
	ret_val = OCIAttrSet ((*conn)->svchp, 
		OCI_HTYPE_SVCCTX, 
		(*conn)->srvhp, 
		0, 
		OCI_ATTR_SERVER, 
		(*conn)->errhp);

	if( ret_val != OCI_SUCCESS )
	{
		printf("Internal Error: Could not initialize the service context handle. ");
		printf("Please contact Velara Technical Support. Shutting down...\n");
		exit(EXIT_FAILURE);
	}
	
	// set the username in the user session handle
	ret_val = OCIAttrSet ((*conn)->authp,
		OCI_HTYPE_SESSION,
		username, 
		strlen(username), 
		OCI_ATTR_USERNAME, 
		(*conn)->errhp);

	if( ret_val != OCI_SUCCESS )
	{
		printf("Internal Error: Could not initialize the user session handle. ");
		printf("Please contact Velara Technical Support. Shutting down...\n");
		exit(EXIT_FAILURE);
	}
	
	// set the password in the user session handle
	ret_val = OCIAttrSet ((*(TM_CONNECTION **)conn)->authp, 
		OCI_HTYPE_SESSION, 
		password, 
		strlen(password), 
		OCI_ATTR_PASSWORD, 
		(*conn)->errhp);
	
	if( ret_val != OCI_SUCCESS )
	{
		printf("Internal Error: Could not initialize the user session handle. ");
		printf("Please contact Velara Technical Support. Shutting down...\n");
		exit(EXIT_FAILURE);
	}

	// attach the error handle to the server handle 
	ret_val = OCIServerAttach( (*conn)->srvhp, 
					(*conn)->errhp, 
					hostdb, 
					strlen(hostdb), 
					OCI_DEFAULT);
	
	if( ret_val != OCI_SUCCESS )
	{
		printf("Internal Error: startup failed. Unable to attach error handle to server. ");
		printf("Please contact Velara Technical Support. Shutting down...\n");
		exit (EXIT_FAILURE);
	}
	
	// log on to the database
	ret_val = OCISessionBegin ((*conn)->svchp, 
					(*conn)->errhp,
					(*conn)->authp, 
					OCI_CRED_RDBMS, 
					OCI_DEFAULT);

	if( ret_val != OCI_SUCCESS )
	{
		printf("Error: unable to log on to %s. ", hostdb);
		printf("Verify that the username and password are valid for this database.\n"); 
		exit(EXIT_FAILURE);
	}
	
	// set the user session attribute in the service context handle
	ret_val = OCIAttrSet ((*conn)->svchp,
					OCI_HTYPE_SVCCTX, 
					(*conn)->authp, 
					0, 
					OCI_ATTR_SESSION, 
					(*conn)->errhp);
	
	if( ret_val != OCI_SUCCESS )
	{
		printf("Internal Error: unable to set user session attribute in service context handle. ");
		printf("Please contact Velara Technical Support. Shutting down...\n");
		exit(EXIT_FAILURE);
	}

}
Exemple #16
0
/******************************************************************************
 *                                                                            *
 * Function: zbx_db_connect                                                   *
 *                                                                            *
 * Purpose: connect to the database                                           *
 *                                                                            *
 * Return value: ZBX_DB_OK - succefully connected                             *
 *               ZBX_DB_DOWN - database is down                               *
 *               ZBX_DB_FAIL - failed to connect                              *
 *                                                                            *
 ******************************************************************************/
int	zbx_db_connect(char *host, char *user, char *password, char *dbname, char *dbschema, char *dbsocket, int port)
{
	int		ret = ZBX_DB_OK;
#if defined(HAVE_IBM_DB2)
	char		*connect = NULL;
#elif defined(HAVE_ORACLE)
	char		*connect = NULL;
	sword		err = OCI_SUCCESS;
#elif defined(HAVE_POSTGRESQL)
	char		*cport = NULL;
	DB_RESULT	result;
	DB_ROW		row;
#endif

	txn_init = 1;

	assert(NULL != host);

#if defined(HAVE_IBM_DB2)
	connect = zbx_strdup(connect, "PROTOCOL=TCPIP;");
	if ('\0' != *host)
		connect = zbx_strdcatf(connect, "HOSTNAME=%s;", host);
	if (NULL != dbname && '\0' != *dbname)
		connect = zbx_strdcatf(connect, "DATABASE=%s;", dbname);
	if (0 != port)
		connect = zbx_strdcatf(connect, "PORT=%d;", port);
	if (NULL != user && '\0' != *user)
		connect = zbx_strdcatf(connect, "UID=%s;", user);
	if (NULL != password && '\0' != *password)
		connect = zbx_strdcatf(connect, "PWD=%s;", password);

	memset(&ibm_db2, 0, sizeof(ibm_db2));

	/* allocate an environment handle */
	if (SUCCEED != zbx_ibm_db2_success(SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &ibm_db2.henv)))
		ret = ZBX_DB_FAIL;

	/* set attribute to enable application to run as ODBC 3.0 application; */
	/* recommended for pure IBM DB2 CLI, but not required */
	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLSetEnvAttr(ibm_db2.henv, SQL_ATTR_ODBC_VERSION,
			(void *)SQL_OV_ODBC3, 0)))
		ret = ZBX_DB_FAIL;

	/* allocate a database connection handle */
	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLAllocHandle(SQL_HANDLE_DBC, ibm_db2.henv,
			&ibm_db2.hdbc)))
		ret = ZBX_DB_FAIL;

	/* connect to the database */
	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLDriverConnect(ibm_db2.hdbc, NULL, (SQLCHAR *)connect,
			SQL_NTS, NULL, 0, NULL, SQL_DRIVER_NOPROMPT)))
		ret = ZBX_DB_FAIL;

	/* set autocommit on */
  	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLSetConnectAttr(ibm_db2.hdbc, SQL_ATTR_AUTOCOMMIT,
								(SQLPOINTER)SQL_AUTOCOMMIT_ON, SQL_NTS)))
		ret = ZBX_DB_DOWN;

	/* we do not generate vendor escape clause sequences */
  	if (ZBX_DB_OK == ret && SUCCEED != zbx_ibm_db2_success(SQLSetConnectAttr(ibm_db2.hdbc, SQL_ATTR_NOSCAN,
								(SQLPOINTER)SQL_NOSCAN_ON, SQL_NTS)))
		ret = ZBX_DB_DOWN;

	/* set current schema */
	if (NULL != dbschema && '\0' != *dbschema && ZBX_DB_OK == ret)
	{
		char	*dbschema_esc;

		dbschema_esc = DBdyn_escape_string(dbschema);
		DBexecute("set current schema='%s'", dbschema_esc);
		zbx_free(dbschema_esc);
	}

	/* output error information */
	if (ZBX_DB_OK != ret)
	{
		zbx_ibm_db2_log_errors(SQL_HANDLE_ENV, ibm_db2.henv);
		zbx_ibm_db2_log_errors(SQL_HANDLE_DBC, ibm_db2.hdbc);

		zbx_db_close();
	}

	zbx_free(connect);
#elif defined(HAVE_MYSQL)
	conn = mysql_init(NULL);

	if (!mysql_real_connect(conn, host, user, password, dbname, port, dbsocket, CLIENT_MULTI_STATEMENTS))
	{
		zabbix_errlog(ERR_Z3001, dbname, mysql_errno(conn), mysql_error(conn));
		ret = ZBX_DB_FAIL;
	}

	if (ZBX_DB_OK == ret)
	{
		if (0 != mysql_select_db(conn, dbname))
		{
			zabbix_errlog(ERR_Z3001, dbname, mysql_errno(conn), mysql_error(conn));
			ret = ZBX_DB_FAIL;
		}
	}

	if (ZBX_DB_OK == ret)
	{
		DBexecute("set names utf8");
	}

	if (ZBX_DB_FAIL == ret)
	{
		switch (mysql_errno(conn))
		{
			case CR_CONN_HOST_ERROR:
			case CR_SERVER_GONE_ERROR:
			case CR_CONNECTION_ERROR:
			case CR_SERVER_LOST:
			case CR_UNKNOWN_HOST:
			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:
				ret = ZBX_DB_DOWN;
				break;
			default:
				break;
		}
	}
#elif defined(HAVE_ORACLE)
#if defined(HAVE_GETENV) && defined(HAVE_PUTENV)
	if (NULL == getenv("NLS_LANG"))
		putenv("NLS_LANG=.UTF8");
#endif
	memset(&oracle, 0, sizeof(oracle));

	/* connection string format: [//]host[:port][/service name] */

	if ('\0' != *host)
	{
		connect = zbx_strdcatf(connect, "//%s", host);
		if (0 != port)
			connect = zbx_strdcatf(connect, ":%d", port);
		if (NULL != dbname && '\0' != *dbname)
			connect = zbx_strdcatf(connect, "/%s", dbname);
	}
	else
		ret = ZBX_DB_FAIL;

	if (ZBX_DB_OK == ret)
	{
		/* initialize environment */
		err = OCIEnvCreate((OCIEnv **)&oracle.envhp, (ub4)OCI_DEFAULT,
				(dvoid *)0, (dvoid * (*)(dvoid *,size_t))0,
				(dvoid * (*)(dvoid *, dvoid *, size_t))0,
				(void (*)(dvoid *, dvoid *))0, (size_t)0, (dvoid **)0);

		if (OCI_SUCCESS != err)
		{
			zabbix_errlog(ERR_Z3001, connect, err, zbx_oci_error(err));
			ret = ZBX_DB_FAIL;
		}
	}

	if (ZBX_DB_OK == ret)
	{
		/* allocate an error handle */
		(void)OCIHandleAlloc((dvoid *)oracle.envhp, (dvoid **)&oracle.errhp, OCI_HTYPE_ERROR,
				(size_t)0, (dvoid **)0);

		/* get the session */
		err = OCILogon2(oracle.envhp, oracle.errhp, &oracle.svchp,
				(text *)user, (ub4)(NULL != user ? strlen(user) : 0),
				(text *)password, (ub4)(NULL != password ? strlen(password) : 0),
				(text *)connect, (ub4)strlen(connect),
				OCI_DEFAULT);

		if (OCI_SUCCESS != err)
		{
			zabbix_errlog(ERR_Z3001, connect, err, zbx_oci_error(err));
			ret = ZBX_DB_DOWN;
		}
		else
		{
			err = OCIAttrGet((void *)oracle.svchp, OCI_HTYPE_SVCCTX, (void *)&oracle.srvhp, (ub4 *)0,
					OCI_ATTR_SERVER, oracle.errhp);

			if (OCI_SUCCESS != err)
			{
				zabbix_errlog(ERR_Z3001, connect, err, zbx_oci_error(err));
				ret = ZBX_DB_DOWN;
			}
		}
	}

	zbx_free(connect);

	if (ZBX_DB_OK != ret)
		zbx_db_close();
#elif defined(HAVE_POSTGRESQL)
	if (0 != port)
		cport = zbx_dsprintf(cport, "%d", port);

	conn = PQsetdbLogin(host, cport, NULL, NULL, dbname, user, password);

	zbx_free(cport);

	/* check to see that the backend connection was successfully made */
	if (CONNECTION_OK != PQstatus(conn))
	{
		zabbix_errlog(ERR_Z3001, dbname, 0, PQerrorMessage(conn));
		ret = ZBX_DB_DOWN;
	}
	else
	{
		result = DBselect("select oid from pg_type where typname='bytea'");
		if (NULL != (row = DBfetch(result)))
			ZBX_PG_BYTEAOID = atoi(row[0]);
		DBfree_result(result);
	}

#ifdef HAVE_FUNCTION_PQSERVERVERSION
	ZBX_PG_SVERSION = PQserverVersion(conn);
	zabbix_log(LOG_LEVEL_DEBUG, "PostgreSQL Server version: %d", ZBX_PG_SVERSION);
#endif

	if (80100 <= ZBX_PG_SVERSION)
	{
		/* disable "nonstandard use of \' in a string literal" warning */
		DBexecute("set escape_string_warning to off");

		result = DBselect("show standard_conforming_strings");
		if (NULL != (row = DBfetch(result)))
			ZBX_PG_ESCAPE_BACKSLASH = (0 == strcmp(row[0], "off"));
		DBfree_result(result);
	}

	if (90000 <= ZBX_PG_SVERSION)
	{
		/* change the output format for values of type bytea from hex (the default) to escape */
		DBexecute("set bytea_output=escape");
	}
#elif defined(HAVE_SQLITE3)
#ifdef HAVE_FUNCTION_SQLITE3_OPEN_V2
	if (SQLITE_OK != sqlite3_open_v2(dbname, &conn, SQLITE_OPEN_READWRITE, NULL))
#else
	if (SQLITE_OK != sqlite3_open(dbname, &conn))
#endif
	{
		zabbix_errlog(ERR_Z3001, dbname, 0, sqlite3_errmsg(conn));
		sqlite3_close(conn);
		ret = ZBX_DB_DOWN;
	}
	else
	{
		char	*p, *path;

		/* do not return SQLITE_BUSY immediately, wait for N ms */
		sqlite3_busy_timeout(conn, SEC_PER_MIN * 1000);

		path = strdup(dbname);
		if (NULL != (p = strrchr(path, '/')))
			*++p = '\0';
		else
			*path = '\0';

		DBexecute("PRAGMA synchronous = 0");	/* OFF */
		DBexecute("PRAGMA temp_store = 2");	/* MEMORY */
		DBexecute("PRAGMA temp_store_directory = '%s'", path);

		zbx_free(path);
	}
#endif	/* HAVE_SQLITE3 */

	txn_init = 0;

	return ret;
}
Exemple #17
0
static void* oracle_open_conn(const DBConf *db_conf)
{
    OracleConf *cfg = db_conf->oracle;
    sword errorcode = 0;
    text version[512];
    struct ora_conn *conn = gw_malloc(sizeof(struct ora_conn));

    gw_assert(conn != NULL);
    memset(conn, 0, sizeof(struct ora_conn));

    debug("dbpool.oracle",0,"oracle_open_conn called");

    /* init OCI environment */
    errorcode = OCIEnvCreate(&conn->envp,
                             OCI_THREADED|OCI_ENV_NO_MUTEX,
                             NULL,
                             oracle_malloc,
                             oracle_realloc,
                             oracle_free,
                             0,0);
    if (errorcode != OCI_SUCCESS) {
         oracle_checkerr(NULL, errorcode);
         error(0, "Got error while OCIEnvCreate %d", errorcode);
         gw_free(conn);
         return NULL;
    }

    debug("dbpool.oracle",0,"oci environment created");

    /* allocate error handle */
    errorcode = OCIHandleAlloc(conn->envp, (dvoid**) &conn->errhp, 
                               OCI_HTYPE_ERROR, 0, 0);
    if (errorcode != OCI_SUCCESS) {
        oracle_checkerr(NULL, errorcode);
        OCIHandleFree(conn->envp, OCI_HTYPE_ENV);
        gw_free(conn);
        return NULL;
    }

    debug("dbpool.oracle",0,"oci error handle allocated");

    /* open oracle user session */
    errorcode = OCILogon(conn->envp, conn->errhp, &conn->svchp,
                         (unsigned char*)octstr_get_cstr(cfg->username), octstr_len(cfg->username),
                         (unsigned char*)octstr_get_cstr(cfg->password), octstr_len(cfg->password),
                         (unsigned char*)octstr_get_cstr(cfg->tnsname), octstr_len(cfg->tnsname));

    if (errorcode != OCI_SUCCESS) {
        oracle_checkerr(conn->errhp, errorcode);
        OCIHandleFree(conn->errhp, OCI_HTYPE_ERROR);
        OCIHandleFree(conn->envp, OCI_HTYPE_ENV);
        gw_free(conn);
        return NULL;
    }

    debug("dbpool.oracle",0,"connected to database");

    errorcode = OCIServerVersion(conn->svchp, conn->errhp, version, 
                                 sizeof(version), OCI_HTYPE_SVCCTX);
    if (errorcode != OCI_SUCCESS) {
        oracle_checkerr(conn->errhp, errorcode);
    } else {
        info(0, "Connected to: %s", version);
    }

    return conn;
}
Exemple #18
0
/* main */
int main(int argc, char* argv[])
{
	double start, total;
	sword status;

	total = get_time();

	printf("START\n");

	get_command_line_arguments(argc, argv);

	start = get_time();
	OCIEnvCreate(&envhp, OCI_THREADED | OCI_OBJECT, (dvoid *)0,  NULL, NULL, NULL, 0, (dvoid *)0);
	elapsed_time("OCIEnvCreate", start);

	start = get_time();
	OCIHandleAlloc((dvoid *) envhp, (dvoid **) &errhp, OCI_HTYPE_ERROR, (size_t) 0, (dvoid **) 0);
	OCIHandleAlloc((dvoid *) envhp, (dvoid **) &poolhp, OCI_HTYPE_CPOOL, (size_t) 0, (dvoid **) 0);
	elapsed_time("OCIHandleAlloc", start);
 
	if (!useConnectionPool)
	{
		/* CONNECT DIRECTLY TO THE SERVER */
		start = get_time();
		status = OCILogon2(
			envhp,					// envhp        (IN) A pointer to the environment where the connection pool is to be created.
			errhp,					// errhp    (IN/OUT) An error handle you can pass to OCIErrorGet() for diagnostic information in the event of an error.
			&svchp,					// svchp    (IN/OUT) Address of an OCI service context pointer. This is filled with a server and session handle.
			username,				// username     (IN) The user name used to authenticate the session. Must be in the encoding specified by the charset parameter of a previous call to OCIEnvNlsCreate().
			olen(username),			// uname_len    (IN) The length of username, in number of bytes, regardless of the encoding.
			password,				// password     (IN) The user's password. For connection pooling, if this parameter is NULL then OCILogon2() assumes that the logon is for a proxy user. It implicitly creates a proxy connection in such a case, using the pool user to authenticate the proxy user. Must be in the encoding specified by the charset parameter of a previous call to OCIEnvNlsCreate().
			olen(password),			// passwd_len   (IN) The length of password, in number of bytes, regardless of the encoding.
			database,				// dbname       (IN) For the default case, this indicates the connect string to use to connect to the Oracle Database.
			olen(database),			// dbname_len   (IN) The length of dbname. For session pooling and connection pooling, this value is returned by the OCISessionPoolCreate() or OCIConnectionPoolCreate() call respectively.
			OCI_DEFAULT				// mode         (IN) The values accepted are: OCI_DEFAULT, OCI_LOGON2_CPOOL, OCI_LOGON2_SPOOL, OCI_LOGON2_STMTCACHE, OCI_LOGON2_PROXY
			);
		elapsed_time("OCILogon2 to the server", start);
		if (status)
		{
			checkerr(errhp, status);
			exit(1);
		}

		/* DISCONNECT */
		start = get_time();
		checkerr(errhp, OCILogoff((dvoid *) svchp, errhp));
		elapsed_time("OCILogoff from the server", start);
	}

	if (useConnectionPool)
	{
		/* CREATE THE CONNECTION POOL */
		start = get_time();
		status = OCIConnectionPoolCreate(
			envhp,					// envhp        (IN) A pointer to the environment where the connection pool is to be created.
			errhp,					// errhp    (IN/OUT) An error handle you can pass to OCIErrorGet() for diagnostic information in the event of an error.
			poolhp,					// poolhp       (IN) An allocated pool handle.
			&poolName,				// poolName    (OUT) The name of the connection pool connected to.
			&poolNameLen,			// poolNameLen (OUT) The length of the string pointed to by poolName.
			database,				// dblink       (IN) Specifies the database (server) to connect to.
			olen(database),			// dblinkLen    (IN) The length of the string pointed to by dblink.
			conMin,					// connMin      (IN) Specifies the minimum number of connections in the connection pool. Valid values are 0 and above.
			conMax,					// connMax      (IN) Specifies the maximum number of connections that can be opened to the database. Once this value is reached, no more connections are opened. Valid values are 1 and above.
			conIncr,				// connIncr     (IN) Allows the application to set the next increment for connections to be opened to the database if the current number of connections are less than connMax. Valid values are 0 and above.
			appusername,			// poolUsername (IN) Connection pooling requires an implicit primary session and this attribute provides a username for that session.
			olen(appusername),		// poolUserLen  (IN) The length of poolUsername.
			apppassword,			// poolPassword (IN) The password for the username poolUsername.
			olen(apppassword),		// poolPassLen  (IN) The length of poolPassword.
			OCI_DEFAULT				// mode         (IN) The modes supported are
			);
		elapsed_time("OCIConnectionPoolCreate", start);
		if (status)
		{
			checkerr(errhp, status);
			exit(1);
		}

		/* CONNECT USING THE CONNECTION POOL */
		start = get_time();
		status = OCILogon2(
			envhp,					// envhp        (IN) A pointer to the environment where the connection pool is to be created.
			errhp,					// errhp    (IN/OUT) An error handle you can pass to OCIErrorGet() for diagnostic information in the event of an error.
			&svchp,					// svchp    (IN/OUT) Address of an OCI service context pointer. This is filled with a server and session handle.
			username,				// username     (IN) The user name used to authenticate the session. Must be in the encoding specified by the charset parameter of a previous call to OCIEnvNlsCreate().
			olen(username),			// uname_len    (IN) The length of username, in number of bytes, regardless of the encoding.
			password,				// password     (IN) The user's password. For connection pooling, if this parameter is NULL then OCILogon2() assumes that the logon is for a proxy user. It implicitly creates a proxy connection in such a case, using the pool user to authenticate the proxy user. Must be in the encoding specified by the charset parameter of a previous call to OCIEnvNlsCreate().
			olen(password),			// passwd_len   (IN) The length of password, in number of bytes, regardless of the encoding.
			poolName,				// dbname       (IN) For the default case, this indicates the connect string to use to connect to the Oracle Database.
			poolNameLen,			// dbname_len   (IN) The length of dbname. For session pooling and connection pooling, this value is returned by the OCISessionPoolCreate() or OCIConnectionPoolCreate() call respectively.
			OCI_LOGON2_CPOOL		// mode         (IN) The values accepted are: OCI_DEFAULT, OCI_LOGON2_CPOOL, OCI_LOGON2_SPOOL, OCI_LOGON2_STMTCACHE, OCI_LOGON2_PROXY
			);
		elapsed_time("OCILogon2 using the connection pool", start);
		if (status)
		{
			checkerr(errhp, status);
			exit(1);
		}

		/* DISCONNECT */
		start = get_time();
		checkerr(errhp, OCILogoff((dvoid *) svchp, errhp));
		elapsed_time("OCILogoff from the connection pool", start);

		/* DESTROY THE CONNECTION POOL */
		start = get_time();
		checkerr(errhp, OCIConnectionPoolDestroy(poolhp, errhp, OCI_DEFAULT));
		elapsed_time("OCIConnectionPoolDestroy", start);
	}

	/* FREE HANDLES */  
	start = get_time();
	checkerr(errhp, OCIHandleFree((dvoid *)poolhp, OCI_HTYPE_CPOOL));
	checkerr(errhp, OCIHandleFree((dvoid *)errhp, OCI_HTYPE_ERROR));
	elapsed_time("OCIHandleFree", start);

	printf("END\n");
	elapsed_time("Total execution time", total);

	return 0;
} 
Exemple #19
0
static void get_db_charsets(conn_info_t *params_p, ub2 *char_csid, 
                            ub2 *nchar_csid)
{
  OCIDefine  *defnp1 = (OCIDefine *) NULL;
  OCIDefine  *defnp2 = (OCIDefine *) NULL;
  oratext     parm[PARM_BUFLEN];
  oratext     value[OCI_NLS_MAXBUFSZ];
  ub2         parm_len = 0;
  ub2         value_len = 0;
  oci_t       ocistruct; 
  oci_t      *ocip = &ocistruct;
   
  *char_csid = 0;
  *nchar_csid = 0;
  memset (ocip, 0, sizeof(ocistruct));

  if (OCIEnvCreate(&ocip->envp, OCI_OBJECT, (dvoid *)0,
                   (dvoid * (*)(dvoid *, size_t)) 0,
                   (dvoid * (*)(dvoid *, dvoid *, size_t))0,
                   (void (*)(dvoid *, dvoid *)) 0,
                   (size_t) 0, (dvoid **) 0))
  {
    ocierror(ocip, (char *)"OCIEnvCreate() failed", TRUE);
  }

  if (OCIHandleAlloc((dvoid *) ocip->envp, (dvoid **) &ocip->errp,
                     (ub4) OCI_HTYPE_ERROR, (size_t) 0, (dvoid **) 0))
  {
    ocierror(ocip, (char *)"OCIHandleAlloc(OCI_HTYPE_ERROR) failed", TRUE);
  }

  OCICALL(ocip, 
          OCILogon(ocip->envp, ocip->errp, &ocip->svcp,
                   params_p->user, params_p->userlen,
                   params_p->passw, params_p->passwlen,
                   params_p->dbname, params_p->dbnamelen));

  OCICALL(ocip, 
          OCIHandleAlloc((dvoid *) ocip->envp, (dvoid **) &ocip->stmtp,
                         (ub4) OCI_HTYPE_STMT, (size_t) 0, (dvoid **) 0));

  /* Execute stmt to select the db nls char and nchar character set */ 
  OCICALL(ocip, 
          OCIStmtPrepare(ocip->stmtp, ocip->errp,
                         (CONST text *)GET_DB_CHARSETS,
                         (ub4)strlen((char *)GET_DB_CHARSETS),
                         (ub4)OCI_NTV_SYNTAX, (ub4)OCI_DEFAULT));

  OCICALL(ocip,
          OCIDefineByPos(ocip->stmtp, &defnp1,
                         ocip->errp, (ub4) 1, parm,
                         PARM_BUFLEN, SQLT_CHR, (void*) 0,
                         &parm_len, (ub2 *)0, OCI_DEFAULT));

  OCICALL(ocip,
          OCIDefineByPos(ocip->stmtp, &defnp2,
                         ocip->errp, (ub4) 2, value,
                         OCI_NLS_MAXBUFSZ, SQLT_CHR, (void*) 0,
                         &value_len, (ub2 *)0, OCI_DEFAULT));

  OCICALL(ocip, 
          OCIStmtExecute(ocip->svcp, ocip->stmtp, 
                         ocip->errp, (ub4)0, (ub4)0, 
                         (const OCISnapshot *)0,
                         (OCISnapshot *)0, (ub4)OCI_DEFAULT));

  while (OCIStmtFetch(ocip->stmtp, ocip->errp, 1,
                      OCI_FETCH_NEXT, OCI_DEFAULT) == OCI_SUCCESS)
  {
    value[value_len] = '\0';
    if (parm_len == strlen("NLS_CHARACTERSET") &&
        !memcmp(parm, "NLS_CHARACTERSET", parm_len))
    {
      *char_csid = OCINlsCharSetNameToId(ocip->envp, value);
      printf("Outbound database NLS_CHARACTERSET = %.*s (csid = %d) \n",
             value_len, value, *char_csid);
    }
    else if (parm_len == strlen("NLS_NCHAR_CHARACTERSET") &&
             !memcmp(parm, "NLS_NCHAR_CHARACTERSET", parm_len))
    {
      *nchar_csid = OCINlsCharSetNameToId(ocip->envp, value);
      printf("Outbound database NLS_NCHAR_CHARACTERSET = %.*s (csid = %d) \n",
             value_len, value, *nchar_csid);
    }
  }

  disconnect_db(ocip);
}
Exemple #20
0
void
Init_oci8lib()
{
    VALUE cOCI8;
    OCIEnv *envhp;
    OCIError *errhp;
    sword rv;

#ifdef RUNTIME_API_CHECK
    Init_oci8_apiwrap();
    if (oracle_client_version < ORAVER_9_0) {
        rb_raise(rb_eLoadError, "Oracle 8 (8.0) and Oracle 8i (8.1) is not supported anymore!");
    }

    if (have_OCIClientVersion) {
        sword major, minor, update, patch, port_update;
        OCIClientVersion(&major, &minor, &update, &patch, &port_update);
        oracle_client_version = ORAVERNUM(major, minor, update, patch, port_update);
    }
#endif

    oci8_id_at_last_error = rb_intern("@last_error");
    oci8_id_new = rb_intern("new");
    oci8_id_get = rb_intern("get");
    oci8_id_set = rb_intern("set");
    oci8_id_oci8_vtable = rb_intern("__oci8_vtable__");
#ifdef CHAR_IS_NOT_A_SHORTCUT_TO_ID
    oci8_id_add_op = rb_intern("+");
    oci8_id_sub_op = rb_intern("-");
    oci8_id_mul_op = rb_intern("*");
    oci8_id_div_op = rb_intern("/");
#endif
#ifdef HAVE_RB_SET_END_PROC
    rb_set_end_proc(at_exit_func, Qnil);
#endif

    Init_oci8_thread_util();
    Init_oci8_error();
    Init_oci8_env();

    /* OCIHandle class */
    Init_oci8_handle();

    /* OCI8 class */
    Init_oci8(&cOCI8);

    /* OCI8::ConnectionPool class */
    Init_oci8_connection_pool(cOCI8);

    /* OCI8::BindType module */
    mOCI8BindType = rb_define_module_under(cOCI8, "BindType");
    /* OCI8::BindType::Base class */
    cOCI8BindTypeBase = rb_define_class_under(mOCI8BindType, "Base", oci8_cOCIHandle);

    /* Handle */
    Init_oci8_bind(cOCI8BindTypeBase);
    Init_oci8_stmt(cOCI8);

    /* Encoding */
    Init_oci8_encoding(cOCI8);

    /* register allocators */
    Init_oci8_metadata(cOCI8);
    Init_oci8_lob(cOCI8);

    /* allocate a temporary errhp to pass Init_oci_number() */
    rv = OCIEnvCreate(&envhp, oci8_env_mode, NULL, NULL, NULL, NULL, 0, NULL);
    if (rv != OCI_SUCCESS) {
        oci8_raise_init_error();
    }
    rv = OCIHandleAlloc(envhp, (dvoid *)&errhp, OCI_HTYPE_ERROR, 0, NULL);
    if (rv != OCI_SUCCESS)
        oci8_env_raise(envhp, rv);
    Init_oci_number(cOCI8, errhp);
    OCIHandleFree(errhp, OCI_HTYPE_ERROR);
    OCIHandleFree(envhp, OCI_HTYPE_ENV);

    Init_ora_date();
    Init_oci_datetime();
    Init_oci_object(cOCI8);

#ifdef USE_WIN32_C
    Init_oci8_win32(cOCI8);
#endif
}
Exemple #21
0
OracleDbConnection *FC_FUNC_(oraclesim_init, ORACLESIM_INIT)
     (char *username, char *password, char *dbname, int *err) {
  sword status;
  OracleDbConnection *dbconnid;

  if ((dbconnid = (OracleDbConnection *) malloc(sizeof(OracleDbConnection)))
      == NULL) {
    *err = 1;
    return dbconnid;
  }

  dbconnid->envhp = NULL;
  dbconnid->errhp = NULL;
  dbconnid->svchp = NULL;
  dbconnid->stmthp = NULL;
  dbconnid->defn1p = NULL;
  dbconnid->defn2p = NULL; 
  dbconnid->defn3p = NULL;
  dbconnid->defn4p = NULL;
  dbconnid->defn5p = NULL;
  dbconnid->defn6p = NULL;
  dbconnid->defn7p = NULL;
  dbconnid->defn8p = NULL;
  dbconnid->bnd1p = NULL;
  dbconnid->bnd2p = NULL;
  dbconnid->bnd3p = NULL;
  dbconnid->bnd4p = NULL;
  dbconnid->table[0] = 0;
  dbconnid->errmsg[0] = 0;

  if ((status = OCIEnvCreate((OCIEnv **) &dbconnid->envhp, (ub4) OCI_DEFAULT,
			     (dvoid *) 0, (dvoid * (*)(dvoid *,size_t)) 0,
			     (dvoid * (*)(dvoid *, dvoid *, size_t)) 0,
			     (void (*)(dvoid *, dvoid *)) 0, (size_t) 0,
			     (dvoid **) 0)) != OCI_SUCCESS) {
    snprintf(dbconnid->errmsg, MSGLEN, 
	     "Oracle error - OCIEnvCreate failed with status = %d", status);
    *err = 2;
  }
  /* Alloco l'error handle */
  else if (checkerr(NULL, OCIHandleAlloc(dbconnid->envhp,
					 (dvoid **) &dbconnid->errhp,
					 OCI_HTYPE_ERROR, (size_t) 0, (dvoid **) 0))
	   != OCI_SUCCESS) *err = 3;
  /* Mi connetto */
  else if (checkerr(dbconnid, OCILogon(dbconnid->envhp, dbconnid->errhp,
				       &dbconnid->svchp,
				       (text *) username, strlen(username),
				       (text *) password, strlen(password),
				       (text *) dbname, strlen(dbname)))
	   != OCI_SUCCESS) *err = 4;
  /* Alloco lo statement handle */
  else if (checkerr(dbconnid, OCIHandleAlloc(dbconnid->envhp,
					    (dvoid **) &dbconnid->stmthp,
					     OCI_HTYPE_STMT, (size_t) 0,
					     (dvoid **) 0))
	   != OCI_SUCCESS) *err = 5;
  else
    *err = 0;
  return dbconnid;

}
Exemple #22
0
/*
 * Create a new connection structure,
 * open the Oracle connection and set reference count to 1
 */
ora_con_t* db_oracle_new_connection(const struct db_id* id)
{
	ora_con_t* con;
	char buf[512];
	size_t uri_len;
	sword status;

	if (!id || !id->username || !*id->username || !id->password ||
		!*id->password || !id->database || !*id->database)
	{
bad_param:
		LM_ERR("invalid parameter value\n");
		return NULL;
	}


	if (!id->host || !*id->host) {
		if (id->port) goto bad_param;
		uri_len = snprintf(buf, sizeof(buf), "%s", id->database);
	} else if (id->port) {
		uri_len = snprintf(buf, sizeof(buf), "%s:%u/%s",
				id->host, id->port, id->database);
	} else {
		uri_len = snprintf(buf, sizeof(buf), "%s/%s",
				id->host, id->database);
	}
	if (uri_len >= sizeof(buf)) goto bad_param;
	LM_DBG("opening connection: oracle://xxxx:xxxx@%s\n", buf);

	con = (ora_con_t*)pkg_malloc(sizeof(*con) + uri_len+1);
	if (!con) {
		LM_ERR("no private memory left\n");
		return NULL;
	}

	memset(con, 0, sizeof(*con));
	con->hdr.ref = 1;
	con->hdr.id = (struct db_id*)id;	/* set here - freed on error */
	con->uri_len = uri_len;
	memcpy(con->uri, buf, uri_len+1);

	if (   OCIEnvCreate(&con->envhp,
			OCI_DEFAULT | OCI_NEW_LENGTH_SEMANTICS,
            		NULL, NULL, NULL, NULL, 0, NULL) != OCI_SUCCESS
	    || OCIHandleAlloc(con->envhp, (dvoid**)(dvoid*)&con->errhp,
		    OCI_HTYPE_ERROR, 0, NULL) != OCI_SUCCESS
	    || OCIHandleAlloc(con->envhp, (dvoid**)(dvoid*)&con->srvhp,
		    OCI_HTYPE_SERVER, 0, NULL) != OCI_SUCCESS
	    || OCIHandleAlloc(con->envhp, (dvoid**)(dvoid*)&con->svchp,
		    OCI_HTYPE_SVCCTX, 0, NULL) != OCI_SUCCESS
	    || OCIHandleAlloc(con->envhp, (dvoid**)(dvoid*)&con->authp,
        	    OCI_HTYPE_SESSION, 0, NULL) != OCI_SUCCESS)
	{

		LM_ERR("no oracle memory left\n");
		db_oracle_free_connection(con);
		return NULL;
	}

	status = OCIAttrSet(con->svchp, OCI_HTYPE_SVCCTX, con->srvhp, 0,
			OCI_ATTR_SERVER, con->errhp);
	if (status != OCI_SUCCESS) goto connect_err;
	status = OCIAttrSet(con->authp, OCI_HTYPE_SESSION,
                 id->username, (ub4)strlen(id->username),
                 OCI_ATTR_USERNAME, con->errhp);
	if (status != OCI_SUCCESS) goto connect_err;
	status = OCIAttrSet(con->authp, OCI_HTYPE_SESSION,
                 id->password, (ub4)strlen(id->password),
                 OCI_ATTR_PASSWORD, con->errhp);
	if (status != OCI_SUCCESS) goto connect_err;
	status = OCIAttrSet(con->svchp, OCI_HTYPE_SVCCTX, con->authp, 0,
                   OCI_ATTR_SESSION, con->errhp);
	if (status != OCI_SUCCESS) goto connect_err;
	status = db_oracle_reconnect(con);
	if (status != OCI_SUCCESS) {
connect_err:
		if (   (status != OCI_ERROR && status != OCI_SUCCESS_WITH_INFO)
		    || OCIErrorGet(con->errhp, 1, NULL, &status, (OraText*)buf,
			    sizeof(buf), OCI_HTYPE_ERROR) != OCI_SUCCESS)
		{
			LM_ERR("internal driver error\n");
		} else {
			LM_ERR("driver: %s\n", buf);
		}
drop_connection:
		db_oracle_free_connection(con);
		return NULL;
	}

	// timelimited operation
	status = begin_timelimit(con, 0);
	if (status != OCI_SUCCESS) goto connect_err;
	do status = OCIServerVersion(con->svchp, con->errhp, (OraText*)buf,
		(ub4)sizeof(buf), OCI_HTYPE_SVCCTX);
	while (wait_timelimit(con, status));
	if (done_timelimit(con, status)) goto drop_connection;
	if (status != OCI_SUCCESS) goto connect_err;
	LM_INFO("server version is %s\n", buf);
	return con;
}
Exemple #23
0
void* COracleDB::oracle_connect( const char* addr, const unsigned short port, const char *user, const char* pass,
		const char* db_name )
{
	char service[256] = {0};
	sprintf( service, "//%s:%d/%s", addr, port, db_name );

	ORACLE_HANDLE* handle = new ORACLE_HANDLE;

	memset( handle, 0, sizeof(ORACLE_HANDLE) );

	int status = 0;

	OCIEnvCreate( ( OCIEnv ** ) & ( handle->envhp ), ( ub4 ) OCI_THREADED, ( dvoid * ) 0,
			( dvoid * (*)( dvoid *, size_t )) 0, (dvoid * (*)(dvoid *, dvoid *, size_t))0,
			(void (*)(dvoid *, dvoid *)) 0 , (size_t) 0, (dvoid **) 0 );

	( void ) OCIHandleAlloc( ( dvoid * ) ( handle->envhp ), ( dvoid ** ) & ( handle->errhp ), OCI_HTYPE_ERROR,
			( size_t ) 0, ( dvoid ** ) 0 );

	/* server contexts */
	( void ) OCIHandleAlloc( ( dvoid * ) ( handle->envhp ), ( dvoid ** ) & ( handle->srvhp ), OCI_HTYPE_SERVER,
			( size_t ) 0, ( dvoid ** ) 0 );

	// service context
	( void ) OCIHandleAlloc( ( dvoid * ) ( handle->envhp ), ( dvoid ** ) & ( handle->svchp ), OCI_HTYPE_SVCCTX,
			( size_t ) 0, ( dvoid ** ) 0 );

	status = OCIServerAttach( handle->srvhp, handle->errhp, ( text * ) service, strlen( ( const char * ) service ), 0 );

	status = checkerr( handle->errhp, status, _errinfo );

	if ( status != 0 ) {
		_handle = handle;
		oracle_close();
		_handle = NULL;

		return NULL;
	}

	/* set attribute server context in the service context */
	OCIAttrSet( ( dvoid * ) handle->svchp, OCI_HTYPE_SVCCTX, ( dvoid * ) handle->srvhp, ( ub4 ) 0, OCI_ATTR_SERVER,
			( OCIError * ) handle->errhp );

	OCIHandleAlloc( ( dvoid * ) handle->envhp, ( dvoid ** ) & ( handle->authp ), ( ub4 ) OCI_HTYPE_SESSION,
			( size_t ) 0, ( dvoid ** ) 0 );

	( void ) OCIAttrSet( ( dvoid * ) handle->authp, ( ub4 ) OCI_HTYPE_SESSION, ( dvoid * ) user,
			( ub4 ) strlen( ( char * ) user ), ( ub4 ) OCI_ATTR_USERNAME, handle->errhp );

	OCIAttrSet( ( dvoid * ) handle->authp, ( ub4 ) OCI_HTYPE_SESSION, ( dvoid * ) pass,
			( ub4 ) strlen( ( char * ) pass ), ( ub4 ) OCI_ATTR_PASSWORD, handle->errhp );

	status = OCISessionBegin( handle->svchp, handle->errhp, handle->authp, OCI_CRED_RDBMS, ( ub4 ) OCI_DEFAULT );

	status = checkerr( handle->errhp, status, _errinfo );

	if ( status != 0 ) {
		_handle = handle;
		oracle_close();
		_handle = NULL;

		return NULL;
	}

	status = OCIAttrSet( ( dvoid * ) ( handle->svchp ), ( ub4 ) OCI_HTYPE_SVCCTX, ( dvoid * ) ( handle->authp ),
			( ub4 ) 0, ( ub4 ) OCI_ATTR_SESSION, handle->errhp );

	status = checkerr( handle->errhp, status, _errinfo );

	if ( status ) {
		_handle = handle;
		oracle_close();
		_handle = NULL;

		return NULL;
	}

	status = OCIHandleAlloc( ( dvoid * ) ( handle->envhp ), ( dvoid ** ) & ( handle->stmthp ), OCI_HTYPE_STMT,
			( size_t ) 0, ( dvoid ** ) 0 );

	status = checkerr( handle->errhp, status, _errinfo );

	if ( status ) {
		_handle = handle;
		oracle_close();
		_handle = NULL;

		return NULL;
	}

	/*
	 OCIAttrSet ( handle->srvhp, (ub4) OCI_HTYPE_SERVER,
	 (dvoid *) 0, (ub4) 0,
	 (ub4) OCI_ATTR_NONBLOCKING_MODE, handle->errhp) ;
	 */
	return ( void* ) handle;

}
Exemple #24
0
/*
 * Connect to database.
 *  db_login	- database login
 *  db_password - database password
 * return : DB_CONNECT_NEW_CONNECTION if a new connection was estabilished
 *	    DB_CONNECT_ALREADY_CONNECTED or
 *	    DB_CONNECT_ERROR
 */
int oralog_db_connect(char *db_login, char *db_password, int quiet)
{
	int	 print_errors = (quiet) ? 0 : 1;
	int	 errors = 0;
	sword	 retval = 0;
	OCIError *hp_error = NULL;


	pthread_mutex_lock(&oralog_oper_lock);	
	
	if (oralog_is_connected()) {
		debug("[logsoracle] already connected\n");
		
		pthread_mutex_unlock(&oralog_oper_lock);
		return DB_CONNECT_ALREADY_CONNECTED;
	}

	
	debug("[logsoracle] connecting.. ");
	
	
	/* initialize the mode to be the threaded and object environment */
	OCIEnvCreate(&hp_env, OCI_THREADED|OCI_OBJECT, (dvoid *)0, 0, 0, 0, (size_t) 0, (dvoid **)0);

	/* allocate a server handle */
	OCIHandleAlloc((dvoid *)hp_env, (dvoid **)&hp_server, OCI_HTYPE_SERVER, 0, (dvoid **) 0);

	/* allocate an error handle */
	OCIHandleAlloc((dvoid *)hp_env, (dvoid **)&hp_error, OCI_HTYPE_ERROR, 0, (dvoid **) 0);

	/* create a server context */
	/* TODO: dblink can be set here */
	retval = OCIServerAttach(hp_server, hp_error, (text *)0, 0, OCI_DEFAULT);
	if(oralog_is_error(hp_error, retval, print_errors))
	 errors++;


	/* allocate a service handle */
	OCIHandleAlloc((dvoid *)hp_env, (dvoid **)&hp_service, OCI_HTYPE_SVCCTX, 0, (dvoid **) 0);

	/* associate server handle with service handle*/
	retval = OCIAttrSet((dvoid *)hp_service, OCI_HTYPE_SVCCTX, (dvoid *)hp_server, (ub4) 0, OCI_ATTR_SERVER, hp_error);
	if(oralog_is_error(hp_error, retval, print_errors))
	 errors++;

	/* allocate a session handle */
	OCIHandleAlloc((dvoid *)hp_env, (dvoid **)&hp_session, OCI_HTYPE_SESSION, 0, (dvoid **) 0);

	/* set username in session handle */
	retval = OCIAttrSet((dvoid *)hp_session, OCI_HTYPE_SESSION, (dvoid *)db_login, (ub4)ora_strlen(db_login), OCI_ATTR_USERNAME, hp_error);
	if(oralog_is_error(hp_error, retval, print_errors))
	 errors++;	

	/* set password in session handle */
	retval = OCIAttrSet((dvoid *)hp_session, OCI_HTYPE_SESSION, (dvoid *)db_password, (ub4)ora_strlen(db_password), OCI_ATTR_PASSWORD, hp_error);
	if(oralog_is_error(hp_error, retval, print_errors))
	 errors++;

	retval = OCISessionBegin ((dvoid *)hp_service, hp_error, hp_session, OCI_CRED_RDBMS, OCI_DEFAULT);
	if(oralog_is_error(hp_error, retval, print_errors))
	 errors++;

	/* associate session with service context */
	retval = OCIAttrSet ((dvoid *)hp_service, OCI_HTYPE_SVCCTX, (dvoid *)hp_session, (ub4) 0, OCI_ATTR_SESSION, hp_error);
	if(oralog_is_error(hp_error, retval, print_errors))
	 errors++;

	/* free local handles */
	if(hp_error)
		OCIHandleFree(hp_error, OCI_HTYPE_ERROR);


	if (errors) {
		debug("[logsoracle] errors encounterd - cleaning up connection\n");
		free_global_handles();
		set_connection_status(0);
		
		pthread_mutex_unlock(&oralog_oper_lock);
		return DB_CONNECT_ERROR;
	}
	
	set_connection_status(1);
	debug("connected\n");

	pthread_mutex_unlock(&oralog_oper_lock);
	return DB_CONNECT_NEW_CONNECTION;
}
Exemple #25
0
void
Init_oci8lib()
{
    VALUE cOCI8;
    OCIEnv *envhp;
    OCIError *errhp;
    sword rv;

#ifdef RUNTIME_API_CHECK
    Init_oci8_apiwrap();
    if (oracle_client_version < ORAVER_10_1) {
        const char *oraver;
        const char *ruby_oci8_ver;
        if (oracle_client_version >= ORAVER_9_2) {
            oraver = "9iR2";
            ruby_oci8_ver = "2.1.x";
        } else if (oracle_client_version >= ORAVER_9_0) {
            oraver = "9iR1";
            ruby_oci8_ver = "2.1.x";
        } else if (oracle_client_version >= ORAVER_8_2) {
            oraver = "8i";
            ruby_oci8_ver = "2.0.x";
        } else {
            oraver = "8";
            ruby_oci8_ver = "2.0.x";
        }
        rb_raise(rb_eLoadError, "Ruby-oci8 %s doesn't support Oracle %s. Use ruby-oci8 %s instead.",
                 OCI8LIB_VERSION, oraver, ruby_oci8_ver);
    }

    if (have_OCIClientVersion) {
        sword major, minor, update, patch, port_update;
        OCIClientVersion(&major, &minor, &update, &patch, &port_update);
        oracle_client_version = ORAVERNUM(major, minor, update, patch, port_update);
    }
#endif

    oci8_id_at_last_error = rb_intern("@last_error");
    oci8_id_get = rb_intern("get");
    oci8_id_set = rb_intern("set");
#ifdef CHAR_IS_NOT_A_SHORTCUT_TO_ID
    oci8_id_add_op = rb_intern("+");
    oci8_id_sub_op = rb_intern("-");
    oci8_id_mul_op = rb_intern("*");
    oci8_id_div_op = rb_intern("/");
#endif
#ifdef HAVE_RB_SET_END_PROC
    rb_set_end_proc(at_exit_func, Qnil);
#endif

    Init_oci8_thread_util();
    Init_oci8_error();
    Init_oci8_env();

    /* OCIHandle class */
    Init_oci8_handle();

    /* OCI8 class */
    Init_oci8(&cOCI8);

    /* OCI8::ConnectionPool class */
    Init_oci8_connection_pool(cOCI8);

    /* OCI8::BindType module */
    mOCI8BindType = rb_define_module_under(cOCI8, "BindType");
    /* OCI8::BindType::Base class */
    cOCI8BindTypeBase = oci8_define_class_under(mOCI8BindType, "Base", &oci8_bind_data_type, bind_base_alloc);

    /* Handle */
    Init_oci8_bind(cOCI8BindTypeBase);
    Init_oci8_stmt(cOCI8);

    /* Encoding */
    Init_oci8_encoding(cOCI8);

    /* register allocators */
    Init_oci8_metadata(cOCI8);
    Init_oci8_lob(cOCI8);

    /* allocate a temporary errhp to pass Init_oci_number() */
    rv = OCIEnvCreate(&envhp, oci8_env_mode, NULL, NULL, NULL, NULL, 0, NULL);
    if (rv != OCI_SUCCESS) {
        oci8_raise_init_error();
    }
    rv = OCIHandleAlloc(envhp, (dvoid *)&errhp, OCI_HTYPE_ERROR, 0, NULL);
    if (rv != OCI_SUCCESS)
        oci8_env_raise(envhp, rv);
    Init_oci_number(cOCI8, errhp);
    OCIHandleFree(errhp, OCI_HTYPE_ERROR);
    OCIHandleFree(envhp, OCI_HTYPE_ENV);

    Init_ora_date();
    Init_oci_datetime();
    Init_oci_object(cOCI8);

#ifdef USE_WIN32_C
    Init_oci8_win32(cOCI8);
#endif
}
Exemple #26
0
static int yada_oracle_connect(yada_t *_yada, char *yada_user, char *yada_pass)
{
  char errbuf[1024];
  sb4 errcode;


  /* check cached user/pass */
  if(_yada->_mod->dbuser && yada_user && strcmp(_yada->_mod->dbuser, yada_user))
    {
    free(_yada->_mod->dbuser);
    _yada->_mod->dbuser = NULL;
    }
  if(_yada->_mod->dbpass && yada_pass && strcmp(_yada->_mod->dbpass, yada_pass))
    {
    free(_yada->_mod->dbpass);
    _yada->_mod->dbpass = NULL;
    }

  /* cache user/pass */
  if(!_yada->_mod->dbuser)
    {
    if(!yada_user)
      {
      _yada_set_err(_yada, -1, "invalid username");
      return(0);
      }
    if(!(_yada->_mod->dbuser = strdup(yada_user)))
      {
      _yada_set_err(_yada, -1, strerror(errno));
      return(0);
      }
    }

  if(!_yada->_mod->dbpass)
    {
    if(!yada_user)
      {
      _yada_set_err(_yada, -1, "invalid username");
      return(0);
      }
    if(!(_yada->_mod->dbpass = strdup(yada_pass)))
      {
      _yada_set_err(_yada, -1, strerror(errno));
      return(0);
      }
    }

  /* create environment */
  if(OCIEnvCreate(&_yada->_mod->env, OCI_DEFAULT,
   NULL, NULL, NULL, NULL, 0, NULL) != OCI_SUCCESS)
    {
    _yada_set_err(_yada, -1, "OCIEnvCreate failed");
    return(0);
    }

  /* allocate error handle */
  if(OCIHandleAlloc(_yada->_mod->env, (dvoid**)&_yada->_mod->err,
   OCI_HTYPE_ERROR, 0, NULL) != OCI_SUCCESS)
    {
    OCIErrorGet(_yada->_mod->env, 1, NULL, &errcode, errbuf, sizeof(errbuf),
     OCI_HTYPE_ENV);
    _yada_set_err(_yada, errcode, errbuf);
    _yada->disconnect(_yada);
    return(0);
    }

  /* allocate server handle */
  if(OCIHandleAlloc(_yada->_mod->env, (dvoid**)&_yada->_mod->srv,
   OCI_HTYPE_SERVER, 0, NULL) != OCI_SUCCESS)
    {
    OCIErrorGet(_yada->_mod->env, 1, NULL, &errcode, errbuf, sizeof(errbuf),
     OCI_HTYPE_ENV);
    _yada_set_err(_yada, errcode, errbuf);
    _yada->disconnect(_yada);
    return(0);
    }

  /* attach to server */
  if(OCIServerAttach(_yada->_mod->srv, _yada->_mod->err, (text*)_yada->dbstr,
   strlen(_yada->dbstr), OCI_DEFAULT) != OCI_SUCCESS)
    {
    OCIErrorGet(_yada->_mod->err, 1, NULL, &errcode, errbuf, sizeof(errbuf),
     OCI_HTYPE_ERROR);
    _yada_set_err(_yada, errcode, errbuf);
    _yada->disconnect(_yada);
    return(0);
    }

  /* allocate context handle */
  if(OCIHandleAlloc(_yada->_mod->env, (dvoid**)&_yada->_mod->ctx,
   OCI_HTYPE_SVCCTX, 0, NULL) != OCI_SUCCESS)
    {
    OCIErrorGet(_yada->_mod->env, 1, NULL, &errcode, errbuf, sizeof(errbuf),
     OCI_HTYPE_ENV);
    _yada_set_err(_yada, errcode, errbuf);
    _yada->disconnect(_yada);
    return(0);
    }

  /* set server attribute of context handle */
  if(OCIAttrSet(_yada->_mod->ctx, OCI_HTYPE_SVCCTX, _yada->_mod->srv, 0,
   OCI_ATTR_SERVER, _yada->_mod->err) != OCI_SUCCESS)
    {
    OCIErrorGet(_yada->_mod->err, 1, NULL, &errcode, errbuf, sizeof(errbuf),
     OCI_HTYPE_ERROR);
    _yada_set_err(_yada, errcode, errbuf);
    _yada->disconnect(_yada);
    return(0);
    }

  /* allocate session handle */
  if(OCIHandleAlloc(_yada->_mod->env, (dvoid**)&_yada->_mod->ses,
   OCI_HTYPE_SESSION, 0, NULL) != OCI_SUCCESS)
    {
    OCIErrorGet(_yada->_mod->env, 1, NULL, &errcode, errbuf, sizeof(errbuf),
     OCI_HTYPE_ENV);
    _yada_set_err(_yada, errcode, errbuf);
    _yada->disconnect(_yada);
    return(0);
    }

  /* set username/password attributes of session handle */
  if(OCIAttrSet(_yada->_mod->ses, OCI_HTYPE_SESSION,
   (dvoid*)_yada->_mod->dbuser, strlen(_yada->_mod->dbuser), OCI_ATTR_USERNAME,
   _yada->_mod->err) != OCI_SUCCESS)
    {
    OCIErrorGet(_yada->_mod->err, 1, NULL, &errcode, errbuf, sizeof(errbuf),
     OCI_HTYPE_ERROR);
    _yada_set_err(_yada, errcode, errbuf);
    _yada->disconnect(_yada);
    return(0);
    }
  if(OCIAttrSet(_yada->_mod->ses, OCI_HTYPE_SESSION,
   (dvoid*)_yada->_mod->dbpass, strlen(_yada->_mod->dbpass), OCI_ATTR_PASSWORD,
   _yada->_mod->err) != OCI_SUCCESS)
    {
    OCIErrorGet(_yada->_mod->err, 1, NULL, &errcode, errbuf, sizeof(errbuf),
     OCI_HTYPE_ERROR);
    _yada_set_err(_yada, errcode, errbuf);
    _yada->disconnect(_yada);
    return(0);
    }

  /* start the session */
  if(OCISessionBegin(_yada->_mod->ctx, _yada->_mod->err, _yada->_mod->ses,
   OCI_CRED_RDBMS, OCI_DEFAULT) != OCI_SUCCESS)
    {
    OCIErrorGet(_yada->_mod->err, 1, NULL, &errcode, errbuf, sizeof(errbuf),
     OCI_HTYPE_ERROR);
    _yada_set_err(_yada, errcode, errbuf);
    _yada->disconnect(_yada);
    return(0);
    }

  /* set session attribute of context handle */
  if(OCIAttrSet(_yada->_mod->ctx, OCI_HTYPE_SVCCTX, _yada->_mod->ses, 0,
   OCI_ATTR_SESSION, _yada->_mod->err) != OCI_SUCCESS)
    {
    OCIErrorGet(_yada->_mod->err, 1, NULL, &errcode, errbuf, sizeof(errbuf),
     OCI_HTYPE_ERROR);
    _yada_set_err(_yada, errcode, errbuf);
    _yada->disconnect(_yada);
    return(0);
    }

  return(1);
}
int main (void)
{
  printf
  ("cdemoin1 - Demonstrating select, insert and update on a subtype table\n");
  /* Initializing the environment in the Object mode*/

  OCIEnvCreate((OCIEnv **) &envhp, OCI_OBJECT, (dvoid *)0,
    (dvoid * (*)(dvoid *, size_t)) 0, (dvoid * (*)(dvoid *, dvoid *, size_t))0,
    (void (*)(dvoid *, dvoid *)) 0, (size_t) 0, (dvoid **) 0 );

  OCIHandleAlloc (envhp, (dvoid **)&errhp, OCI_HTYPE_ERROR, (size_t)0, 
    (dvoid **)0);

  OCIHandleAlloc(envhp, (dvoid **)&svrhp, OCI_HTYPE_SERVER, (size_t)0,
    (dvoid **)0);

  status = OCIServerAttach(svrhp, errhp, (text *)database,
    (sb4)strlen((char *)database), OCI_DEFAULT);

  if (status != OCI_SUCCESS)
  {
    printf("OCIServerAttach failed \n");
  }
  else
    printf("OCIServerAttach - Success \n");

  OCIHandleAlloc(envhp, (dvoid **)&svchp, OCI_HTYPE_SVCCTX, (size_t)0, 
    (dvoid **)0);
  OCIAttrSet(svchp, OCI_HTYPE_SVCCTX, (dvoid *)svrhp, (ub4)0, OCI_ATTR_SERVER, 
    errhp);

  OCIHandleAlloc(envhp, (dvoid **)&sesnhp, OCI_HTYPE_SESSION, (size_t)0, 
    (dvoid **)0);

  OCIAttrSet(sesnhp, OCI_HTYPE_SESSION, (dvoid *)username, 
    (ub4)strlen((char *)username), OCI_ATTR_USERNAME, errhp);

  OCIAttrSet(sesnhp, OCI_HTYPE_SESSION, (dvoid*)password,
    (ub4)strlen((char *)password), OCI_ATTR_PASSWORD, errhp);

  printf("Connecting as %s/%s@%s\n",username,password,database);

  status = OCISessionBegin(svchp, errhp, sesnhp, OCI_CRED_RDBMS, OCI_DEFAULT);
  if (status != OCI_SUCCESS)
  {
    printf("Connection  failed \n");
  }
  else
    printf("Connection - Success \n");

  OCIAttrSet(svchp, OCI_HTYPE_SVCCTX, sesnhp, (ub4)0, OCI_ATTR_SESSION, errhp);

  /* Calling function to get an array of REFs to populate the varray */
  getRef(); 

  /* Function to insert an instance of the subtype into a supertype table */
  insertFunction();
 
  /* Function to modify the data of an inherited object */
  modifyFunction();  

  /* Function to display data from the table */
  selectFunction();  

  /* Free the allocated handles */
  cleanup();

  printf("cdemoin1 - Done\n");
  return 1;
} /* End of main() */
Exemple #28
0
void init_conn(OCI_CONNECTION **conn)
{
	int  ret_val;
	
	*conn = (OCI_CONNECTION *) malloc(sizeof(OCI_CONNECTION));
	
	/* Initialize the environment */
	ret_val = OCIEnvCreate(&(*(OCI_CONNECTION**)conn)->envhp, OCI_THREADED | OCI_OBJECT, NULL, NULL, NULL, NULL, 0, NULL);
	
	if( ret_val != OCI_SUCCESS )
	{
		printf("Error: unable to create an environment to open a connection to the DBMS.\n");
		exit(EXIT_FAILURE);
	}

	// allocate the neccessary handles to open and maintain a connection to the database
	OCIHandleAlloc ((*conn)->envhp, &((*conn)->errhp), OCI_HTYPE_ERROR, 0, NULL);
	OCIHandleAlloc ((*conn)->envhp, &((*conn)->svchp), OCI_HTYPE_SVCCTX, 0, NULL);
	OCIHandleAlloc ((*conn)->envhp, &((*conn)->srvhp), OCI_HTYPE_SERVER, 0, NULL);
	OCIHandleAlloc ((*conn)->envhp, &((*conn)->authp), OCI_HTYPE_SESSION, 0, NULL);
	
	// initialize the service context handle
	ret_val = OCIAttrSet ((*conn)->svchp, 
		                  OCI_HTYPE_SVCCTX, 
		                  (*conn)->srvhp, 
		                  0, 
	                      OCI_ATTR_SERVER, 
		                  (*conn)->errhp);

	if( ret_val != OCI_SUCCESS )
	{
		printf ("Error: unable to initialize the service context handle.\n");
		exit(EXIT_FAILURE);
	}
	
	// set the username in the user session handle
	ret_val = OCIAttrSet ((*conn)->authp,
		                  OCI_HTYPE_SESSION,
		                  username, 
		                  strlen(username), 
		                  OCI_ATTR_USERNAME, 
		                  (*conn)->errhp);

	if( ret_val != OCI_SUCCESS )
	{
		printf ("Error: unable to initialize the user session handle.\n");
		exit(EXIT_FAILURE);
	}
	
	// set the password in the user session handle
	ret_val = OCIAttrSet ((*conn)->authp, 
		                  OCI_HTYPE_SESSION, 
		                  password, 
		                  strlen(password), 
		                  OCI_ATTR_PASSWORD, 
		                  (*conn)->errhp);
	
	if( ret_val != OCI_SUCCESS )
	{
		printf ("Error: unable to initialize the user session handle.\n");
		exit(EXIT_FAILURE);
	}

	// attach the error handle to the server handle 
	ret_val = OCIServerAttach((*conn)->srvhp, 
					          (*conn)->errhp, 
					          (unsigned char *)connect_string, 
					          strlen(connect_string), 
					          OCI_DEFAULT);
	
	if( ret_val != OCI_SUCCESS )
	{
		printf ("Error: unable to attach error handle to server.\n");
		exit (EXIT_FAILURE);
	}
	
	// log on to the database
	ret_val = OCISessionBegin((*conn)->svchp, 
					          (*conn)->errhp,
				              (*conn)->authp, 
				 	          OCI_CRED_RDBMS, 
					          OCI_DEFAULT);

	if( ret_val != OCI_SUCCESS )
	{
		printf ("Error: unable to log on to %s.\n", connect_string);
		printf ("Verify that the username and password are valid for this database.\n"); 
		exit(EXIT_FAILURE);
	}
	
	// set the user session attribute in the service context handle
	ret_val = OCIAttrSet((*conn)->svchp,
					     OCI_HTYPE_SVCCTX, 
					     (*conn)->authp, 
					     0, 
					     OCI_ATTR_SESSION, 
					     (*conn)->errhp);
	
	if( ret_val != OCI_SUCCESS )
	{
		printf ("Error: unable to set user session attribute in service context handle.\n");
		exit(EXIT_FAILURE);
	}
}