void insert_logentry(ACE_CString pq, ACE_CString dig, ACE_CString step0, ACE_CString note, ACE_CString dest){ /* ACE_DEBUG((LM_INFO, "note = %s dest= %s\n", note.c_str(),dest.c_str())); */ ACE_CString sql = "insert into logentry0(pq,dig,note,dest,valid,setup) values('" + pq +"','" +dig+"','"; sql += note + "','"; sql += dest + "', 1, now())" ; /* ACE_DEBUG((LM_INFO, "(%P|%t):%l sql = %s\n", sql.c_str())); */ PGconn* con; PGresult* res; con = PQconnectdb("host=45.33.3.188 port=5432 dbname=nv user=dec"); if(PQstatus(con)!= CONNECTION_OK){ ACE_DEBUG((LM_INFO, "Connection to database failed:%s\n", PQerrorMessage(con))); reclaim_conn(con); } PQexec(con, sql.c_str()); reclaim_conn(con); }
void DBConnection::connect(void) { QString str_aux; /* If the connection string is not established indicates that the user is trying to connect without configuring connection parameters, thus an error is raised */ if(connection_str=="") throw Exception(ERR_CONNECTION_NOT_CONFIGURED, __PRETTY_FUNCTION__, __FILE__, __LINE__); //Try to connect to the database connection=PQconnectdb(connection_str.toStdString().c_str()); /* If the connection descriptor has not been allocated or if the connection state is CONNECTION_BAD it indicates that the connection was not successful */ if(connection==NULL || PQstatus(connection)==CONNECTION_BAD) { //Raise the error generated by the DBMS str_aux=QString(Exception::getErrorMessage(ERR_CONNECTION_NOT_STABLISHED)) .arg(PQerrorMessage(connection)); throw Exception(str_aux, ERR_CONNECTION_NOT_STABLISHED, __PRETTY_FUNCTION__, __FILE__, __LINE__); } }
void CPokerTrackerThread::Connect(void) { write_log(preferences.debug_pokertracker(), "[PokerTracker] Trying to open PostgreSQL DB...\n"); if (!AllConnectionDataSpecified()) { write_log(preferences.debug_pokertracker(), "[PokerTracker] Can't connect to DB. Vital data missing\n"); return; } _conn_str = CreateConnectionString(preferences.pt_ip_addr(), preferences.pt_port(), preferences.pt_user(), preferences.pt_pass(), preferences.pt_dbname()); _pgconn = PQconnectdb(_conn_str.GetString()); if (PQstatus(_pgconn) == CONNECTION_OK) { write_log(preferences.debug_pokertracker(), "[PokerTracker] PostgreSQL DB opened successfully <%s/%s/%s>\n", preferences.pt_ip_addr(), preferences.pt_port(), preferences.pt_dbname()); _connected = true; } else { write_log(preferences.debug_pokertracker(), "[PokerTracker] ERROR opening PostgreSQL DB: %s\n\n", PQerrorMessage(_pgconn)); PQfinish(_pgconn); _connected = false; _pgconn = NULL; } }
int main(int argc, char **argv) { strcpy(baza, argv[1]); //należy uzupelnic dane sprintf(zapytanie, "host=localhost port=5432 dbname=%s user= password="******"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"); printf("<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv = \"Content-type\" content = \"text/html; charset=iso-8859-2\"/><title>zad2</title><style type=\"text/css\">table { border-color: DarkOrchid; border-style: solid; }</style></head><body bgcolor = 'aqua'>\n"); for (i = 2; i < argc; ++i) { strcpy(tabela, argv[i]); sprintf(zapytanie, "SELECT * FROM %s", tabela); result = PQexec(conn, zapytanie); PQprint2(result); } printf("</body></html>\n"); } PQfinish(conn); return EXIT_SUCCESS; }
int main() { // próba po³±czenia PGconn *myconnection = PQconnectdb(""); // sprawdzamy status po³±czenia if(PQstatus(myconnection) == CONNECTION_OK) { printf("connection made\n"); // informacje o po³±czeniu printf("PGDBNAME = %s\n",PQdb(myconnection)); printf("PGUSER = %s\n",PQuser(myconnection)); printf("PGPASSWORD = %s\n",PQpass(myconnection)); printf("PGHOST = %s\n",PQhost(myconnection)); printf("PGPORT = %s\n",PQport(myconnection)); printf("OPTIONS = %s\n",PQoptions(myconnection)); } else printf("connection failed: %s\n", PQerrorMessage(myconnection)); // w razie utraty po³±czenia wywo³anie // PQreset(myconnection); // zamyka op³±czenie i nawi±zuje je raz jeszcze // z dotychczasowymi parametrami PQfinish(myconnection); return EXIT_SUCCESS; }
/* perform an internal connection to the database in separate process and execute sql * statement */ bRC pg_internal_conn ( bpContext *ctx, const char * sql ){ PGconn * db; ConnStatusType status; PGresult * result; int pid = 0; struct stat st; uid_t pguid; int err; char connstring[CONNSTRLEN]; pgsqlpinst * pinst; bRC exitstatus = bRC_OK; /* check input data */ ASSERT_ctx_p; pinst = (pgsqlpinst *)ctx->pContext; /* dynamic production database owner verification, we use it do connect to production * database. Required PGDATA from config file */ ASSERT_p ( pinst->paramlist ); err = stat ( search_key ( pinst->paramlist, "PGDATA" ) , &st ); if ( err ){ /* error, invalid PGDATA in config file */ //FIXME printf ( PLUGIN_INFO "invalid 'PGDATA' variable in config file.\n" ); return bRC_Error; } /* we will fork to the owner of PGDATA database cluster */ pguid = st.st_uid; /* switch pg xlog in different process, so make a fork */ pid = fork (); if ( pid == 0 ){ // printf ( PLUGIN_INFO "forked process\n" ); /* sleep used for debuging forked process in gdb */ // sleep ( 60 ); /* we are in forked process, do a real job */ /* switch to pgcluster owner (postgres) */ err = seteuid ( pguid ); if ( err ){ /* error switching uid, report a problem */ /* TODO: add an errorlog display */ //FIXME printf ( PLUGIN_INFO "seteuid to uid=%i failed!\n", pguid ); exit (bRC_Error); } /* host is a socket directory, port is a socket 'port', we perform an 'internal' * connection through a postgresql socket, which is required by plugin */ snprintf ( connstring, CONNSTRLEN, "host=%s port=%s", search_key ( pinst->paramlist, "PGHOST" ), search_key ( pinst->paramlist, "PGPORT" ) ); db = PQconnectdb ( connstring ); status = PQstatus ( db ); if ( status == CONNECTION_BAD ){ /* TODO: add an errorlog display */ //FIXME printf ( PLUGIN_INFO "conndb failed!\n"); exit (bRC_Error); } /* we have a successful production database connection, so execute sql */ result = PQexec ( db, sql ); if ( PQresultStatus ( result ) != PGRES_TUPLES_OK ){ /* TODO: add an errorlog display */ //FIXME printf ( PLUGIN_INFO "pg_internal_conn failed! (%s)\n", sql); exit (bRC_Error); } /* finish database connection */ PQfinish ( db ); /* finish forked process */ exit (bRC_OK); } else { /* we are waiting for background process to finish */ waitpid ( pid, (int*)&exitstatus, 0 ); } /* XXX: we should check for forked process exit status */ return exitstatus; }
int msPOSTGRESQLJoinConnect(layerObj *layer, joinObj *join) { char *maskeddata, *temp, *sql, *column; char *conn_decrypted; int i, count, test; PGresult *query_result; msPOSTGRESQLJoinInfo *joininfo; if(join->joininfo) return MS_SUCCESS; joininfo = (msPOSTGRESQLJoinInfo *)malloc(sizeof(msPOSTGRESQLJoinInfo)); if(!joininfo) { msSetError(MS_MEMERR, "Error allocating join info struct.", "msPOSTGRESQLJoinConnect()"); return MS_FAILURE; } joininfo->conn = NULL; joininfo->row_num = 0; joininfo->query_result = NULL; joininfo->from_index = 0; joininfo->to_column = join->to; joininfo->from_value = NULL; joininfo->layer_debug = layer->debug; join->joininfo = joininfo; /* * We need three things at a minimum, the connection string, a table * name, and a column to join on. */ if(!join->connection) { msSetError(MS_QUERYERR, "No connection information provided.", "MSPOSTGRESQLJoinConnect()"); return MS_FAILURE; } if(!join->table) { msSetError(MS_QUERYERR, "No join table name found.", "msPOSTGRESQLJoinConnect()"); return MS_FAILURE; } if(!joininfo->to_column) { msSetError(MS_QUERYERR, "No join to column name found.", "msPOSTGRESQLJoinConnect()"); return MS_FAILURE; } /* Establish database connection */ conn_decrypted = msDecryptStringTokens(layer->map, join->connection); if (conn_decrypted != NULL) { joininfo->conn = PQconnectdb(conn_decrypted); free(conn_decrypted); } if(!joininfo->conn || PQstatus(joininfo->conn) == CONNECTION_BAD) { maskeddata = (char *)malloc(strlen(layer->connection) + 1); strcpy(maskeddata, join->connection); temp = strstr(maskeddata, "password="******" ") - temp); for(i = 0; i < count; i++) { strlcpy(temp, "*", (int)1); temp++; } } msSetError(MS_QUERYERR, "Unable to connect to PostgreSQL using the string %s.\n Error reported: %s\n", "msPOSTGRESQLJoinConnect()", maskeddata, PQerrorMessage(joininfo->conn)); free(maskeddata); if(!joininfo->conn) { free(joininfo->conn); } free(joininfo); join->joininfo = NULL; return MS_FAILURE; } /* Determine the number and names of columns in the join table. */ sql = (char *)malloc(36 + strlen(join->table) + 1); sprintf(sql, "SELECT * FROM %s WHERE false LIMIT 0", join->table); if(joininfo->layer_debug) { msDebug("msPOSTGRESQLJoinConnect(): executing %s.\n", sql); } query_result = PQexec(joininfo->conn, sql); if(!query_result || PQresultStatus(query_result) != PGRES_TUPLES_OK) { msSetError(MS_QUERYERR, "Error determining join items: %s.", "msPOSTGRESQLJoinConnect()", PQerrorMessage(joininfo->conn)); if(query_result) { PQclear(query_result); query_result = NULL; } free(sql); return MS_FAILURE; } free(sql); join->numitems = PQnfields(query_result); join->items = malloc(sizeof(char *) * (join->numitems)); /* We want the join-to column to be first in the list. */ test = 1; for(i = 0; i < join->numitems; i++) { column = PQfname(query_result, i); if(strcmp(column, joininfo->to_column) != 0) { join->items[i + test] = (char *)malloc(strlen(column) + 1); strcpy(join->items[i + test], column); } else { test = 0; join->items[0] = (char *)malloc(strlen(column) + 1); strcpy(join->items[0], column); } } PQclear(query_result); query_result = NULL; if(test == 1) { msSetError(MS_QUERYERR, "Unable to find join to column: %s", "msPOSTGRESQLJoinConnect()", joininfo->to_column); return MS_FAILURE; } if(joininfo->layer_debug) { for(i = 0; i < join->numitems; i++) { msDebug("msPOSTGRESQLJoinConnect(): Column %d named %s\n", i, join->items[i]); } } /* Determine the index of the join from column. */ for(i = 0; i < layer->numitems; i++) { if(strcasecmp(layer->items[i], join->from) == 0) { joininfo->from_index = i; break; } } if(i == layer->numitems) { msSetError(MS_JOINERR, "Item %s not found in layer %s.", "msPOSTGRESQLJoinConnect()", join->from, layer->name); return MS_FAILURE; } return MS_SUCCESS; }
/* * cmd_open: attempts to open a named connection to the database. * * Inputs: * cmd->argv[0]: connection name * * Returns: * either a properly filled error modret_t if a connection could not be * opened, or a simple non-error modret_t. * * Notes: * mod_sql depends on these semantics -- a backend should not open * a connection unless mod_sql requests it, nor close one unless * mod_sql requests it. Connection counting is *REQUIRED* for complete * compatibility; a connection should not be closed unless the count * reaches 0, and ideally will not need to be re-opened for counts > 1. */ MODRET cmd_open(cmd_rec *cmd) { conn_entry_t *entry = NULL; db_conn_t *conn = NULL; const char *server_version = NULL; sql_log(DEBUG_FUNC, "%s", "entering \tpostgres cmd_open"); _sql_check_cmd(cmd, "cmd_open" ); if (cmd->argc < 1) { sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_open"); return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION, "badly formed request"); } /* get the named connection */ if (!(entry = _sql_get_connection(cmd->argv[0]))) { sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_open"); return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION, "unknown named connection"); } conn = (db_conn_t *) entry->data; /* if we're already open (connections > 0) increment connections * reset our timer if we have one, and return HANDLED */ if (entry->connections > 0) { if (PQstatus(conn->postgres) == CONNECTION_OK) { entry->connections++; if (entry->timer) { pr_timer_reset(entry->timer, &sql_postgres_module); } sql_log(DEBUG_INFO, "connection '%s' count is now %d", entry->name, entry->connections); sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_open"); return PR_HANDLED(cmd); } else { char *reason; size_t reason_len; /* Unless we've been told not to reconnect, try to reconnect now. * We only try once; if it fails, we return an error. */ if (!(pr_sql_opts & SQL_OPT_NO_RECONNECT)) { PQreset(conn->postgres); if (PQstatus(conn->postgres) == CONNECTION_OK) { entry->connections++; if (entry->timer) { pr_timer_reset(entry->timer, &sql_postgres_module); } sql_log(DEBUG_INFO, "connection '%s' count is now %d", entry->name, entry->connections); sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_open"); return PR_HANDLED(cmd); } } reason = PQerrorMessage(conn->postgres); reason_len = strlen(reason); /* Postgres might give us an empty string as the reason; not helpful. */ if (reason_len == 0) { reason = "(unknown)"; reason_len = strlen(reason); } /* The error message returned by Postgres is usually appended with * a newline. Let's prettify it by removing the newline. Note * that yes, we are overwriting the pointer given to us by Postgres, * but it's OK. The Postgres docs say that we're not supposed to * free the memory associated with the returned string anyway. */ reason = pstrdup(session.pool, reason); if (reason[reason_len-1] == '\n') { reason[reason_len-1] = '\0'; reason_len--; } sql_log(DEBUG_INFO, "lost connection to database: %s", reason); entry->connections = 0; if (entry->timer) { pr_timer_remove(entry->timer, &sql_postgres_module); entry->timer = 0; } sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_open"); return PR_ERROR_MSG(cmd, MOD_SQL_POSTGRES_VERSION, "lost connection to database"); } } /* make sure we have a new conn struct */ conn->postgres = PQconnectdb(conn->connectstring); if (PQstatus(conn->postgres) == CONNECTION_BAD) { /* if it didn't work, return an error */ sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_open"); return _build_error( cmd, conn ); } #if defined(PG_VERSION_STR) sql_log(DEBUG_FUNC, "Postgres client: %s", PG_VERSION_STR); #endif server_version = PQparameterStatus(conn->postgres, "server_version"); if (server_version != NULL) { sql_log(DEBUG_FUNC, "Postgres server version: %s", server_version); } #ifdef PR_USE_NLS if (pr_encode_get_encoding() != NULL) { const char *encoding; encoding = get_postgres_encoding(pr_encode_get_encoding()); /* Configure the connection for the current local character set. */ if (PQsetClientEncoding(conn->postgres, encoding) < 0) { /* if it didn't work, return an error */ sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_open"); return _build_error(cmd, conn); } sql_log(DEBUG_FUNC, "Postgres connection character set now '%s' " "(from '%s')", pg_encoding_to_char(PQclientEncoding(conn->postgres)), pr_encode_get_encoding()); } #endif /* !PR_USE_NLS */ /* bump connections */ entry->connections++; if (pr_sql_conn_policy == SQL_CONN_POLICY_PERSESSION) { /* If the connection policy is PERSESSION... */ if (entry->connections == 1) { /* ...and we are actually opening the first connection to the database; * we want to make sure this connection stays open, after this first use * (as per Bug#3290). To do this, we re-bump the connection count. */ entry->connections++; } } else if (entry->ttl > 0) { /* Set up our timer if necessary */ entry->timer = pr_timer_add(entry->ttl, -1, &sql_postgres_module, sql_timer_cb, "postgres connection ttl"); sql_log(DEBUG_INFO, "connection '%s' - %d second timer started", entry->name, entry->ttl); /* Timed connections get re-bumped so they don't go away when cmd_close * is called. */ entry->connections++; } /* return HANDLED */ sql_log(DEBUG_INFO, "connection '%s' opened", entry->name); sql_log(DEBUG_INFO, "connection '%s' count is now %d", entry->name, entry->connections); sql_log(DEBUG_FUNC, "%s", "exiting \tpostgres cmd_open"); return PR_HANDLED(cmd); }
/* * Establish the connection to the primary server for XLOG streaming */ static bool libpqrcv_connect(char *conninfo, XLogRecPtr startpoint) { char conninfo_repl[MAXCONNINFO + 37]; char *primary_sysid; char standby_sysid[32]; TimeLineID primary_tli; TimeLineID standby_tli; PGresult *res; char cmd[64]; /* * Connect using deliberately undocumented parameter: replication. The * database name is ignored by the server in replication mode, but specify * "replication" for .pgpass lookup. */ snprintf(conninfo_repl, sizeof(conninfo_repl), "%s dbname=replication replication=true", conninfo); streamConn = PQconnectdb(conninfo_repl); if (PQstatus(streamConn) != CONNECTION_OK) ereport(ERROR, (errmsg("could not connect to the primary server: %s", PQerrorMessage(streamConn)))); /* * Get the system identifier and timeline ID as a DataRow message from the * primary server. */ res = libpqrcv_PQexec("IDENTIFY_SYSTEM"); if (PQresultStatus(res) != PGRES_TUPLES_OK) { PQclear(res); ereport(ERROR, (errmsg("could not receive database system identifier and timeline ID from " "the primary server: %s", PQerrorMessage(streamConn)))); } if (PQnfields(res) != 2 || PQntuples(res) != 1) { int ntuples = PQntuples(res); int nfields = PQnfields(res); PQclear(res); ereport(ERROR, (errmsg("invalid response from primary server"), errdetail("Expected 1 tuple with 2 fields, got %d tuples with %d fields.", ntuples, nfields))); } primary_sysid = PQgetvalue(res, 0, 0); primary_tli = pg_atoi(PQgetvalue(res, 0, 1), 4, 0); /* * Confirm that the system identifier of the primary is the same as ours. */ snprintf(standby_sysid, sizeof(standby_sysid), UINT64_FORMAT, GetSystemIdentifier()); if (strcmp(primary_sysid, standby_sysid) != 0) { PQclear(res); ereport(ERROR, (errmsg("database system identifier differs between the primary and standby"), errdetail("The primary's identifier is %s, the standby's identifier is %s.", primary_sysid, standby_sysid))); } /* * Confirm that the current timeline of the primary is the same as the * recovery target timeline. */ standby_tli = GetRecoveryTargetTLI(); PQclear(res); if (primary_tli != standby_tli) ereport(ERROR, (errmsg("timeline %u of the primary does not match recovery target timeline %u", primary_tli, standby_tli))); ThisTimeLineID = primary_tli; /* Start streaming from the point requested by startup process */ snprintf(cmd, sizeof(cmd), "START_REPLICATION %X/%X", startpoint.xlogid, startpoint.xrecoff); res = libpqrcv_PQexec(cmd); if (PQresultStatus(res) != PGRES_COPY_BOTH) { PQclear(res); ereport(ERROR, (errmsg("could not start WAL streaming: %s", PQerrorMessage(streamConn)))); } PQclear(res); justconnected = true; ereport(LOG, (errmsg("streaming replication successfully connected to primary"))); return true; }
// this constructor creates empty network // this is base for network mapping IONet::IONet() { // create map to keep all pages this->ioPages = new std::map<int, IONetPage> (); // create connection to the server std::string conncetString = CS_SUP_HOST + " " + CS_SUP_USER + " " + CS_SUP_PWD + " " + CS_SUP_DBNAME ; this->databaseConnection = PQconnectdb("host=localhost user=postgres password=postgres dbname=RoverConfiguration"); //check connection status switch (PQstatus(this->databaseConnection)) { case CONNECTION_OK: std::cout << "Connection is OK" << std::endl ; break ; case CONNECTION_BAD: std::cout << "Connection is bad." << std::endl ; break ; default: std::cout << "status is other" << std::endl ; break ; } // now we get list of variables bool resultOK = false ; PGresult *queryResult = PQexec( this->databaseConnection, "select * from public.\"IONetwork\"" ) ; if (queryResult != NULL) { switch (PQresultStatus(queryResult)){ case PGRES_TUPLES_OK: std::cout << "result OK" << std::endl ; resultOK = true ; break ; case PGRES_COMMAND_OK: std::cout << "command OK" << std::endl ; resultOK = true ; break ; case PGRES_EMPTY_QUERY: std::cout << "empty query" << std::endl ; break ; case PGRES_BAD_RESPONSE: std::cout << "bad response" << std::endl ; break ; case PGRES_FATAL_ERROR: std::cout << "fatal error: " << PQerrorMessage(this->databaseConnection) << std::endl ; break ; case PGRES_NONFATAL_ERROR: std::cout << "non-fatal error" << std::endl ; break ; default: std::cout << "result not OK" << std::endl ; break ; } } else { std::cout << "result is NULL" << std::endl ; } // of there were rows returned if (resultOK) { std::cout << "returned " << PQntuples(queryResult) << " rows x " << PQnfields(queryResult) << " columns" << std::endl ; std::cout << "-----------------" << std::endl ; int returnedRows = PQntuples(queryResult) ; int returnedCols = PQnfields(queryResult) ; // create temporary map std::map<std::string, IONetVar> *tempMap = new std::map<std::string, IONetVar>() ; for (int i=0; i<returnedRows; i++){ int *variable = new int(); std::string varName = PQgetvalue(queryResult, i, 0) ; IONetVar *netVarA = new IONetVar((char*)variable, integer, varName) ; tempMap->insert(std::pair<std::string, IONetVar>(varName, *netVarA)) ; delete variable ; delete netVarA ; } // add new page this->addPage(1, *tempMap); delete tempMap ; } }
static int config_connect(struct config *conf) { static const struct { const char *name; int cols; } qspec[SQL_MAX] = { { "query_alias", 1 }, { "query_domain", 1 }, { "query_credentials", 2 }, { "query_netaddr", 1 }, { "query_userinfo", 3 }, { "query_source", 1 }, { "query_mailaddr", 1 }, { "query_addrname", 1 }, }; size_t i; char *conninfo, *q; log_debug("debug: table-postgres: (re)connecting"); /* Disconnect first, if needed */ config_reset(conf); conninfo = dict_get(&conf->conf, "conninfo"); if (conninfo == NULL) { log_warnx("warn: table-postgres: missing \"conninfo\" configuration directive"); goto end; } conf->db = PQconnectdb(conninfo); if (conf->db == NULL) { log_warnx("warn: table-postgres: PQconnectdb return NULL"); goto end; } if (PQstatus(conf->db) != CONNECTION_OK) { log_warnx("warn: table-postgres: PQconnectdb: %s", PQerrorMessage(conf->db)); goto end; } for (i = 0; i < SQL_MAX; i++) { q = dict_get(&conf->conf, qspec[i].name); if (q && (conf->statements[i] = table_postgres_prepare_stmt( conf->db, q, 1, qspec[i].cols)) == NULL) goto end; } q = dict_get(&conf->conf, "fetch_source"); if (q && (conf->stmt_fetch_source = table_postgres_prepare_stmt(conf->db, q, 0, 1)) == NULL) goto end; log_debug("debug: table-postgres: connected"); return (1); end: config_reset(conf); return (0); }
int main(int argc, char **argv) { PGconn *conn; PQExpBufferData sql; PGresult *res; PGresult *pkrel_res; PGresult *fkrel_res; char *fk_relname; char *fk_nspname; char *fk_attname; char *pk_relname; char *pk_nspname; int fk, pk; /* loop counters */ if (argc != 2) { fprintf(stderr, "Usage: %s database\n", argv[0]); exit(EXIT_FAILURE); } initPQExpBuffer(&sql); appendPQExpBuffer(&sql, "dbname=%s", argv[1]); conn = PQconnectdb(sql.data); if (PQstatus(conn) == CONNECTION_BAD) { fprintf(stderr, "connection error: %s\n", PQerrorMessage(conn)); exit(EXIT_FAILURE); } /* Get a list of relations that have OIDs */ printfPQExpBuffer(&sql, "%s", "SET search_path = public;" "SELECT c.relname, (SELECT nspname FROM " "pg_catalog.pg_namespace n WHERE n.oid = c.relnamespace) AS nspname " "FROM pg_catalog.pg_class c " "WHERE c.relkind = " CppAsString2(RELKIND_RELATION) " AND c.relhasoids " "ORDER BY nspname, c.relname" ); res = PQexec(conn, sql.data); if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, "sql error: %s\n", PQerrorMessage(conn)); exit(EXIT_FAILURE); } pkrel_res = res; /* Get a list of columns of OID type (or any OID-alias type) */ printfPQExpBuffer(&sql, "%s", "SELECT c.relname, " "(SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = c.relnamespace) AS nspname, " "a.attname " "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a " "WHERE a.attnum > 0" " AND c.relkind = " CppAsString2(RELKIND_RELATION) " AND a.attrelid = c.oid" " AND a.atttypid IN ('pg_catalog.oid'::regtype, " " 'pg_catalog.regclass'::regtype, " " 'pg_catalog.regoper'::regtype, " " 'pg_catalog.regoperator'::regtype, " " 'pg_catalog.regproc'::regtype, " " 'pg_catalog.regprocedure'::regtype, " " 'pg_catalog.regtype'::regtype, " " 'pg_catalog.regconfig'::regtype, " " 'pg_catalog.regdictionary'::regtype) " "ORDER BY nspname, c.relname, a.attnum" ); res = PQexec(conn, sql.data); if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, "sql error: %s\n", PQerrorMessage(conn)); exit(EXIT_FAILURE); } fkrel_res = res; /* * For each column and each relation-having-OIDs, look to see if the * column contains any values matching entries in the relation. */ for (fk = 0; fk < PQntuples(fkrel_res); fk++) { fk_relname = PQgetvalue(fkrel_res, fk, 0); fk_nspname = PQgetvalue(fkrel_res, fk, 1); fk_attname = PQgetvalue(fkrel_res, fk, 2); for (pk = 0; pk < PQntuples(pkrel_res); pk++) { pk_relname = PQgetvalue(pkrel_res, pk, 0); pk_nspname = PQgetvalue(pkrel_res, pk, 1); printfPQExpBuffer(&sql, "SELECT 1 " "FROM \"%s\".\"%s\" t1, " "\"%s\".\"%s\" t2 " "WHERE t1.\"%s\"::pg_catalog.oid = t2.oid " "LIMIT 1", fk_nspname, fk_relname, pk_nspname, pk_relname, fk_attname); res = PQexec(conn, sql.data); if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, "sql error: %s\n", PQerrorMessage(conn)); exit(EXIT_FAILURE); } if (PQntuples(res) != 0) printf("Join %s.%s.%s => %s.%s.oid\n", fk_nspname, fk_relname, fk_attname, pk_nspname, pk_relname); PQclear(res); } } PQclear(fkrel_res); /* Now, do the same for referencing columns that are arrays */ /* Get a list of columns of OID-array type (or any OID-alias type) */ printfPQExpBuffer(&sql, "%s", "SELECT c.relname, " "(SELECT nspname FROM pg_catalog.pg_namespace n WHERE n.oid = c.relnamespace) AS nspname, " "a.attname " "FROM pg_catalog.pg_class c, pg_catalog.pg_attribute a " "WHERE a.attnum > 0" " AND c.relkind = " CppAsString2(RELKIND_RELATION) " AND a.attrelid = c.oid" " AND a.atttypid IN ('pg_catalog.oid[]'::regtype, " " 'pg_catalog.regclass[]'::regtype, " " 'pg_catalog.regoper[]'::regtype, " " 'pg_catalog.regoperator[]'::regtype, " " 'pg_catalog.regproc[]'::regtype, " " 'pg_catalog.regprocedure[]'::regtype, " " 'pg_catalog.regtype[]'::regtype, " " 'pg_catalog.regconfig[]'::regtype, " " 'pg_catalog.regdictionary[]'::regtype) " "ORDER BY nspname, c.relname, a.attnum" ); res = PQexec(conn, sql.data); if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, "sql error: %s\n", PQerrorMessage(conn)); exit(EXIT_FAILURE); } fkrel_res = res; /* * For each column and each relation-having-OIDs, look to see if the * column contains any values matching entries in the relation. */ for (fk = 0; fk < PQntuples(fkrel_res); fk++) { fk_relname = PQgetvalue(fkrel_res, fk, 0); fk_nspname = PQgetvalue(fkrel_res, fk, 1); fk_attname = PQgetvalue(fkrel_res, fk, 2); for (pk = 0; pk < PQntuples(pkrel_res); pk++) { pk_relname = PQgetvalue(pkrel_res, pk, 0); pk_nspname = PQgetvalue(pkrel_res, pk, 1); printfPQExpBuffer(&sql, "SELECT 1 " "FROM \"%s\".\"%s\" t1, " "\"%s\".\"%s\" t2 " "WHERE t2.oid = ANY(t1.\"%s\")" "LIMIT 1", fk_nspname, fk_relname, pk_nspname, pk_relname, fk_attname); res = PQexec(conn, sql.data); if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, "sql error: %s\n", PQerrorMessage(conn)); exit(EXIT_FAILURE); } if (PQntuples(res) != 0) printf("Join %s.%s.%s []=> %s.%s.oid\n", fk_nspname, fk_relname, fk_attname, pk_nspname, pk_relname); PQclear(res); } } PQclear(fkrel_res); PQclear(pkrel_res); PQfinish(conn); termPQExpBuffer(&sql); exit(EXIT_SUCCESS); }
main() { char *pghost, *pgport, *pgoptions, *pgtty; char *dbName; int nFields; int row, field; PGconn *conn; PGresult *res; int junk; char *field_name; int field_type; int WKB_OID; char conn_string[255]; bool *bool_val; int *int_val; float *float_val; double *double_val; char *char_val; char *wkb_val; char *table_name = "wkbreader_test"; char query_str[1000]; /* make a connection to the database */ conn = PQconnectdb(""); /* * check to see that the backend connection was successfully made */ if (PQstatus(conn) == CONNECTION_BAD) { fprintf(stderr, "%s", PQerrorMessage(conn)); exit_nicely(conn); } //what is the geometry type's OID #? WKB_OID = find_WKB_typeid(conn); /* start a transaction block */ res = PQexec(conn, "BEGIN"); if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) { fprintf(stderr, "%s", PQerrorMessage(conn)); PQclear(res); exit_nicely(conn); } /* * should PQclear PGresult whenever it is no longer needed to avoid * memory leaks */ PQclear(res); /* * fetch rows from the pg_database, the system catalog of * databases */ sprintf(query_str, "DECLARE mycursor BINARY CURSOR FOR select text(num), asbinary(the_geom,'ndr') as wkb from %s", table_name); printf(query_str); printf("\n"); res = PQexec(conn, query_str); if (!res || PQresultStatus(res) != PGRES_COMMAND_OK) { fprintf(stderr, "DECLARE CURSOR command failed\n"); fprintf(stderr, "%s", PQerrorMessage(conn)); PQclear(res); exit_nicely(conn); } PQclear(res); res = PQexec(conn, "FETCH ALL in mycursor"); if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, "FETCH ALL command didn't return tuples properly\n"); fprintf(stderr, "%s", PQerrorMessage(conn)); PQclear(res); exit_nicely(conn); } for (row=0; row< PQntuples(res); row++) { printf("------------------------------row %i --------------------------\n",row); //not so efficient, but... for (field =0 ; field< PQnfields(res); field++) { field_type =PQftype(res,field); field_name = PQfname(res, field); //we just handle a few of the popular type since this is just an example if (field_type ==16)// bool { bool_val = (bool *) PQgetvalue(res, row, field); if (*bool_val) printf("%s: TRUE\n",field_name); else printf("%s: FALSE\n",field_name); } else if (field_type ==23 )//int4 (int) { int_val = (int *) PQgetvalue(res, row, field); printf("%s: %i\n",field_name,*int_val); } else if (field_type ==700 )//float4 (float) { float_val = (float *) PQgetvalue(res, row, field); printf("%s: %g\n",field_name,*float_val); } else if (field_type ==701 )//float8 (double) { double_val = (double *) PQgetvalue(res, row, field); printf("%s: %g\n",field_name,*double_val); } else if ( (field_type ==1043 ) || (field_type==25) )//varchar { char_val = (char *) PQgetvalue(res, row, field); printf("%s: %s\n",field_name,char_val); } else if (field_type == WKB_OID ) //wkb { char_val = (char *) PQgetvalue(res, row, field); printf("%s: ", field_name); // skip 4 bytes varlena size decode_wkb(char_val, &junk); printf("\n"); } } } PQclear(res); /* close the cursor */ res = PQexec(conn, "CLOSE mycursor"); PQclear(res); /* commit the transaction */ res = PQexec(conn, "COMMIT"); PQclear(res); /* close the connection to the database and cleanup */ PQfinish(conn); return 0; }
int map_collect_data_osm_db(char *dbstr, struct maptool_osm *osm) { PGconn *conn; PGresult *res,*node,*way,*tag; int count,tagged,i,j,k; long min, max, id, tag_id, node_id; char query[256]; sig_alrm(0); conn=PQconnectdb(dbstr); if (! conn) { fprintf(stderr,"Failed to connect to database with '%s'\n",dbstr); exit(1); } res=PQexec(conn, "begin"); if (! res) { fprintf(stderr, "Cannot begin transaction: %s\n", PQerrorMessage(conn)); PQclear(res); exit(1); } res=PQexec(conn, "set transaction isolation level serializable"); if (! res) { fprintf(stderr, "Cannot set isolation level: %s\n", PQerrorMessage(conn)); PQclear(res); exit(1); } res=PQexec(conn, "declare node cursor for select id,x(coordinate),y(coordinate) from node order by id"); if (! res) { fprintf(stderr, "Cannot setup cursor for nodes: %s\n", PQerrorMessage(conn)); PQclear(res); exit(1); } res=PQexec(conn, "declare way cursor for select id from way order by id"); if (! res) { fprintf(stderr, "Cannot setup cursor for nodes: %s\n", PQerrorMessage(conn)); PQclear(res); exit(1); } res=PQexec(conn, "declare relation cursor for select id from relation order by id"); if (! res) { fprintf(stderr, "Cannot setup cursor for nodes: %s\n", PQerrorMessage(conn)); PQclear(res); exit(1); } for (;;) { node=PQexec(conn, "fetch 100000 from node"); if (! node) { fprintf(stderr, "Cannot setup cursor for nodes: %s\n", PQerrorMessage(conn)); PQclear(node); exit(1); } count=PQntuples(node); if (! count) break; min=atol(PQgetvalue(node, 0, 0)); max=atol(PQgetvalue(node, count-1, 0)); sprintf(query,"select node_id,name,value from node_tag where node_id >= %ld and node_id <= %ld order by node_id", min, max); tag=PQexec(conn, query); if (! tag) { fprintf(stderr, "Cannot query node_tag: %s\n", PQerrorMessage(conn)); exit(1); } j=0; for (i = 0 ; i < count ; i++) { id=atol(PQgetvalue(node, i, 0)); osm_add_node(id, atof(PQgetvalue(node, i, 1)), atof(PQgetvalue(node, i, 2))); tagged=0; processed_nodes++; while (j < PQntuples(tag)) { tag_id=atol(PQgetvalue(tag, j, 0)); if (tag_id == id) { osm_add_tag(PQgetvalue(tag, j, 1), PQgetvalue(tag, j, 2)); tagged=1; j++; } if (tag_id < id) j++; if (tag_id > id) break; } osm_end_node(osm); } PQclear(tag); PQclear(node); } for (;;) { way=PQexec(conn, "fetch 100000 from way"); if (! way) { fprintf(stderr, "Cannot setup cursor for ways: %s\n", PQerrorMessage(conn)); PQclear(node); exit(1); } count=PQntuples(way); if (! count) break; min=atol(PQgetvalue(way, 0, 0)); max=atol(PQgetvalue(way, count-1, 0)); sprintf(query,"select way_id,node_id from way_node where way_id >= %ld and way_id <= %ld order by way_id,sequence_id", min, max); node=PQexec(conn, query); if (! node) { fprintf(stderr, "Cannot query way_node: %s\n", PQerrorMessage(conn)); exit(1); } sprintf(query,"select way_id,name,value from way_tag where way_id >= %ld and way_id <= %ld order by way_id", min, max); tag=PQexec(conn, query); if (! tag) { fprintf(stderr, "Cannot query way_tag: %s\n", PQerrorMessage(conn)); exit(1); } j=0; k=0; for (i = 0 ; i < count ; i++) { id=atol(PQgetvalue(way, i, 0)); osm_add_way(id); tagged=0; processed_ways++; while (k < PQntuples(node)) { node_id=atol(PQgetvalue(node, k, 0)); if (node_id == id) { osm_add_nd(atoll(PQgetvalue(node, k, 1))); tagged=1; k++; } if (node_id < id) k++; if (node_id > id) break; } while (j < PQntuples(tag)) { tag_id=atol(PQgetvalue(tag, j, 0)); if (tag_id == id) { osm_add_tag(PQgetvalue(tag, j, 1), PQgetvalue(tag, j, 2)); tagged=1; j++; } if (tag_id < id) j++; if (tag_id > id) break; } if (tagged) osm_end_way(osm); } PQclear(tag); PQclear(node); PQclear(way); } res=PQexec(conn, "commit"); if (! res) { fprintf(stderr, "Cannot commit transaction: %s\n", PQerrorMessage(conn)); PQclear(res); exit(1); } sig_alrm(0); sig_alrm_end(); return 1; }
int main(int argc, char **argv) { const char *conninfo; TestSpec *testspec; int i, j; int n; PGresult *res; PQExpBufferData wait_query; int opt; int nallsteps; Step **allsteps; while ((opt = getopt(argc, argv, "nV")) != -1) { switch (opt) { case 'n': dry_run = true; break; case 'V': puts("isolationtester (PostgreSQL) " PG_VERSION); exit(0); default: fprintf(stderr, "Usage: isolationtester [-n] [CONNINFO]\n"); return EXIT_FAILURE; } } /* * Make stdout unbuffered to match stderr; and ensure stderr is unbuffered * too, which it should already be everywhere except sometimes in Windows. */ setbuf(stdout, NULL); setbuf(stderr, NULL); /* * If the user supplies a non-option parameter on the command line, use it * as the conninfo string; otherwise default to setting dbname=postgres * and using environment variables or defaults for all other connection * parameters. */ if (argc > optind) conninfo = argv[optind]; else conninfo = "dbname = postgres"; /* Read the test spec from stdin */ spec_yyparse(); testspec = &parseresult; /* Create a lookup table of all steps. */ nallsteps = 0; for (i = 0; i < testspec->nsessions; i++) nallsteps += testspec->sessions[i]->nsteps; allsteps = malloc(nallsteps * sizeof(Step *)); n = 0; for (i = 0; i < testspec->nsessions; i++) { for (j = 0; j < testspec->sessions[i]->nsteps; j++) allsteps[n++] = testspec->sessions[i]->steps[j]; } qsort(allsteps, nallsteps, sizeof(Step *), &step_qsort_cmp); testspec->nallsteps = nallsteps; testspec->allsteps = allsteps; /* Verify that all step names are unique */ for (i = 1; i < testspec->nallsteps; i++) { if (strcmp(testspec->allsteps[i - 1]->name, testspec->allsteps[i]->name) == 0) { fprintf(stderr, "duplicate step name: %s\n", testspec->allsteps[i]->name); exit_nicely(); } } /* * In dry-run mode, just print the permutations that would be run, and * exit. */ if (dry_run) { run_testspec(testspec); return 0; } printf("Parsed test spec with %d sessions\n", testspec->nsessions); /* * Establish connections to the database, one for each session and an * extra for lock wait detection and global work. */ nconns = 1 + testspec->nsessions; conns = calloc(nconns, sizeof(PGconn *)); backend_pids = calloc(nconns, sizeof(*backend_pids)); for (i = 0; i < nconns; i++) { conns[i] = PQconnectdb(conninfo); if (PQstatus(conns[i]) != CONNECTION_OK) { fprintf(stderr, "Connection %d to database failed: %s", i, PQerrorMessage(conns[i])); exit_nicely(); } /* * Suppress NOTIFY messages, which otherwise pop into results at odd * places. */ res = PQexec(conns[i], "SET client_min_messages = warning;"); if (PQresultStatus(res) != PGRES_COMMAND_OK) { fprintf(stderr, "message level setup failed: %s", PQerrorMessage(conns[i])); exit_nicely(); } PQclear(res); /* Get the backend pid for lock wait checking. */ res = PQexec(conns[i], "SELECT pg_backend_pid()"); if (PQresultStatus(res) == PGRES_TUPLES_OK) { if (PQntuples(res) == 1 && PQnfields(res) == 1) backend_pids[i] = strdup(PQgetvalue(res, 0, 0)); else { fprintf(stderr, "backend pid query returned %d rows and %d columns, expected 1 row and 1 column", PQntuples(res), PQnfields(res)); exit_nicely(); } } else { fprintf(stderr, "backend pid query failed: %s", PQerrorMessage(conns[i])); exit_nicely(); } PQclear(res); } /* Set the session index fields in steps. */ for (i = 0; i < testspec->nsessions; i++) { Session *session = testspec->sessions[i]; int stepindex; for (stepindex = 0; stepindex < session->nsteps; stepindex++) session->steps[stepindex]->session = i; } /* * Build the query we'll use to detect lock contention among sessions in * the test specification. Most of the time, we could get away with * simply checking whether a session is waiting for *any* lock: we don't * exactly expect concurrent use of test tables. However, autovacuum will * occasionally take AccessExclusiveLock to truncate a table, and we must * ignore that transient wait. */ initPQExpBuffer(&wait_query); appendPQExpBufferStr(&wait_query, "SELECT pg_catalog.pg_blocking_pids($1) && '{"); /* The spec syntax requires at least one session; assume that here. */ appendPQExpBufferStr(&wait_query, backend_pids[1]); for (i = 2; i < nconns; i++) appendPQExpBuffer(&wait_query, ",%s", backend_pids[i]); appendPQExpBufferStr(&wait_query, "}'::integer[]"); res = PQprepare(conns[0], PREP_WAITING, wait_query.data, 0, NULL); if (PQresultStatus(res) != PGRES_COMMAND_OK) { fprintf(stderr, "prepare of lock wait query failed: %s", PQerrorMessage(conns[0])); exit_nicely(); } PQclear(res); termPQExpBuffer(&wait_query); /* * Run the permutations specified in the spec, or all if none were * explicitly specified. */ run_testspec(testspec); /* Clean up and exit */ for (i = 0; i < nconns; i++) PQfinish(conns[i]); return 0; }
int main(int argc, const char * const *argv) { char *args_string; char *member_id; char *image_type; const char *sql_member_image_params[2]; #ifndef PUBLIC_ACCESS #ifdef PUBLIC_AVATAR_ACCESS int authorization_required = 0; #endif char *cookies; regex_t session_ident_regex; ssize_t start, length; regmatch_t session_ident_regmatch[3]; char *session_ident; const char *sql_session_params[1]; #endif PGconn *conn; PGresult *dbr; args_string = getenv("QUERY_STRING"); if (!args_string) { fputs("Status: 403 Access Denied\n\n", stdout); return 0; } member_id = strtok(args_string, "+"); image_type = strtok(NULL, "+"); if (!member_id || !image_type) { fputs("Status: 403 Access Denied\n\n", stdout); return 0; } sql_member_image_params[0] = member_id; sql_member_image_params[1] = image_type; #ifndef PUBLIC_ACCESS #ifdef PUBLIC_AVATAR_ACCESS if (strcmp(image_type, "avatar")) { authorization_required = 1; #endif cookies = getenv("HTTP_COOKIE"); if (!args_string || !cookies) { fputs("Status: 403 Access Denied\n\n", stdout); return 0; } if (regcomp(&session_ident_regex, "(^|[; \t])liquid_feedback_session=([0-9A-Za-z]+)", REG_EXTENDED) != 0) { // shouldn't happen abort(); } if (regexec(&session_ident_regex, cookies, 3, session_ident_regmatch, 0) != 0) { fputs("Status: 403 Access Denied\n\n", stdout); return 0; } start = session_ident_regmatch[2].rm_so; length = session_ident_regmatch[2].rm_eo - session_ident_regmatch[2].rm_so; session_ident = malloc(length + 1); if (!session_ident) abort(); // shouldn't happen strncpy(session_ident, cookies + start, length); session_ident[length] = 0; sql_session_params[0] = session_ident; #ifdef PUBLIC_AVATAR_ACCESS } #endif #endif conn = PQconnectdb(GETPIC_CONNINFO); if (!conn) { fputs("Could not create PGconn structure.\n", stderr); return 1; } if (PQstatus(conn) != CONNECTION_OK) { fputs(PQerrorMessage(conn), stderr); PQfinish(conn); return 1; } #ifndef PUBLIC_ACCESS #ifdef PUBLIC_AVATAR_ACCESS if (authorization_required) { #endif dbr = PQexecParams(conn, "SELECT NULL FROM session JOIN member ON member.id = session.member_id WHERE session.ident = $1 AND member.active", 1, NULL, sql_session_params, NULL, NULL, 0 ); if (PQresultStatus(dbr) != PGRES_TUPLES_OK) { fputs(PQresultErrorMessage(dbr), stderr); PQfinish(conn); return 1; } if (PQntuples(dbr) != 1) { fputs("Status: 403 Access Denied\n\n", stdout); PQfinish(conn); return 0; } #ifdef PUBLIC_AVATAR_ACCESS } #endif #endif dbr = PQexecParams(conn, "SELECT content_type, data " "FROM member_image " "WHERE member_id = $1 " "AND image_type = $2 " "AND scaled " "LIMIT 1;", 2, NULL, sql_member_image_params, NULL, NULL, 1 ); if (PQresultStatus(dbr) != PGRES_TUPLES_OK) { fputs(PQresultErrorMessage(dbr), stderr); PQfinish(conn); return 1; } if (PQntuples(dbr) == 0) { struct stat sb; PQclear(dbr); PQfinish(conn); fputs("Content-Type: image/jpeg\n\n", stdout); if (stat(GETPIC_DEFAULT_AVATAR, &sb)) return 1; fprintf(stdout, "Content-Length: %i\n", (int)sb.st_size); execl("/bin/cat", "cat", GETPIC_DEFAULT_AVATAR, NULL); return 1; } else { if (PQnfields(dbr) < 0) { fputs("Too few columns returned by database.\n", stderr); PQfinish(conn); return 1; } if (PQfformat(dbr, 0) != 1 || PQfformat(dbr, 1) != 1) { fputs("Database did not return data in binary format.\n", stderr); PQfinish(conn); return 1; } if (PQgetisnull(dbr, 0, 0) || PQgetisnull(dbr, 0, 1)) { fputs("Unexpected NULL in database result.\n", stderr); PQfinish(conn); return 1; } fprintf(stdout, "Content-Type: %s\n\n", PQgetvalue(dbr, 0, 0)); fwrite(PQgetvalue(dbr, 0, 1), PQgetlength(dbr, 0, 1), 1, stdout); } PQfinish(conn); return 0; }
/* * MakeDBConnection: This function creates a connection string based on * fields in the SegmentDatabase parameter and then connects to the database. * The PGconn* is returned. Y=This must be checked by the calling * routine for errors etc. */ PGconn * MakeDBConnection(const SegmentDatabase *pSegDB, bool bDispatch) { char *pszOptions; char *pszHost; char *pszDBName; char *tmpDBName = NULL; char *pszUser; char *pszDBPswd; char *pszConnInfo; PGconn *pConn; if (bDispatch) pszOptions = NULL; else pszOptions = MakeString("options='-c gp_session_role=UTILITY'"); if (pSegDB->pszHost == NULL || *pSegDB->pszHost == '\0') pszHost = strdup("host=''"); else pszHost = MakeString("host=%s", pSegDB->pszHost); if (pSegDB->pszDBName != NULL && *pSegDB->pszDBName != '\0') { tmpDBName = escape_backslashes(pSegDB->pszDBName, true); pszDBName = MakeString("dbname='%s'", tmpDBName); } else pszDBName = NULL; if (pSegDB->pszDBUser != NULL && *pSegDB->pszDBUser != '\0') pszUser = MakeString("user=%s", pSegDB->pszDBUser); else pszUser = NULL; if (pSegDB->pszDBPswd != NULL && *pSegDB->pszDBPswd != '\0') pszDBPswd = MakeString("password='******'", pSegDB->pszDBPswd); else pszDBPswd = NULL; pszConnInfo = MakeString("%s %s port=%u %s %s %s", StringNotNull(pszOptions, ""), pszHost, pSegDB->port, StringNotNull(pszDBName, ""), //database, StringNotNull(pszUser, ""), StringNotNull(pszDBPswd, "")); pConn = PQconnectdb(pszConnInfo); if (pszOptions != NULL) free(pszOptions); if (pszHost != NULL) free(pszHost); if (tmpDBName != NULL) free(tmpDBName); if (pszDBName != NULL) free(pszDBName); if (pszUser != NULL) free(pszUser); if (pszDBPswd != NULL) free(pszDBPswd); if (pszConnInfo != NULL) free(pszConnInfo); return pConn; }
int main(int argc, char *argv[]) { int append=0; int create=0; int slim=0; int sanitize=0; int long_usage_bool=0; int pass_prompt=0; int projection = PROJ_SPHERE_MERC; int expire_tiles_zoom = -1; int expire_tiles_zoom_min = -1; int enable_hstore = HSTORE_NONE; int enable_hstore_index = 0; int hstore_match_only = 0; int enable_multi = 0; int parallel_indexing = 1; int flat_node_cache_enabled = 0; #ifdef __amd64__ int alloc_chunkwise = ALLOC_SPARSE | ALLOC_DENSE; #else int alloc_chunkwise = ALLOC_SPARSE; #endif int num_procs = 1; int droptemp = 0; int unlogged = 0; int excludepoly = 0; time_t start, end; time_t overall_start, overall_end; time_t now; time_t end_nodes; time_t end_way; time_t end_rel; const char *expire_tiles_filename = "dirty_tiles"; const char *db = "gis"; const char *username=NULL; const char *host=NULL; const char *password=NULL; const char *port = "5432"; const char *tblsmain_index = NULL; /* no default TABLESPACE for index on main tables */ const char *tblsmain_data = NULL; /* no default TABLESPACE for main tables */ const char *tblsslim_index = NULL; /* no default TABLESPACE for index on slim mode tables */ const char *tblsslim_data = NULL; /* no default TABLESPACE for slim mode tables */ const char *conninfo = NULL; const char *prefix = "planet_osm"; const char *style = OSM2PGSQL_DATADIR "/default.style"; const char *temparg; const char *output_backend = "pgsql"; const char *input_reader = "auto"; const char **hstore_columns = NULL; const char *flat_nodes_file = NULL; const char *tag_transform_script = NULL; int n_hstore_columns = 0; int keep_coastlines=0; int cache = 800; struct output_options options; PGconn *sql_conn; int (*streamFile)(char *, int, struct osmdata_t *); fprintf(stderr, "osm2pgsql SVN version %s (%lubit id space)\n\n", VERSION, 8 * sizeof(osmid_t)); while (1) { int c, option_index = 0; static struct option long_options[] = { {"append", 0, 0, 'a'}, {"bbox", 1, 0, 'b'}, {"create", 0, 0, 'c'}, {"database", 1, 0, 'd'}, {"latlong", 0, 0, 'l'}, {"verbose", 0, 0, 'v'}, {"slim", 0, 0, 's'}, {"prefix", 1, 0, 'p'}, {"proj", 1, 0, 'E'}, {"merc", 0, 0, 'm'}, {"oldmerc", 0, 0, 'M'}, {"utf8-sanitize", 0, 0, 'u'}, {"cache", 1, 0, 'C'}, {"username", 1, 0, 'U'}, {"password", 0, 0, 'W'}, {"host", 1, 0, 'H'}, {"port", 1, 0, 'P'}, {"tablespace-index", 1, 0, 'i'}, {"tablespace-slim-data", 1, 0, 200}, {"tablespace-slim-index", 1, 0, 201}, {"tablespace-main-data", 1, 0, 202}, {"tablespace-main-index", 1, 0, 203}, {"help", 0, 0, 'h'}, {"style", 1, 0, 'S'}, {"expire-tiles", 1, 0, 'e'}, {"expire-output", 1, 0, 'o'}, {"output", 1, 0, 'O'}, {"extra-attributes", 0, 0, 'x'}, {"hstore", 0, 0, 'k'}, {"hstore-all", 0, 0, 'j'}, {"hstore-column", 1, 0, 'z'}, {"hstore-match-only", 0, 0, 208}, {"hstore-add-index",0,0,211}, {"multi-geometry", 0, 0, 'G'}, {"keep-coastlines", 0, 0, 'K'}, {"input-reader", 1, 0, 'r'}, {"version", 0, 0, 'V'}, {"disable-parallel-indexing", 0, 0, 'I'}, {"cache-strategy", 1, 0, 204}, {"number-processes", 1, 0, 205}, {"drop", 0, 0, 206}, {"unlogged", 0, 0, 207}, {"flat-nodes",1,0,209}, {"exclude-invalid-polygon",0,0,210}, {"tag-transform-script",1,0,212}, {0, 0, 0, 0} }; c = getopt_long (argc, argv, "ab:cd:KhlmMp:suvU:WH:P:i:IE:C:S:e:o:O:xkjGz:r:V", long_options, &option_index); if (c == -1) break; switch (c) { case 'a': append=1; break; case 'b': osmdata.bbox=optarg; break; case 'c': create=1; break; case 'v': verbose=1; break; case 's': slim=1; break; case 'K': keep_coastlines=1; break; case 'u': sanitize=1; break; case 'l': projection=PROJ_LATLONG; break; case 'm': projection=PROJ_SPHERE_MERC; break; case 'M': projection=PROJ_MERC; break; case 'E': projection=-atoi(optarg); break; case 'p': prefix=optarg; break; case 'd': db=optarg; break; case 'C': cache = atoi(optarg); break; case 'U': username=optarg; break; case 'W': pass_prompt=1; break; case 'H': host=optarg; break; case 'P': port=optarg; break; case 'S': style=optarg; break; case 'i': tblsmain_index=tblsslim_index=optarg; break; case 200: tblsslim_data=optarg; break; case 201: tblsslim_index=optarg; break; case 202: tblsmain_data=optarg; break; case 203: tblsmain_index=optarg; break; case 'e': expire_tiles_zoom_min = atoi(optarg); temparg = strchr(optarg, '-'); if (temparg) expire_tiles_zoom = atoi(temparg + 1); if (expire_tiles_zoom < expire_tiles_zoom_min) expire_tiles_zoom = expire_tiles_zoom_min; break; case 'o': expire_tiles_filename=optarg; break; case 'O': output_backend = optarg; break; case 'x': osmdata.extra_attributes=1; break; case 'k': enable_hstore=HSTORE_NORM; break; case 208: hstore_match_only = 1; break; case 'j': enable_hstore=HSTORE_ALL; break; case 'z': n_hstore_columns++; hstore_columns = (const char**)realloc(hstore_columns, sizeof(char *) * n_hstore_columns); hstore_columns[n_hstore_columns-1] = optarg; break; case 'G': enable_multi=1; break; case 'r': input_reader = optarg; break; case 'h': long_usage_bool=1; break; case 'I': #ifdef HAVE_PTHREAD parallel_indexing=0; #endif break; case 204: if (strcmp(optarg,"dense") == 0) alloc_chunkwise = ALLOC_DENSE; else if (strcmp(optarg,"chunk") == 0) alloc_chunkwise = ALLOC_DENSE | ALLOC_DENSE_CHUNK; else if (strcmp(optarg,"sparse") == 0) alloc_chunkwise = ALLOC_SPARSE; else if (strcmp(optarg,"optimized") == 0) alloc_chunkwise = ALLOC_DENSE | ALLOC_SPARSE; else {fprintf(stderr, "ERROR: Unrecognized cache strategy %s.\n", optarg); exit(EXIT_FAILURE); } break; case 205: #ifdef HAVE_FORK num_procs = atoi(optarg); #else fprintf(stderr, "WARNING: osm2pgsql was compiled without fork, only using one process!\n"); #endif break; case 206: droptemp = 1; break; case 207: unlogged = 1; break; case 209: flat_node_cache_enabled = 1; flat_nodes_file = optarg; break; case 210: excludepoly = 1; exclude_broken_polygon(); break; case 211: enable_hstore_index = 1; break; case 212: tag_transform_script = optarg; break; case 'V': exit(EXIT_SUCCESS); case '?': default: short_usage(argv[0]); exit(EXIT_FAILURE); } } if (long_usage_bool) { long_usage(argv[0]); exit(EXIT_SUCCESS); } if (argc == optind) { /* No non-switch arguments */ short_usage(argv[0]); exit(EXIT_FAILURE); } if (append && create) { fprintf(stderr, "Error: --append and --create options can not be used at the same time!\n"); exit(EXIT_FAILURE); } if (droptemp && !slim) { fprintf(stderr, "Error: --drop only makes sense with --slim.\n"); exit(EXIT_FAILURE); } if (unlogged && !create) { fprintf(stderr, "Warning: --unlogged only makes sense with --create; ignored.\n"); unlogged = 0; } if (enable_hstore == HSTORE_NONE && !n_hstore_columns && hstore_match_only) { fprintf(stderr, "Warning: --hstore-match-only only makes sense with --hstore, --hstore-all, or --hstore-column; ignored.\n"); hstore_match_only = 0; } if (enable_hstore_index && enable_hstore == HSTORE_NONE && !n_hstore_columns) { fprintf(stderr, "Warning: --hstore-add-index only makes sense with hstore enabled.\n"); enable_hstore_index = 0; } if (cache < 0) cache = 0; if (num_procs < 1) num_procs = 1; if (pass_prompt) password = simple_prompt("Password:"******"PGPASS"); } conninfo = build_conninfo(db, username, password, host, port); sql_conn = PQconnectdb(conninfo); if (PQstatus(sql_conn) != CONNECTION_OK) { fprintf(stderr, "Error: Connection to database failed: %s\n", PQerrorMessage(sql_conn)); exit(EXIT_FAILURE); } if (unlogged && PQserverVersion(sql_conn) < 90100) { fprintf(stderr, "Error: --unlogged works only with PostgreSQL 9.1 and above, but\n"); fprintf(stderr, "you are using PostgreSQL %d.%d.%d.\n", PQserverVersion(sql_conn) / 10000, (PQserverVersion(sql_conn) / 100) % 100, PQserverVersion(sql_conn) % 100); exit(EXIT_FAILURE); } PQfinish(sql_conn); text_init(); initList(&osmdata.tags); osmdata.count_node = osmdata.max_node = 0; osmdata.count_way = osmdata.max_way = 0; osmdata.count_rel = osmdata.max_rel = 0; LIBXML_TEST_VERSION project_init(projection); fprintf(stderr, "Using projection SRS %d (%s)\n", project_getprojinfo()->srs, project_getprojinfo()->descr ); if (parse_bbox(&osmdata)) return 1; options.conninfo = conninfo; options.prefix = prefix; options.append = append; options.slim = slim; options.projection = project_getprojinfo()->srs; options.scale = (projection==PROJ_LATLONG)?10000000:100; options.mid = slim ? &mid_pgsql : &mid_ram; options.cache = cache; options.style = style; options.tblsmain_index = tblsmain_index; options.tblsmain_data = tblsmain_data; options.tblsslim_index = tblsslim_index; options.tblsslim_data = tblsslim_data; options.expire_tiles_zoom = expire_tiles_zoom; options.expire_tiles_zoom_min = expire_tiles_zoom_min; options.expire_tiles_filename = expire_tiles_filename; options.enable_multi = enable_multi; options.enable_hstore = enable_hstore; options.enable_hstore_index = enable_hstore_index; options.hstore_match_only = hstore_match_only; options.hstore_columns = hstore_columns; options.n_hstore_columns = n_hstore_columns; options.keep_coastlines = keep_coastlines; options.parallel_indexing = parallel_indexing; options.alloc_chunkwise = alloc_chunkwise; options.num_procs = num_procs; options.droptemp = droptemp; options.unlogged = unlogged; options.flat_node_cache_enabled = flat_node_cache_enabled; options.flat_node_file = flat_nodes_file; options.excludepoly = excludepoly; options.tag_transform_script = tag_transform_script; if (strcmp("pgsql", output_backend) == 0) { osmdata.out = &out_pgsql; } else if (strcmp("gazetteer", output_backend) == 0) { osmdata.out = &out_gazetteer; } else if (strcmp("null", output_backend) == 0) { osmdata.out = &out_null; } else { fprintf(stderr, "Output backend `%s' not recognised. Should be one of [pgsql, gazetteer, null].\n", output_backend); exit(EXIT_FAILURE); } options.out = osmdata.out; if (strcmp("auto", input_reader) != 0) { if (strcmp("libxml2", input_reader) == 0) { streamFile = &streamFileXML2; } else if (strcmp("primitive", input_reader) == 0) { streamFile = &streamFilePrimitive; #ifdef BUILD_READER_PBF } else if (strcmp("pbf", input_reader) == 0) { streamFile = &streamFilePbf; #endif } else if (strcmp("o5m", input_reader) == 0) { streamFile = &streamFileO5m; } else { fprintf(stderr, "Input parser `%s' not recognised. Should be one of [libxml2, primitive, o5m" #ifdef BUILD_READER_PBF ", pbf" #endif "].\n", input_reader); exit(EXIT_FAILURE); } } time(&overall_start); osmdata.out->start(&options); realloc_nodes(&osmdata); realloc_members(&osmdata); if (sizeof(int*) == 4 && options.slim != 1) { fprintf(stderr, "\n!! You are running this on 32bit system, so at most\n"); fprintf(stderr, "!! 3GB of RAM can be used. If you encounter unexpected\n"); fprintf(stderr, "!! exceptions during import, you should try running in slim\n"); fprintf(stderr, "!! mode using parameter -s.\n"); } while (optind < argc) { /* if input_reader is not forced by -r switch try to auto-detect it by file extension */ if (strcmp("auto", input_reader) == 0) { if (strcasecmp(".pbf",argv[optind]+strlen(argv[optind])-4) == 0) { #ifdef BUILD_READER_PBF streamFile = &streamFilePbf; #else fprintf(stderr, "ERROR: PBF support has not been compiled into this version of osm2pgsql, please either compile it with pbf support or use one of the other input formats\n"); exit(EXIT_FAILURE); #endif } else if (strcasecmp(".o5m",argv[optind]+strlen(argv[optind])-4) == 0 || strcasecmp(".o5c",argv[optind]+strlen(argv[optind])-4) == 0) { streamFile = &streamFileO5m; } else { streamFile = &streamFileXML2; } } fprintf(stderr, "\nReading in file: %s\n", argv[optind]); time(&start); if (streamFile(argv[optind], sanitize, &osmdata) != 0) exit_nicely(); time(&end); fprintf(stderr, " parse time: %ds\n", (int)(end - start)); optind++; } xmlCleanupParser(); xmlMemoryDump(); if (osmdata.count_node || osmdata.count_way || osmdata.count_rel) { time(&now); end_nodes = osmdata.start_way > 0 ? osmdata.start_way : now; end_way = osmdata.start_rel > 0 ? osmdata.start_rel : now; end_rel = now; fprintf(stderr, "\n"); fprintf(stderr, "Node stats: total(%" PRIdOSMID "), max(%" PRIdOSMID ") in %is\n", osmdata.count_node, osmdata.max_node, osmdata.count_node > 0 ? (int)(end_nodes - osmdata.start_node) : 0); fprintf(stderr, "Way stats: total(%" PRIdOSMID "), max(%" PRIdOSMID ") in %is\n", osmdata.count_way, osmdata.max_way, osmdata.count_way > 0 ? (int)(end_way - osmdata.start_way) : 0); fprintf(stderr, "Relation stats: total(%" PRIdOSMID "), max(%" PRIdOSMID ") in %is\n", osmdata.count_rel, osmdata.max_rel, osmdata.count_rel > 0 ? (int)(end_rel - osmdata.start_rel) : 0); } osmdata.out->stop(); free(osmdata.nds); free(osmdata.members); /* free the column pointer buffer */ free(hstore_columns); project_exit(); text_exit(); fprintf(stderr, "\n"); time(&overall_end); fprintf(stderr, "Osm2pgsql took %ds overall\n", (int)(overall_end - overall_start)); return 0; }
static void* server_thread(void *arg){ int i; struct judge_submit_info *submit_info; struct judgx_line_info *line_info; char tname[NAME_MAX + 1]; char tpath[PATH_MAX + 1]; line_run_fn line_run; PGconn *sqlc; sqlc = PQconnectdb("host=localhost port=5432 dbname=xxxxx user=xxxxx password=xxxxx"); while(1){ printf("in\n"); sem_wait(&server_queue_sem); pthread_mutex_lock(&server_queue_mutex); printf("in1\n"); submit_info = server_queue_head.next; server_queue_head.next = submit_info->next; submit_info->next->prev = &server_queue_head; pthread_mutex_unlock(&server_queue_mutex); printf("in2\n"); line_info = malloc(sizeof(struct judgx_line_info)); printf("in3\n"); snprintf(line_info->pro_path,sizeof(line_info->pro_path),"pro/%d",submit_info->proid); snprintf(line_info->cpp_path,sizeof(line_info->cpp_path),"submit/%d_submit.cpp",submit_info->submitid); snprintf(line_info->exe_path,sizeof(line_info->exe_path),"run/%d_submit",submit_info->submitid); printf("in4"); snprintf(tpath,sizeof(tpath),"pro/%d/%d_setting.txt",submit_info->proid,submit_info->proid); while((line_info->set_file = fopen(tpath,"r")) == NULL){ printf("Oops %s\n",strerror(errno)); printf("Path %s %d %d\n",tpath,submit_info->proid,submit_info->submitid); break; } printf("in5\n"); fgets(tname,sizeof(tname),line_info->set_file); tname[strlen(tname) - 1] = '\0'; snprintf(tpath,sizeof(tpath),"judge/%s.so",tname); printf("in5-1\n"); line_info->line_dll = dlopen(tpath,RTLD_LAZY | RTLD_NODELETE); printf("in5-2\n"); fgets(tname,sizeof(tname),line_info->set_file); tname[strlen(tname) - 1] = '\0'; snprintf(tpath,sizeof(tpath),"judge/%s.so",tname); printf("in5-3\n"); line_info->check_dll = dlopen(tpath,RTLD_LAZY | RTLD_NODELETE); printf("in6\n"); line_run = dlsym(line_info->line_dll,"run"); line_run(line_info); printf("in7\n"); server_updatedb(sqlc,submit_info->submitid,line_info->result_count,line_info->result); printf("in8\n"); fclose(line_info->set_file); dlclose(line_info->line_dll); dlclose(line_info->check_dll); free(line_info); free(submit_info); printf("out\n"); } PQfinish(sqlc); return NULL; }
int main( int argc, char** argv ) { PGconn* t_PGconn = NULL; PGresult* t_PGresult_select = NULL; PGresult* t_PGresult; int t_returnCode = EXIT_FAILURE; int i = -1; int j; int k; int q; CURLcode t_curlCode; CURL* t_hEasy = NULL; char t_curlErrorMessage[CURL_ERROR_SIZE]; tDataBuffer t_responseBuffer = { NULL, 0 }; long t_httpResponseCode; json_object* j_getSTH = NULL; json_object* j_treeSize = NULL; json_object* j_timestamp = NULL; json_object* j_getEntries = NULL; json_object* j_entries = NULL; json_object* j_entry = NULL; json_object* j_leafInput = NULL; json_object* j_extraData = NULL; array_list* t_entriesArr = NULL; uint32_t t_entryID; uint32_t t_confirmedEntryID = -1; uint64_t t_timestamp; int64_t t_sthTimestamp; int t_treeSize; uint16_t t_logEntryType; char t_temp[255]; char* t_pointer; char* t_pointer1; char* t_b64Data; char* t_data = NULL; int32_t t_totalLength; X509* t_x509 = NULL; uint32_t t_certSize; char* t_query[32]; char* t_subjectName; uint8_t* t_cachedCACerts = NULL; uint32_t t_nCachedCACerts = 0; uint32_t t_nCertsInChain; EVP_MD_CTX t_mdctx; const EVP_MD* t_md; unsigned char t_sha256Hash_data[32]; uint32_t t_sha256Hash_size; /* Initialize the OpenSSL library */ OpenSSL_add_all_algorithms(); t_md = EVP_sha256(); EVP_MD_CTX_init(&t_mdctx); /* Install signal handlers */ signal(SIGHUP, signalHandler); signal(SIGINT, signalHandler); signal(SIGQUIT, signalHandler); signal(SIGTERM, signalHandler); for (q = 0; q < 32; q++) t_query[q] = malloc(128 * 1024); /* Connect to the database */ t_PGconn = PQconnectdb( "user=crtsh dbname=certwatch" " connect_timeout=5 client_encoding=auto" " application_name=ct_monitor" ); if (PQstatus(t_PGconn) != CONNECTION_OK) { printError("PQconnectdb()", PQerrorMessage(t_PGconn)); return EXIT_FAILURE; } printError("Connected OK", NULL); /* Get the latest CT Entry ID that we've added to the DB already */ sprintf( t_query[0], "SELECT ctl.ID, ctl.URL, ctl.LATEST_ENTRY_ID, ctl.NAME" " FROM ct_log ctl" " WHERE ctl.IS_ACTIVE" ); if (argc > 1) /* Only process one log */ sprintf( t_query[0] + strlen(t_query[0]), " AND ctl.ID = %s", argv[1] ); else /* Process all logs */ strcat( t_query[0], " ORDER BY ctl.ID" ); t_PGresult_select = PQexec( t_PGconn, t_query[0] ); if (PQresultStatus(t_PGresult_select) != PGRES_TUPLES_OK) { /* The SQL query failed */ printError("Query failed", PQerrorMessage(t_PGconn)); goto label_exit; } /* curl_global_init() must be called EXACTLY once */ t_curlCode = curl_global_init(CURL_GLOBAL_ALL); if (t_curlCode != CURLE_OK) { printError( "curl_global_init()", curl_easy_strerror(t_curlCode) ); /* Something went wrong, so we cannot continue */ return EXIT_FAILURE; } for (i = 0; i < PQntuples(t_PGresult_select); i++) { t_confirmedEntryID = -1; /* Initialize the "easy handle" */ t_hEasy = curl_easy_init(); if (!t_hEasy) { printError("curl_easy_init()", "returned NULL"); goto label_exit; } /* SETUP CURL BEHAVIOUR OPTIONS */ /* CURLOPT_NOPROGRESS: No progress meter */ CURL_EASY_SETOPT(CURLOPT_NOPROGRESS, 0) /* CURLOPT_NOSIGNAL: Don't use signals */ CURL_EASY_SETOPT(CURLOPT_NOSIGNAL, 1) /* SETUP CURL CALLBACK OPTIONS */ /* CURLOPT_WRITEFUNCTION: "Data Received" Callback Function */ CURL_EASY_SETOPT(CURLOPT_WRITEFUNCTION, curlDataReceivedFunction) /* CURLOPT_WRITEDATA: Data Pointer to pass to "Data Received" Callback Function */ CURL_EASY_SETOPT(CURLOPT_WRITEDATA, &t_responseBuffer) /* SETUP CURL ERROR OPTIONS */ /* CURLOPT_ERRORBUFFER: Buffer for potential error message */ CURL_EASY_SETOPT(CURLOPT_ERRORBUFFER, t_curlErrorMessage) /* SETUP CURL NETWORK OPTIONS */ /* CURLOPT_URL: The URL to deal with */ sprintf(t_temp, "%s/ct/v1/get-sth", PQgetvalue(t_PGresult_select, i, 1)); printError(t_temp, PQgetvalue(t_PGresult_select, i, 3)); CURL_EASY_SETOPT(CURLOPT_URL, t_temp) /* Use IPv4 rather than IPv6 */ CURL_EASY_SETOPT(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4) /* SETUP CURL HTTP OPTIONS */ /* CURLOPT_FOLLOWLOCATION: Don't follow "Location:" redirects */ CURL_EASY_SETOPT(CURLOPT_FOLLOWLOCATION, 0) /* SETUP CURL CONNECTION OPTIONS */ /* CURLOPT_TIMEOUT: Transfer Timeout (in seconds) */ CURL_EASY_SETOPT(CURLOPT_TIMEOUT, 300) /* CURLOPT_CONNECTTIMEOUT: Connect Timeout (in seconds) */ CURL_EASY_SETOPT(CURLOPT_CONNECTTIMEOUT, 300) /* Perform the transfer */ t_curlCode = curl_easy_perform(t_hEasy); if (t_curlCode != CURLE_OK) { printError("curl_easy_perform()", t_curlErrorMessage); goto label_exit; } /* Get the HTTP response code */ t_curlCode = curl_easy_getinfo( t_hEasy, CURLINFO_RESPONSE_CODE, &t_httpResponseCode ); if (t_curlCode != CURLE_OK) { printError("curl_easy_getinfo()", t_curlErrorMessage); goto label_exit; } else if (t_httpResponseCode != 200) { printError( "curl_easy_getinfo()", "Unexpected HTTP Response Code" ); goto label_exit; } if (PQgetisnull(t_PGresult_select, i, 2)) t_entryID = -1; else t_entryID = strtoul( PQgetvalue(t_PGresult_select, i, 2), NULL, 10 ); printf("Highest Entry ID stored: %d\n", t_entryID); j_getSTH = json_tokener_parse(t_responseBuffer.data); if (!json_object_object_get_ex(j_getSTH, "tree_size", &j_treeSize)) goto label_exit; t_treeSize = json_object_get_int(j_treeSize); printf("Current Tree Size: %d\n", t_treeSize); if (!json_object_object_get_ex(j_getSTH, "timestamp", &j_timestamp)) goto label_exit; t_sthTimestamp = json_object_get_int64(j_timestamp); printf("Timestamp: %" LENGTH64 "d\n", t_sthTimestamp); if (json_object_put(j_getSTH) != 1) { printError("json_object_put(j_getSTH)", "Did not return 1"); goto label_exit; } free(t_responseBuffer.data); t_responseBuffer.data = NULL; t_responseBuffer.size = 0; /* TODO: Verify the STH signature */ for (t_entryID++; t_entryID < t_treeSize; t_entryID = t_confirmedEntryID + 1) { sprintf( t_temp, "%s/ct/v1/get-entries?start=%d&end=%d", PQgetvalue(t_PGresult_select, i, 1), t_entryID, (t_treeSize > (t_entryID + 1023)) ? (t_entryID + 1023) : (t_treeSize - 1) ); printError(t_temp, NULL); CURL_EASY_SETOPT(CURLOPT_URL, t_temp) /* Perform the transfer */ t_curlCode = curl_easy_perform(t_hEasy); if (t_curlCode != CURLE_OK) { printError("curl_easy_perform()", t_curlErrorMessage); goto label_exit; } /* Get the HTTP response code */ t_curlCode = curl_easy_getinfo( t_hEasy, CURLINFO_RESPONSE_CODE, &t_httpResponseCode ); if (t_curlCode != CURLE_OK) { printError("curl_easy_getinfo()", t_curlErrorMessage); goto label_exit; } else if (t_httpResponseCode != 200) { printError( "curl_easy_getinfo()", "Unexpected HTTP Response Code" ); goto label_exit; } /* Update the "Last Contacted" timestamp */ sprintf( t_query[0], "UPDATE ct_log" " SET LATEST_UPDATE=statement_timestamp()" " WHERE ID=%s", PQgetvalue(t_PGresult_select, i, 0) ); t_PGresult = PQexec(t_PGconn, t_query[0]); if (PQresultStatus(t_PGresult) != PGRES_COMMAND_OK) { /* The SQL query failed */ printError( "UPDATE Query failed", PQerrorMessage(t_PGconn) ); } PQclear(t_PGresult); /* Parse the JSON response */ j_getEntries = json_tokener_parse(t_responseBuffer.data); if (!json_object_object_get_ex(j_getEntries, "entries", &j_entries)) goto label_exit; t_entriesArr = json_object_get_array(j_entries); for (j = 0; j < json_object_array_length(j_entries); j++) { j_entry = array_list_get_idx(t_entriesArr, j); if (!json_object_object_get_ex(j_entry, "leaf_input", &j_leafInput)) goto label_exit; /* Decode the Base64 leaf_input string */ t_b64Data = (char*)json_object_get_string(j_leafInput); t_data = NULL; Base64Decode(t_b64Data, &t_data); if (!t_data) { printError("Base64 decode error", ""); goto label_exit; } /* Check the header fields */ if (*(unsigned char*)t_data != 0) { sprintf( t_temp, "%u", *(unsigned char*)t_data ); printError("Unexpected Version", t_temp); goto label_exit; } if (*(unsigned char*)(t_data + 1) != 0) { sprintf( t_temp, "%u", *(unsigned char*)(t_data + 1) ); printError("Unexpected MerkleLeafType", t_temp); goto label_exit; } t_timestamp = be64toh(*(uint64_t*)(t_data + 2)); t_logEntryType = be16toh(*(uint16_t*)(t_data + 10)); if (t_logEntryType == 1) { /* Precertificate. The leaf_input contains a SHA-256 hash of the Issuer Public Key, then the TBSCertificate. Ignore both of these. The submitted Precertificate is the first cert in the extra_data */ } else if (t_logEntryType == 0) { /* Parse the certificate */ t_certSize = 0; memcpy(((char*)&t_certSize) + 1, t_data + 12, 3); t_certSize = be32toh(t_certSize); printf("%d: ", (t_entryID + j)); t_pointer = t_data + 15; t_x509 = d2i_X509( NULL, (const unsigned char**)&t_pointer, t_certSize ); if (t_x509) { t_subjectName = X509_NAME_oneline( X509_get_subject_name(t_x509), NULL, 0 ); if (t_subjectName) { printf("%s\n", t_subjectName); OPENSSL_free(t_subjectName); } X509_free(t_x509); if (t_certSize != (t_pointer - (t_data + 15))) { printError("Additional data after EE cert", t_b64Data); t_certSize = t_pointer - (t_data + 15); } } else printError("Failed to decode EE cert", t_b64Data); /* Construct the "INSERT" query */ sprintf(t_query[0], "SELECT import_ct_cert(%s::smallint, %d, %" LENGTH64 "u, E'\\\\x", PQgetvalue(t_PGresult_select, i, 0), (t_entryID + j), t_timestamp); for (k = 0; k < t_certSize; k++) sprintf( t_query[0] + strlen(t_query[0]), "%02X", *(unsigned char*)(t_data + 15 + k)); strcat(t_query[0], "')"); } else { sprintf(t_temp, "%u", t_logEntryType); printError("Unexpected LogEntryType", t_temp); goto label_exit; } free(t_data); t_nCertsInChain = 1; if (!json_object_object_get_ex(j_entry, "extra_data", &j_extraData)) goto label_addCerts; /* Decode the Base64 extra_data string */ t_b64Data = (char*)json_object_get_string(j_extraData); t_data = NULL; Base64Decode(t_b64Data, &t_data); if (!t_data) { printError("Base64 decode error", ""); goto label_exit; } t_pointer1 = t_data; if (t_logEntryType == 1) { t_certSize = 0; memcpy(((char*)&t_certSize) + 1, t_pointer1, 3); t_certSize = be32toh(t_certSize); t_pointer1 += 3; t_pointer = t_pointer1; t_x509 = d2i_X509( NULL, (const unsigned char**)&t_pointer, t_certSize ); if (!t_x509) { printError("Failed to decode Precertificate", t_b64Data); goto label_exit; } if (t_certSize != (t_pointer - t_pointer1)) { printError("Additional data after Precertificate", t_b64Data); t_certSize = t_pointer - t_pointer1; } t_subjectName = X509_NAME_oneline( X509_get_subject_name(t_x509), NULL, 0 ); printf("Precertificate: %s\n", t_subjectName); X509_free(t_x509); if (t_subjectName) OPENSSL_free(t_subjectName); /* Construct the "INSERT" query */ sprintf(t_query[0], "SELECT import_ct_cert(%s::smallint, %d, %" LENGTH64 "u, E'\\\\x", PQgetvalue(t_PGresult_select, i, 0), (t_entryID + j), t_timestamp); for (k = 0; k < t_certSize; k++) sprintf( t_query[0] + strlen(t_query[0]), "%02X", *(unsigned char*)(t_pointer1 + k)); strcat(t_query[0], "')"); t_pointer1 = t_pointer; } /* Find the total length of the CA certificate array */ t_totalLength = 0; memcpy(((char*)&t_totalLength) + 1, t_pointer1, 3); t_totalLength = be32toh(t_totalLength); t_pointer1 += 3; /* Parse each CA Certificate */ while (t_totalLength > 0) { t_certSize = 0; memcpy(((char*)&t_certSize) + 1, t_pointer1, 3); t_certSize = be32toh(t_certSize); t_totalLength -= 3; t_pointer1 += 3; t_pointer = t_pointer1; t_x509 = d2i_X509( NULL, (const unsigned char**)&t_pointer, t_certSize ); if (!t_x509) { printError("Failed to decode CA cert", t_b64Data); goto label_exit; } if (t_certSize != (t_pointer - t_pointer1)) { printError("Additional data after CA cert", t_b64Data); t_certSize = t_pointer - t_pointer1; } t_subjectName = X509_NAME_oneline( X509_get_subject_name(t_x509), NULL, 0 ); printf("CA: %s", t_subjectName); X509_free(t_x509); if (t_subjectName) OPENSSL_free(t_subjectName); /* Generate SHA-256(CACertificate) */ EVP_DigestInit_ex(&t_mdctx, t_md, NULL); EVP_DigestUpdate(&t_mdctx, t_pointer1, t_certSize); EVP_DigestFinal_ex(&t_mdctx, t_sha256Hash_data, &t_sha256Hash_size); if ((!t_cachedCACerts) || (!bsearch(t_sha256Hash_data, t_cachedCACerts, t_nCachedCACerts, 32, compareSHA256Hashes))) { /* We've not cached this CA Certificate yet, so let's "INSERT" it and cache it */ /* Construct the "INSERT" query */ strcpy(t_query[t_nCertsInChain], "SELECT import_cert(E'\\\\x"); for (k = 0; k < t_certSize; k++) sprintf( t_query[t_nCertsInChain] + strlen(t_query[t_nCertsInChain]), "%02X", *(unsigned char*)(t_pointer1 + k)); strcat(t_query[t_nCertsInChain], "')"); t_nCertsInChain++; /* Cache this SHA-256(CACertificate), then re-sort the list */ t_nCachedCACerts++; t_cachedCACerts = realloc(t_cachedCACerts, t_nCachedCACerts * 32); (void)memcpy(t_cachedCACerts + ((t_nCachedCACerts - 1) * 32), t_sha256Hash_data, t_sha256Hash_size); qsort(t_cachedCACerts, t_nCachedCACerts, 32, compareSHA256Hashes); } else printf(" (Already cached)"); printf("\n"); t_totalLength -= (t_pointer - t_pointer1); t_pointer1 = t_pointer; } free(t_data); label_addCerts: /* Execute the "INSERT" quer(ies) */ printf("Import %d cert%s: ", t_nCertsInChain, (t_nCertsInChain == 1) ? "" : "s"); for (q = t_nCertsInChain - 1; q >= 0; q--) { t_PGresult = PQexec(t_PGconn, t_query[q]); if (PQresultStatus(t_PGresult) != PGRES_TUPLES_OK) { /* The SQL query failed */ printError("Query failed", PQerrorMessage(t_PGconn)); goto label_exit; } else if (PQgetisnull(t_PGresult, 0, 0)) { /* The SQL query failed */ printError("Query failed", t_query[q]); goto label_exit; } PQclear(t_PGresult); } printf("OK\n"); t_confirmedEntryID = t_entryID + j; if (g_terminateNow) goto label_exit; printf("\n"); } if (json_object_put(j_getEntries) != 1) { printError( "json_object_put(j_getEntries)", "Did not return 1" ); goto label_exit; } free(t_responseBuffer.data); t_responseBuffer.data = NULL; t_responseBuffer.size = 0; if (g_terminateNow) goto label_exit; } /* Cleanup the "easy handle" */ curl_easy_cleanup(t_hEasy); t_hEasy = NULL; if (t_confirmedEntryID == -1) t_entryID--; else t_entryID = t_confirmedEntryID; /* Update the "Latest STH" timestamp, now that we've processed all of the entries covered by this STH */ sprintf( t_query[0], "UPDATE ct_log" " SET LATEST_UPDATE=statement_timestamp()," " LATEST_STH_TIMESTAMP=TIMESTAMP WITH TIME ZONE 'epoch'" " + interval'%" LENGTH64 "d seconds'" " + interval'%" LENGTH64 "d milliseconds'" " WHERE ID=%s", t_sthTimestamp / 1000, t_sthTimestamp % 1000, PQgetvalue(t_PGresult_select, i, 0) ); t_PGresult = PQexec(t_PGconn, t_query[0]); if (PQresultStatus(t_PGresult) != PGRES_COMMAND_OK) { /* The SQL query failed */ printError( "UPDATE Query failed", PQerrorMessage(t_PGconn) ); } PQclear(t_PGresult); } t_returnCode = EXIT_SUCCESS; label_exit: if (t_returnCode == EXIT_FAILURE) if (t_confirmedEntryID != -1) { sprintf( t_query[0], "UPDATE ct_log" " SET LATEST_UPDATE=statement_timestamp()" " WHERE ID=%s", PQgetvalue(t_PGresult_select, i, 0) ); t_PGresult = PQexec(t_PGconn, t_query[0]); if (PQresultStatus(t_PGresult) != PGRES_COMMAND_OK) { /* The SQL query failed */ printError( "UPDATE Query failed", PQerrorMessage(t_PGconn) ); } PQclear(t_PGresult); } printError("Terminated", NULL); /* Clear the query results */ if (t_PGresult_select) PQclear(t_PGresult_select); /* Close this DB connection */ if (t_PGconn) PQfinish(t_PGconn); /* Free the Response Buffer */ if (t_responseBuffer.data) free(t_responseBuffer.data); /* Cleanup the "easy handle" */ if (t_hEasy) curl_easy_cleanup(t_hEasy); /* curl_global_cleanup() must be called EXACTLY once */ curl_global_cleanup(); for (q = 0; q < 32; q++) if (t_query[q]) free(t_query[q]); if (t_cachedCACerts) free(t_cachedCACerts); EVP_MD_CTX_cleanup(&t_mdctx); return t_returnCode; }
int main(int argc, char **argv) { const char *conninfo; PGconn *conn; PGresult *res; const char *paramValues[1]; int paramLengths[1]; int paramFormats[1]; uint32_t binaryIntVal; /* * If the user supplies a parameter on the command line, use it as the * conninfo string; otherwise default to setting dbname=postgres and using * environment variables or defaults for all other connection parameters. */ if (argc > 1) conninfo = argv[1]; else conninfo = "dbname = postgres"; /* Make a connection to the database */ conn = PQconnectdb(conninfo); /* Check to see that the backend connection was successfully made */ if (PQstatus(conn) != CONNECTION_OK) { fprintf(stderr, "Connection to database failed: %s", PQerrorMessage(conn)); exit_nicely(conn); } /* * The point of this program is to illustrate use of PQexecParams() with * out-of-line parameters, as well as binary transmission of data. * * This first example transmits the parameters as text, but receives the * results in binary format. By using out-of-line parameters we can avoid * a lot of tedious mucking about with quoting and escaping, even though * the data is text. Notice how we don't have to do anything special with * the quote mark in the parameter value. */ /* Here is our out-of-line parameter value */ paramValues[0] = "joe's place"; res = PQexecParams(conn, "SELECT * FROM test1 WHERE t = $1", 1, /* one param */ NULL, /* let the backend deduce param type */ paramValues, NULL, /* don't need param lengths since text */ NULL, /* default to all text params */ 1); /* ask for binary results */ if (PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn)); PQclear(res); exit_nicely(conn); } show_binary_results(res); PQclear(res); /* * In this second example we transmit an integer parameter in binary form, * and again retrieve the results in binary form. * * Although we tell PQexecParams we are letting the backend deduce * parameter type, we really force the decision by casting the parameter * symbol in the query text. This is a good safety measure when sending * binary parameters. */ /* Convert integer value "2" to network byte order */ binaryIntVal = htonl((uint32_t) 2); /* Set up parameter arrays for PQexecParams */ paramValues[0] = (char *) &binaryIntVal; paramLengths[0] = sizeof(binaryIntVal); paramFormats[0] = 1; /* binary */ res = PQexecParams(conn, "SELECT * FROM test1 WHERE i = $1::int4", 1, /* one param */ NULL, /* let the backend deduce param type */ paramValues, paramLengths, paramFormats, 1); /* ask for binary results */ if (PQresultStatus(res) != PGRES_TUPLES_OK) { fprintf(stderr, "SELECT failed: %s", PQerrorMessage(conn)); PQclear(res); exit_nicely(conn); } show_binary_results(res); PQclear(res); /* close the connection to the database and cleanup */ PQfinish(conn); return 0; }
QgsPostgresConn::QgsPostgresConn( QString conninfo, bool readOnly ) : mRef( 1 ) , mOpenCursors( 0 ) , mConnInfo( conninfo ) , mGotPostgisVersion( false ) , mReadOnly( readOnly ) { QgsDebugMsg( QString( "New PostgreSQL connection for " ) + conninfo ); mConn = PQconnectdb( conninfo.toLocal8Bit() ); // use what is set based on locale; after connecting, use Utf8 // check the connection status if ( PQstatus() != CONNECTION_OK ) { QgsDataSourceURI uri( conninfo ); QString username = uri.username(); QString password = uri.password(); while ( PQstatus() != CONNECTION_OK ) { bool ok = QgsCredentials::instance()->get( conninfo, username, password, PQerrorMessage() ); if ( !ok ) break; PQfinish(); if ( !username.isEmpty() ) uri.setUsername( username ); if ( !password.isEmpty() ) uri.setPassword( password ); QgsDebugMsg( "Connecting to " + uri.connectionInfo() ); mConn = PQconnectdb( uri.connectionInfo().toLocal8Bit() ); } if ( PQstatus() == CONNECTION_OK ) QgsCredentials::instance()->put( conninfo, username, password ); } if ( PQstatus() != CONNECTION_OK ) { PQfinish(); QgsMessageLog::logMessage( tr( "Connection to database failed" ), tr( "PostGIS" ) ); mRef = 0; return; } //set client encoding to unicode because QString uses UTF-8 anyway QgsDebugMsg( "setting client encoding to UNICODE" ); int errcode = PQsetClientEncoding( mConn, QString( "UNICODE" ).toLocal8Bit() ); if ( errcode == 0 ) { QgsDebugMsg( "encoding successfully set" ); } else if ( errcode == -1 ) { QgsMessageLog::logMessage( tr( "error in setting encoding" ), tr( "PostGIS" ) ); } else { QgsMessageLog::logMessage( tr( "undefined return value from encoding setting" ), tr( "PostGIS" ) ); } QgsDebugMsg( "Connection to the database was successful" ); deduceEndian(); /* Check to see if we have working PostGIS support */ if ( postgisVersion().isNull() ) { QgsMessageLog::logMessage( tr( "Your database has no working PostGIS support." ), tr( "PostGIS" ) ); PQfinish(); mRef = 0; return; } if ( mPostgresqlVersion >= 90000 ) { PQexecNR( "SET application_name='Quantum GIS'" ); } /* Check to see if we have GEOS support and if not, warn the user about the problems they will see :) */ QgsDebugMsg( "Checking for GEOS support" ); if ( !hasGEOS() ) { QgsMessageLog::logMessage( tr( "Your PostGIS installation has no GEOS support. Feature selection and identification will not work properly. Please install PostGIS with GEOS support (http://geos.refractions.net)" ), tr( "PostGIS" ) ); } if ( hasTopology() ) { QgsDebugMsg( "Topology support available!" ); } }
int main( int argc, char *argv[] ) { int res; PGconn *conn; struct fuse_args args = FUSE_ARGS_INIT( argc, argv ); PgFuseOptions pgfuse; PgFuseData userdata; const char *value; memset( &pgfuse, 0, sizeof( pgfuse ) ); pgfuse.multi_threaded = 1; pgfuse.block_size = DEFAULT_BLOCK_SIZE; if( fuse_opt_parse( &args, &pgfuse, pgfuse_opts, pgfuse_opt_proc ) == -1 ) { if( pgfuse.print_help ) { /* print our options */ print_usage( basename( argv[0] ) ); fflush( stdout ); /* print options of FUSE itself */ argv[1] = "-ho"; argv[2] = "mountpoint"; (void)dup2( STDOUT_FILENO, STDERR_FILENO ); /* force fuse help to stdout */ fuse_main( 2, argv, &pgfuse_oper, NULL); exit( EXIT_SUCCESS ); } if( pgfuse.print_version ) { printf( "%s\n", PGFUSE_VERSION ); exit( EXIT_SUCCESS ); } exit( EXIT_FAILURE ); } if( pgfuse.conninfo == NULL ) { fprintf( stderr, "Missing Postgresql connection data\n" ); fprintf( stderr, "See '%s -h' for usage\n", basename( argv[0] ) ); exit( EXIT_FAILURE ); } /* just test if the connection can be established, do the * real connection in the fuse init function! */ conn = PQconnectdb( pgfuse.conninfo ); if( PQstatus( conn ) != CONNECTION_OK ) { fprintf( stderr, "Connection to database failed: %s", PQerrorMessage( conn ) ); PQfinish( conn ); exit( EXIT_FAILURE ); } /* test storage of timestamps (expecting uint64 as it is the * standard for PostgreSQL 8.4 or newer). Otherwise bail out * currently.. */ value = PQparameterStatus( conn, "integer_datetimes" ); if( value == NULL ) { fprintf( stderr, "PQ param integer_datetimes not available?\n" "You use a too old version of PostgreSQL..can't continue.\n" ); PQfinish( conn ); exit( EXIT_FAILURE ); } if( strcmp( value, "on" ) != 0 ) { fprintf( stderr, "Expecting UINT64 for timestamps, not doubles. You may use an old version of PostgreSQL (<8.4)\n" "or PostgreSQL has been compiled with the deprecated compile option '--disable-integer-datetimes'\n" ); PQfinish( conn ); exit( EXIT_FAILURE ); } openlog( basename( argv[0] ), LOG_PID, LOG_USER ); /* Compare blocksize given as parameter and blocksize in database */ res = psql_get_block_size( conn, pgfuse.block_size ); if( res < 0 ) { PQfinish( conn ); exit( EXIT_FAILURE ); } if( res != pgfuse.block_size ) { fprintf( stderr, "Blocksize parameter mismatch (is '%zu', in database we have '%zu') taking the later one!\n", pgfuse.block_size, (size_t)res ); PQfinish( conn ); exit( EXIT_FAILURE ); } PQfinish( conn ); /* check sanity of the mount point, remember it's permission and owner in * case we want to inherit them or overrule them */ res = check_mountpoint( &pgfuse.mountpoint ); if( res < 0 ) { /* something is fishy, bail out, check_mountpointed reported errors already */ exit( EXIT_FAILURE ); } memset( &userdata, 0, sizeof( PgFuseData ) ); userdata.conninfo = pgfuse.conninfo; userdata.mountpoint = pgfuse.mountpoint; userdata.verbose = pgfuse.verbose; userdata.read_only = pgfuse.read_only; userdata.noatime = pgfuse.noatime; userdata.multi_threaded = pgfuse.multi_threaded; userdata.block_size = pgfuse.block_size; res = fuse_main( args.argc, args.argv, &pgfuse_oper, &userdata ); closelog( ); exit( res ); }
/* pg_data insert sensor data into postgresql database */ int pg_data ( struct wthio *wth) { int j; /* database variables */ const char *conninfo; PGconn *conn; PGresult *res; int humi, humo, bar, windd, rain; float tempi, tempo, winds; char sqlstr[300]; time_t tpc; struct tm *tmpc; char timebuff[40] = ""; char *rbuf; int conncount; /* make a connection to the database "weather" */ conninfo = "dbname=weather user=postgres"; conn = PQconnectdb(conninfo); /* Check to see that the backend connection was successfully made */ if (PQstatus(conn) != CONNECTION_OK){ fprintf(stderr, "wcmd: cmd7 Connection to database failed: %s", PQerrorMessage(conn)); exit_nicely(conn); } /* reset data logger access command counter */ conncount=0; /* Use simple variable names for the data just retreived */ for ( j = 0; j < wth->wstat.ndats; j++) { tempo = -wth->sens[0].mess[j].value; if(!wth->sens[0].mess[j].sign){ tempo = -tempo; } humo = (int)wth->sens[1].mess[j].value; rain = (int)wth->sens[16].mess[j].value; winds = wth->sens[17].mess[j].value; windd = (int)wth->sens[18].mess[j].value; bar = (int)wth->sens[20].mess[j].value; tempi = -wth->sens[21].mess[j].value; if(!wth->sens[21].mess[j].sign){ tempi = -tempi; } humi = (int)wth->sens[22].mess[j].value; tpc = wth->sens[20].mess[j].time; tmpc = localtime(&tpc); strftime(timebuff, sizeof(timebuff), "%Y-%m-%d %X", tmpc); /* Write data out to the database */ sprintf(sqlstr, "INSERT into weather (" "tempo," "humo," "rain," "winds," "windd," "bar," "tempi," "humi," "t )" " values ( '%3.1f', " "'%3d','%4d','%3.1f','%3d','%3d','%3.1f','%3d','%s')", tempo,humo,rain,winds,windd,bar,tempi,humi,timebuff); printf("wcmd: command 7: sqlstr: %s\n",sqlstr); res = PQexec(conn, sqlstr); if( PQresultStatus( res ) != PGRES_COMMAND_OK ) { rbuf = mkmsg("wcmd: postgresql: %s", PQerrorMessage( conn ) ); return(-1); } PQclear(res); } /* Clean up database connection when exiting */ exit_nicely(conn); return(0); }
int main (int argc, char **argv) { int agentx_subagent = 1; // change this if you want to be a SNMP master agent int background = 0; // change this if you want to run in the background int syslog = 0; // change this if you want to use syslog const char *conninfo; // connection string (in libpq format) /* print log errors to syslog or stderr */ if (syslog) snmp_enable_calllog(); else snmp_enable_stderrlog(); /* we're an agentx subagent? */ if (agentx_subagent) { /* make us a agentx client. */ netsnmp_ds_set_boolean(NETSNMP_DS_APPLICATION_ID, NETSNMP_DS_AGENT_ROLE, 1); } /* run in background, if requested */ if (background && netsnmp_daemonize(1, !syslog)) exit(1); /* initialize tcpip, if necessary */ SOCK_STARTUP; /* initialize the agent library */ init_agent("pgstatmibd"); /* initialize mib code here */ /* * If the user supplies a parameter on the command line, use it as the * conninfo string; otherwise default to setting dbname=postgres and using * environment variables or defaults for all other connection parameters. */ if (argc > 1) conninfo = argv[1]; else conninfo = "dbname=postgres user=postgres"; /* Make a connection to the database */ dbconn = PQconnectdb(conninfo); /* Check to see that the backend connection was successfully made */ if (PQstatus(dbconn) != CONNECTION_OK) { //printf("Connection to database failed: %s", // PQerrorMessage(dbconn)); snmp_log(LOG_ERR, "Connection to database failed: %s", PQerrorMessage(dbconn)); //exit_nicely(conn); } /* mib code */ init_pgstatServer(); init_pgstatDatabaseTable(); init_pgstatBgWriter(); /* initialize vacm/usm access control */ /*if (!agentx_subagent) { init_vacm_vars(); init_usmUser(); }*/ /* pgstatmibd will be used to read pgstatmibd.conf files. */ init_snmp("pgstatmibd"); /* If we're going to be a snmp master agent, initial the ports */ if (!agentx_subagent) init_master_agent(); /* open the port to listen on (defaults to udp:161) */ /* In case we recevie a request to stop (kill -TERM or kill -INT) */ keep_running = 1; signal(SIGTERM, stop_server); signal(SIGINT, stop_server); snmp_log(LOG_INFO, "pgstatmibd is up and running.\n"); /* your main loop here... */ while (keep_running) { /* if you use select(), see snmp_select_info() in snmp_api(3) */ /* --- OR --- */ agent_check_and_process(1); /* 0 == don't block */ } /* close the connection to the database and cleanup */ PQfinish(dbconn); /* at shutdown time */ snmp_shutdown("pgstatmibd"); SOCK_CLEANUP; return 0; }
int main(int argc, char **argv) { const char *conninfo; TestSpec *testspec; int i; /* * If the user supplies a parameter on the command line, use it as the * conninfo string; otherwise default to setting dbname=postgres and using * environment variables or defaults for all other connection parameters. */ if (argc > 1) conninfo = argv[1]; else conninfo = "dbname = postgres"; /* Read the test spec from stdin */ spec_yyparse(); testspec = &parseresult; printf("Parsed test spec with %d sessions\n", testspec->nsessions); /* Establish connections to the database, one for each session */ nconns = testspec->nsessions; conns = calloc(nconns, sizeof(PGconn *)); for (i = 0; i < testspec->nsessions; i++) { PGresult *res; conns[i] = PQconnectdb(conninfo); if (PQstatus(conns[i]) != CONNECTION_OK) { fprintf(stderr, "Connection %d to database failed: %s", i, PQerrorMessage(conns[i])); exit_nicely(); } /* * Suppress NOTIFY messages, which otherwise pop into results at odd * places. */ res = PQexec(conns[i], "SET client_min_messages = warning;"); if (PQresultStatus(res) != PGRES_COMMAND_OK) { fprintf(stderr, "message level setup failed: %s", PQerrorMessage(conns[i])); exit_nicely(); } PQclear(res); } /* Set the session index fields in steps. */ for (i = 0; i < testspec->nsessions; i++) { Session *session = testspec->sessions[i]; int stepindex; for (stepindex = 0; stepindex < session->nsteps; stepindex++) session->steps[stepindex]->session = i; } /* * Run the permutations specified in the spec, or all if none were * explicitly specified. */ if (testspec->permutations) run_named_permutations(testspec); else run_all_permutations(testspec); /* Clean up and exit */ for (i = 0; i < nconns; i++) PQfinish(conns[i]); return 0; }
/*% * create an instance of the driver. Remember, only 1 copy of the driver's * code is ever loaded, the driver has to remember which context it's * operating in. This is done via use of the dbdata argument which is * passed into all query functions. */ static isc_result_t postgres_create(const char *dlzname, unsigned int argc, char *argv[], void *driverarg, void **dbdata) { isc_result_t result; dbinstance_t *dbi = NULL; unsigned int j; #ifdef ISC_PLATFORM_USETHREADS /* if multi-threaded, we need a few extra variables. */ int dbcount; db_list_t *dblist = NULL; int i; char *endp; #endif /* ISC_PLATFORM_USETHREADS */ UNUSED(driverarg); UNUSED(dlzname); /* seed random # generator */ srand( (unsigned)time( NULL ) ); #ifdef ISC_PLATFORM_USETHREADS /* if debugging, let user know we are multithreaded. */ isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_DEBUG(1), "Postgres driver running multithreaded"); #else /* ISC_PLATFORM_USETHREADS */ /* if debugging, let user know we are single threaded. */ isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_DEBUG(1), "Postgres driver running single threaded"); #endif /* ISC_PLATFORM_USETHREADS */ /* verify we have at least 5 arg's passed to the driver */ if (argc < 5) { isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "Postgres driver requires at least " "4 command line args."); return (ISC_R_FAILURE); } /* no more than 8 arg's should be passed to the driver */ if (argc > 8) { isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "Postgres driver cannot accept more than " "7 command line args."); return (ISC_R_FAILURE); } /* multithreaded build can have multiple DB connections */ #ifdef ISC_PLATFORM_USETHREADS /* check how many db connections we should create */ dbcount = strtol(argv[1], &endp, 10); if (*endp != '\0' || dbcount < 0) { isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "Postgres driver database connection count " "must be positive."); return (ISC_R_FAILURE); } /* allocate memory for database connection list */ dblist = isc_mem_get(ns_g_mctx, sizeof(db_list_t)); if (dblist == NULL) return (ISC_R_NOMEMORY); /* initialize DB connection list */ ISC_LIST_INIT(*dblist); /* * create the appropriate number of database instances (DBI) * append each new DBI to the end of the list */ for (i=0; i < dbcount; i++) { #endif /* ISC_PLATFORM_USETHREADS */ /* how many queries were passed in from config file? */ switch(argc) { case 5: result = build_sqldbinstance(ns_g_mctx, NULL, NULL, NULL, argv[3], argv[4], NULL, &dbi); break; case 6: result = build_sqldbinstance(ns_g_mctx, NULL, NULL, argv[5], argv[3], argv[4], NULL, &dbi); break; case 7: result = build_sqldbinstance(ns_g_mctx, argv[6], NULL, argv[5], argv[3], argv[4], NULL, &dbi); break; case 8: result = build_sqldbinstance(ns_g_mctx, argv[6], argv[7], argv[5], argv[3], argv[4], NULL, &dbi); break; default: /* not really needed, should shut up compiler. */ result = ISC_R_FAILURE; } if (result == ISC_R_SUCCESS) { isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_DEBUG(2), "Postgres driver created database " "instance object."); } else { /* unsuccessful?, log err msg and cleanup. */ isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "Postgres driver could not create " "database instance object."); goto cleanup; } #ifdef ISC_PLATFORM_USETHREADS /* when multithreaded, build a list of DBI's */ ISC_LINK_INIT(dbi, link); ISC_LIST_APPEND(*dblist, dbi, link); #endif /* create and set db connection */ dbi->dbconn = PQconnectdb(argv[2]); /* * if db connection cannot be created, log err msg and * cleanup. */ if (dbi->dbconn == NULL) { isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "Postgres driver could not allocate " "memory for database connection"); goto cleanup; } /* if we cannot connect the first time, try 3 more times. */ for (j = 0; PQstatus((PGconn *) dbi->dbconn) != CONNECTION_OK && j < 3; j++) PQreset((PGconn *) dbi->dbconn); #ifdef ISC_PLATFORM_USETHREADS /* * if multi threaded, let user know which connection * failed. user could be attempting to create 10 db * connections and for some reason the db backend only * allows 9 */ if (PQstatus((PGconn *) dbi->dbconn) != CONNECTION_OK) { isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "Postgres driver failed to create " "database connection number %u " "after 4 attempts", i + 1); goto cleanup; } /* set DBI = null for next loop through. */ dbi = NULL; } /* end for loop */ /* set dbdata to the list we created. */ *dbdata = dblist; #else /* ISC_PLATFORM_USETHREADS */ /* if single threaded, just let user know we couldn't connect. */ if (PQstatus((PGconn *) dbi->dbconn) != CONNECTION_OK) { isc_log_write(dns_lctx, DNS_LOGCATEGORY_DATABASE, DNS_LOGMODULE_DLZ, ISC_LOG_ERROR, "Postgres driver failed to create database " "connection after 4 attempts"); goto cleanup; } /* * single threaded build can only use 1 db connection, return * it via dbdata */ *dbdata = dbi; #endif /* ISC_PLATFORM_USETHREADS */ /* hey, we got through all of that ok, return success. */ return(ISC_R_SUCCESS); cleanup: #ifdef ISC_PLATFORM_USETHREADS /* * if multithreaded, we could fail because only 1 connection * couldn't be made. We should cleanup the other successful * connections properly. */ postgres_destroy_dblist(dblist); #else /* ISC_PLATFORM_USETHREADS */ if (dbi != NULL) destroy_sqldbinstance(dbi); #endif /* ISC_PLATFORM_USETHREADS */ return(ISC_R_FAILURE); }
/* * MultiClientConnect synchronously tries to establish a connection. If it * succeeds, it returns the connection id. Otherwise, it reports connection * error and returns INVALID_CONNECTION_ID. * * nodeDatabase and userName can be NULL, in which case values from the * current session are used. */ int32 MultiClientConnect(const char *nodeName, uint32 nodePort, const char *nodeDatabase, const char *userName) { PGconn *connection = NULL; char connInfoString[STRING_BUFFER_SIZE]; ConnStatusType connStatusType = CONNECTION_OK; int32 connectionId = AllocateConnectionId(); char *effectiveDatabaseName = NULL; char *effectiveUserName = NULL; if (XactModificationLevel > XACT_MODIFICATION_NONE) { ereport(ERROR, (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION), errmsg("cannot open new connections after the first modification " "command within a transaction"))); } if (connectionId == INVALID_CONNECTION_ID) { ereport(WARNING, (errmsg("could not allocate connection in connection pool"))); return connectionId; } if (nodeDatabase == NULL) { effectiveDatabaseName = get_database_name(MyDatabaseId); } else { effectiveDatabaseName = pstrdup(nodeDatabase); } if (userName == NULL) { effectiveUserName = CurrentUserName(); } else { effectiveUserName = pstrdup(userName); } /* * FIXME: This code is bad on several levels. It completely forgoes any * escaping, it misses setting a number of parameters, it works with a * limited string size without erroring when it's too long. We shouldn't * even build a query string this way, there's PQconnectdbParams()! */ /* transcribe connection paremeters to string */ snprintf(connInfoString, STRING_BUFFER_SIZE, CONN_INFO_TEMPLATE, nodeName, nodePort, effectiveDatabaseName, effectiveUserName, CLIENT_CONNECT_TIMEOUT); /* establish synchronous connection to worker node */ connection = PQconnectdb(connInfoString); connStatusType = PQstatus(connection); if (connStatusType == CONNECTION_OK) { ClientConnectionArray[connectionId] = connection; } else { WarnRemoteError(connection, NULL); PQfinish(connection); connectionId = INVALID_CONNECTION_ID; } pfree(effectiveDatabaseName); pfree(effectiveUserName); return connectionId; }
int main(int argc, char **argv) { const char *conninfo; TestSpec *testspec; int i; PGresult *res; PQExpBufferData wait_query; int opt; while ((opt = getopt(argc, argv, "n")) != -1) { switch (opt) { case 'n': dry_run = true; break; default: fprintf(stderr, "Usage: isolationtester [-n] [CONNINFO]\n"); return EXIT_FAILURE; } } /* * If the user supplies a non-option parameter on the command line, use it * as the conninfo string; otherwise default to setting dbname=postgres * and using environment variables or defaults for all other connection * parameters. */ if (argc > optind) conninfo = argv[optind]; else conninfo = "dbname = postgres"; /* Read the test spec from stdin */ spec_yyparse(); testspec = &parseresult; /* * In dry-run mode, just print the permutations that would be run, and * exit. */ if (dry_run) { run_testspec(testspec); return 0; } printf("Parsed test spec with %d sessions\n", testspec->nsessions); /* * Establish connections to the database, one for each session and an * extra for lock wait detection and global work. */ nconns = 1 + testspec->nsessions; conns = calloc(nconns, sizeof(PGconn *)); backend_pids = calloc(nconns, sizeof(*backend_pids)); for (i = 0; i < nconns; i++) { conns[i] = PQconnectdb(conninfo); if (PQstatus(conns[i]) != CONNECTION_OK) { fprintf(stderr, "Connection %d to database failed: %s", i, PQerrorMessage(conns[i])); exit_nicely(); } /* * Suppress NOTIFY messages, which otherwise pop into results at odd * places. */ res = PQexec(conns[i], "SET client_min_messages = warning;"); if (PQresultStatus(res) != PGRES_COMMAND_OK) { fprintf(stderr, "message level setup failed: %s", PQerrorMessage(conns[i])); exit_nicely(); } PQclear(res); /* Get the backend pid for lock wait checking. */ res = PQexec(conns[i], "SELECT pg_backend_pid()"); if (PQresultStatus(res) == PGRES_TUPLES_OK) { if (PQntuples(res) == 1 && PQnfields(res) == 1) backend_pids[i] = strdup(PQgetvalue(res, 0, 0)); else { fprintf(stderr, "backend pid query returned %d rows and %d columns, expected 1 row and 1 column", PQntuples(res), PQnfields(res)); exit_nicely(); } } else { fprintf(stderr, "backend pid query failed: %s", PQerrorMessage(conns[i])); exit_nicely(); } PQclear(res); } /* Set the session index fields in steps. */ for (i = 0; i < testspec->nsessions; i++) { Session *session = testspec->sessions[i]; int stepindex; for (stepindex = 0; stepindex < session->nsteps; stepindex++) session->steps[stepindex]->session = i; } /* * Build the query we'll use to detect lock contention among sessions in * the test specification. Most of the time, we could get away with * simply checking whether a session is waiting for *any* lock: we don't * exactly expect concurrent use of test tables. However, autovacuum will * occasionally take AccessExclusiveLock to truncate a table, and we must * ignore that transient wait. */ initPQExpBuffer(&wait_query); appendPQExpBufferStr(&wait_query, "SELECT 1 FROM pg_locks holder, pg_locks waiter " "WHERE NOT waiter.granted AND waiter.pid = $1 " "AND holder.granted " "AND holder.pid <> $1 AND holder.pid IN ("); /* The spec syntax requires at least one session; assume that here. */ appendPQExpBuffer(&wait_query, "%s", backend_pids[1]); for (i = 2; i < nconns; i++) appendPQExpBuffer(&wait_query, ", %s", backend_pids[i]); appendPQExpBufferStr(&wait_query, ") " "AND holder.mode = ANY (CASE waiter.mode " "WHEN 'AccessShareLock' THEN ARRAY[" "'AccessExclusiveLock'] " "WHEN 'RowShareLock' THEN ARRAY[" "'ExclusiveLock'," "'AccessExclusiveLock'] " "WHEN 'RowExclusiveLock' THEN ARRAY[" "'ShareLock'," "'ShareRowExclusiveLock'," "'ExclusiveLock'," "'AccessExclusiveLock'] " "WHEN 'ShareUpdateExclusiveLock' THEN ARRAY[" "'ShareUpdateExclusiveLock'," "'ShareLock'," "'ShareRowExclusiveLock'," "'ExclusiveLock'," "'AccessExclusiveLock'] " "WHEN 'ShareLock' THEN ARRAY[" "'RowExclusiveLock'," "'ShareUpdateExclusiveLock'," "'ShareRowExclusiveLock'," "'ExclusiveLock'," "'AccessExclusiveLock'] " "WHEN 'ShareRowExclusiveLock' THEN ARRAY[" "'RowExclusiveLock'," "'ShareUpdateExclusiveLock'," "'ShareLock'," "'ShareRowExclusiveLock'," "'ExclusiveLock'," "'AccessExclusiveLock'] " "WHEN 'ExclusiveLock' THEN ARRAY[" "'RowShareLock'," "'RowExclusiveLock'," "'ShareUpdateExclusiveLock'," "'ShareLock'," "'ShareRowExclusiveLock'," "'ExclusiveLock'," "'AccessExclusiveLock'] " "WHEN 'AccessExclusiveLock' THEN ARRAY[" "'AccessShareLock'," "'RowShareLock'," "'RowExclusiveLock'," "'ShareUpdateExclusiveLock'," "'ShareLock'," "'ShareRowExclusiveLock'," "'ExclusiveLock'," "'AccessExclusiveLock'] END) " "AND holder.locktype IS NOT DISTINCT FROM waiter.locktype " "AND holder.database IS NOT DISTINCT FROM waiter.database " "AND holder.relation IS NOT DISTINCT FROM waiter.relation " "AND holder.page IS NOT DISTINCT FROM waiter.page " "AND holder.tuple IS NOT DISTINCT FROM waiter.tuple " "AND holder.virtualxid IS NOT DISTINCT FROM waiter.virtualxid " "AND holder.transactionid IS NOT DISTINCT FROM waiter.transactionid " "AND holder.classid IS NOT DISTINCT FROM waiter.classid " "AND holder.objid IS NOT DISTINCT FROM waiter.objid " "AND holder.objsubid IS NOT DISTINCT FROM waiter.objsubid "); res = PQprepare(conns[0], PREP_WAITING, wait_query.data, 0, NULL); if (PQresultStatus(res) != PGRES_COMMAND_OK) { fprintf(stderr, "prepare of lock wait query failed: %s", PQerrorMessage(conns[0])); exit_nicely(); } PQclear(res); termPQExpBuffer(&wait_query); /* * Run the permutations specified in the spec, or all if none were * explicitly specified. */ run_testspec(testspec); /* Clean up and exit */ for (i = 0; i < nconns; i++) PQfinish(conns[i]); fflush(stderr); fflush(stdout); return 0; }
return 0; } //-----------------------------------------------------// CONCEPT_DLL_API ON_DESTROY_CONTEXT MANAGEMENT_PARAMETERS { #ifdef _WIN32 if (!HANDLER) WSACleanup(); #endif return 0; } //-----------------------------------------------------// CONCEPT_FUNCTION_IMPL(PQConnect, 1) T_STRING(PQConnect, 0) RETURN_NUMBER((SYS_INT)PQconnectdb(PARAM(0))) END_IMPL //-----------------------------------------------------// CONCEPT_FUNCTION_IMPL(PQLogin, 7) T_STRING(PQLogin, 0) // host T_STRING(PQLogin, 1) // port T_STRING(PQLogin, 2) // options T_STRING(PQLogin, 3) // tty T_STRING(PQLogin, 4) // db T_STRING(PQLogin, 5) // user T_STRING(PQLogin, 6) // password char *host = PARAM_LEN(0) ? PARAM(0) : 0; char *port = PARAM_LEN(1) ? PARAM(1) : 0; char *options = PARAM_LEN(2) ? PARAM(2) : 0; char *tty = PARAM_LEN(3) ? PARAM(3) : 0;