bool DatabasePostgre::Initialize(const char *infoString) { if(!Database::Initialize(infoString)) return false; tranThread = NULL; InitDelayThread(); Tokens tokens = StrSplit(infoString, ";"); Tokens::iterator iter; std::string host, port_or_socket_dir, user, password, database; iter = tokens.begin(); if(iter != tokens.end()) host = *iter++; if(iter != tokens.end()) port_or_socket_dir = *iter++; if(iter != tokens.end()) user = *iter++; if(iter != tokens.end()) password = *iter++; if(iter != tokens.end()) database = *iter++; if (host == ".") mPGconn = PQsetdbLogin(NULL, port_or_socket_dir == "." ? NULL : port_or_socket_dir.c_str(), NULL, NULL, database.c_str(), user.c_str(), password.c_str()); else mPGconn = PQsetdbLogin(host.c_str(), port_or_socket_dir.c_str(), NULL, NULL, database.c_str(), user.c_str(), password.c_str()); /* check to see that the backend connection was successfully made */ if (PQstatus(mPGconn) != CONNECTION_OK) { sLog.outError( "Could not connect to Postgre database at %s: %s", host.c_str(), PQerrorMessage(mPGconn)); PQfinish(mPGconn); mPGconn = NULL; return false; } else { sLog.outDetail( "Connected to Postgre database at %s", host.c_str()); sLog.outString( "PostgreSQL server ver: %d",PQserverVersion(mPGconn)); return true; } }
void PostgresProvider::Init(const xml::Element& rConfig) { // initialize connection const xml::Element& rConnection = rConfig.GetChildElementByName("connection"); m_pImpl->m_sHost = rConnection.GetChildElementByName("host").GetTextValue(); m_pImpl->m_sPort = rConnection.GetChildElementByName("port").GetTextValue(); m_pImpl->m_sDataBase = rConnection.GetChildElementByName("db").GetTextValue(); m_pImpl->m_sLogin = rConnection.GetChildElementByName("login").GetTextValue(); m_pImpl->m_sPassword = rConnection.GetChildElementByName("password").GetTextValue(); STAFF_ASSERT(!m_pImpl->m_pConn, "Already connected"); m_pImpl->m_pConn = PQsetdbLogin(m_pImpl->m_sHost.c_str(), m_pImpl->m_sPort.c_str(), "", "", m_pImpl->m_sDataBase.c_str(), m_pImpl->m_sLogin.c_str(), m_pImpl->m_sPassword.c_str()); STAFF_ASSERT(m_pImpl->m_pConn, "Failed to set db login"); if (PQstatus(m_pImpl->m_pConn) != CONNECTION_OK) { std::string sError = std::string("Failed to login: "******"UTF8"); STAFF_ASSERT(nResult == 0, std::string("error setting encoding: ") + PQerrorMessage(m_pImpl->m_pConn)); }
/* establish connection with database. */ PGconn * sql_conn(struct options * my_opts) { PGconn *conn; /* login */ conn = PQsetdbLogin(my_opts->hostname, my_opts->port, NULL, /* options */ NULL, /* tty */ my_opts->dbname, my_opts->username, my_opts->password); /* deal with errors */ if (PQstatus(conn) != CONNECTION_OK) { fprintf(stderr, "%s: connection to database '%s' failed.\n", "oid2name", my_opts->dbname); fprintf(stderr, "%s", PQerrorMessage(conn)); PQfinish(conn); exit(1); } /* return the conn if good */ return conn; }
/* * plpgsql_connect_single - * used to reconnect to a single database when one is down or none is * connected yet. Log all errors and set the stat field of host accordingly */ static void plpgsql_connect_single(HOST *host, char *dbname, char *username, char *password) { if ((host->db = PQsetdbLogin(host->name, host->port, NULL, NULL, dbname, username, password)) == NULL || PQstatus(host->db) != CONNECTION_OK) { msg_warn("connect to pgsql server %s: %s", host->hostname, PQerrorMessage(host->db)); plpgsql_down_host(host); return; } if (msg_verbose) msg_info("dict_pgsql: successful connection to host %s", host->hostname); /* * XXX Postfix does not send multi-byte characters. The following piece * of code is an explicit statement of this fact, and the database server * should not accept multi-byte information after this point. */ if (PQsetClientEncoding(host->db, "LATIN1") != 0) { msg_warn("dict_pgsql: cannot set the encoding to LATIN1, skipping %s", host->hostname); plpgsql_down_host(host); return; } /* Success. */ host->stat = STATACTIVE; }
/** * Connect to Postgres with the current settings through libpq. * * @author Martin Turon * * @return Error code from Postgres after executing command * * @version 2004/8/8 mturon Initial version * */ PGconn *xdb_connect() { char *pgoptions, *pgtty; PGconn *conn; /* * begin, by setting the parameters for a backend connection if the * parameters are null, then the system will try to use reasonable * defaults by looking up environment variables or, failing that, * using hardwired constants */ pgoptions = NULL; /* special options to start up the backend * server */ pgtty = NULL; /* debugging tty for the backend server */ /* make a connection to the database */ conn = PQsetdbLogin(g_server, g_port, pgoptions, pgtty, g_dbname, g_user, g_passwd); /* * check to see that the backend connection was successfully made */ if (PQstatus(conn) == CONNECTION_BAD) { fprintf(stderr, "error: Connection to database '%s' failed.\n", g_dbname); fprintf(stderr, "%s", PQerrorMessage(conn)); conn = xdb_exit(conn); } return conn; }
PGConnection * pgconn_create(const char *host, const char *db, const char *user, const char *password) { PGConnection *conn; if (db == NULL) THROW("SQLException", "Database may not be (null)"); conn = emalloc(sizeof(PGConnection)); conn->stream = PQsetdbLogin(host,"5432",NULL,NULL,db,user,password); if (PQstatus(conn->stream) != CONNECTION_OK) THROW("SQLException", "%s", PQerrorMessage(conn->stream)); if(pgTypes == NULL){ PGResultSet *rset = pgconn_query(conn, "SELECT oid,typname FROM pg_type"); pgTypes = ihtab_createDefault(); while(pgrset_next(rset)){ ihtab_put(pgTypes, pgrset_getInt(rset, 0), pgrset_getString(rset, 1)); } } return conn; }
void db_init_pg_conn(const char *conf_file) { if(config_read_file(&config, conf_file) != CONFIG_TRUE) { fprintf(stderr, "%s:%d %s\n", config_error_file(&config), config_error_line(&config), config_error_text(&config)); config_destroy(&config); exit(EXIT_FAILURE); } conn = PQsetdbLogin( read_db_setting("db_host"), read_db_setting("db_port"), NULL, NULL, read_db_setting("db_name"), read_db_setting("db_login"), read_db_setting("db_password")); const char *store_dir_tmp = read_db_setting("store_dir"); store_dir = (char*)malloc(strlen(store_dir_tmp)+1); strcpy(store_dir, store_dir_tmp); if(PQstatus(conn) != CONNECTION_OK) { fprintf(stderr, "Connection to database failed: %s\n", PQerrorMessage(conn)); config_destroy(&config); exit(EXIT_FAILURE); } else { fprintf(stderr, "database OK\n"); } if(pthread_mutex_init(&db_lock, NULL) < 0) { fprintf(stderr, "pthread_mutex_init failed\n"); exit(EXIT_FAILURE); } }
static int switch_database(struct dbpath *dbpath) { PGconn *newdbconn; if (dbpath_is_root(*dbpath)) return 1; if (strcmp(dbpath->database, PQdb(dbconn)) == 0) return 1; newdbconn = PQsetdbLogin(PQhost(dbconn), PQport(dbconn), PQoptions(dbconn), PQtty(dbconn), dbpath->database, PQuser(dbconn), PQpass(dbconn)); if (PQstatus(newdbconn) != CONNECTION_OK) { debug("new connection failed"); PQfinish(newdbconn); return 0; } PQfinish(dbconn); dbconn = newdbconn; return 1; }
gboolean quorra_db_object_initConnection(QuorraDbObject * obj, gchar * pghost, gchar * pgport, gchar * dbName, gchar * login, gchar * pwd) { QuorraDbObjectPrivate * priv; if (dbName == NULL) { g_warning("Connection to database failed: database isn't set!"); return FALSE; } priv = QUORRA_DBOBJ_GET_PRIVATE (obj); if (priv) { priv->connection = PQsetdbLogin(pghost,pgport,NULL,NULL,dbName,login,pwd); /* Check to see that the backend connection was successfully made */ if (PQstatus(priv->connection) != CONNECTION_OK) { g_warning("Connection to database failed: %s", PQerrorMessage(priv->connection)); PQfinish(priv->connection); return FALSE; } return TRUE; } return FALSE; }
static HB_ERRCODE pgsqlConnect( SQLDDCONNECTION * pConnection, PHB_ITEM pItem ) { PGconn * pConn; ConnStatusType status; const char * pszHost; pszHost = hb_arrayGetCPtr( pItem, 2 ); if( pszHost && ( strncmp( pszHost, "postgresql://", 13 ) == 0 || strchr( pszHost, '=' ) ) ) pConn = PQconnectdb( pszHost ); else pConn = PQsetdbLogin( pszHost, hb_arrayGetCPtr( pItem, 6 ), hb_arrayGetCPtr( pItem, 7 ), hb_arrayGetCPtr( pItem, 8 ), hb_arrayGetCPtr( pItem, 5 ), hb_arrayGetCPtr( pItem, 3 ), hb_arrayGetCPtr( pItem, 4 ) ); if( ! pConn ) /* Low memory, etc */ { /* TODO: error */ return HB_FAILURE; } status = PQstatus( pConn ); if( status != CONNECTION_OK ) { /* TODO: error */ PQfinish( pConn ); return HB_FAILURE; } pConnection->pSDDConn = hb_xgrab( sizeof( SDDCONN ) ); ( ( SDDCONN * ) pConnection->pSDDConn )->pConn = pConn; return HB_SUCCESS; }
void PostgreSQLConnection::connect() { bool reconnecting = false; if (_pgConn != nullptr) //reconnection attempt { if (!_ConnectionLost()) return; else reconnecting = true; } //remove any state from previous session this->clear(); Poco::Logger& logger = _dbEngine->getLogger(); for(;;) { if (reconnecting) PQreset(_pgConn); else { if (_host == ".") _pgConn = PQsetdbLogin(nullptr, _port == "." ? nullptr : _port.c_str(), nullptr, nullptr, _database.c_str(), _user.c_str(), _password.c_str()); else _pgConn = PQsetdbLogin(_host.c_str(), _port.c_str(), nullptr, nullptr, _database.c_str(), _user.c_str(), _password.c_str()); } //check to see that the backend connection was successfully made if (_ConnectionLost()) { const char* actionToDo = "connect"; if (reconnecting) actionToDo = "reconnect"; static const long sleepTime = 1000; logger.warning(Poco::format("Could not %s to Postgre database at %s: %s, retrying in %d seconds", string(actionToDo),_host,lastErrorDescr(),static_cast<int>(sleepTime/1000))); Poco::Thread::sleep(sleepTime); continue; } break; } string actionDone = (reconnecting)?string("Reconnected"):string("Connected"); poco_information(logger,Poco::format("%s to Postgre database %s:%s/%s server ver: %d",actionDone,_host,_port,_database,PQserverVersion(_pgConn))); }
int main (int argc, char **argv) { int elapsed_time; int status = STATE_UNKNOWN; /* begin, by setting the parameters for a backend connection if the * parameters are null, then the system will try to use reasonable * defaults by looking up environment variables or, failing that, * using hardwired constants */ pgoptions = NULL; /* special options to start up the backend server */ pgtty = NULL; /* debugging tty for the backend server */ setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); /* Set signal handling and alarm */ if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) { usage4 (_("Cannot catch SIGALRM")); } alarm (timeout_interval); /* make a connection to the database */ time (&start_time); conn = PQsetdbLogin (pghost, pgport, pgoptions, pgtty, dbName, pguser, pgpasswd); time (&end_time); elapsed_time = (int) (end_time - start_time); /* check to see that the backend connection was successfully made */ if (PQstatus (conn) == CONNECTION_BAD) { printf (_("CRITICAL - no connection to '%s' (%s).\n"), dbName, PQerrorMessage (conn)); PQfinish (conn); return STATE_CRITICAL; } else if (elapsed_time > tcrit) { status = STATE_CRITICAL; } else if (elapsed_time > twarn) { status = STATE_WARNING; } else { status = STATE_OK; } PQfinish (conn); printf (_(" %s - database %s (%d sec.)|%s\n"), state_text(status), dbName, elapsed_time, fperfdata("time", elapsed_time, "s", (int)twarn, twarn, (int)tcrit, tcrit, TRUE, 0, FALSE,0)); return status; }
/* * Connect to the database. */ static isc_result_t db_connect (struct dbinfo *dbi) { dbi->conn = PQsetdbLogin (dbi->host, NULL, NULL, NULL, dbi->database, dbi->user, dbi->passwd); if (PQstatus (dbi->conn) == CONNECTION_OK) return (ISC_R_SUCCESS); else return (ISC_R_FAILURE); }
/*! * \brief Create a new connection * * Create a new connection structure in private memory, open the PostgreSQL * connection and set reference count to 1 * \param id database id * \return postgres connection structure, 0 on error */ struct pg_con* db_postgres_new_connection(struct db_id* id) { struct pg_con* ptr; char *ports; LM_DBG("db_id = %p\n", id); if (!id) { LM_ERR("invalid db_id parameter value\n"); return 0; } ptr = (struct pg_con*)pkg_malloc(sizeof(struct pg_con)); if (!ptr) { LM_ERR("failed trying to allocated %lu bytes for connection structure." "\n", (unsigned long)sizeof(struct pg_con)); return 0; } LM_DBG("%p=pkg_malloc(%lu)\n", ptr, (unsigned long)sizeof(struct pg_con)); memset(ptr, 0, sizeof(struct pg_con)); ptr->ref = 1; if (id->port) { ports = int2str(id->port, 0); LM_DBG("opening connection: postgres://xxxx:xxxx@%s:%d/%s\n", ZSW(id->host), id->port, ZSW(id->database)); } else { ports = NULL; LM_DBG("opening connection: postgres://xxxx:xxxx@%s/%s\n", ZSW(id->host), ZSW(id->database)); } ptr->con = PQsetdbLogin(id->host, ports, NULL, NULL, id->database, id->username, id->password); LM_DBG("PQsetdbLogin(%p)\n", ptr->con); if( (ptr->con == 0) || (PQstatus(ptr->con) != CONNECTION_OK) ) { LM_ERR("%s\n", PQerrorMessage(ptr->con)); PQfinish(ptr->con); goto err; } ptr->connected = 1; ptr->timestamp = time(0); ptr->id = id; return ptr; err: if (ptr) { LM_ERR("cleaning up %p=pkg_free()\n", ptr); pkg_free(ptr); } return 0; }
void *be_pg_init() { struct pg_backend *conf; char *host, *user, *pass, *dbname, *p, *port; char *userquery; _log(LOG_DEBUG, "}}}} POSTGRES"); host = p_stab("host"); p = p_stab("port"); user = p_stab("user"); pass = p_stab("pass"); dbname = p_stab("dbname"); host = (host) ? host : strdup("localhost"); port = (p) ? p : strdup("5432"); userquery = p_stab("userquery"); if (!userquery) { _fatal("Mandatory option 'userquery' is missing"); return (NULL); } if ((conf = (struct pg_backend *)malloc(sizeof(struct pg_backend))) == NULL) return (NULL); conf->conn = NULL; conf->host = host; conf->port = port; conf->user = user; conf->pass = pass; conf->dbname = dbname; conf->userquery = userquery; conf->superquery = p_stab("superquery"); conf->aclquery = p_stab("aclquery"); _log( LOG_DEBUG, "HERE: %s", conf->superquery ); _log( LOG_DEBUG, "HERE: %s", conf->aclquery ); char *connect_string = NULL; conf->conn = PQsetdbLogin(conf->host, conf->port, NULL, NULL, conf->dbname, conf->user, conf->pass ); if (PQstatus(conf->conn) == CONNECTION_BAD) { free(conf); free(connect_string); _fatal("We were unable to connect to the database"); return (NULL); } free(connect_string); return ((void *)conf); }
int main() { Conn_pointer=PQsetdbLogin(pghost, pgport, pgoptions, pgtty, dbName, username, password); if (PQstatus(Conn_pointer) == CONNECTION_BAD) { printf("cannot connect to the database!\n"); return -1; } printf ("Connect to database seccess\n"); return 0; }
PGconn *make_connection(database_settings *db) { PGconn *conn = NULL; print_info("Trying to connect to database.\n"); conn = PQsetdbLogin(db->host, db->port, NULL, NULL, db->name, db->user, db->pass); if (PQstatus(conn) != CONNECTION_OK) { fprintf(stderr, "Error connecting to database.\n"); exit(-1); } print_info("Successfully connected to database.\n"); return conn; }
/* ML type : 6-element record -> pgconn_ */ EXTERNML value pq_setdb(value args) { char* dbhost = StringOrNull_val(Field(args, 0)); char* dbname = StringOrNull_val(Field(args, 1)); char* dboptions = StringOrNull_val(Field(args, 2)); char* dbport = StringOrNull_val(Field(args, 3)); char* dbpwd = StringOrNull_val(Field(args, 4)); char* dbtty = StringOrNull_val(Field(args, 5)); char* dbuser = StringOrNull_val(Field(args, 6)); return (value)(pgconn_alloc(PQsetdbLogin(dbhost, dbport, dboptions, dbtty, dbname, dbuser, dbpwd))); }
/* establish connection with database. */ PGconn * sql_conn(struct options * my_opts) { PGconn *conn; char *password = NULL; bool new_pass; /* * Start the connection. Loop until we have a password if requested by * backend. */ do { new_pass = false; conn = PQsetdbLogin(my_opts->hostname, my_opts->port, NULL, /* options */ NULL, /* tty */ my_opts->dbname, my_opts->username, password); if (!conn) { fprintf(stderr, "%s: could not connect to database %s\n", "oid2name", my_opts->dbname); exit(1); } if (PQstatus(conn) == CONNECTION_BAD && PQconnectionNeedsPassword(conn) && password == NULL) { PQfinish(conn); password = simple_prompt("Password: "******"%s: could not connect to database %s: %s", "oid2name", my_opts->dbname, PQerrorMessage(conn)); PQfinish(conn); exit(1); } /* return the conn if good */ return conn; }
/* * Make a database connection with the given parameters. An * interactive password prompt is automatically issued if required. */ PGconn * connectDatabase(const char *dbname, const char *pghost, const char *pgport, const char *pguser, enum trivalue prompt_password, const char *progname) { PGconn *conn; char *password = NULL; bool new_pass; if (prompt_password == TRI_YES) password = simple_prompt("Password: "******"%s: could not connect to database %s\n"), progname, dbname); exit(1); } if (PQstatus(conn) == CONNECTION_BAD && PQconnectionNeedsPassword(conn) && password == NULL && prompt_password != TRI_NO) { PQfinish(conn); password = simple_prompt("Password: "******"%s: could not connect to database %s: %s"), progname, dbname, PQerrorMessage(conn)); exit(1); } return conn; }
int PGDatabase::Connect( const PGConnInfo& dbConnInfo ) { m_pConnect= PQsetdbLogin(dbConnInfo.pghost, dbConnInfo.pgport, "", "", dbConnInfo.dbName, dbConnInfo.login, dbConnInfo.passwd); if (PQstatus(m_pConnect) != CONNECTION_OK) { fprintf(stderr, "Connection to database failed: %s", PQerrorMessage(m_pConnect)); PQfinish(m_pConnect); return 1; } return 0; }
int pg_createconn(ClipMachine* mp){ char* pghost = _clip_parc(mp,2); char* pgport = _clip_parc(mp,3); char* login = _clip_parc(mp,4); char* pwd = _clip_parc(mp,5); char* dbName = _clip_parc(mp,6); char* pgtty = _clip_parc(mp,7); char* pgoptions = _clip_parc(mp,8); char* trpars = _clip_parc(mp,10); PGconn* tmpconn; PGresult* res; PG_CONN* conn; char str[256]; tmpconn = PQsetdbLogin(pghost,pgport,pgoptions,pgtty,dbName,login,pwd); if(PQstatus(tmpconn)!=CONNECTION_OK){ _clip_trap_err(mp,0,0,0,subsys,ER_CONNECT,PQerrorMessage(tmpconn)); return -1; } conn = malloc(sizeof(PG_CONN)); memset(conn,0,sizeof(PG_CONN)); conn->conn = tmpconn; conn->vtbl = &vtbl; res = PQexec(tmpconn,"SET DATESTYLE='ISO'"); if(PQresultStatus(res) != PGRES_COMMAND_OK){ _clip_trap_err(mp,0,0,0,subsys,ER_BADSTATEMENT, PQresultErrorMessage(res)); return -1; } if(!trpars) trpars = _clip_fetch_item(mp, _clip_hashstr("PG_ISOLATION_LEVEL")); if(!trpars) trpars = _clip_fetch_item(mp, _clip_hashstr("SQL_ISOLATION_LEVEL")); if(trpars){ snprintf(str,sizeof(str),"set session characteristics as transaction isolation level %s",trpars); res = PQexec(tmpconn,str); if(PQresultStatus(res) != PGRES_COMMAND_OK){ _clip_trap_err(mp,0,0,0,subsys,ER_BADSTATEMENT, PQresultErrorMessage(res)); return -1; } } PQsetNoticeProcessor(tmpconn, notice_processor, NULL); return _clip_store_c_item(mp,(void*)conn,_C_ITEM_TYPE_SQL,destroy_pg_conn); }
DatabasePostgreSQL::DatabasePostgreSQL(string user, string pass, string host, string port, string name) { db = nullptr; db = PQsetdbLogin(host.c_str(), port.c_str(), nullptr, nullptr, name.c_str(), user.c_str(), pass.c_str()); if(!db) { Log.Out(Logs::General, Logs::Error, "Failed to connect to PostgreSQL Database."); } if(PQstatus(db) != CONNECTION_OK) { Log.Out(Logs::General, Logs::Error, "Failed to connect to PostgreSQL Database."); PQfinish(db); db = nullptr; } }
DatabasePostgreSQL::DatabasePostgreSQL(string user, string pass, string host, string port, string name) { db = nullptr; db = PQsetdbLogin(host.c_str(), port.c_str(), nullptr, nullptr, name.c_str(), user.c_str(), pass.c_str()); if(!db) { server_log->Log(log_database, "Failed to connect to PostgreSQL Database."); } if(PQstatus(db) != CONNECTION_OK) { server_log->Log(log_database, "Failed to connect to PostgreSQL Database."); PQfinish(db); db = nullptr; } }
bool ConnectToDatabase( PGconn*& connection, char* host_name, char* port, char* options, char* tty, char* database_name, char* username, char* password ) { if (database_name == "") return false; if (username == "") return false; if (password == "") return false; connection = PQsetdbLogin( host_name, port, options, tty, database_name, username, password ); if ( PQstatus( connection ) != CONNECTION_OK ) { PQfinish( connection ); connection = NULL; return false; } return true; }
void sql_database::init(const std::string & host, uint16_t port, const std::string & user, const std::string & password, const std::string & name) { for (auto && c : _connections) { auto temp = PQsetdbLogin(host.c_str(), boost::lexical_cast<std::string>(port).c_str(), nullptr, nullptr, name.c_str(), user.c_str(), password.c_str()); auto guard = make_guard(std::bind(&PQfinish, temp)); if (PQstatus(temp) == CONNECTION_BAD) throw sql_error { "connection failed due to: "_s + PQerrorMessage(temp) }; guard.dismiss(); if (c.conn != nullptr) PQfinish(c.conn); c.conn = temp; } }
/** void *postgresql_osdb_connect(char *host, char *user, char *pass, char *db) * Create the PostgreSQL database connection. * Return NULL on error */ void *postgresql_osdb_connect(char *host, char *user, char *pass, char *db, int port, char *sock) { PGconn *conn; conn = PQsetdbLogin(host, NULL, NULL, NULL, db, user, pass); if(PQstatus(conn) == CONNECTION_BAD) { merror(DBCONN_ERROR, ARGV0, host, db, PQerrorMessage(conn)); PQfinish(conn); return(NULL); } return(conn); }
/* * Open a database connection */ static PGconn * DBConnect(const char *host, const char *port, char *database, const char *user) { char *password = NULL; char *password_prompt = NULL; bool need_pass; PGconn *conn = NULL; /* loop until we have a password if requested by backend */ do { need_pass = false; conn = PQsetdbLogin(host, port, NULL, NULL, database, user, password); if (PQstatus(conn) == CONNECTION_BAD && strcmp(PQerrorMessage(conn), PQnoPasswordSupplied) == 0 && !feof(stdin)) { PQfinish(conn); need_pass = true; free(password); password = NULL; printf("\nPassword: "******"Connection to database failed: %s", PQerrorMessage(conn)); exit_gracefuly(1); } if (password) free(password); return conn; }
/* ** Connects to a data source. */ static int env_connect (lua_State *L) { const char *sourcename = luaL_checkstring(L, 2); const char *username = luaL_optstring(L, 3, NULL); const char *password = luaL_optstring(L, 4, NULL); const char *pghost = luaL_optstring(L, 5, NULL); const char *pgport = luaL_optstring(L, 6, NULL); PGconn *conn; getenvironment (L); /* validate environment */ conn = PQsetdbLogin(pghost, pgport, NULL, NULL, sourcename, username, password); if (PQstatus(conn) == CONNECTION_BAD) { int rc = luasql_failmsg(L, "error connecting to database. PostgreSQL: ", PQerrorMessage(conn)); PQfinish(conn); return rc; } PQsetNoticeProcessor(conn, notice_processor, NULL); return create_connection(L, 1, conn); }
void probe(gpointer data, gpointer user_data) { char *dbhost, *dbuser, *dbpasswd, *dbname; struct probedef *probe = (struct probedef *)data; PGconn *conn; PGresult *res; struct timeval start, now; if (!probe->query || strlen(probe->query) < 5) { probe->msg = strdup("Please specify a valid query."); return; } dbhost = probe->ipaddress; dbname = probe->dbname; dbuser = probe->dbuser; dbpasswd = probe->dbpasswd; gettimeofday(&start, NULL); conn = PQsetdbLogin(dbhost, NULL, NULL, NULL, dbname, dbuser, dbpasswd); if (PQstatus(conn) == CONNECTION_BAD) { probe->msg = strdup(PQerrorMessage(conn)); goto err_exit; } gettimeofday(&now, NULL); probe->connect = ((float) timeval_diff(&now, &start)) * 0.000001; res = PQexec(conn, probe->query); if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) { probe->msg = strdup(PQerrorMessage(conn)); goto exit; } if (PQntuples(res) == 0) { probe->msg = strdup("Empty set"); } exit: PQclear(res); err_exit: PQfinish(conn); gettimeofday(&now, NULL); probe->total = ((float) timeval_diff(&now, &start)) * 0.000001; return; }