// Recursive Function void _ftpEntry::removeFolderChildren( size_t folderID ) { Connection *sqlConnect = dbConnect(); bool isDone = false; Query serverQuery = sqlConnect->query(); StoreQueryResult serverResults; StoreQueryResult::iterator storeQueryIT; size_t ID; // Find all folders that parent us serverQuery << "select * from ServerFolders where parentID = " << quote << folderID; serverQuery.execute(); // for(storeQueryIT = serverResults.begin(); storeQueryIT != serverResults.end(); storeQueryIT++ ) { // Remove all children from this parent ID = (size_t) (*storeQueryIT)["folderID"]; removeFolderChildren( ID ); // Now remove the parent serverQuery.str(""); serverQuery << "delete from ServerFolders where folderID = " << quote << ID; serverQuery.execute(); } delete sqlConnect; }
void IRCBot::actionMIA( ircChannel pChannel, irc_reply_data *hostd, string pParameters ) { size_t count = 1; size_t lastOnline; bool active, showAll = false; if( pParameters == "all" ) showAll = true; StoreQueryResult members = _db->membersReadSeen( true ); StoreQueryResult::iterator memberIT; Row member; for(memberIT = members.begin(); memberIT != members.end(); memberIT++ ) { stringstream irc; member = *memberIT; active = (bool) member["active"]; if( !showAll && !active ) continue; if( _smokingman->thepipeGet()->userOnline( ((size_t) member["memberID"] ) ) != userOFFLINE ) continue; lastOnline = (size_t) member["lastOnline"]; irc << count << ". " << ((string) member["nameUser"]) << " : " << timeCalc( time(0) - lastOnline ); speak( "LastOn", irc, pChannel ); ++count; } }
/** @brief Return the list of all orders of a given user @param[in] pp An instance of User @return A vector of Order */ vector<Order *> & Order::ordersForUser(User & pp) { vector<Order *> *orders = new vector<Order *>; // get an instance of the database Database& db = Database::instance(); try { // ask Database for a valid connection to mySQL Connection *conn = db.getConnection(); // obtain an instance of mysqlpp::Query and init it Query q = conn->query(); q << "SELECT * FROM orders WHERE uid = " << pp.uniqueID() << " ORDER BY oid, date"; StoreQueryResult res = q.store(); if (!res.empty()) { orders->reserve(res.num_rows()); StoreQueryResult::const_iterator it; for (it = res.begin(); it != res.end(); it++){ Row row = *it; orders->push_back(new Order(row)); } } } catch (std::exception &e) { cerr << "an error occurred: " << e.what() << endl; } return *orders; }
void createParmFiles2(string mask, int popid, int popno, int totaltrait, int totalmarker, string db, string name_str) { int distinctpop = -1; try { ifstream sqlparmfile("../exe/SQLparms.txt"); string servername, dbname, username, password; getline(sqlparmfile,servername); getline(sqlparmfile,dbname); getline(sqlparmfile,username); getline(sqlparmfile,password); Connection conn( dbname.c_str(), servername.c_str(), username.c_str(), password.c_str()); Query query = conn.query(); string pp = "pop"+toStrings(popno); //SELECT COUNT(DISTINCT pop1 ) as number FROM structure where popstructid = 1; query << "SELECT COUNT(DISTINCT "<<pp<<" ) as number FROM structure WHERE popstructid = " << popid; StoreQueryResult ares = query.store(); if(!ares) { cerr << query.error() << endl; return; } else { for(size_t i = 0; i < ares.num_rows(); i ++) { distinctpop = ares[i]["number"] ; } } } catch(BadQuery er) { cerr << "Error: " << er.what() << endl; return; } catch(const BadConversion& er) { cerr << "Conversion error: " << er.what() << endl; return; } catch(const Exception& er) { cerr << "Error: " << er.what() << endl; return; } ofstream myfile; myfile.open("parms2.txt"); myfile <<mask<<" "<<popid<<" "<<popno<<" "<<totaltrait<<" "<<totalmarker<<" "<<name_str<<" "<<db<<" "<<distinctpop<< " " << team << endl; myfile<<"vanilla"<<endl; myfile.close(); }
/** @brief Returns the list of products (and requested quantity) of an order @return A std::map where the key is product ID and the value the quantity */ map<int, int>& Order::products() { map<int, int> *prd = NULL; // get an instance of the database Database& db = Database::instance(); try { // ask Database for a valid connection to mySQL Connection *conn = db.getConnection(); // obtain an instance of mysqlpp::Query and init it Query q = conn->query(); q << "SELECT * FROM order_details WHERE oid = " << valueForKey(KEY_ORD_OID); StoreQueryResult res = q.store(); if (!res.empty()) { prd = new map<int, int>; StoreQueryResult::const_iterator it; for (it = res.begin(); it != res.end(); it++){ Row row = *it; int key = atoi(row["pid"]); int qty = atoi(row["qty"]); (*prd)[key] = qty; } } } catch (std::exception &e) { cerr << "an error occurred: " << e.what() << endl; } return *prd; }
int run() { c.connect("crowdify", "localhost", "root", "root"); create_test_data(); stringstream qs; qs.clear(); qs.str(string()); qs << "SELECT * FROM clients;"; Query q = c.query(qs.str()); StoreQueryResult r = q.store(); StoreQueryResult::iterator it; struct sockaddr_in sin; char *username, *password; for (it = r.begin(); it != r.end(); it++) { Row r = *it; run_client(r[0]); } print_query("select * from blocks;"); print_query("select * from files;"); print_query("select * from clients;"); print_query("select * from filestoblocks;"); print_query("select * from directoriestofiles;"); print_query("select * from clientstodirectories;"); return 0; }
int _ftpEntry::checkEntryDBFolder( ) { Query serverQuery = _sqlConnection->query(); StoreQueryResult serverResults; serverQuery << "select * from ServerFolders where serverID = " << quote << _serverID; serverQuery << " AND parentID = " << quote << _parentID; serverQuery << " AND name = " << quote << name; // Do the query serverResults = serverQuery.store(); // Folder not found? if( serverResults.size() == 0 ) return 0; // Root dir?, Number of entrys changed?. time/date diff?, force rescan? if((timeModified == "" && name == "/") || serverResults[0]["entrys"] != entrys || serverResults[0]["modTimeDate"] != timeModified || (int) serverResults[0]["rescanForce"] == 1 ) return serverResults[0]["folderID"]; // Return the folderID return -1; } // checkEntryDBFolder
int writeStructureFile(int popid, int popnum) { int noidis = 0; int tts=-1; try { ifstream sqlparmfile("../exe/SQLparms.txt"); string servername, dbname, username, password; getline(sqlparmfile,servername); getline(sqlparmfile,dbname); getline(sqlparmfile,username); getline(sqlparmfile,password); Connection conn( dbname.c_str(), servername.c_str(), username.c_str(), password.c_str()); Query query = conn.query(); string pp = "pop"+toStrings(popnum); query << "SELECT "<<pp<<" FROM structure WHERE popstructid = " << popid << " ORDER BY sampleid"; StoreQueryResult ares = query.store(); if(!ares) { cerr << query.error() << endl; return -1; } else { ofstream myfile; string fname = "data.test.Z"; myfile.open(fname.c_str()); tts = ares.num_rows(); for(size_t i = 0; i < ares.num_rows(); i ++) { myfile << ares[i][pp.c_str()] << "\n"; } myfile.close(); } } catch(BadQuery er) { cerr << "Error: " << er.what() << endl; return -1; } catch(const BadConversion& er) { cerr << "Conversion error: " << er.what() << endl; return -1; } catch(const Exception& er) { cerr << "Error: " << er.what() << endl; return -1; } return tts; }
Row Mysql::getRow(std::string sql){ Query query = _con.query(sql); Row row; StoreQueryResult res = query.store(); if (res) { row = *res.begin(); } return row; }
static void print_header(IntVectorType& widths, StoreQueryResult& res) { cout << " |" << setfill(' '); for (size_t i = 0; i < res.field_names()->size(); i++) { cout << " " << setw(widths.at(i)) << res.field_name(int(i)) << " |"; } cout << endl; }
int CScheduler::getProcessNum() { Query select = conn->query(); select << "SELECT ProcessQuota FROM crawler WHERE name=" <<quote<<crawler; StoreQueryResult res = select.store(); if (!res || res.size() == 0) return -1; return res[0]["ProcessQuota"]; }
bool IRCBot::testPrepare() { StoreQueryResult ircBots = _db->ircBotReadAll(); StoreQueryResult::iterator ircIT; stringstream ircs; size_t sleepTime = 500, count = 0; Row irc, ircBot; _ircMii *botMii; if(ircBots.empty()) return false; // loop through and start each server test for( ircIT = ircBots.begin(); ircIT != ircBots.end(); ++ircIT, ++count ) { ircBot = *ircIT; irc = _db->ircRead( (size_t) ircBot["ircID"] ); if(irc.empty()) return false; botMii = _Miis->ircMiiLoad( (string) irc["nick"] ); if(botMii) { botMii->ircBotRowLoad(); botMii->silentSet(); botTestAdd( botMii, 0 ); } else { stringstream ircs; ircs << "Bot " << ( (string) irc["nick"] ) << " is not online."; speak("Test", ircs, _testChannel); } Sleep(sleepTime); // Every 4, sleep triple time if(count == 4) { Sleep(sleepTime*2); count=0; } } // Nothing to do? if(_testMiis.empty()) { stringstream ircs; ircs << "No bots to test."; speak("Test", ircs, _testChannel); return false; } return true; }
int print_query(const char *q) { Query q2 = c.query(q); StoreQueryResult r = q2.store(); StoreQueryResult::iterator it; for (it = r.begin(); it != r.end(); it++) { Row r = *it; cout << " " << r[0] << endl; } cout << endl; return 0; }
void _ftpEntry::checkDBFolders() { bool isDone = false; Query serverQuery = _sqlConnection->query(); StoreQueryResult serverResults; StoreQueryResult::iterator storeQueryIT; vector<_ftpEntry*>::iterator entryIT; // Nothing to do here... if( directorys.empty() ) return; // Get a list of all the directorys that we parent serverQuery << "select * from ServerFolders where serverID = " << quote << _serverID; serverQuery << " AND parentID = " << quote << _folderID; // Do the query serverResults = serverQuery.store(); // None? if( !serverResults.size() ) return; // We now have to check each DB result, against the results in directorys vector for(storeQueryIT = serverResults.begin(); storeQueryIT != serverResults.end(); storeQueryIT++ , isDone = false) { for( entryIT = directorys.begin(); entryIT != directorys.end(); entryIT++) { // Does this directory still exist? if((*entryIT)->getName() == (string) (*storeQueryIT)["name"]) { isDone = true; // Yes it exists break; } // parentID check } // entryIT // Deleted? if(!isDone) { // Yes, remove the entry from the DB removeFolderChildren( (size_t) (*storeQueryIT)["folderID"] ); serverQuery.str(""); serverQuery << "delete from ServerFolders where folderID = " << quote << (*storeQueryIT)["folderID"]; // bye bye :) serverQuery.execute(); } // !isDone } // storeQueryIT } // checkDBFolders
int db::get_station(std::string mac) { StoreQueryResult res = q_get_station.store(mac.c_str(), ""); // found station if (res.num_rows() > 0) { mysqlpp::StoreQueryResult::const_iterator it; mysqlpp::Row row = *(res.begin()); return row[0]; } cerr << mac << endl; // new station to db SimpleResult r_exp = q_insert_station.execute("0", "0", mac.c_str()); return r_exp.insert_id(); }
int _ftpEntry::checkEntryDBFile( ) { Query serverQuery = _sqlConnection->query(); serverQuery << "select * from ServerFiles where folderID = " << quote << _folderID; serverQuery << " AND name = " << quote << name; // Fire Scotty! StoreQueryResult serverResults = serverQuery.store(); // Folder not found? if( serverResults.size() == 0 ) return 0; return serverResults[0]["folderID"]; } // checkEntryDBFile
int gettsid(string mask) { try { ifstream sqlparmfile("../exe/SQLparms.txt"); string servername, dbname, username, password; getline(sqlparmfile,servername); getline(sqlparmfile,dbname); getline(sqlparmfile,username); getline(sqlparmfile,password); Connection conn( dbname.c_str(), servername.c_str(), username.c_str(), password.c_str()); //cout << conn.error() << endl; Query query = conn.query(); query << "SELECT get_ts_id('" << mask << "') as id"; StoreQueryResult ares = query.store(); if(!ares) { cerr << query.error() << endl; return -1; } int id; for(size_t i = 0; i < ares.num_rows(); i++) { id = ares[i]["id"]; return id; } } catch(BadQuery er) { cerr<< "Error: " <<er.what() <<endl; return -1; } catch(const BadConversion& er) { cerr <<"Conversion error: " << er.what() << endl; return -1; } catch (const Exception& er) { cerr << "Error: " <<er.what() << endl; return -1; } }
static bool handle_name_exists(const StoreQueryResult& result) { size_t rowCount = result.num_rows(); assert(rowCount < 2); return rowCount == 1; }
int DocDb::getSourceIdFromName(int packageId,string name,int parameter_count) { CHECK_CONNECTED(m_wrapper->isConnected); try { string idAsString; StoreQueryResult res; res = m_wrapper->getSourceIdQuery->store(packageId, name, parameter_count); if (res.empty()) return -1; idAsString = string(res[0][0]); return std::stoi(idAsString); } catch (const Exception &ex) { printException(ex); return -1; } }
int DocDb::getGlobalSourceIdFromName(string name) { CHECK_CONNECTED(m_wrapper->isConnected); try { string idAsString; StoreQueryResult res; res = m_wrapper->getGlobalSourceIdQuery->store(name); if (res.empty()) return -1; idAsString = string(res[0][0]); return std::stoi(idAsString); } catch (const Exception &ex) { printException(ex); return -1; } }
// Find users with <ip> vector<size_t> ipFind( database *database, string IP_ ) { socketTCP socket("0.0.0.0"); string domain, ip, ipTmp; vector<size_t> members; size_t pos; // Resolve domain/ip ip = socket.hostnameLookup( IP_ ); domain = socket.ipLookup( IP_ ); if(!ip.size()) { // Remove after * size_t pos = IP_.find("*"); if(pos != string::npos) { IP_ = IP_.substr(0, pos); } ip = IP_; } // Get a list of similar ips StoreQueryResult IPs = database->ipFind( ip ); StoreQueryResult::iterator ipIT; Row IPRow; if( !IPs.size() ) IPs = database->ipFind( domain ); if(IPs.size() ) { // Add each matching member to the vector for( ipIT = IPs.begin(); ipIT != IPs.end(); ipIT++ ) { IPRow = *ipIT; members.push_back( (size_t) IPRow["memberID"] ); } return members; } // Now get all IPs, resolve them all and try and match IPs = database->ipsRead(0); for( ipIT = IPs.begin(); ipIT != IPs.end(); ipIT++ ) { IPRow = *ipIT; ipTmp = (string) IPRow["ip"]; if( (pos = ipTmp.find("*")) != string::npos) { ipTmp = ipTmp.substr(0, pos-1); if( ip.find( ipTmp) != string::npos ) members.push_back( (size_t) IPRow["memberID"] ); } ipTmp = socket.hostnameLookup( ipTmp ); if( ip == ipTmp ) members.push_back( (size_t) IPRow["memberID"] ); } return members; }
int main() { try { Connection conn(false); conn.connect("map", "localhost", "root", "dtbs"); Query query = conn.query(); /* To insert stuff with escaping */ /* query << "INSERT INTO map " << "VALUES (" << "'', " << // This is left empty because the column is AUTO_INCREMENT "\"" << escape << "some_var_that_contains_some_value" << "\"" << ");"; query.execute();*/ /* That's it for INSERT */ /* Now SELECT */ query << "SELECT * FROM Station"; StoreQueryResult ares = query.store(); for (size_t i = 0; i < ares.num_rows(); i++) cout << "Name: " << ares[i]["id"] << " - Address: " << ares[i]["name"] << endl; /* Let's get a count of something */ query << "SELECT COUNT(*) FROM Station"; StoreQueryResult bres = query.store(); cout << "Total rows: " << bres[0]["id"]; } catch (BadQuery er) { // handle any connection or // query errors that may come up cerr << "Error: " << er.what() << endl; return -1; } catch (const BadConversion& er) { // Handle bad conversions cerr << "Conversion error: " << er.what() << endl << "\tretrieved data size: " << er.retrieved << ", actual size: " << er.actual_size << endl; return -1; } catch (const Exception& er) { // Catch-all for any other MySQL++ exceptions cerr << "Error: " << er.what() << endl; return -1; } return (EXIT_SUCCESS); }
int getRunning(int id) { int running; Connection con(use_exceptions); try{ ostringstream strbuf; Query query = con.query(); con.connect(DATABASE, HOST, USER, PASSWORD); strbuf << "select running from tasks WHERE id=" << id; query << strbuf.str(); StoreQueryResult res = query.store(); if (res) { mysqlpp::Row row; row = res.at(0); running = row["running"]; } } catch (const BadQuery& er) { // Handle any query errors cerr << "getRunning - Query error: " << er.what() << endl; return -1; } catch (const BadConversion& er) { // Handle bad conversions cerr << "getStarted - Conversion error: " << er.what() << endl << "\tretrieved data size: " << er.retrieved << ", actual size: " << er.actual_size << endl; return -1; } catch (const Exception& er) { // Catch-all for any other MySQL++ exceptions cerr << "getRunning - Error: " << er.what() << endl; return -1; } return running; }
bool MasterServer::get_fileinfo(const string &fid, FileInfo &fileinfo) { //查找cache map<string, FileInfo>::iterator it = m_fileinfo_cache.find(fid); if(it != m_fileinfo_cache.end()) { fileinfo = it->second; return true; } //查找数据库 if(m_db_connection == NULL) return false; char sql_str[1024]; snprintf(sql_str, 1024, "select fid,name,size,chunkid,chunkip,chunkport,findex,foffset from SFS.fileinfo_%s where fid='%s'" ,fid.substr(0,2).c_str(), fid.c_str()); Query query = m_db_connection->query(sql_str); StoreQueryResult res = query.store(); if (!res || res.empty()) return false; size_t i; for(i=0; i<res.num_rows(); ++i) { ChunkPath chunk_path; fileinfo.fid = res[i]["fid"].c_str(); fileinfo.name = res[i]["name"].c_str(); fileinfo.size = atoi(res[i]["size"].c_str()); chunk_path.id = res[i]["chunkid"].c_str(); chunk_path.ip = res[i]["chunkip"].c_str(); chunk_path.port = atoi(res[i]["chunkport"].c_str()); chunk_path.index = atoi(res[i]["findex"].c_str()); chunk_path.offset = atoi(res[i]["foffset"].c_str()); fileinfo.add_chunkpath(chunk_path); } //添加到cache m_fileinfo_cache.insert(std::make_pair(fileinfo.fid, fileinfo)); return true; }
void IRCBot::actionTotalTime( ircChannel pChannel, irc_reply_data *hostd, string pParameters ) { size_t count = 1; time_t timeOnline; bool active, showAll = false; if( pParameters == "all" ) showAll = true; StoreQueryResult members = _db->memberTimeOnGet( false ); StoreQueryResult::iterator memberIT; Row member; for(memberIT = members.begin(); memberIT != members.end(); memberIT++ ) { member = *memberIT; active = (bool) member["active"]; if( !showAll && !active ) continue; timeOnline = (time_t) member["timeOnline"]; /* if( _smokingman->thepipeGet()->userOnline( ((size_t) member["memberID"] ) ) != userOFFLINE ) { client *user = _smokingman->thepipeGet()->userClient(((size_t) member["memberID"] ) ); time_t addTime = time(0) - user->connectedTimeGet(); timeOnline += addTime; }*/ if(timeOnline > 0) { stringstream irc; irc << count << ". " << ((string) member["nameUser"]) << " : " << timeCalc( timeOnline ); speak( "TotalTime", irc, pChannel ); ++count; } } }
/** @brief Fetch a category by specifing its ID @param[in] aCid Category ID to be fetched @return An instance of category */ Category *Category::categoryByID(int aCid) { Category *cat = NULL; // get an instance of the database Database &db = Database::instance(); // obtain an instance of mysqlpp::Query and init it Query q = db.getConnection()->query(); q << SQL_CATEGORY_BYID << aCid; StoreQueryResult res = q.store(); if (!res.empty()) { cat = new Category(); cat->setIntForKey(KEY_CAT_CID, aCid); cat->setValueForKey(KEY_CAT_NAME, (string) res[0][KEY_CAT_NAME]); return cat; } return NULL; }
/** @brief Returns a product with given ID @param[in] aPid The requested product ID @return A pointer to the requested Product, NULL if not found */ Product * Product::productByID(int aPid) { // get an instance of the database Database &db = Database::instance(); // ask Database for a valid connection to mySQL Connection *conn = db.getConnection(); // obtain an instance of mysqlpp::Query and init it Query q = conn->query(); q << SQL_PRODUCT_PROXY << aPid; StoreQueryResult res = q.store(); if (!res.empty()) { StoreQueryResult::const_iterator it = res.begin(); Row row = *it; return new Product(row); } return NULL; }
bool ipValidate( database *database, string IP, size_t memberID ) { socketTCP socket("0.0.0.0"); string domain; // Resolve domain/ip IP = socket.hostnameLookup(IP); // Current Connect Client IP domain = socket.ipLookup( IP ); // Resolve the clients IP // Get any IP/Host matches for this member's ID / Connected IP/Domain StoreQueryResult IPs = database->ipsRead( memberID, IP ); StoreQueryResult Domains = database->ipsRead( memberID, domain ); // Did we find any? if(!IPs.empty()) return true; if(!Domains.empty()) return true; if(!IP.size()) return false; // Nope, so we need to get all IPs/Domains for this user from the database // Remove all wildcards and check the domain for matches Domains = database->ipsRead( memberID ); StoreQueryResult::iterator addressIT; string testName; string resolvedIP; string::iterator sIT; Row row; for( addressIT = Domains.begin(); addressIT != Domains.end(); addressIT++ ) { row = *addressIT; // Get an address to test testName = (string) row["ip"]; // Resolve the name from the database, and try it against the connected IP resolvedIP = socket.hostnameLookup( testName ); if( ! IP.compare( resolvedIP ) ) return true; // Remove wildcards sIT = remove( testName.begin(), testName.end(), '*' ); if(sIT != testName.end()) testName.erase(sIT); // Check against the connected IP if( IP.find( testName ) != string::npos ) return true; // Check against the connected domain name if( domain.find( testName ) != string::npos ) return true; } return false; }
/** @brief Returns the list of available categories. @return Vector of pointer to Category */ vector<Category *> &Category::catalog() { // get an instance of the database Database& db = Database::instance(); vector<Category *> *catalog = NULL; try { // ask Database for a valid connection to mySQL Connection *conn = db.getConnection(); // obtain an instance of mysqlpp::Query and init it Query q = conn->query(SQL_CATEGORY_CAT); StoreQueryResult res = q.store(); if (!res.empty()) { catalog = new vector<Category *>; catalog->reserve(res.num_rows()); for (size_t i = 0; i < res.num_rows(); ++i) { Category *c = new Category(); c->setValueForKey(KEY_CAT_CID, (string) res[i][KEY_CAT_CID]); c->setValueForKey(KEY_CAT_NAME, (string) res[i][KEY_CAT_NAME]); catalog->push_back(c); } } } catch (const mysqlpp::BadQuery& e) { // Something went wrong with the SQL query. cerr << "Query failed: " << e.what() << endl; } catch (const Exception& er) { cerr << "Error: " << er.what() << endl; } return *catalog; }
void IRCBot::actionIP ( ircChannel pChannel, irc_reply_data *hostd, string pParameters ) { stringstream str; vector<size_t> members = ipFind( _db, pParameters ); vector<size_t>::iterator memberIT; Row member; string memberName; // // for( memberIT = members.begin(); memberIT != members.end(); memberIT++ ) { StoreQueryResult Members = _db->membersRead( *memberIT ); if(Members.size()) { member = Members[0]; memberName = (string) member["nameUser"]; str << "[" << memberName << "] Matches " << pParameters; _irc->talkMain( str.str(), pChannel); str.str(""); } } }