void MessageRouter::_loadMessageProcessMap(void) { MessageRoute route; // We need to populate our message map. // setup our databinding parameters. DataBinding* binding = mDatabase->createDataBinding(2); binding->addField(DFT_uint32, offsetof(MessageRoute, mMessageId), 4); binding->addField(DFT_uint32, offsetof(MessageRoute, mProcessId), 4); // Execute our statement DatabaseResult* result = mDatabase->executeSynchSql("SELECT messageId, processId FROM %s.config_message_routes;",mDatabase->galaxy()); uint32 count = static_cast<uint32>(result->getRowCount()); // Retrieve our routes and add them to the map. for(uint32 i = 0; i < count; i++) { result->getNextRow(binding, &route); mMessageRouteMap.insert(std::make_pair(route.mMessageId, route.mProcessId)); } // Delete our DB objects. mDatabase->destroyDataBinding(binding); mDatabase->destroyResult(result); }
//====================================================================================================================== DatabaseResult* DatabaseImplementationMySql::ExecuteSql(int8* sql,bool procedure) { DatabaseResult* newResult = new(ResultPool::ordered_malloc()) DatabaseResult(procedure); newResult->setDatabaseImplementation(this); // Execute the statement uint32 len = (uint32)strlen(sql); mysql_real_query(mConnection, sql, len); if(mysql_errno(mConnection) != 0) { gLogger->log(LogManager::EMERGENCY, "DatabaseError: %s", mysql_error(mConnection)); } mResultSet = mysql_store_result(mConnection); newResult->setConnectionReference((void*)mConnection); newResult->setResultSetReference((void*)mResultSet); if (mResultSet) { newResult->setRowCount(mResultSet->row_count); } return newResult; }
std::vector<Device *> ControllerDatabaseFactory::fetchDevices( const std::size_t id ) const { std::vector<Device *> devices; DatabaseStatement * statement; DatabaseResult * result; DatabaseResultRow * row; std::string query; std::size_t deviceId; query = "SELECT id " "FROM devices " "WHERE controller_id = "; query = query + std::to_string(id); statement = getDbConnection()->createStatement(query); if( statement != nullptr ) { result = statement->execute(); if( result != nullptr ) { while( result->hasNext() ) { row = result->next(); deviceId = static_cast<std::size_t>( atol(row->getColumn(0).c_str())); devices.push_back(mDeviceContainer->get(deviceId)); delete row; } delete result; } delete statement; } return ( devices ); }
int Database::coutTables() throw() { if(dbStatus != SQLITE_OK) throw DatabaseNotOpenException() << DebugInfo(TRACE(), DebugInfo::Error); DatabaseResult res; int tableCount = -1; try { res = exec("SELECT COUNT(name) FROM (" "SELECT name FROM sqlite_master " "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' " "UNION ALL " "SELECT name FROM sqlite_temp_master " "WHERE type IN ('table','view') )"); tableCount = res.getRowData().at(0).getColumnData().at(0).getIntData(); } catch (...) { throw; } return tableCount; }
void StorageManager::restoreThoughts(LocatedEntity * ent) { Database * db = Database::instance(); const DatabaseResult res = db->selectThoughts(ent->getId()); Atlas::Message::ListType thoughts_data; DatabaseResult::const_iterator I = res.begin(); DatabaseResult::const_iterator Iend = res.end(); for (; I != Iend; ++I) { const std::string thought = I.column("thought"); if (thought.empty()) { log(ERROR, compose("No thought column in property row for %1", ent->getId())); continue; } MapType thought_data; db->decodeMessage(thought, thought_data); thoughts_data.push_back(thought_data); } if (!thoughts_data.empty()) { OpVector opRes; Atlas::Objects::Operation::Think thoughtOp; Atlas::Objects::Operation::Set setOp; setOp->setArgsAsList(thoughts_data); //Make the thought come from the entity itself thoughtOp->setArgs1(setOp); thoughtOp->setTo(ent->getId()); thoughtOp->setFrom(ent->getId()); ent->sendWorld(thoughtOp); } }
std::shared_ptr<std::string> fCache::get(const std::string &key) { std::stringstream sql; DatabaseResult result; sql << "SELECT data FROM " << TABLE_NAME << " WHERE id='" << key << "';"; _db.executeSQL(sql.str().c_str(), result); if(result.isOK()) { /////////////////////////////////////////////////////////////////////////// // Update timestamp sql.str(""); sql << "UPDATE " << TABLE_NAME << " SET timestamp=" << Timestamp::unixTime() << " WHERE id='" << key << "';"; _db.executeSQL(sql.str().c_str()); /////////////////////////////////////////////////////////////////////////// if(result.records.size()==1 && result.records[0].size() == 1) { auto readBuffer = std::make_shared<std::string>(std::move(result.records.at(0).at(0))); if(!readBuffer->empty()) { return readBuffer; } } } else { AMIGO_LOG_E(TAG, "::get() sql failed: '%s'\n", sql.str().c_str()); } return nullptr; }
NetworkClient* ServerManager::handleSessionConnect(Session* session, Service* service) { NetworkClient* newClient = 0; ServerAddress serverAddress; // Execute our statement int8 sql[500]; sprintf(sql,"SELECT id, address, port, status, active FROM config_process_list WHERE address='%s' AND port=%u;", session->getAddressString(), session->getPortHost()); DatabaseResult* result = mDatabase->ExecuteSynchSql(sql); // If we found them if(result->getRowCount() == 1) { // Retrieve our routes and add them to the map. result->GetNextRow(mServerBinding,&serverAddress); // put this fresh data in our list. newClient = new ConnectionClient(); ConnectionClient* connClient = reinterpret_cast<ConnectionClient*>(newClient); ConnectionClient* oldClient = mServerAddressMap[serverAddress.mId].mConnectionClient; if(oldClient) { delete(oldClient); --mTotalConnectedServers; } connClient->setServerId(serverAddress.mId); memcpy(&mServerAddressMap[serverAddress.mId], &serverAddress, sizeof(ServerAddress)); mServerAddressMap[serverAddress.mId].mConnectionClient = connClient; gLogger->log(LogManager::DEBUG,"*** Backend server connected id: %u\n",mServerAddressMap[serverAddress.mId].mId); // If this is one of the servers we're waiting for, then update our count if(mServerAddressMap[serverAddress.mId].mActive) { ++mTotalConnectedServers; if(mTotalConnectedServers == mTotalActiveServers) { mDatabase->ExecuteProcedureAsync(0, 0, "CALL sp_GalaxyStatusUpdate(%u, %u);", 2, mClusterId); // Set status to online } } } else { gLogger->log(LogManager::CRITICAL,"*** Backend server connect error - Server not found in DB\n"); gLogger->log(LogManager::DEBUG,sql); gLogger->log(LogManager::DEBUG,"\n"); } // Delete our DB objects. mDatabase->DestroyResult(result); return(newClient); }
/// \brief Read all the rules in one ruleset from the rules table. /// /// @param ruleset the name of the ruleset to be read. /// @param o Atlas map to store the rules in. void readRuleTable(const std::string & ruleset, MapType & o) { std::stringstream query; query << "SELECT * FROM " << m_connection.rule() << " WHERE " << " ruleset = '" << ruleset << "'"; DatabaseResult res = m_connection.runSimpleSelectQuery(query.str()); DatabaseResult::const_iterator I = res.begin(); DatabaseResult::const_iterator Iend = res.end(); for (; I != Iend; ++I) { MapType & data = (o[I.column("id")] = MapType()).asMap(); m_connection.decodeMessage(I.column("contents"), data); } }
int fCache::_getCacheSize() { DatabaseResult result; std::stringstream sql; sql << "SELECT COUNT(*) FROM " << TABLE_NAME << " WHERE persistent=0;"; _db.executeSQL(sql.str().c_str(), result); if(result.isOK() && result.records.size()==1 && result.records[0].size() == 1) { return atoi(result.records.at(0).at(0).c_str()); } return -1; }
bool fCache::isExist(const std::string &key) { std::stringstream sql; DatabaseResult result; sql << "SELECT EXISTS(SELECT 1 FROM " << TABLE_NAME << " WHERE id='" << key << "');"; _db.executeSQL(sql.str().c_str(), result); bool exist=false; if(result.isOK() && result.records.size()==1 && result.records[0].size() == 1) { exist = (atoi(result.records.at(0).at(0).c_str()) > 0); } return exist; }
/// \brief Read all the rules sets from the rules table /// void readRuleTableSets(std::set<std::string> & sets) { std::stringstream query; query << "SELECT ruleset FROM " << m_connection.rule(); DatabaseResult res = m_connection.runSimpleSelectQuery(query.str()); DatabaseResult::const_iterator I = res.begin(); DatabaseResult::const_iterator Iend = res.end(); for (; I != Iend; ++I) { std::string ruleset_name = I.column("ruleset"); if (sets.find(ruleset_name) == sets.end()) { sets.insert(ruleset_name); } } }
//====================================================================================================================== void ClientManager::_processSelectCharacter(ConnectionClient* client, Message* message) { uint64 characterId = message->getUint64(); DatabaseResult* result = mDatabase->executeSynchSql("SELECT planet_id FROM %s.characters WHERE id=%"PRIu64";",mDatabase->galaxy(), characterId); uint32 serverId; DataBinding* binding = mDatabase->createDataBinding(1); binding->addField(DFT_uint32, 0, 4); result->getNextRow(binding, &serverId); client->setServerId(serverId + 8); // server ids for zones are planetId + 8; mDatabase->destroyDataBinding(binding); mDatabase->destroyResult(result); // send an opClusterClientConnect message to zone server. gMessageFactory->StartMessage(); gMessageFactory->addUint32(opClusterClientConnect); gMessageFactory->addUint64(characterId); Message* zoneMessage = gMessageFactory->EndMessage(); // This one goes to the ZoneServer the client is currently on. zoneMessage->setAccountId(client->getAccountId()); zoneMessage->setDestinationId(static_cast<uint8>(serverId + 8)); zoneMessage->setRouted(true); mMessageRouter->RouteMessage(zoneMessage, client); // send an opClusterClientConnect message to chat server. gMessageFactory->StartMessage(); gMessageFactory->addUint32(opClusterClientConnect); gMessageFactory->addUint64(characterId); gMessageFactory->addUint32(serverId); Message* chatMessage = gMessageFactory->EndMessage(); // This one goes to the ChatServer chatMessage->setAccountId(client->getAccountId()); chatMessage->setDestinationId(CR_Chat); chatMessage->setRouted(true); mMessageRouter->RouteMessage(chatMessage, client); // Now send the SelectCharacter message off to the zone server. gMessageFactory->StartMessage(); gMessageFactory->addData(message->getData(), message->getSize()); Message* selectMessage = gMessageFactory->EndMessage(); selectMessage->setAccountId(client->getAccountId()); selectMessage->setDestinationId(static_cast<uint8>(serverId + 8)); selectMessage->setRouted(true); mMessageRouter->RouteMessage(selectMessage, client); }
void WorldManager::LoadCurrentGlobalTick() { uint64 Tick; DatabaseResult* temp = mDatabase->executeSynchSql("SELECT Global_Tick_Count FROM %s.galaxy WHERE galaxy_id = '2'",mDatabase->galaxy()); DataBinding* tickbinding = mDatabase->createDataBinding(1); tickbinding->addField(DFT_uint64,0,8,0); temp->getNextRow(tickbinding,&Tick); mDatabase->destroyDataBinding(tickbinding); mDatabase->destroyResult(temp); LOG(info) << "Current global tick count [" << Tick << "]"; mTick = Tick; mSubsystemScheduler->addTask(fastdelegate::MakeDelegate(this,&WorldManager::_handleTick),7,1000,NULL); }
long fCache::getCacheSize(bool persistent) { std::stringstream sql; DatabaseResult result; if(persistent) sql << "SELECT SUM(LENGTH(data)) FROM " << TABLE_NAME << " WHERE persistent=" << persistent << ""; else sql << "SELECT SUM(LENGTH(data)) FROM " << TABLE_NAME; _db.executeSQL(sql.str().c_str(), result); if(result.isOK()) { if(result.records.size()==1 && result.records[0].size() == 1) { std::string cacheSize = result.records.at(0).at(0); return atol(cacheSize.c_str()); } } return 0; }
void StorageManager::restoreChildren(LocatedEntity * parent) { Database * db = Database::instance(); DatabaseResult res = db->selectEntities(parent->getId()); EntityBuilder * eb = EntityBuilder::instance(); // Iterate over res creating entities, and sorting out position, location // and orientation. Restore children, but don't restore any properties yet. DatabaseResult::const_iterator I = res.begin(); DatabaseResult::const_iterator Iend = res.end(); for (; I != Iend; ++I) { const std::string id = I.column("id"); const int int_id = forceIntegerId(id); const std::string type = I.column("type"); //By sending an empty attributes pointer we're telling the builder not to apply any default //attributes. We will instead apply all attributes ourselves when we later on restore attributes. Atlas::Objects::SmartPtr<Atlas::Objects::Entity::RootEntityData> attrs(nullptr); LocatedEntity * child = eb->newEntity(id, int_id, type, attrs, BaseWorld::instance()); if (!child) { log(ERROR, compose("Could not restore entity with id %1 of type %2" ", most likely caused by this type missing.", id, type)); continue; } const std::string location_string = I.column("location"); MapType loc_data; db->decodeMessage(location_string, loc_data); child->m_location.readFromMessage(loc_data); if (!child->m_location.pos().isValid()) { std::cout << "No pos data" << std::endl << std::flush; log(ERROR, compose("Entity %1 restored from database has no " "POS data. Ignored.", child->getId())); delete child; continue; } child->m_location.m_loc = parent; child->setFlags(entity_clean | entity_pos_clean | entity_orient_clean); BaseWorld::instance().addEntity(child); restoreChildren(child); } }
void ZoneServer::_connectToConnectionServer(void) { ProcessAddress processAddress; memset(&processAddress, 0, sizeof(ProcessAddress)); // Query the DB to find out who this is. // setup our databinding parameters. DataBinding* binding = mDatabase->CreateDataBinding(5); binding->addField(DFT_uint32, offsetof(ProcessAddress, mType), 4); binding->addField(DFT_string, offsetof(ProcessAddress, mAddress), 16); binding->addField(DFT_uint16, offsetof(ProcessAddress, mPort), 2); binding->addField(DFT_uint32, offsetof(ProcessAddress, mStatus), 4); binding->addField(DFT_uint32, offsetof(ProcessAddress, mActive), 4); // Execute our statement DatabaseResult* result = mDatabase->ExecuteSynchSql("SELECT id, address, port, status, active FROM config_process_list WHERE name='connection';"); uint32 count = static_cast<uint32>(result->getRowCount()); // If we found them if (count == 1) { // Retrieve our routes and add them to the map. result->GetNextRow(binding, &processAddress); } // Delete our DB objects. mDatabase->DestroyDataBinding(binding); mDatabase->DestroyResult(result); // Now connect to the ConnectionServer DispatchClient* client = new DispatchClient(); mRouterService->Connect(client, processAddress.mAddress, processAddress.mPort); // Send our registration message gMessageFactory->StartMessage(); gMessageFactory->addUint32(opClusterRegisterServer); gMessageFactory->addString(mZoneName); Message* message = gMessageFactory->EndMessage(); client->SendChannelA(message, 0, CR_Connection, 1); }
std::vector<ValueType *> ValueTypeDatabaseFactory::fetchAll( void ) { DatabaseStatement * statement; DatabaseResult * result; DatabaseResultRow * row; std::vector<ValueType *> types; std::string strId; long bufferId; std::size_t id; std::string identifier; std::string name; std::string description; std::string regex; statement = getDbConnection()->createStatement( "SELECT *" "FROM value_types" ); if( statement != nullptr ) { result = statement->execute(); if( result != nullptr ) { while( result->hasNext() ) { row = result->next(); strId = row->getColumn(0); identifier = row->getColumn(1); regex = row->getColumn(2); name = row->getColumn(3); description = row->getColumn(4); bufferId = atol(strId.c_str()); id = static_cast<std::size_t>(bufferId); types.push_back( new ValueType(id,identifier,name,description,regex) ); delete row; } delete result; } delete statement; } return ( types ); }
void ServerManager::_loadProcessAddressMap(void) { //bool serversOnline = false; ServerAddress serverAddress; // retrieve our list of process addresses. DatabaseResult* result = mDatabase->ExecuteSynchSql("SELECT id, address, port, status, active FROM config_process_list WHERE active=1 ORDER BY id;"); mTotalActiveServers = static_cast<uint32>(result->getRowCount()); for(uint32 i = 0; i < mTotalActiveServers; i++) { // Retrieve our server data result->GetNextRow(mServerBinding,&serverAddress); memcpy(&mServerAddressMap[serverAddress.mId], &serverAddress, sizeof(ServerAddress)); mServerAddressMap[serverAddress.mId].mConnectionClient = NULL; } // Delete our DB objects. mDatabase->DestroyResult(result); }
std::vector<Controller *> ControllerDatabaseFactory::fetchAll( void ) { std::vector<Controller *> controllers; Controller * controller; DatabaseStatement * statement; DatabaseResult * result; DatabaseResultRow * row; std::string id; std::string identifier; std::string description; std::string name; std::string securityCode; statement = getDbConnection()->createStatement( "SELECT * " "FROM controllers;" ); if( statement != nullptr ) { result = statement->execute(); if( result != nullptr ) { while( result->hasNext() ) { row = result->next(); id = row->getColumn(0); identifier = row->getColumn(1); securityCode = row->getColumn(2); name = row->getColumn(3); description = row->getColumn(4); controller = allocateController(id,identifier,name, description,securityCode); controllers.push_back(controller); delete row; } delete result; } delete statement; } return ( controllers ); }
void StorageManager::restorePropertiesRecursively(LocatedEntity * ent) { Database * db = Database::instance(); PropertyManager * pm = PropertyManager::instance(); DatabaseResult res = db->selectProperties(ent->getId()); //Keep track of those properties that have been set on the instance, so we'll know what //type properties we should ignore. std::unordered_set<std::string> instanceProperties; DatabaseResult::const_iterator I = res.begin(); DatabaseResult::const_iterator Iend = res.end(); for (; I != Iend; ++I) { const std::string name = I.column("name"); if (name.empty()) { log(ERROR, compose("No name column in property row for %1", ent->getId())); continue; } const std::string val_string = I.column("value"); if (name.empty()) { log(ERROR, compose("No value column in property row for %1,%2", ent->getId(), name)); continue; } MapType prop_data; db->decodeMessage(val_string, prop_data); MapType::const_iterator J = prop_data.find("val"); if (J == prop_data.end()) { log(ERROR, compose("No property value data for %1:%2", ent->getId(), name)); continue; } assert(ent->getType() != 0); const Element & val = J->second; Element existingVal; if (ent->getAttr(name, existingVal) == 0) { if (existingVal == val) { //If the existing property, either on the instance or the type, is equal to the persisted one just skip it. continue; } } PropertyBase * prop = ent->modProperty(name); if (prop == nullptr) { prop = pm->addProperty(name, val.getType()); prop->install(ent, name); //This transfers ownership of the property to the entity. ent->setProperty(name, prop); } //If we get to here the property either doesn't exists, or have a different value than the default or existing property. prop->set(val); prop->setFlags(per_clean | per_seen); prop->apply(ent); instanceProperties.insert(name); } if (ent->getType()) { for (auto& propIter : ent->getType()->defaults()) { if (!instanceProperties.count(propIter.first)) { PropertyBase * prop = propIter.second; // If a property is in the class it won't have been installed // as setAttr() checks prop->install(ent, propIter.first); // The property will have been applied if it has an overriden // value, so we only apply it the value is still default. prop->apply(ent); } } } //Now restore all properties of the child entities. if (ent->m_contains) { for (auto& childEntity : *ent->m_contains) { restorePropertiesRecursively(childEntity); } } //We must send a sight op to the entity informing it of itself before we send any thoughts. //Else the mind won't have any information about itself. { Atlas::Objects::Operation::Sight sight; sight->setTo(ent->getId()); Atlas::Objects::Entity::Anonymous args; ent->addToEntity(args); sight->setArgs1(args); ent->sendWorld(sight); } //We should also send a sight op to the parent entity which owns the entity. //TODO: should this really be necessary or should we rely on other Sight functionality? if (ent->m_location.m_loc) { Atlas::Objects::Operation::Sight sight; sight->setTo(ent->m_location.m_loc->getId()); Atlas::Objects::Entity::Anonymous args; ent->addToEntity(args); sight->setArgs1(args); ent->m_location.m_loc->sendWorld(sight); } restoreThoughts(ent); }
DatabaseResult Database::exec(const String sqlStmt) { DatabaseColumn dbCol; DatabaseRow dbRow; DatabaseResult dbRes; if(sqliteStatus != SQLITE_OK) throw DatabaseNotOpenException() << DebugInfo(TRACE(), DebugInfo::Error); sqliteStatus = sqlite3_prepare_v2(db, sqlStmt.data(), -1, &dbStmt, NULL); if(sqliteStatus != SQLITE_OK) throw DatabaseStatementInvalidException() << DebugInfo(String(sqlStmt) << "\n\"" << sqlite3_errmsg(db) << "\"\n" << TRACE(), DebugInfo::Error); int iCol = 0, colType = -1; int colCount = sqlite3_column_count(dbStmt); int stepRet = sqlite3_step(dbStmt); bool isNoResult = true; if(stepRet == SQLITE_ROW) isNoResult = false; while(stepRet == SQLITE_ROW) { for(iCol=0; iCol<colCount; ++iCol) { colType = sqlite3_column_type(dbStmt, iCol); if(colType == SQLITE_INTEGER) { dbCol = DatabaseColumn(sqlite3_column_int(dbStmt, iCol)); dbCol.setInt64Data(sqlite3_column_int64(dbStmt, iCol)); } else if(colType == SQLITE_FLOAT) { dbCol = DatabaseColumn(sqlite3_column_double(dbStmt, iCol)); } else if(colType == SQLITE_TEXT) { dbCol = DatabaseColumn(String(sqlite3_column_text(dbStmt, iCol))); } else if(colType == SQLITE_BLOB) { dbCol = DatabaseColumn((unsigned char*)sqlite3_column_blob(dbStmt, iCol)); } else if(colType == SQLITE_NULL) { dbCol = DatabaseColumn(true); } dbRow.addColumn(dbCol); } dbRes.addRowData(dbRow); dbRow = DatabaseRow(); stepRet = sqlite3_step(dbStmt); } sqlite3_finalize(dbStmt); if(stepRet != SQLITE_DONE) throw DatabaseResultNotDoneException() << DebugInfo(sqlite3_errmsg(db) << TRACE(), DebugInfo::Error); if(isNoResult == true) dbRes.setRowChanged(sqlite3_changes(db)); return dbRes; }
/// \brief Retrieve an Account from the accounts database /// /// @param username Username of the Account to be found /// @param account Account description returned here bool Storage::getAccount(const std::string & username, Atlas::Message::MapType & account) { std::string namestr = "'" + username + "'"; DatabaseResult dr = m_connection.selectSimpleRowBy("accounts", "username", namestr); if (dr.error()) { return false; } if (dr.empty()) { dr.clear(); return false; } if (dr.size() > 1) { return false; } const char * c = dr.field("id"); if (c == 0) { dr.clear(); return false; } std::string id = c; c = dr.field("password"); if (c == 0) { dr.clear(); return false; } std::string password = c; c = dr.field("type"); if (c == 0) { dr.clear(); return false; } std::string type = c; dr.clear(); account["id"] = id; account["username"] = username; account["password"] = password; account["type"] = type; return true; }
bool DatabaseUtils::GetDatabaseResults(const MediaType &mediaType, const FieldList &fields, const std::unique_ptr<dbiplus::Dataset> &dataset, DatabaseResults &results) { if (dataset->num_rows() == 0) return true; const dbiplus::result_set &resultSet = dataset->get_result_set(); unsigned int offset = results.size(); if (fields.empty()) { DatabaseResult result; for (unsigned int index = 0; index < resultSet.records.size(); index++) { result[FieldRow] = index + offset; results.push_back(result); } return true; } if (resultSet.record_header.size() < fields.size()) return false; std::vector<int> fieldIndexLookup; fieldIndexLookup.reserve(fields.size()); for (FieldList::const_iterator it = fields.begin(); it != fields.end(); ++it) fieldIndexLookup.push_back(GetFieldIndex(*it, mediaType)); results.reserve(resultSet.records.size() + offset); for (unsigned int index = 0; index < resultSet.records.size(); index++) { DatabaseResult result; result[FieldRow] = index + offset; unsigned int lookupIndex = 0; for (FieldList::const_iterator it = fields.begin(); it != fields.end(); ++it) { int fieldIndex = fieldIndexLookup[lookupIndex++]; if (fieldIndex < 0) return false; std::pair<Field, CVariant> value; value.first = *it; if (!GetFieldValue(resultSet.records[index]->at(fieldIndex), value.second)) CLog::Log(LOGWARNING, "GetDatabaseResults: unable to retrieve value of field %s", resultSet.record_header[fieldIndex].name.c_str()); if (value.first == FieldYear && (mediaType == MediaTypeTvShow || mediaType == MediaTypeEpisode)) { CDateTime dateTime; dateTime.SetFromDBDate(value.second.asString()); if (dateTime.IsValid()) { value.second.clear(); value.second = dateTime.GetYear(); } } result.insert(value); } result[FieldMediaType] = mediaType; if (mediaType == MediaTypeMovie || mediaType == MediaTypeVideoCollection || mediaType == MediaTypeTvShow || mediaType == MediaTypeMusicVideo) result[FieldLabel] = result.at(FieldTitle).asString(); else if (mediaType == MediaTypeEpisode) { std::ostringstream label; label << (int)(result.at(FieldSeason).asInteger() * 100 + result.at(FieldEpisodeNumber).asInteger()); label << ". "; label << result.at(FieldTitle).asString(); result[FieldLabel] = label.str(); } else if (mediaType == MediaTypeAlbum) result[FieldLabel] = result.at(FieldAlbum).asString(); else if (mediaType == MediaTypeSong) { std::ostringstream label; label << (int)result.at(FieldTrackNumber).asInteger(); label << ". "; label << result.at(FieldTitle).asString(); result[FieldLabel] = label.str(); } else if (mediaType == MediaTypeArtist) result[FieldLabel] = result.at(FieldArtist).asString(); results.push_back(result); } return true; }
ZoneServer::ZoneServer(int8* zoneName) : mZoneName(zoneName), mNetworkManager(0), mDatabaseManager(0), mRouterService(0), mDatabase(0) { Anh_Utils::Clock::Init(); // gLogger->logMsgF("ZoneServer - %s Startup %s",MSG_NORMAL,zoneName,GetBuildString()); gLogger->logMsg("ZoneServer Startup", FOREGROUND_GREEN | FOREGROUND_RED); // Create and startup our core services. mDatabaseManager = new DatabaseManager(); mNetworkManager = new NetworkManager(); // Connect to the DB and start listening for the RouterServer. mDatabase = mDatabaseManager->Connect(DBTYPE_MYSQL, (int8*)(gConfig->read<std::string>("DBServer")).c_str(), gConfig->read<int>("DBPort"), (int8*)(gConfig->read<std::string>("DBUser")).c_str(), (int8*)(gConfig->read<std::string>("DBPass")).c_str(), (int8*)(gConfig->read<std::string>("DBName")).c_str()); //make sure our logger has db access gLogger->connecttoDB(mDatabaseManager); //create an error log int8 log[128]; sprintf(log,"%s.log",zoneName); gLogger->createErrorLog(log,(LogLevel)(gConfig->read<int>("LogLevel",2)), (bool)(gConfig->read<bool>("LogToFile", true)), (bool)(gConfig->read<bool>("ConsoleOut",true)), (bool)(gConfig->read<bool>("LogAppend",true))); //increase the server start that will help us to organize our logs to the corresponding serverstarts (mostly for errors) mDatabase->ExecuteSqlAsync(0,0,"UPDATE config_process_list SET serverstartID = serverstartID+1 WHERE name like \'%s\'",zoneName); mRouterService = mNetworkManager->GenerateService((char*)gConfig->read<std::string>("BindAddress").c_str(), gConfig->read<uint16>("BindPort"),gConfig->read<uint32>("ServiceMessageHeap")*1024,true); // Grab our zoneId out of the DB for this zonename. uint32 zoneId = 0; DatabaseResult* result = mDatabase->ExecuteSynchSql("SELECT planet_id FROM planet WHERE name=\'%s\';", zoneName); if (!result->getRowCount()) { gLogger->logMsgF("FATAL: Map \'%s\' not found. Aborting startup.", MSG_HIGH, zoneName); abort(); } // Yea, I'm getting annoyed with the DataBinding for such simple tasks. Will implement a simple interface soon. gLogger->logMsgF("ZoneServer initializing for zone %s", MSG_NORMAL, zoneName); DataBinding* binding = mDatabase->CreateDataBinding(1); binding->addField(DFT_uint32, 0, 4); result->GetNextRow(binding, &zoneId); mDatabase->DestroyDataBinding(binding); mDatabase->DestroyResult(result); // We need to register our IP and port in the DB so the connection server can connect to us. // Status: 0=offline, 1=loading, 2=online _updateDBServerList(1); // Place all startup code here. mMessageDispatch = new MessageDispatch(mRouterService); WorldConfig::Init(zoneId,mDatabase,zoneName); ObjectControllerCommandMap::Init(mDatabase); MessageLib::Init(); ObjectFactory::Init(mDatabase); //attribute commands for foodbuffs FoodCommandMapClass::Init(); //structuremanager callback functions StructureManagerCommandMapClass::Init(); WorldManager::Init(zoneId,this,mDatabase); // Init the non persistent factories. For now we take them one-by-one here, until we have a collection of them. // We can NOT create these factories among the already existing ones, if we want to have any kind of "ownership structure", // since the existing factories are impossible to delete without crashing the server. // NonPersistentContainerFactory::Init(mDatabase); (void)NonPersistentItemFactory::Instance(); // This call is just for clarity, when matching the deletion of classes. // The object will create itself upon first usage, (void)NonPersistentNpcFactory::Instance(); (void)ForageManager::Instance(); (void)ScoutManager::Instance(); (void)NonPersistantObjectFactory::Instance(); UIManager::Init(mDatabase,mMessageDispatch); CombatManager::Init(mDatabase); TravelMapHandler::Init(mDatabase,mMessageDispatch,zoneId); CharSheetManager::Init(mDatabase,mMessageDispatch); TradeManager::Init(mDatabase,mMessageDispatch); BuffManager::Init(mDatabase); MedicManager::Init(mMessageDispatch); AdminManager::Init(mMessageDispatch); EntertainerManager::Init(mDatabase,mMessageDispatch); GroupManager::Init(mDatabase,mMessageDispatch); StructureManager::Init(mDatabase,mMessageDispatch); // Invoked when all creature regions for spawning of lairs are loaded // (void)NpcManager::Instance(); ScriptEngine::Init(); mCharacterLoginHandler = new CharacterLoginHandler(mDatabase,mMessageDispatch); mObjectControllerDispatch = new ObjectControllerDispatch(mDatabase,mMessageDispatch); }