Esempio n. 1
0
File: IoDBI.c Progetto: cdcarter/io
IoObject *IoDBI_with(IoDBI *self, IoObject *locals, IoMessage *m)
{
	//doc DBI with(driverName) Get a new connection with the given driver.
	
	IoObject *name = IoMessage_locals_valueArgAt_(m, locals, 0);
	if (!ISSYMBOL(name))
	{
		IoState_error_(IOSTATE, m, "argument 0 to method '%s' must be a Symbol, not a '%s'\n",
			CSTRING(IoMessage_name(m)), IoObject_name(name));
		return IONIL(self);
	}

	if (DATA(self)->didInit != 1)
	{
		IoDBI_init(self, locals, m);
	}

	dbi_conn c = dbi_conn_new(CSTRING(name));
	if (c == NULL)
	{
		IoState_error_(IOSTATE, m, "libdbi error during dbi_conn_new\n");
		return IONIL(self);
	}

	return IoDBIConn_new(IOSTATE, c);
}
Esempio n. 2
0
static char
query_handler(char *query_name, char *myq)
{

    if(myq == NULL) {
        myq = "SELECT NULL";
    }
    if(query_name == NULL) {
        query_name = "noname";
    }
    if(query_name == "") {
        query_name = "noname";
    }
    dbi_initialize(NULL);
    conn = dbi_conn_new("mysql");
    dbi_conn_set_option(conn, "host", getenv("DB_HOSTNAME"));
    dbi_conn_set_option(conn, "username", getenv("DB_USERNAME"));
    dbi_conn_set_option(conn, "password", getenv("DB_PASSWORD"));
    dbi_conn_set_option(conn, "dbname", getenv("DB_DATABASE"));
    dbi_conn_set_option(conn, "encoding", "UTF-8");
    if (dbi_conn_connect(conn) < 0) {
        printf("Could not connect. Please check the option settings and if the" \
            "specific driver is available\n");
    } else {
        result = dbi_conn_queryf(conn, myq, threshold);
        if (result) {
        xmlAddChild(sql_node,query_doc(result,query_name));
        dbi_result_free(result);
        }
        dbi_conn_close(conn);
    }
    return 0;

}
Esempio n. 3
0
int
main (int argc, char *argv[])
{
  dbi_conn conn;
  dbi_result result;
  const char *err_msg;
  int err_code;

  if (argc < 2)
    {
      fprintf (stderr, "%s: Need a libdir as argument!\n", argv[0]);
      return 1;
    }

  dbi_initialize (argv[1]);

  conn = dbi_conn_new ("null");
  dbi_conn_connect (conn);

  /*
   * Queries
   */
  result = dbi_conn_query (conn, "COMMIT");
  assert (result != NULL);
  dbi_result_free (result);

  dbi_conn_set_option_numeric (conn, "null.error.commit", 1);
  result = dbi_conn_query (conn, "COMMIT");
  assert (result == NULL);

  dbi_conn_set_option_numeric (conn, "null.error.commit", 0);
  result = dbi_conn_query (conn, "COMMIT");
  assert (result != NULL);
  dbi_result_free (result);

  /*
   * Normal queries
   */
  result = dbi_conn_query (conn, "SELECT * FROM DUAL");
  assert (result != NULL);
  dbi_result_free (result);

  dbi_conn_set_option_numeric (conn, "null.error.query", 1);
  result = dbi_conn_query (conn, "SELECT * FROM DUAL");
  assert (result == NULL);

  dbi_conn_set_option_numeric (conn, "null.error.query", 0);
  result = dbi_conn_query (conn, "SELECT * FROM DUAL");
  assert (result != NULL);
  dbi_result_free (result);

  /*
   * Cleanup
   */
  dbi_conn_close (conn);

  dbi_shutdown ();

  return 0;
}
Esempio n. 4
0
/* The following function is responsible for initializing a connection
 */
static rsRetVal initConn(instanceData *pData, int bSilent)
{
	DEFiRet;
	int iDrvrsLoaded;

	ASSERT(pData != NULL);
	ASSERT(pData->conn == NULL);

	if(bDbiInitialized == 0) {
		/* we need to init libdbi first */
#		ifdef HAVE_DBI_R
		iDrvrsLoaded = dbi_initialize_r((char*) pData->dbiDrvrDir, &dbiInst);
#		else
		iDrvrsLoaded = dbi_initialize((char*) pData->dbiDrvrDir);
#		endif
		if(iDrvrsLoaded == 0) {
			errmsg.LogError(0, RS_RET_SUSPENDED, "libdbi error: libdbi or libdbi drivers not present on this system - suspending.");
			ABORT_FINALIZE(RS_RET_SUSPENDED);
		} else if(iDrvrsLoaded < 0) {
			errmsg.LogError(0, RS_RET_SUSPENDED, "libdbi error: libdbi could not be "
				"initialized (do you have any dbi drivers installed?) - suspending.");
			ABORT_FINALIZE(RS_RET_SUSPENDED);
		}
		bDbiInitialized = 1; /* we are done for the rest of our existence... */
	}

#	ifdef HAVE_DBI_R
	pData->conn = dbi_conn_new_r((char*)pData->drvrName, dbiInst);
#	else
	pData->conn = dbi_conn_new((char*)pData->drvrName);
#	endif
	if(pData->conn == NULL) {
		errmsg.LogError(0, RS_RET_SUSPENDED, "can not initialize libdbi connection");
		ABORT_FINALIZE(RS_RET_SUSPENDED);
	} else { /* we could get the handle, now on with work... */
		/* Connect to database */
		dbi_conn_set_option(pData->conn, "host",     (char*) pData->host);
		dbi_conn_set_option(pData->conn, "username", (char*) pData->usrName);
		dbi_conn_set_option(pData->conn, "dbname",   (char*) pData->dbName);
		if(pData->pwd != NULL)
			dbi_conn_set_option(pData->conn, "password", (char*) pData->pwd);
		if(dbi_conn_connect(pData->conn) < 0) {
			reportDBError(pData, bSilent);
			closeConn(pData); /* ignore any error we may get */
			ABORT_FINALIZE(RS_RET_SUSPENDED);		
		}
		pData->txSupport = dbi_conn_cap_get(pData->conn, "transaction_support");
	}

finalize_it:
	RETiRet;
}
Esempio n. 5
0
/* Connect to the MYSQL database */
static logsql_opendb_ret log_sql_dbi_connect(server_rec *s, logsql_dbconnection *db)
{
    const char *driver = apr_table_get(db->parms,"driver");
	const char *host = apr_table_get(db->parms,"hostname");
	const char *user = apr_table_get(db->parms,"username");
	const char *passwd = apr_table_get(db->parms,"password");
	const char *database = apr_table_get(db->parms,"database");
	const char *s_tcpport = apr_table_get(db->parms,"port");
	unsigned int tcpport = (s_tcpport)?atoi(s_tcpport):0;
	const char *socketfile = apr_table_get(db->parms,"socketfile");
    //dbi_result result;
    dbi_conn_rec *dblink = db->handle;
    if (!dblink) {
        dblink = apr_pcalloc(db->p, sizeof(*dblink));
        db->handle = (void *)dblink;
    }

	dblink->conn = dbi_conn_new(driver);

    dbi_conn_set_option(dblink->conn, "host", host);
    dbi_conn_set_option(dblink->conn, "username", user);
    dbi_conn_set_option(dblink->conn, "password", passwd);
    dbi_conn_set_option(dblink->conn, "dbname", database);
    if (tcpport) {
        dbi_conn_set_option_numeric(dblink->conn, "port", tcpport);
    }

	if (socketfile && !strcmp(driver,"mysql")) {
		dbi_conn_set_option(dblink->conn, "mysql_unix_socket", socketfile);
	}
    
	if (!dbi_conn_connect(dblink->conn)) {
		log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
            "HOST: '%s' PORT: '%d' DB: '%s' USER: '******' SOCKET: '%s'",
			host, tcpport, database, user, socketfile);
		return LOGSQL_OPENDB_SUCCESS;
	} else {
        const char *error;
        dbi_conn_error(dblink->conn, &error);
		log_error(APLOG_MARK, APLOG_ERR, 0, s,
            "DBI Error: %s", error);
		log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
            "HOST: '%s' PORT: '%d' DB: '%s' USER: '******' SOCKET: '%s'",
			host, tcpport, database, user, socketfile);
		return LOGSQL_OPENDB_FAIL;
	}
}
Esempio n. 6
0
template <DbType Type> dbi_conn
conn_setup (QofBackend* qbe, PairVec& options,
            UriStrings& uri)
{
    const char* dbstr = (Type == DbType::DBI_SQLITE ? "sqlite3" :
                         Type == DbType::DBI_MYSQL ? "mysql" : "pgsql");
#if HAVE_LIBDBI_R
    dbi_conn conn = nullptr;
    if (dbi_instance)
        conn = dbi_conn_new_r (dbstr, dbi_instance);
    else
        PERR ("Attempt to connect with an uninitialized dbi_instance");
#else
    auto conn = dbi_conn_new (dbstr);
#endif

    if (conn == nullptr)
    {
        PERR ("Unable to create %s dbi connection", dbstr);
        qof_backend_set_error (qbe, ERR_BACKEND_BAD_URL);
	return nullptr;
    }

    dbi_conn_error_handler (conn, error_handler<Type>, qbe);
    if (!uri.m_dbname.empty() &&
        !set_standard_connection_options(qbe, conn, uri))
    {
        dbi_conn_close(conn);
        return nullptr;
    }
    if(!options.empty())
    {
        try {
            set_options(conn, options);
        }
        catch (std::runtime_error& err)
        {
            dbi_conn_close(conn);
            qof_backend_set_error (qbe, ERR_BACKEND_SERVER_ERR);
            return nullptr;
        }
    }

    return conn;
}
Esempio n. 7
0
int main() {
	dbi_conn conn;
	dbi_result result;
	int v;

	dbi_initialize(NULL);
	conn = dbi_conn_new("pgsql");

	dbi_conn_set_option(conn, "host", "localhost");
	dbi_conn_set_option(conn, "username", "mud");
	dbi_conn_set_option(conn, "dbname", "mud");

	if ( (v = dbi_conn_connect(conn)) < 0 ) {
		const char* p;

		dbi_conn_error(conn, &p);
		printf(" :: %s\n", p);
		return 0;
	}
	else printf("%d\n", v);
	result = dbi_conn_query(conn, "select * from account");
}
Esempio n. 8
0
void swd::database::connect(const std::string& driver, const std::string& host,
 const std::string& port, const std::string& username, const std::string& password,
 const std::string& name, const std::string& encoding) {
#if defined(HAVE_DBI_NEW)
    dbi_initialize_r(NULL, &instance_);
    conn_ = dbi_conn_new_r(driver.c_str(), instance_);
#else
    dbi_initialize(NULL);
    conn_ = dbi_conn_new(driver.c_str());
#endif

    dbi_conn_set_option(conn_, "host", host.c_str());
    dbi_conn_set_option(conn_, "port", port.c_str());
    dbi_conn_set_option(conn_, "username", username.c_str());
    dbi_conn_set_option(conn_, "password", password.c_str());
    dbi_conn_set_option(conn_, "dbname", name.c_str());
    dbi_conn_set_option(conn_, "encoding", encoding.c_str());

    /* If the initial connection can not be established the process is shut down. */
    if (dbi_conn_connect(conn_) < 0) {
        throw swd::exceptions::core_exception("Can't connect to database server");
    }
}
Esempio n. 9
0
dbi_conn open_database(const char *dbtype, const char *dbhost, const char *dbport, const char *dbname, const char *dbuser, const char *dbpasswd)
{
  dbi_conn conn;

  dbi_initialize(NULL);
  conn = dbi_conn_new(dbtype);
  if ( ! conn ) { LOG(LOG_ERR, "Cannot start a connection with driver %s", dbtype); }

  dbi_conn_set_option(conn, "host", dbhost);
  dbi_conn_set_option(conn, "port", dbport);
  dbi_conn_set_option(conn, "username", dbuser);
  dbi_conn_set_option(conn, "password", dbpasswd);
  dbi_conn_set_option(conn, "dbname", dbname);
  dbi_conn_set_option(conn, "encoding", "UTF-8");

  if (dbi_conn_connect(conn) < 0) {
    const char *errmsg;
    dbi_conn_error(conn, &errmsg);
    LOG(LOG_ERR, "%s dbhost=%s,dbport=%d,dbname=%s,dbuser=%s,dbpasswd=%s",
           errmsg, dbhost, dbport, dbname, dbuser, dbpasswd);
    return(NULL);
  }
  return(conn);
}
Esempio n. 10
0
static gboolean
afsql_dd_ensure_initialized_connection(AFSqlDestDriver *self)
{
  if (self->dbi_ctx)
    return TRUE;

  self->dbi_ctx = dbi_conn_new(self->type);

  if (!self->dbi_ctx)
    {
      msg_error("No such DBI driver",
                evt_tag_str("type", self->type),
                NULL);
      return FALSE;
    }

  dbi_conn_set_option(self->dbi_ctx, "host", self->host);

  if (strcmp(self->type, "mysql"))
    dbi_conn_set_option(self->dbi_ctx, "port", self->port);
  else
    dbi_conn_set_option_numeric(self->dbi_ctx, "port", atoi(self->port));

  dbi_conn_set_option(self->dbi_ctx, "username", self->user);
  dbi_conn_set_option(self->dbi_ctx, "password", self->password);
  dbi_conn_set_option(self->dbi_ctx, "dbname", self->database);
  dbi_conn_set_option(self->dbi_ctx, "encoding", self->encoding);
  dbi_conn_set_option(self->dbi_ctx, "auto-commit", self->flags & AFSQL_DDF_EXPLICIT_COMMITS ? "false" : "true");

  /* database specific hacks */
  dbi_conn_set_option(self->dbi_ctx, "sqlite_dbdir", "");
  dbi_conn_set_option(self->dbi_ctx, "sqlite3_dbdir", "");

  /* Set user-specified options */
  g_hash_table_foreach(self->dbd_options, afsql_dd_set_dbd_opt, self->dbi_ctx);
  g_hash_table_foreach(self->dbd_options_numeric, afsql_dd_set_dbd_opt_numeric, self->dbi_ctx);

  if (dbi_conn_connect(self->dbi_ctx) < 0)
    {
      const gchar *dbi_error;

      dbi_conn_error(self->dbi_ctx, &dbi_error);

      msg_error("Error establishing SQL connection",
                evt_tag_str("type", self->type),
                evt_tag_str("host", self->host),
                evt_tag_str("port", self->port),
                evt_tag_str("username", self->user),
                evt_tag_str("database", self->database),
                evt_tag_str("error", dbi_error),
                NULL);

      return FALSE;
    }

  if (self->session_statements != NULL)
    {
      GList *l;

      for (l = self->session_statements; l; l = l->next)
        {
          if (!afsql_dd_run_query(self, (gchar *) l->data, FALSE, NULL))
            {
              msg_error("Error executing SQL connection statement",
                        evt_tag_str("statement", (gchar *) l->data),
                        NULL);

              return FALSE;
            }
        }
    }

  return TRUE;
}
Esempio n. 11
0
dbi_result _db_rawquery(const char *file, int line, database *db, int log_dupes, char *qry)
{
    dbi_result result;
    const char *errmsg;
    int tries = 0;

    if (debug > 4) {
        LOGRAW(LOG_DEBUG, qry);
    }

    if (!dbi_conn_ping(db->conn)) {
        if (db->conn) dbi_conn_close(db->conn);
        db->conn = dbi_conn_new(db->driver);
        if (db->conn == NULL) {
            perror(db->driver);
            exit(1);
        }

        dbi_conn_set_option(db->conn, "host", db->host);
        dbi_conn_set_option(db->conn, "port", db->port);
        dbi_conn_set_option(db->conn, "username", db->username);
        dbi_conn_set_option(db->conn, "password", db->password);
        dbi_conn_set_option(db->conn, "dbname", db->name);

retry:
        if (++tries == 3) exit(1);
        if (dbi_conn_connect(db->conn) < 0) {
            dbi_conn_error(db->conn, &errmsg);
            _logsrce = file;
            _logline = line;
            _LOG(LOG_ERR, "%s connection failed to %s:%s:%s %s", db->driver, db->host, db->port, db->name, errmsg);
            sleep(3);
            goto retry;
        }

        {
            char versionstring[VERSIONSTRING_LENGTH];
            dbi_driver driver;

            driver = dbi_conn_get_driver(db->conn);
            dbi_conn_get_engine_version_string(db->conn, versionstring);
            LOG(LOG_INFO, "using driver: %s, version %s, compiled %s", dbi_driver_get_filename(driver), dbi_driver_get_version(driver),
                dbi_driver_get_date_compiled(driver));
            LOG(LOG_INFO, "connected to %s:%s:%s, server version %s", db->host, db->port, db->name, versionstring);
        }
    }

    if (debug > 2) {
        char *src, *dst, buf[4096];

        for (dst = buf, src = qry; *src; src++, dst++) {
            if (*src == '%') *dst++ = '%';
            *dst = *src;
        }
        *dst = 0;
        LOG(LOG_INFO, buf);
    }
    result = dbi_conn_query(db->conn, qry);
    if (result == NULL) {
        int ret = dbi_conn_error(db->conn, &errmsg);
        _logsrce = file;
        _logline = line;
        _LOG(LOG_ERR, "query failed: %s (%s)", errmsg, qry);
        if (ret == DBI_ERROR_NOCONN) {
            dbi_conn_close(db->conn);
            db->conn = NULL;
            sleep(3);
            goto retry;
        }
    }
    return(result);
}
Esempio n. 12
0
/**
 * Parse command line options, create connection object,
 * start the connection and finally create database schema
 *
 * @return DBI connection handle
 */
dbi_conn *tagsistant_db_connection(int start_transaction)
{
	/* DBI connection handler used by subsequent calls to dbi_* functions */
	dbi_conn dbi = NULL;

	if (start_transaction) {
		g_rw_lock_writer_lock(&(tagsistant_query_rwlock));
	} else {
		g_rw_lock_reader_lock(&(tagsistant_query_rwlock));
	}

	/* lock the pool */
	g_mutex_lock(&tagsistant_connection_pool_lock);

	GList *pool = tagsistant_connection_pool;
	while (pool) {
		dbi = (dbi_conn) pool->data;

		/* check if the connection is still alive */
		if (!dbi_conn_ping(dbi) && dbi_conn_connect(dbi) < 0) {
			dbi_conn_close(dbi);
			tagsistant_connection_pool = g_list_delete_link(tagsistant_connection_pool, pool);
			connections--;
		} else {
			tagsistant_connection_pool = g_list_remove_link(tagsistant_connection_pool, pool);
			g_list_free_1(pool);
			break;
		}

		pool = pool->next;
	}

	/*
	 * unlock the pool mutex only if the backend is not SQLite
	 */
	g_mutex_unlock(&tagsistant_connection_pool_lock);

	if (!dbi) {
		// initialize DBI drivers
		if (TAGSISTANT_DBI_MYSQL_BACKEND == dboptions.backend) {
			if (!tagsistant_driver_is_available("mysql")) {
				fprintf(stderr, "MySQL driver not installed\n");
				dbg('s', LOG_ERR, "MySQL driver not installed");
				exit (1);
			}

			// unlucky, MySQL does not provide INTERSECT operator
			tagsistant.sql_backend_have_intersect = 0;

			// create connection
#if TAGSISTANT_REENTRANT_DBI
			dbi = dbi_conn_new_r("mysql", tagsistant.dbi_instance);
#else
			dbi = dbi_conn_new("mysql");
#endif
			if (NULL == dbi) {
				dbg('s', LOG_ERR, "Error creating MySQL connection");
				exit (1);
			}

			// set connection options
			dbi_conn_set_option(dbi, "host",     dboptions.host);
			dbi_conn_set_option(dbi, "dbname",   dboptions.db);
			dbi_conn_set_option(dbi, "username", dboptions.username);
			dbi_conn_set_option(dbi, "password", dboptions.password);
			dbi_conn_set_option(dbi, "encoding", "UTF-8");

		} else if (TAGSISTANT_DBI_SQLITE_BACKEND == dboptions.backend) {
			if (!tagsistant_driver_is_available("sqlite3")) {
				fprintf(stderr, "SQLite3 driver not installed\n");
				dbg('s', LOG_ERR, "SQLite3 driver not installed");
				exit(1);
			}

			// create connection
#if TAGSISTANT_REENTRANT_DBI
			dbi = dbi_conn_new_r("sqlite3", tagsistant.dbi_instance);
#else
			dbi = dbi_conn_new("sqlite3");
#endif
			if (NULL == dbi) {
				dbg('s', LOG_ERR, "Error connecting to SQLite3");
				exit (1);
			}

			// set connection options
			dbi_conn_set_option(dbi, "dbname", "tags.sql");
			dbi_conn_set_option(dbi, "sqlite3_dbdir", tagsistant.repository);

		} else {

			dbg('s', LOG_ERR, "No or wrong database family specified!");
			exit (1);
		}

		// try to connect
		if (dbi_conn_connect(dbi) < 0) {
			int error = dbi_conn_error(dbi, NULL);
			dbg('s', LOG_ERR, "Could not connect to DB (error %d). Please check the --db settings", error);
			exit(1);
		}

		connections++;

		dbg('s', LOG_INFO, "SQL connection established");
	}

	/* start a transaction */
	if (start_transaction) {
#if TAGSISTANT_USE_INTERNAL_TRANSACTIONS
		switch (tagsistant.sql_database_driver) {
			case TAGSISTANT_DBI_SQLITE_BACKEND:
				tagsistant_query("begin transaction", dbi, NULL, NULL);
				break;

			case TAGSISTANT_DBI_MYSQL_BACKEND:
				tagsistant_query("start transaction", dbi, NULL, NULL);
				break;
		}
#else
		dbi_conn_transaction_begin(dbi);
#endif
	}

	return(dbi);
}
Esempio n. 13
0
int main( int argc, char* argv[] ) {

	// Parse command line

	const char* idl_file_name = NULL;
	const char* query_file_name = NULL;
	int verbose = 0;                        // boolean

	int opt;
	opterr = 0;
	const char optstring[] = ":f:i:v";

	while( ( opt = getopt( argc, argv, optstring ) ) != -1 ) {
		switch( opt )
		{
			case 'f' :  // get file name of query
				if( query_file_name ) {
					fprintf( stderr, "Multiple input files not allowed\n" );
					return EXIT_FAILURE;
				}
				else
					query_file_name = optarg;
				break;
			case 'i' :  // get name of IDL file
				if( idl_file_name ) {
					fprintf( stderr, "Multiple IDL file names not allowed\n" );
					return EXIT_FAILURE;
				}
				else
					idl_file_name = optarg;
				break;
			case 'v' :  // Verbose
				verbose = 1;
				break;
			case '?' :  // Invalid option
				fprintf( stderr, "Invalid option '-%c' on command line\n",
						 (char) optopt );
				return EXIT_FAILURE;
			default :  // Huh?
				fprintf( stderr, "Internal error: unexpected value '%c'"
						"for optopt", (char) optopt );
				return EXIT_FAILURE;

		}
	}

	// If the command line doesn't specify an IDL file, get it
	// from an environmental variable, or apply a default
	if( NULL == idl_file_name ) {
		idl_file_name = getenv( "OILS_IDL_FILENAME" );
		if( NULL == idl_file_name )
			idl_file_name = "/openils/conf/fm_IDL.xml";
	}

	if( verbose )
		printf( "IDL file: %s\n", idl_file_name );

	char* loaded_json = NULL;
	const char* json_query = NULL;

	// Get the JSON query into a string
	if( query_file_name ) {   // Got a file?  Load it
		if( optind < argc )
			fprintf( stderr, "Extra parameter(s) ignored\n" );
		loaded_json = load_query( query_file_name );
		if( !loaded_json )
			return EXIT_FAILURE;
		json_query = loaded_json;
	} else {                  // No file?  Use command line parameter
		if ( optind == argc ) {
			fprintf( stderr, "No JSON query specified\n" );
			return EXIT_FAILURE;
		} else
			json_query = argv[ optind ];
	}

	if( verbose )
		printf( "JSON query: %s\n", json_query );

	osrfLogSetLevel( OSRF_LOG_WARNING );    // Suppress informational messages
	(void) oilsIDLInit( idl_file_name );    // Load IDL into memory

	// Load a database driver, connect to it, and install the connection in
	// the cstore module.  We don't actually connect to a database, but we
	// need the driver to process quoted strings correctly.
	if( dbi_initialize( NULL ) < 0 ) {
		printf( "Unable to load database driver\n" );
		return EXIT_FAILURE;
	};

	dbi_conn conn = dbi_conn_new( "pgsql" );  // change string if ever necessary
	if( !conn ) {
		printf( "Unable to establish dbi connection\n" );
		dbi_shutdown();
		return EXIT_FAILURE;
	}

	oilsSetDBConnection( conn );

	// The foregoing is an inelegant kludge.  The true, proper, and uniquely
	// correct thing to do is to load the system settings and then call
	// osrfAppInitialize() and osrfAppChildInit().  Maybe we'll actually
	// do that some day, but this will do for now.

	// Translate the JSON into SQL
	int rc = test_json_query( json_query );

	dbi_conn_close( conn );
	dbi_shutdown();
	if( loaded_json )
		free( loaded_json );

	return rc ? EXIT_FAILURE : EXIT_SUCCESS;
}
Esempio n. 14
0
File: dbi.c Progetto: Bradan/gammu
/* Connects to database */
static GSM_Error SMSDDBI_Connect(GSM_SMSDConfig * Config)
{
	int rc;
	struct GSM_SMSDdbobj *db = Config->db;

	rc = dbi_initialize(Config->driverspath);

	if (rc == 0) {
		SMSD_Log(DEBUG_ERROR, Config, "DBI did not find any drivers, try using DriversPath option");
		dbi_shutdown();
		return ERR_DB_DRIVER;
	} else if (rc < 0) {
		SMSD_Log(DEBUG_ERROR, Config, "DBI failed to initialize!");
		return ERR_DB_DRIVER;
	}

	Config->conn.dbi = dbi_conn_new(Config->driver);
	if (Config->conn.dbi == NULL) {
		SMSD_Log(DEBUG_ERROR, Config, "DBI failed to init %s driver!", Config->driver);
		dbi_shutdown();
		return ERR_DB_DRIVER;
	} else {
		SMSD_Log(DEBUG_SQL, Config, "Using DBI driver '%s'", dbi_driver_get_name(dbi_conn_get_driver(Config->conn.dbi)));
	}

	dbi_conn_error_handler(Config->conn.dbi, SMSDDBI_Callback, Config);

	if (dbi_conn_set_option(Config->conn.dbi, "sqlite_dbdir", Config->dbdir) != 0) {
		SMSD_Log(DEBUG_ERROR, Config, "DBI failed to set sqlite_dbdir!");
		SMSDDBI_Free(Config);
		return ERR_DB_CONFIG;
	}
	if (dbi_conn_set_option(Config->conn.dbi, "sqlite3_dbdir", Config->dbdir) != 0) {
		SMSD_Log(DEBUG_ERROR, Config, "DBI failed to set sqlite3_dbdir!");
		SMSDDBI_Free(Config);
		return ERR_DB_CONFIG;
	}
	if (dbi_conn_set_option(Config->conn.dbi, "host", Config->host) != 0) {
		SMSD_Log(DEBUG_ERROR, Config, "DBI failed to set host!");
		SMSDDBI_Free(Config);
		return ERR_DB_CONFIG;
	}
	if (dbi_conn_set_option(Config->conn.dbi, "username", Config->user) != 0) {
		SMSD_Log(DEBUG_ERROR, Config, "DBI failed to set username!");
		SMSDDBI_Free(Config);
		return ERR_DB_CONFIG;
	}
	if (dbi_conn_set_option(Config->conn.dbi, "password", Config->password) != 0) {
		SMSD_Log(DEBUG_ERROR, Config, "DBI failed to set password!");
		SMSDDBI_Free(Config);
		return ERR_DB_CONFIG;
	}
	if (dbi_conn_set_option(Config->conn.dbi, "dbname", Config->database) != 0) {
		SMSD_Log(DEBUG_ERROR, Config, "DBI failed to set dbname!");
		SMSDDBI_Free(Config);
		return ERR_DB_CONFIG;
	}
	if (dbi_conn_set_option(Config->conn.dbi, "encoding", "UTF-8") != 0) {
		SMSD_Log(DEBUG_ERROR, Config, "DBI failed to set encoding!");
		SMSDDBI_Free(Config);
		return ERR_DB_CONFIG;
	}

	if (dbi_conn_connect(Config->conn.dbi) != 0) {
		SMSD_Log(DEBUG_ERROR, Config, "DBI failed to connect!");
		SMSDDBI_Free(Config);
		return ERR_DB_CONNECT;
	}
	Config->db = db;
	return ERR_NONE;
}
Esempio n. 15
0
static apr_status_t safe_dbi_new_conn(void **resource, void *params,
                                      apr_pool_t * r)
{
    apr_status_t rv = APR_SUCCESS;
    ftpd_dbi_config_rec *conf = params;
    int err_num = 0;
    const char *err_str;
    const char *host = conf->dbi_host;
    const char *driver = conf->dbi_driver;
    const char *name = conf->dbi_name;
    const char *user = conf->dbi_user;
    const char *pwd = conf->dbi_pass;
    ftpd_dbi_rest *myres;

    dbi_conn_count++;

    if (DBI_HARD_MAX_CONNS > dbi_conn_count) {

        ap_log_perror(APLOG_MARK, APLOG_DEBUG, 0, r,
                      "[mod_ftpd_dbi.c] Creating New DBI Server Connection");

        myres = apr_palloc(r, sizeof(*myres));

        myres->conn = dbi_conn_new(driver);
        if (myres->conn == NULL) {
            ap_log_perror(APLOG_MARK, APLOG_EMERG, 0, r,
                          "[mod_ftpd_dbi.c] DBI Connection Failed. dbi_conn_new returned NULL.");
            rv = !APR_SUCCESS;
            /*
             * modules/ssl/ssl_engine_log.c:103
             *  said this was okay. so i do it.
             */
            exit(1);
        }
        else {
            dbi_conn_set_option(myres->conn, "host", (char *)host);
            dbi_conn_set_option(myres->conn, "username", (char *)user);
            dbi_conn_set_option(myres->conn, "password", (char *)pwd);
            dbi_conn_set_option(myres->conn, "dbname", (char *)name);
            if (dbi_conn_connect(myres->conn) != 0) {
                err_num = dbi_conn_error(myres->conn, (const char **)&err_str);
                /* Connetion Failed */
                ap_log_perror(APLOG_MARK, APLOG_ERR, 0, r,
                              "[mod_ftpd_dbi.c] DBI Connection to %s://%s@%s/%s Failed. Error: (%d) %s",
                              driver, user, host, name, err_num, err_str);
                rv = !APR_SUCCESS;
            }
            else {
                ap_log_perror(APLOG_MARK, APLOG_DEBUG, 0, r,
                              "[mod_ftpd_dbi.c] Connection was created sucessfully");
            }
        }
        *resource = myres;
    }
    else {
        /* Error -- we have too many TOTAL DBI Connections. Maybe a Evil User trying to hurt our system? */
        ap_log_perror(APLOG_MARK, APLOG_ERR, 0, r,
                      "[mod_ftpd_dbi.c] DBI Connection Failed. Hard Max Limit of %d Connections has been reached",
                      DBI_HARD_MAX_CONNS);
        /* we didn't create a new connection! */
        dbi_conn_count--;
        rv = !APR_SUCCESS;
    }
    return rv;
}