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; }
int dbiw_connect(db_wrap * self) { DB_DECL(DB_WRAP_E_BAD_ARG); return dbi_conn_connect(conn) ? DB_WRAP_E_CHECK_DB_ERROR : 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; }
void swd::database::ensure_connection() { boost::unique_lock<boost::mutex> scoped_lock(dbi_mutex_); if (dbi_conn_ping(conn_) < 1) { swd::log::i()->send(swd::notice, "Dropped database connection"); if (dbi_conn_connect(conn_) < 0) { throw swd::exceptions::database_exception("Lost database connection"); } } }
static bool create_database(DbType type, QofBackend *qbe, dbi_conn conn, const char* db) { const char *dbname; const char *dbcreate; if (type == DbType::DBI_MYSQL) { dbname = "mysql"; dbcreate = "CREATE DATABASE %s CHARACTER SET utf8"; } else { dbname = "postgres"; dbcreate = "CREATE DATABASE %s WITH TEMPLATE template0 ENCODING 'UTF8'"; } PairVec options; options.push_back(std::make_pair("dbname", dbname)); try { set_options(conn, options); } catch (std::runtime_error& err) { qof_backend_set_error (qbe, ERR_BACKEND_SERVER_ERR); return false; } auto result = dbi_conn_connect (conn); if (result < 0) { PERR ("Unable to connect to %s database", dbname); qof_backend_set_error (qbe, ERR_BACKEND_SERVER_ERR); return false; } if (type == DbType::DBI_MYSQL) adjust_sql_options(conn); auto dresult = dbi_conn_queryf (conn, dbcreate, db); if (dresult == nullptr) { PERR ("Unable to create database '%s'\n", db); qof_backend_set_error (qbe, ERR_BACKEND_SERVER_ERR); return false; } if (type == DbType::DBI_PGSQL) { const char *alterdb = "ALTER DATABASE %s SET " "standard_conforming_strings TO on"; dbi_conn_queryf (conn, alterdb, db); } dbi_conn_close(conn); conn = nullptr; return true; }
/* 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; }
/* 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; } }
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"); }
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"); } }
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); }
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; }
static int cdbi_connect_database (cdbi_database_t *db) /* {{{ */ { dbi_driver driver; dbi_conn connection; size_t i; int status; if (db->connection != NULL) { status = dbi_conn_ping (db->connection); if (status != 0) /* connection is alive */ return (0); dbi_conn_close (db->connection); db->connection = NULL; } driver = dbi_driver_open_r (db->driver, dbi_instance); if (driver == NULL) { ERROR ("dbi plugin: cdbi_connect_database: dbi_driver_open_r (%s) failed.", db->driver); INFO ("dbi plugin: Maybe the driver isn't installed? " "Known drivers are:"); for (driver = dbi_driver_list_r (NULL, dbi_instance); driver != NULL; driver = dbi_driver_list_r (driver, dbi_instance)) { INFO ("dbi plugin: * %s", dbi_driver_get_name (driver)); } return (-1); } connection = dbi_conn_open (driver); if (connection == NULL) { ERROR ("dbi plugin: cdbi_connect_database: dbi_conn_open (%s) failed.", db->driver); return (-1); } /* Set all the driver options. Because this is a very very very generic * interface, the error handling is kind of long. If an invalid option is * encountered, it will get a list of options understood by the driver and * report that as `INFO'. This way, users hopefully don't have too much * trouble finding out how to configure the plugin correctly.. */ for (i = 0; i < db->driver_options_num; i++) { if (db->driver_options[i].is_numeric) { status = dbi_conn_set_option_numeric (connection, db->driver_options[i].key, db->driver_options[i].value.numeric); if (status != 0) { char errbuf[1024]; ERROR ("dbi plugin: cdbi_connect_database (%s): " "dbi_conn_set_option_numeric (\"%s\", %i) failed: %s.", db->name, db->driver_options[i].key, db->driver_options[i].value.numeric, cdbi_strerror (connection, errbuf, sizeof (errbuf))); } } else { status = dbi_conn_set_option (connection, db->driver_options[i].key, db->driver_options[i].value.string); if (status != 0) { char errbuf[1024]; ERROR ("dbi plugin: cdbi_connect_database (%s): " "dbi_conn_set_option (\"%s\", \"%s\") failed: %s.", db->name, db->driver_options[i].key, db->driver_options[i].value.string, cdbi_strerror (connection, errbuf, sizeof (errbuf))); } } if (status != 0) { char const *opt; INFO ("dbi plugin: This is a list of all options understood " "by the `%s' driver:", db->driver); for (opt = dbi_conn_get_option_list (connection, NULL); opt != NULL; opt = dbi_conn_get_option_list (connection, opt)) { INFO ("dbi plugin: * %s", opt); } dbi_conn_close (connection); return (-1); } } /* for (i = 0; i < db->driver_options_num; i++) */ status = dbi_conn_connect (connection); if (status != 0) { char errbuf[1024]; ERROR ("dbi plugin: cdbi_connect_database (%s): " "dbi_conn_connect failed: %s", db->name, cdbi_strerror (connection, errbuf, sizeof (errbuf))); dbi_conn_close (connection); return (-1); } if (db->select_db != NULL) { status = dbi_conn_select_db (connection, db->select_db); if (status != 0) { char errbuf[1024]; WARNING ("dbi plugin: cdbi_connect_database (%s): " "dbi_conn_select_db (%s) failed: %s. Check the `SelectDB' option.", db->name, db->select_db, cdbi_strerror (connection, errbuf, sizeof (errbuf))); dbi_conn_close (connection); return (-1); } } db->connection = connection; return (0); } /* }}} int cdbi_connect_database */
template <> void gnc_dbi_session_begin<DbType::DBI_SQLITE>(QofBackend* qbe, QofSession* session, const char* book_id, gboolean ignore_lock, gboolean create, gboolean force) { GncDbiBackend* be = (GncDbiBackend*)qbe; const char* msg = nullptr; gboolean file_exists; PairVec options; g_return_if_fail (qbe != nullptr); g_return_if_fail (session != nullptr); g_return_if_fail (book_id != nullptr); ENTER (" "); /* Remove uri type if present */ auto path = gnc_uri_get_path (book_id); std::string filepath{path}; g_free(path); GFileTest ftest = static_cast<decltype (ftest)> ( G_FILE_TEST_IS_REGULAR | G_FILE_TEST_EXISTS) ; file_exists = g_file_test (filepath.c_str(), ftest); if (!create && !file_exists) { qof_backend_set_error (qbe, ERR_FILEIO_FILE_NOT_FOUND); qof_backend_set_message (qbe, "Sqlite3 file %s not found", filepath.c_str()); PWARN ("Sqlite3 file %s not found", filepath.c_str()); LEAVE("Error"); return; } if (create && !force && file_exists) { qof_backend_set_error (qbe, ERR_BACKEND_STORE_EXISTS); msg = "Might clobber, no force"; PWARN ("%s", msg); LEAVE("Error"); return; } be->connect(nullptr); /* dbi-sqlite3 documentation says that sqlite3 doesn't take a "host" option */ options.push_back(std::make_pair("host", "localhost")); auto dirname = g_path_get_dirname (filepath.c_str()); auto basename = g_path_get_basename (filepath.c_str()); options.push_back(std::make_pair("dbname", basename)); options.push_back(std::make_pair("sqlite3_dbdir", dirname)); if (basename != nullptr) g_free (basename); if (dirname != nullptr) g_free (dirname); UriStrings uri; auto conn = conn_setup<DbType::DBI_SQLITE>(qbe, options, uri); if (conn == nullptr) { LEAVE("Error"); return; } auto result = dbi_conn_connect (conn); if (result < 0) { dbi_conn_close(conn); PERR ("Unable to connect to %s: %d\n", book_id, result); qof_backend_set_error (qbe, ERR_BACKEND_BAD_URL); LEAVE("Error"); return; } if (!conn_test_dbi_library(conn, qbe)) { if (create && !file_exists) { /* File didn't exist before, but it does now, and we don't want to * leave it lying around. */ dbi_conn_close (conn); conn = nullptr; g_unlink (filepath.c_str()); } dbi_conn_close(conn); LEAVE("Bad DBI Library"); return; } try { be->connect(new GncDbiSqlConnection(DbType::DBI_SQLITE, qbe, conn, ignore_lock)); } catch (std::runtime_error& err) { return; } /* We should now have a proper session set up. * Let's start logging */ xaccLogSetBaseName (filepath.c_str()); PINFO ("logpath=%s", filepath.c_str() ? filepath.c_str() : "(null)"); LEAVE (""); }
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); }
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; }
static int _sql_fetchrow(struct sql_table_helper* th,time_t *timestamp, rrd_value_t *value,int ordered) { char* dbi_errstr=NULL; char sql[10240]; time_t startt=0,endt=0; /*connect to the database if needed */ if (! th->conn) { rrd_set_error( "libdbi no parameters set for libdbi",th->filename,dbi_errstr); return -1; } if (! th->connected) { /* and now connect */ if (getenv("RRDDEBUGSQL")) { fprintf(stderr,"RRDDEBUGSQL: %li: connect to DB\n",time(NULL) ); } if (dbi_conn_connect(th->conn) <0) { dbi_conn_error(th->conn,(const char**)&dbi_errstr); rrd_set_error( "libdbi: problems connecting to db with connect string %s - error: %s",th->filename,dbi_errstr); _sql_close(th); return -1; } th->connected=1; } /* now find out regarding an existing result-set */ if (! th->result) { /* return if table_next is NULL */ if (th->table_next==NULL) { if (getenv("RRDDEBUGSQL")) { fprintf(stderr,"RRDDEBUGSQL: %li: reached last table to connect to\n",time(NULL) ); } /* but first close connection */ _sql_close(th); /* and return with end of data */ return 0; } /* calculate the table to use next */ th->table_start=th->table_next; th->table_next=_find_next_separator(th->table_start,'+'); _inline_unescape(th->table_start); /* and prepare FULL SQL Statement */ if (ordered) { snprintf(sql,sizeof(sql)-1,"SELECT %s as rrd_time, %s as rrd_value FROM %s WHERE %s ORDER BY %s", th->timestamp,th->value,th->table_start,th->where,th->timestamp); } else { snprintf(sql,sizeof(sql)-1,"SELECT %s as rrd_time, %s as rrd_value FROM %s WHERE %s", th->timestamp,th->value,th->table_start,th->where); } /* and execute sql */ if (getenv("RRDDEBUGSQL")) { startt=time(NULL); fprintf(stderr,"RRDDEBUGSQL: %li: executing %s\n",startt,sql); } th->result=dbi_conn_query(th->conn,sql); if (startt) { endt=time(NULL);fprintf(stderr,"RRDDEBUGSQL: %li: timing %li\n",endt,endt-startt); } /* handle error case */ if (! th->result) { dbi_conn_error(th->conn,(const char**)&dbi_errstr); if (startt) { fprintf(stderr,"RRDDEBUGSQL: %li: error %s\n",endt,dbi_errstr); } rrd_set_error("libdbi: problems with query: %s - errormessage: %s",sql,dbi_errstr); _sql_close(th); return -1; } } /* and now fetch key and value */ if (! dbi_result_next_row(th->result)) { /* free result */ dbi_result_free(th->result); th->result=NULL; /* and call recursively - this will open the next table or close connection as a whole*/ return _sql_fetchrow(th,timestamp,value,ordered); } /* and return with flag for one value */ *timestamp=rrd_fetch_dbi_long(th->result,1); *value=rrd_fetch_dbi_double(th->result,2); return 1; }
template <DbType T> void gnc_dbi_session_begin (QofBackend* qbe, QofSession* session, const char* book_id, gboolean ignore_lock, gboolean create, gboolean force) { GncDbiBackend* be = (GncDbiBackend*)qbe; GncDbiTestResult dbi_test_result = GNC_DBI_PASS; PairVec options; g_return_if_fail (qbe != nullptr); g_return_if_fail (session != nullptr); g_return_if_fail (book_id != nullptr); ENTER (" "); /* Split the book-id * Format is protocol://username:password@hostname:port/dbname where username, password and port are optional) */ UriStrings uri(book_id); if (T == DbType::DBI_PGSQL) { if (uri.m_portnum == 0) uri.m_portnum = PGSQL_DEFAULT_PORT; /* Postgres's SQL interface coerces identifiers to lower case, but the * C interface is case-sensitive. This results in a mixed-case dbname * being created (with a lower case name) but then dbi can't conect to * it. To work around this, coerce the name to lowercase first. */ auto lcname = g_utf8_strdown (uri.dbname(), -1); uri.m_dbname = std::string{lcname}; g_free(lcname); } be->connect(nullptr); auto conn = conn_setup<T>(qbe, options, uri); if (conn == nullptr) { LEAVE("Error"); return; } be->set_exists(true); //May be unset in the error handler. auto result = dbi_conn_connect (conn); if (result == 0) { if (T == DbType::DBI_MYSQL) adjust_sql_options (conn); if(!conn_test_dbi_library(conn, qbe)) { dbi_conn_close(conn); LEAVE("Error"); return; } if (create && !force && save_may_clobber_data (conn, uri.quote_dbname(T))) { qof_backend_set_error (qbe, ERR_BACKEND_STORE_EXISTS); PWARN ("Databse already exists, Might clobber it."); dbi_conn_close(conn); LEAVE("Error"); return; } } else { if (be->exists()) { PERR ("Unable to connect to database '%s'\n", uri.dbname()); qof_backend_set_error (qbe, ERR_BACKEND_SERVER_ERR); dbi_conn_close(conn); LEAVE("Error"); return; } if (create) { if (!create_database(T, qbe, conn, uri.quote_dbname(T).c_str())) { dbi_conn_close(conn); LEAVE("Error"); return; } conn = conn_setup<T>(qbe, options, uri); result = dbi_conn_connect (conn); if (result < 0) { PERR ("Unable to create database '%s'\n", uri.dbname()); qof_backend_set_error (qbe, ERR_BACKEND_SERVER_ERR); dbi_conn_close(conn); LEAVE("Error"); return; } if (T == DbType::DBI_MYSQL) adjust_sql_options (conn); if (!conn_test_dbi_library(conn, qbe)) { if (T == DbType::DBI_PGSQL) dbi_conn_select_db (conn, "template1"); dbi_conn_queryf (conn, "DROP DATABASE %s", uri.quote_dbname(T).c_str()); dbi_conn_close(conn); return; } } else { qof_backend_set_error (qbe, ERR_BACKEND_NO_SUCH_DB); qof_backend_set_message (qbe, "Database %s not found", uri.dbname()); } } be->connect(nullptr); try { be->connect(new GncDbiSqlConnection(T, qbe, conn, ignore_lock)); } catch (std::runtime_error& err) { return; } /* We should now have a proper session set up. * Let's start logging */ auto translog_path = gnc_build_translog_path (uri.basename().c_str()); xaccLogSetBaseName (translog_path); PINFO ("logpath=%s", translog_path ? translog_path : "(null)"); g_free (translog_path); LEAVE (" "); }
/** * 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); }
/* 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; }
/** * Prepare SQL queries and perform them. * * @param format printf-like string of SQL query * @param callback pointer to function to be called on results of SQL query * @param firstarg pointer to buffer for callback returned data * @return 0 (always, due to SQLite policy) */ int tagsistant_real_query( dbi_conn dbi, const char *format, int (*callback)(void *, dbi_result), char *file, int line, void *firstarg, ...) { va_list ap; va_start(ap, firstarg); /* check if connection has been created */ if (NULL == dbi) { dbg('s', LOG_ERR, "ERROR! DBI connection was not initialized!"); return(0); } #if TAGSISTANT_USE_QUERY_MUTEX /* lock the connection mutex */ g_mutex_lock(&tagsistant_query_mutex); #endif /* check if the connection is alive */ if (!dbi_conn_ping(dbi) && dbi_conn_connect(dbi) < 0) { #if TAGSISTANT_USE_QUERY_MUTEX g_mutex_unlock(&tagsistant_query_mutex); #endif dbg('s', LOG_ERR, "ERROR! DBI Connection has gone!"); return(0); } /* replace all the single or double quotes with "<><>" in the format */ gchar *escaped_format = g_regex_replace_literal(RX1, format, -1, 0, "<><>", 0, NULL); /* format the statement */ gchar *statement = g_strdup_vprintf(escaped_format, ap); if (NULL == statement) { #if TAGSISTANT_USE_QUERY_MUTEX /* lock the connection mutex */ g_mutex_unlock(&tagsistant_query_mutex); #endif dbg('s', LOG_ERR, "Null SQL statement"); g_free(escaped_format); return(0); } /* prepend a backslash to all the single quotes inside the arguments */ gchar *escaped_statement_tmp = g_regex_replace_literal(RX2, statement, -1, 0, "''", 0, NULL); /* replace "<><>" with a single quote */ gchar *escaped_statement = g_regex_replace_literal(RX3, escaped_statement_tmp, -1, 0, "'", 0, NULL); /* log and do the query */ dbg('s', LOG_INFO, "SQL from %s:%d: [%s]", file, line, escaped_statement); dbi_result result = dbi_conn_query(dbi, escaped_statement); tagsistant_dirty_logging(escaped_statement); tagsistant_wal(dbi, escaped_statement); g_free_null(escaped_format); g_free_null(escaped_statement_tmp); g_free_null(escaped_statement); /* call the callback function on results or report an error */ int rows = 0; if (result) { if (callback) { while (dbi_result_next_row(result)) { callback(firstarg, result); rows++; } } dbi_result_free(result); } else { /* get the error message */ const char *errmsg = NULL; dbi_conn_error(dbi, &errmsg); if (errmsg) dbg('s', LOG_ERR, "Error: %s.", errmsg); } #if TAGSISTANT_USE_QUERY_MUTEX g_mutex_unlock(&tagsistant_query_mutex); #endif return(rows); }