diff --git a/src/game/AI/ScriptDevAI/system/system.cpp b/src/game/AI/ScriptDevAI/system/system.cpp index d435c249794..e4392b53c7e 100644 --- a/src/game/AI/ScriptDevAI/system/system.cpp +++ b/src/game/AI/ScriptDevAI/system/system.cpp @@ -24,14 +24,13 @@ SystemMgr& SystemMgr::Instance() void SystemMgr::LoadVersion() { // Get Version information - QueryResult* result = WorldDatabase.PQuery("SELECT version FROM sd2_db_version LIMIT 1"); + auto queryResult = WorldDatabase.PQuery("SELECT version FROM sd2_db_version LIMIT 1"); - if (result) + if (queryResult) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); strSD2Version = fields[0].GetCppString(); - delete result; } else script_error_log("Missing `sd2_db_version` information."); @@ -73,7 +72,7 @@ void SystemMgr::LoadScriptWaypoints() outstring_log("SD2: Loading Script Waypoints for " UI64FMTD " creature(s)...", creatureCount); // 0 1 2 3 4 5 6 7 8 - result.reset(WorldDatabase.PQuery("SELECT Entry, PathId, Point, PositionX, PositionY, PositionZ, Orientation, WaitTime, ScriptId FROM script_waypoint ORDER BY Entry, PathId, Point")); + result = WorldDatabase.PQuery("SELECT Entry, PathId, Point, PositionX, PositionY, PositionZ, Orientation, WaitTime, ScriptId FROM script_waypoint ORDER BY Entry, PathId, Point"); if (result) { diff --git a/src/game/Accounts/AccountMgr.cpp b/src/game/Accounts/AccountMgr.cpp index 19ace4c0728..559360b29db 100644 --- a/src/game/Accounts/AccountMgr.cpp +++ b/src/game/Accounts/AccountMgr.cpp @@ -105,18 +105,17 @@ AccountOpResult AccountMgr::CreateAccount(std::string username, std::string pass AccountOpResult AccountMgr::DeleteAccount(uint32 accid) const { - QueryResult* result = LoginDatabase.PQuery("SELECT 1 FROM account WHERE id='%u'", accid); - if (!result) + auto queryResult = LoginDatabase.PQuery("SELECT 1 FROM account WHERE id='%u'", accid); + if (!queryResult) return AOR_NAME_NOT_EXIST; // account doesn't exist - delete result; // existing characters list - result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE account='%u'", accid); - if (result) + queryResult = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE account='%u'", accid); + if (queryResult) { do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 guidlo = fields[0].GetUInt32(); ObjectGuid guid = ObjectGuid(HIGHGUID_PLAYER, guidlo); @@ -124,9 +123,7 @@ AccountOpResult AccountMgr::DeleteAccount(uint32 accid) const ObjectAccessor::KickPlayer(guid); Player::DeleteFromDB(guid, accid, false); // no need to update realm characters } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); } // table realm specific but common for all characters of account for realm @@ -148,10 +145,9 @@ AccountOpResult AccountMgr::DeleteAccount(uint32 accid) const AccountOpResult AccountMgr::ChangeUsername(uint32 accid, std::string new_uname, std::string new_passwd) const { - QueryResult* result = LoginDatabase.PQuery("SELECT 1 FROM account WHERE id='%u'", accid); - if (!result) + auto queryResult = LoginDatabase.PQuery("SELECT 1 FROM account WHERE id='%u'", accid); + if (!queryResult) return AOR_NAME_NOT_EXIST; // account doesn't exist - delete result; if (utf8length(new_uname) > MAX_ACCOUNT_STR) return AOR_NAME_TOO_LONG; @@ -222,21 +218,19 @@ AccountOpResult AccountMgr::ChangePassword(uint32 accid, std::string new_passwd) uint32 AccountMgr::GetId(std::string username) const { LoginDatabase.escape_string(username); - QueryResult* result = LoginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'", username.c_str()); - if (!result) + auto queryResult = LoginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'", username.c_str()); + if (!queryResult) return 0; - uint32 id = (*result)[0].GetUInt32(); - delete result; + uint32 id = (*queryResult)[0].GetUInt32(); return id; } AccountTypes AccountMgr::GetSecurity(uint32 acc_id) { - QueryResult* result = LoginDatabase.PQuery("SELECT gmlevel FROM account WHERE id = '%u'", acc_id); - if (result) + auto queryResult = LoginDatabase.PQuery("SELECT gmlevel FROM account WHERE id = '%u'", acc_id); + if (queryResult) { - AccountTypes sec = AccountTypes((*result)[0].GetInt32()); - delete result; + AccountTypes sec = AccountTypes((*queryResult)[0].GetInt32()); return sec; } @@ -245,11 +239,10 @@ AccountTypes AccountMgr::GetSecurity(uint32 acc_id) bool AccountMgr::GetName(uint32 acc_id, std::string& name) const { - QueryResult* result = LoginDatabase.PQuery("SELECT username FROM account WHERE id = '%u'", acc_id); - if (result) + auto queryResult = LoginDatabase.PQuery("SELECT username FROM account WHERE id = '%u'", acc_id); + if (queryResult) { - name = (*result)[0].GetCppString(); - delete result; + name = (*queryResult)[0].GetCppString(); return true; } @@ -259,12 +252,11 @@ bool AccountMgr::GetName(uint32 acc_id, std::string& name) const uint32 AccountMgr::GetCharactersCount(uint32 acc_id) const { // check character count - QueryResult* result = CharacterDatabase.PQuery("SELECT COUNT(guid) FROM characters WHERE account = '%u'", acc_id); - if (result) + auto queryResult = CharacterDatabase.PQuery("SELECT COUNT(guid) FROM characters WHERE account = '%u'", acc_id); + if (queryResult) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 charcount = fields[0].GetUInt32(); - delete result; return charcount; } return 0; @@ -279,10 +271,10 @@ bool AccountMgr::CheckPassword(uint32 accid, std::string passwd) const normalizeString(passwd); normalizeString(username); - QueryResult* result = LoginDatabase.PQuery("SELECT s, v FROM account WHERE id='%u'", accid); - if (result) + auto queryResult = LoginDatabase.PQuery("SELECT s, v FROM account WHERE id='%u'", accid); + if (queryResult) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); SRP6 srp; bool calcv = srp.CalculateVerifier( @@ -290,11 +282,8 @@ bool AccountMgr::CheckPassword(uint32 accid, std::string passwd) const if (calcv && srp.ProofVerifier(fields[1].GetCppString())) { - delete result; return true; } - - delete result; } return false; diff --git a/src/game/Arena/ArenaTeam.cpp b/src/game/Arena/ArenaTeam.cpp index 8e9b6a93e57..2278b5f0d54 100644 --- a/src/game/Arena/ArenaTeam.cpp +++ b/src/game/Arena/ArenaTeam.cpp @@ -123,14 +123,13 @@ bool ArenaTeam::AddMember(ObjectGuid playerGuid) } else { - // 0 1 - QueryResult* result = CharacterDatabase.PQuery("SELECT name, class FROM characters WHERE guid='%u'", playerGuid.GetCounter()); - if (!result) + // 0 1 + auto queryResult = CharacterDatabase.PQuery("SELECT name, class FROM characters WHERE guid='%u'", playerGuid.GetCounter()); + if (!queryResult) return false; - plName = (*result)[0].GetCppString(); - plClass = (*result)[1].GetUInt8(); - delete result; + plName = (*queryResult)[0].GetCppString(); + plClass = (*queryResult)[1].GetUInt8(); // check if player already in arenateam of that size if (Player::GetArenaTeamIdFromDB(playerGuid, GetType()) != 0) diff --git a/src/game/AuctionHouseBot/AuctionHouseBot.cpp b/src/game/AuctionHouseBot/AuctionHouseBot.cpp index 9b3daefd704..5b89643117e 100644 --- a/src/game/AuctionHouseBot/AuctionHouseBot.cpp +++ b/src/game/AuctionHouseBot/AuctionHouseBot.cpp @@ -132,12 +132,12 @@ void AuctionHouseBot::Initialize() m_buyValue = GetMinMaxConfig("AuctionHouseBot.Buy.Value", 0, 200, 90); // overridden items - QueryResult* result = CharacterDatabase.PQuery("SELECT item, value, add_chance, min_amount, max_amount FROM ahbot_items"); - if (result) + auto queryResult = CharacterDatabase.PQuery("SELECT item, value, add_chance, min_amount, max_amount FROM ahbot_items"); + if (queryResult) { do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 itemId = fields[0].GetUInt32(); AuctionHouseBotItemData itemData; itemData.Value = fields[1].GetUInt32(); @@ -146,8 +146,7 @@ void AuctionHouseBot::Initialize() itemData.MaxAmount = fields[4].GetUInt32(); m_itemData[itemId] = itemData; } - while (result->NextRow()); - delete result; + while (queryResult->NextRow()); } } } @@ -433,19 +432,18 @@ void AuctionHouseBot::ParseLootConfig(char const* fieldname, std::vector& void AuctionHouseBot::FillUintVectorFromQuery(char const* query, std::vector& lootTemplates) { lootTemplates.clear(); - if (QueryResult* result = WorldDatabase.PQuery("%s", query)) + if (auto queryResult = WorldDatabase.PQuery("%s", query)) { - BarGoLink bar(result->GetRowCount()); + BarGoLink bar(queryResult->GetRowCount()); do { bar.step(); - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 entry = fields[0].GetUInt32(); if (!entry) continue; lootTemplates.push_back(fields[0].GetUInt32()); - } while (result->NextRow()); - delete result; + } while (queryResult->NextRow()); } } diff --git a/src/game/BattleGround/BattleGroundMgr.cpp b/src/game/BattleGround/BattleGroundMgr.cpp index 7dd4cfc07cf..fd5f942db2f 100644 --- a/src/game/BattleGround/BattleGroundMgr.cpp +++ b/src/game/BattleGround/BattleGroundMgr.cpp @@ -2307,12 +2307,12 @@ void BattleGroundMgr::RewardArenaSeason(uint32 seasonId) } else { - QueryResult* result = CharacterDatabase.PQuery("SELECT knownTitles FROM characters WHERE guid = '%u'", data.first.GetCounter()); - if (result) + auto queryResult = CharacterDatabase.PQuery("SELECT knownTitles FROM characters WHERE guid = '%u'", data.first.GetCounter()); + if (queryResult) { uint32 titleValueCount = 2; uint32 titleValues[2]; - std::string titlesData = result->Fetch()[0].GetCppString(); + std::string titlesData = queryResult->Fetch()[0].GetCppString(); Tokens tokens = StrSplit(titlesData, " "); if (tokens.size() != titleValueCount) return; @@ -2326,7 +2326,6 @@ void BattleGroundMgr::RewardArenaSeason(uint32 seasonId) std::string newTitleData = std::to_string(titleValues[0]) + " " + std::to_string(titleValues[1]) + " "; CharacterDatabase.PExecute("UPDATE characters SET knownTitles='%s' WHERE guid = '%u'", newTitleData.data(), data.first.GetCounter()); - delete result; } } } diff --git a/src/game/Calendar/CalendarHandler.cpp b/src/game/Calendar/CalendarHandler.cpp index ad7a9f45b22..fbe22e73f9d 100644 --- a/src/game/Calendar/CalendarHandler.cpp +++ b/src/game/Calendar/CalendarHandler.cpp @@ -444,22 +444,20 @@ void WorldSession::HandleCalendarEventInvite(WorldPacket& recv_data) { // Invitee offline, get data from database CharacterDatabase.escape_string(name); - QueryResult* result = CharacterDatabase.PQuery("SELECT guid,race FROM characters WHERE name ='%s'", name.c_str()); - if (result) + auto queryResult = CharacterDatabase.PQuery("SELECT guid,race FROM characters WHERE name ='%s'", name.c_str()); + if (queryResult) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); inviteeGuid = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32()); inviteeTeam = Player::TeamForRace(fields[1].GetUInt8()); inviteeGuildId = Player::GetGuildIdFromDB(inviteeGuid); - delete result; - result = CharacterDatabase.PQuery("SELECT flags FROM character_social WHERE guid = %u AND friend = %u", inviteeGuid.GetCounter(), playerGuid.GetCounter()); - if (result) + queryResult = CharacterDatabase.PQuery("SELECT flags FROM character_social WHERE guid = %u AND friend = %u", inviteeGuid.GetCounter(), playerGuid.GetCounter()); + if (queryResult) { - fields = result->Fetch(); + fields = queryResult->Fetch(); if (fields[0].GetUInt8() & SOCIAL_FLAG_IGNORED) isIgnored = true; - delete result; } } } diff --git a/src/game/Chat/Chat.h b/src/game/Chat/Chat.h index ec9c9cfd1e7..ad82f36187e 100644 --- a/src/game/Chat/Chat.h +++ b/src/game/Chat/Chat.h @@ -847,18 +847,18 @@ class ChatHandler GameObject* GetGameObjectWithGuid(uint32 lowguid, uint32 entry) const; // Utility methods for commands - bool ShowAccountListHelper(QueryResult* result, uint32* limit = nullptr, bool title = true, bool error = true); + bool ShowAccountListHelper(std::unique_ptr queryResult, uint32* limit = nullptr, bool title = true, bool error = true); void ShowAchievementListHelper(AchievementEntry const* achEntry, LocaleConstant loc, time_t const* date = nullptr, Player* target = nullptr); void ShowAchievementCriteriaListHelper(AchievementCriteriaEntry const* criEntry, AchievementEntry const* achEntry, LocaleConstant loc, Player* target = nullptr); void ShowFactionListHelper(FactionEntry const* factionEntry, LocaleConstant loc, FactionState const* repState = nullptr, Player* target = nullptr); void ShowItemListHelper(uint32 itemId, int loc_idx, Player* target = nullptr); void ShowQuestListHelper(uint32 questId, int32 loc_idx, Player* target = nullptr); - bool ShowPlayerListHelper(QueryResult* result, uint32* limit = nullptr, bool title = true, bool error = true); + bool ShowPlayerListHelper(std::unique_ptr queryResult, uint32* limit = nullptr, bool title = true, bool error = true); void ShowSpellListHelper(Player* target, SpellEntry const* spellInfo, LocaleConstant loc); void ShowPoolListHelper(uint16 pool_id); void ShowTriggerListHelper(AreaTriggerEntry const* atEntry); void ShowTriggerTargetListHelper(uint32 id, AreaTrigger const* at, bool subpart = false); - bool LookupPlayerSearchCommand(QueryResult* result, uint32* limit = nullptr); + bool LookupPlayerSearchCommand(std::unique_ptr queryResult, uint32* limit = nullptr); bool HandleBanListHelper(std::unique_ptr queryResult); bool HandleBanHelper(BanMode mode, char* args); bool HandleBanInfoHelper(uint32 accountid, char const* accountname); diff --git a/src/game/Chat/Level2.cpp b/src/game/Chat/Level2.cpp index e01b501a16d..05f78c0bab3 100644 --- a/src/game/Chat/Level2.cpp +++ b/src/game/Chat/Level2.cpp @@ -582,12 +582,12 @@ bool ChatHandler::HandleGoCreatureCommand(char* args) { std::string name = pParam1; WorldDatabase.escape_string(name); - QueryResult* result = WorldDatabase.PQuery("SELECT creature.guid, creature_spawn_entry.guid " + auto queryResult = WorldDatabase.PQuery("SELECT creature.guid, creature_spawn_entry.guid " "FROM creature, creature_template, creature_spawn_entry " "WHERE (creature.id = creature_template.entry " "OR (creature_spawn_entry.entry = creature_template.entry AND creature.guid = creature_spawn_entry.guid)) " "AND creature_template.name LIKE '%%%s%%' LIMIT 1;", name.c_str()); - if (!result) + if (!queryResult) { SendSysMessage(LANG_COMMAND_GOCREATNOTFOUND); SetSentErrorMessage(true); @@ -598,7 +598,7 @@ bool ChatHandler::HandleGoCreatureCommand(char* args) do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 guid = fields[0].GetUInt32(); CreatureDataPair const* cr_data = sObjectMgr.GetCreatureDataPair(guid); @@ -606,9 +606,7 @@ bool ChatHandler::HandleGoCreatureCommand(char* args) continue; worker(*cr_data); - } while (result->NextRow()); - - delete result; + } while (queryResult->NextRow()); CreatureDataPair const* dataPair = worker.GetResult(); if (!dataPair) @@ -796,12 +794,12 @@ bool ChatHandler::HandleGoObjectCommand(char* args) { std::string name = pParam1; WorldDatabase.escape_string(name); - QueryResult* result = WorldDatabase.PQuery("SELECT gameobject.guid, gameobject_spawn_entry.guid " + auto queryResult = WorldDatabase.PQuery("SELECT gameobject.guid, gameobject_spawn_entry.guid " "FROM gameobject, gameobject_template, gameobject_spawn_entry " "WHERE (gameobject.id = gameobject_template.entry " "OR (gameobject_spawn_entry.entry = gameobject_template.entry AND gameobject.guid = gameobject_spawn_entry.guid)) " "AND gameobject_template.name LIKE '%%%s%%' LIMIT 1;", name.c_str()); - if (!result) + if (!queryResult) { SendSysMessage(LANG_COMMAND_GOOBJNOTFOUND); SetSentErrorMessage(true); @@ -812,7 +810,7 @@ bool ChatHandler::HandleGoObjectCommand(char* args) do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 guid = fields[0].GetUInt32(); GameObjectDataPair const* go_data = sObjectMgr.GetGODataPair(guid); @@ -821,9 +819,7 @@ bool ChatHandler::HandleGoObjectCommand(char* args) worker(*go_data); } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); GameObjectDataPair const* dataPair = worker.GetResult(); if (!dataPair) @@ -845,7 +841,7 @@ bool ChatHandler::HandleGoObjectCommand(char* args) bool ChatHandler::HandleGameObjectTargetCommand(char* args) { Player* pl = m_session->GetPlayer(); - QueryResult* result; + std::unique_ptr queryResult; GameEventMgr::ActiveEvents const& activeEventsList = sGameEventMgr.GetActiveEventList(); if (*args) { @@ -857,14 +853,14 @@ bool ChatHandler::HandleGameObjectTargetCommand(char* args) uint32 id; if (ExtractUInt32(&cId, id)) { - result = WorldDatabase.PQuery("SELECT guid, id, position_x, position_y, position_z, orientation, map, (POW(position_x - '%f', 2) + POW(position_y - '%f', 2) + POW(position_z - '%f', 2)) AS order_ FROM gameobject WHERE map = '%i' AND guid = '%u' ORDER BY order_ ASC LIMIT 1", + queryResult = WorldDatabase.PQuery("SELECT guid, id, position_x, position_y, position_z, orientation, map, (POW(position_x - '%f', 2) + POW(position_y - '%f', 2) + POW(position_z - '%f', 2)) AS order_ FROM gameobject WHERE map = '%i' AND guid = '%u' ORDER BY order_ ASC LIMIT 1", pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(), pl->GetMapId(), id); } else { std::string name = cId; WorldDatabase.escape_string(name); - result = WorldDatabase.PQuery( + queryResult = WorldDatabase.PQuery( "SELECT guid, id, position_x, position_y, position_z, orientation, map, (POW(position_x - %f, 2) + POW(position_y - %f, 2) + POW(position_z - %f, 2)) AS order_ " "FROM gameobject,gameobject_template WHERE gameobject_template.entry = gameobject.id AND map = %i AND name " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'")" ORDER BY order_ ASC LIMIT 1", pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(), pl->GetMapId(), name.c_str()); @@ -892,13 +888,13 @@ bool ChatHandler::HandleGameObjectTargetCommand(char* args) else eventFilter << ")"; - result = WorldDatabase.PQuery("SELECT gameobject.guid, id, position_x, position_y, position_z, orientation, map, " - "(POW(position_x - %f, 2) + POW(position_y - %f, 2) + POW(position_z - %f, 2)) AS order_ FROM gameobject " - "LEFT OUTER JOIN game_event_gameobject on gameobject.guid=game_event_gameobject.guid WHERE map = '%i' %s ORDER BY order_ ASC LIMIT 10", - pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(), pl->GetMapId(), eventFilter.str().c_str()); + queryResult = WorldDatabase.PQuery("SELECT gameobject.guid, id, position_x, position_y, position_z, orientation, map, " + "(POW(position_x - %f, 2) + POW(position_y - %f, 2) + POW(position_z - %f, 2)) AS order_ FROM gameobject " + "LEFT OUTER JOIN game_event_gameobject on gameobject.guid=game_event_gameobject.guid WHERE map = '%i' %s ORDER BY order_ ASC LIMIT 10", + pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(), pl->GetMapId(), eventFilter.str().c_str()); } - if (!result) + if (!queryResult) { SendSysMessage(LANG_COMMAND_TARGETOBJNOTFOUND); return true; @@ -911,7 +907,7 @@ bool ChatHandler::HandleGameObjectTargetCommand(char* args) do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); lowguid = fields[0].GetUInt32(); id = fields[1].GetUInt32(); x = fields[2].GetFloat(); @@ -923,9 +919,7 @@ bool ChatHandler::HandleGameObjectTargetCommand(char* args) if (!pool_id || pl->GetMap()->GetPersistentState()->IsSpawnedPoolObject(lowguid)) found = true; } - while (result->NextRow() && (!found)); - - delete result; + while (queryResult->NextRow() && (!found)); if (!found) { @@ -1258,17 +1252,17 @@ bool ChatHandler::HandleGameObjectNearCommand(char* args) uint32 count = 0; Player* pl = m_session->GetPlayer(); - QueryResult* result = WorldDatabase.PQuery("SELECT guid, id, position_x, position_y, position_z, map, " + auto queryResult = WorldDatabase.PQuery("SELECT guid, id, position_x, position_y, position_z, map, " "(POW(position_x - '%f', 2) + POW(position_y - '%f', 2) + POW(position_z - '%f', 2)) AS order_ " "FROM gameobject WHERE map='%u' AND (POW(position_x - '%f', 2) + POW(position_y - '%f', 2) + POW(position_z - '%f', 2)) <= '%f' ORDER BY order_", pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(), pl->GetMapId(), pl->GetPositionX(), pl->GetPositionY(), pl->GetPositionZ(), distance * distance); - if (result) + if (queryResult) { do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 guid = fields[0].GetUInt32(); uint32 entry = fields[1].GetUInt32(); float x = fields[2].GetFloat(); @@ -1291,9 +1285,7 @@ bool ChatHandler::HandleGameObjectNearCommand(char* args) ++count; } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); } PSendSysMessage(LANG_COMMAND_NEAROBJMESSAGE, distance, count); @@ -2936,16 +2928,15 @@ bool ChatHandler::HandlePInfoCommand(char* args) return false; // 0 1 2 3 - QueryResult* result = CharacterDatabase.PQuery("SELECT totaltime, level, money, account FROM characters WHERE guid = '%u'", target_guid.GetCounter()); - if (!result) + auto queryResult = CharacterDatabase.PQuery("SELECT totaltime, level, money, account FROM characters WHERE guid = '%u'", target_guid.GetCounter()); + if (!queryResult) return false; - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); total_player_time = fields[0].GetUInt32(); level = fields[1].GetUInt32(); money = fields[2].GetUInt32(); accId = fields[3].GetUInt32(); - delete result; } std::string username = GetMangosString(LANG_ERROR); @@ -2953,10 +2944,10 @@ bool ChatHandler::HandlePInfoCommand(char* args) AccountTypes security = SEC_PLAYER; std::string last_login = GetMangosString(LANG_ERROR); - QueryResult* result = LoginDatabase.PQuery("SELECT username,gmlevel,ip,loginTime FROM account a JOIN account_logons b ON(a.id=b.accountId) WHERE a.id = '%u' ORDER BY loginTime DESC LIMIT 1", accId); - if (result) + auto queryResult = LoginDatabase.PQuery("SELECT username,gmlevel,ip,loginTime FROM account a JOIN account_logons b ON(a.id=b.accountId) WHERE a.id = '%u' ORDER BY loginTime DESC LIMIT 1", accId); + if (queryResult) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); username = fields[0].GetCppString(); security = (AccountTypes)fields[1].GetUInt32(); @@ -2970,8 +2961,6 @@ bool ChatHandler::HandlePInfoCommand(char* args) last_ip = "-"; last_login = "-"; } - - delete result; } std::string nameLink = playerLink(target_name); @@ -3156,10 +3145,9 @@ bool ChatHandler::HandleWpAddCommand(char* args) wpDestination = PATH_FROM_ENTRY; // Default place to store paths if (wpOwner->HasStaticDBSpawnData()) { - QueryResult* result = WorldDatabase.PQuery("SELECT COUNT(id) FROM creature WHERE id = %u", wpOwner->GetEntry()); - if (result && result->Fetch()[0].GetUInt32() != 1) + auto queryResult = WorldDatabase.PQuery("SELECT COUNT(id) FROM creature WHERE id = %u", wpOwner->GetEntry()); + if (queryResult && queryResult->Fetch()[0].GetUInt32() != 1) wpDestination = PATH_FROM_GUID; - delete result; } } } @@ -4346,10 +4334,10 @@ bool ChatHandler::HandleLookupAccountEmailCommand(char* args) std::string email = emailStr; LoginDatabase.escape_string(email); - // 0 1 2 3 4 - QueryResult* result = LoginDatabase.PQuery("SELECT a.id, username, ip, gmlevel, expansion FROM account a join account_logons b on (a.id=b.accountId) WHERE email " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%' ORDER BY loginTime DESC LIMIT 1"), email.c_str()); + // 0 1 2 3 4 + auto queryResult = LoginDatabase.PQuery("SELECT a.id, username, ip, gmlevel, expansion FROM account a join account_logons b on (a.id=b.accountId) WHERE email " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%' ORDER BY loginTime DESC LIMIT 1"), email.c_str()); - return ShowAccountListHelper(result, &limit); + return ShowAccountListHelper(std::move(queryResult), &limit); } bool ChatHandler::HandleLookupAccountIpCommand(char* args) @@ -4365,10 +4353,10 @@ bool ChatHandler::HandleLookupAccountIpCommand(char* args) std::string ip = ipStr; LoginDatabase.escape_string(ip); - // 0 1 2 3 4 - QueryResult* result = LoginDatabase.PQuery("SELECT distinct id, username, ip, gmlevel, expansion FROM account a join account_logons b on(a.id=b.accountId) WHERE ip " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'"), ip.c_str()); + // 0 1 2 3 4 + auto queryResult = LoginDatabase.PQuery("SELECT distinct id, username, ip, gmlevel, expansion FROM account a join account_logons b on(a.id=b.accountId) WHERE ip " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'"), ip.c_str()); - return ShowAccountListHelper(result, &limit); + return ShowAccountListHelper(std::move(queryResult), &limit); } bool ChatHandler::HandleLookupAccountNameCommand(char* args) @@ -4386,15 +4374,15 @@ bool ChatHandler::HandleLookupAccountNameCommand(char* args) return false; LoginDatabase.escape_string(account); - // 0 1 2 3 4 - QueryResult* result = LoginDatabase.PQuery("SELECT a.id, username, ip, gmlevel, expansion FROM account a join account_logons b on (a.id=b.accountId) WHERE username " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%' ORDER BY loginTime DESC LIMIT 1"), account.c_str()); + // 0 1 2 3 4 + auto queryResult = LoginDatabase.PQuery("SELECT a.id, username, ip, gmlevel, expansion FROM account a join account_logons b on (a.id=b.accountId) WHERE username " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%' ORDER BY loginTime DESC LIMIT 1"), account.c_str()); - return ShowAccountListHelper(result, &limit); + return ShowAccountListHelper(std::move(queryResult), &limit); } -bool ChatHandler::ShowAccountListHelper(QueryResult* result, uint32* limit, bool title, bool error) +bool ChatHandler::ShowAccountListHelper(std::unique_ptr queryResult, uint32* limit, bool title, bool error) { - if (!result) + if (!queryResult) { if (error) SendSysMessage(LANG_ACCOUNT_LIST_EMPTY); @@ -4420,7 +4408,7 @@ bool ChatHandler::ShowAccountListHelper(QueryResult* result, uint32* limit, bool --*limit; } - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 account = fields[0].GetUInt32(); WorldSession* session = sWorld.FindSession(account); @@ -4434,9 +4422,7 @@ bool ChatHandler::ShowAccountListHelper(QueryResult* result, uint32* limit, bool PSendSysMessage(LANG_ACCOUNT_LIST_LINE_CONSOLE, account, fields[1].GetString(), char_name, fields[2].GetString(), fields[3].GetUInt32(), fields[4].GetUInt32()); } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); if (!m_session) // not output header for online case SendSysMessage(LANG_ACCOUNT_LIST_BAR); @@ -4457,9 +4443,9 @@ bool ChatHandler::HandleLookupPlayerIpCommand(char* args) std::string ip = ipStr; LoginDatabase.escape_string(ip); - QueryResult* result = LoginDatabase.PQuery("SELECT a.id, username, distinct ip FROM account a join account_logons b on (a.id=b.accountId) WHERE b.ip " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%' ORDER BY loginTime DESC LIMIT 1"), ip.c_str()); + auto queryResult = LoginDatabase.PQuery("SELECT a.id, username, distinct ip FROM account a join account_logons b on (a.id=b.accountId) WHERE b.ip " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%' ORDER BY loginTime DESC LIMIT 1"), ip.c_str()); - return LookupPlayerSearchCommand(result, &limit); + return LookupPlayerSearchCommand(std::move(queryResult), &limit); } bool ChatHandler::HandleLookupPlayerAccountCommand(char* args) @@ -4478,9 +4464,9 @@ bool ChatHandler::HandleLookupPlayerAccountCommand(char* args) LoginDatabase.escape_string(account); - QueryResult* result = LoginDatabase.PQuery("SELECT id,username FROM account WHERE username " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'"), account.c_str()); + auto queryResult = LoginDatabase.PQuery("SELECT id,username FROM account WHERE username " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'"), account.c_str()); - return LookupPlayerSearchCommand(result, &limit); + return LookupPlayerSearchCommand(std::move(queryResult), &limit); } bool ChatHandler::HandleLookupPlayerEmailCommand(char* args) @@ -4496,14 +4482,14 @@ bool ChatHandler::HandleLookupPlayerEmailCommand(char* args) std::string email = emailStr; LoginDatabase.escape_string(email); - QueryResult* result = LoginDatabase.PQuery("SELECT id,username FROM account WHERE email " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'"), email.c_str()); + auto queryResult = LoginDatabase.PQuery("SELECT id,username FROM account WHERE email " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'"), email.c_str()); - return LookupPlayerSearchCommand(result, &limit); + return LookupPlayerSearchCommand(std::move(queryResult), &limit); } -bool ChatHandler::LookupPlayerSearchCommand(QueryResult* result, uint32* limit) +bool ChatHandler::LookupPlayerSearchCommand(std::unique_ptr queryResult, uint32* limit) { - if (!result) + if (!queryResult) { PSendSysMessage(LANG_NO_PLAYERS_FOUND); SetSentErrorMessage(true); @@ -4522,26 +4508,22 @@ bool ChatHandler::LookupPlayerSearchCommand(QueryResult* result, uint32* limit) if (limit && *limit == 0) break; - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 acc_id = fields[0].GetUInt32(); std::string acc_name = fields[1].GetCppString(); ///- Get the characters for account id - QueryResult* chars = CharacterDatabase.PQuery("SELECT guid, name, race, class, level FROM characters WHERE account = %u", acc_id); + auto chars = CharacterDatabase.PQuery("SELECT guid, name, race, class, level FROM characters WHERE account = %u", acc_id); if (chars) { if (chars->GetRowCount()) { PSendSysMessage(LANG_LOOKUP_PLAYER_ACCOUNT, acc_name.c_str(), acc_id); - ShowPlayerListHelper(chars, limit, true, false); + ShowPlayerListHelper(std::move(chars), limit, true, false); } - else - delete chars; } } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); if (*limit == limit_original) // empty accounts only { diff --git a/src/game/Chat/Level3.cpp b/src/game/Chat/Level3.cpp index de7e5aafe31..d53577098a3 100644 --- a/src/game/Chat/Level3.cpp +++ b/src/game/Chat/Level3.cpp @@ -137,15 +137,14 @@ bool ChatHandler::HandleAHBotItemCommand(char* args) { std::string itemName = cId; WorldDatabase.escape_string(itemName); - QueryResult* result = WorldDatabase.PQuery("SELECT entry FROM item_template WHERE name = '%s'", itemName.c_str()); - if (!result) + auto queryResult = WorldDatabase.PQuery("SELECT entry FROM item_template WHERE name = '%s'", itemName.c_str()); + if (!queryResult) { PSendSysMessage(LANG_COMMAND_COULDNOTFIND, cId); SetSentErrorMessage(true); return false; } - itemId = result->Fetch()->GetUInt16(); - delete result; + itemId = queryResult->Fetch()->GetUInt16(); } ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId); if (!proto) @@ -2098,15 +2097,14 @@ bool ChatHandler::HandleAddItemCommand(char* args) { std::string itemName = cId; WorldDatabase.escape_string(itemName); - QueryResult* result = WorldDatabase.PQuery("SELECT entry FROM item_template WHERE name = '%s'", itemName.c_str()); - if (!result) + auto queryResult = WorldDatabase.PQuery("SELECT entry FROM item_template WHERE name = '%s'", itemName.c_str()); + if (!queryResult) { PSendSysMessage(LANG_COMMAND_COULDNOTFIND, cId); SetSentErrorMessage(true); return false; } - itemId = result->Fetch()->GetUInt16(); - delete result; + itemId = queryResult->Fetch()->GetUInt16(); } int32 count; @@ -2264,25 +2262,24 @@ bool ChatHandler::HandleListItemCommand(char* args) // inventory case uint32 inv_count = 0; - QueryResult* result = CharacterDatabase.PQuery("SELECT COUNT(item_template) FROM character_inventory WHERE item_template='%u'", item_id); - if (result) + auto queryResult = CharacterDatabase.PQuery("SELECT COUNT(item_template) FROM character_inventory WHERE item_template='%u'", item_id); + if (queryResult) { - inv_count = (*result)[0].GetUInt32(); - delete result; + inv_count = (*queryResult)[0].GetUInt32(); } - result = CharacterDatabase.PQuery( + queryResult = CharacterDatabase.PQuery( // 0 1 2 3 4 5 "SELECT ci.item, cibag.slot AS bag, ci.slot, ci.guid, characters.account,characters.name " "FROM character_inventory AS ci LEFT JOIN character_inventory AS cibag ON (cibag.item=ci.bag),characters " "WHERE ci.item_template='%u' AND ci.guid = characters.guid LIMIT %u ", item_id, uint32(count)); - if (result) + if (queryResult) { do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 item_guid = fields[0].GetUInt32(); uint32 item_bag = fields[1].GetUInt32(); uint32 item_slot = fields[2].GetUInt32(); @@ -2303,11 +2300,9 @@ bool ChatHandler::HandleListItemCommand(char* args) PSendSysMessage(LANG_ITEMLIST_SLOT, item_guid, owner_name.c_str(), owner_guid, owner_acc, item_pos); } - while (result->NextRow()); - - uint32 res_count = uint32(result->GetRowCount()); + while (queryResult->NextRow()); - delete result; + uint32 res_count = uint32(queryResult->GetRowCount()); if (count > res_count) count -= res_count; @@ -2317,16 +2312,15 @@ bool ChatHandler::HandleListItemCommand(char* args) // mail case uint32 mail_count = 0; - result = CharacterDatabase.PQuery("SELECT COUNT(item_template) FROM mail_items WHERE item_template='%u'", item_id); - if (result) + queryResult = CharacterDatabase.PQuery("SELECT COUNT(item_template) FROM mail_items WHERE item_template='%u'", item_id); + if (queryResult) { - mail_count = (*result)[0].GetUInt32(); - delete result; + mail_count = (*queryResult)[0].GetUInt32(); } if (count > 0) { - result = CharacterDatabase.PQuery( + queryResult = CharacterDatabase.PQuery( // 0 1 2 3 4 5 6 "SELECT mail_items.item_guid, mail.sender, mail.receiver, char_s.account, char_s.name, char_r.account, char_r.name " "FROM mail,mail_items,characters as char_s,characters as char_r " @@ -2334,13 +2328,13 @@ bool ChatHandler::HandleListItemCommand(char* args) item_id, uint32(count)); } else - result = nullptr; + queryResult.reset(); - if (result) + if (queryResult) { do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 item_guid = fields[0].GetUInt32(); uint32 item_s = fields[1].GetUInt32(); uint32 item_r = fields[2].GetUInt32(); @@ -2354,11 +2348,9 @@ bool ChatHandler::HandleListItemCommand(char* args) PSendSysMessage(LANG_ITEMLIST_MAIL, item_guid, item_s_name.c_str(), item_s, item_s_acc, item_r_name.c_str(), item_r, item_r_acc, item_pos); } - while (result->NextRow()); - - uint32 res_count = uint32(result->GetRowCount()); + while (queryResult->NextRow()); - delete result; + uint32 res_count = uint32(queryResult->GetRowCount()); if (count > res_count) count -= res_count; @@ -2368,29 +2360,28 @@ bool ChatHandler::HandleListItemCommand(char* args) // auction case uint32 auc_count = 0; - result = CharacterDatabase.PQuery("SELECT COUNT(item_template) FROM auction WHERE item_template='%u'", item_id); - if (result) + queryResult = CharacterDatabase.PQuery("SELECT COUNT(item_template) FROM auction WHERE item_template='%u'", item_id); + if (queryResult) { - auc_count = (*result)[0].GetUInt32(); - delete result; + auc_count = (*queryResult)[0].GetUInt32(); } if (count > 0) { - result = CharacterDatabase.PQuery( + queryResult = CharacterDatabase.PQuery( // 0 1 2 3 "SELECT auction.itemguid, auction.itemowner, characters.account, characters.name " "FROM auction,characters WHERE auction.item_template='%u' AND characters.guid = auction.itemowner LIMIT %u", item_id, uint32(count)); } else - result = nullptr; + queryResult.reset(); - if (result) + if (queryResult) { do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 item_guid = fields[0].GetUInt32(); uint32 owner = fields[1].GetUInt32(); uint32 owner_acc = fields[2].GetUInt32(); @@ -2400,31 +2391,28 @@ bool ChatHandler::HandleListItemCommand(char* args) PSendSysMessage(LANG_ITEMLIST_AUCTION, item_guid, owner_name.c_str(), owner, owner_acc, item_pos); } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); } // guild bank case uint32 guild_count = 0; - result = CharacterDatabase.PQuery("SELECT COUNT(item_entry) FROM guild_bank_item WHERE item_entry='%u'", item_id); - if (result) + queryResult = CharacterDatabase.PQuery("SELECT COUNT(item_entry) FROM guild_bank_item WHERE item_entry='%u'", item_id); + if (queryResult) { - guild_count = (*result)[0].GetUInt32(); - delete result; + guild_count = (*queryResult)[0].GetUInt32(); } - result = CharacterDatabase.PQuery( + queryResult = CharacterDatabase.PQuery( // 0 1 2 "SELECT gi.item_guid, gi.guildid, guild.name " "FROM guild_bank_item AS gi, guild WHERE gi.item_entry='%u' AND gi.guildid = guild.guildid LIMIT %u ", item_id, uint32(count)); - if (result) + if (queryResult) { do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 item_guid = fields[0].GetUInt32(); uint32 guild_guid = fields[1].GetUInt32(); std::string guild_name = fields[2].GetCppString(); @@ -2433,11 +2421,9 @@ bool ChatHandler::HandleListItemCommand(char* args) PSendSysMessage(LANG_ITEMLIST_GUILD, item_guid, guild_name.c_str(), guild_guid, item_pos); } - while (result->NextRow()); - - uint32 res_count = uint32(result->GetRowCount()); + while (queryResult->NextRow()); - delete result; + uint32 res_count = uint32(queryResult->GetRowCount()); if (count > res_count) count -= res_count; @@ -2544,7 +2530,7 @@ bool ChatHandler::HandleListObjectCommand(char* args) }; std::set tempData; - std::unique_ptr result; + std::unique_ptr queryResult; uint32 counter = 0; uint32 worldCounter = 0; uint32 zoneCounter = 0; @@ -2558,7 +2544,7 @@ bool ChatHandler::HandleListObjectCommand(char* args) { do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); TempGobData data; data.guid = fields[0].GetUInt32(); data.x = fields[1].GetFloat(); @@ -2596,7 +2582,7 @@ bool ChatHandler::HandleListObjectCommand(char* args) tempData.emplace(data); worldCounter++; - } while (result->NextRow()); + } while (queryResult->NextRow()); }; // this lambda just fill tempData with request data (expect guid, position_x, position_y, position_z, map) in that order! @@ -2605,7 +2591,7 @@ bool ChatHandler::HandleListObjectCommand(char* args) { do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); TempGobData data; data.guid = fields[0].GetUInt32(); data.x = fields[1].GetFloat(); @@ -2618,39 +2604,39 @@ bool ChatHandler::HandleListObjectCommand(char* args) worldCounter++; tempData.emplace(data); - } while (result->NextRow()); + } while (queryResult->NextRow()); }; // query gameobject - result.reset(WorldDatabase.PQuery( + queryResult = WorldDatabase.PQuery( "SELECT guid, position_x, position_y, position_z, map " "FROM gameobject " "WHERE id = '%u'", - go_id)); + go_id); - if (result) + if (queryResult) player ? AddPlayerData() : AddSimpleData(); // query gameobject_spawn_entry queryTableNameIndex = 1; - result.reset(WorldDatabase.PQuery( + queryResult = WorldDatabase.PQuery( "SELECT a.guid, b.position_x, b.position_y, b.position_z, b.map " "FROM gameobject_spawn_entry a LEFT JOIN gameobject b ON a.guid = b.guid " "WHERE a.entry = '%u'", - go_id)); + go_id); - if (result) + if (queryResult) player ? AddPlayerData() : AddSimpleData(); // query spawn_group_entry queryTableNameIndex = 2; - result.reset(WorldDatabase.PQuery( + queryResult = WorldDatabase.PQuery( "SELECT d.guid, d.position_x, d.position_y, d.position_z, d.map " "FROM spawn_group_entry a LEFT JOIN spawn_group b ON a.Id = b.Id LEFT JOIN spawn_group_spawn c ON a.ID = c.Id LEFT JOIN gameobject d ON c.Guid = d.guid " "WHERE a.Entry = '%u' AND b.Type = 1", - go_id)); + go_id); - if (result) + if (queryResult) player ? AddPlayerData() : AddSimpleData(); // send result to client @@ -2852,33 +2838,33 @@ bool ChatHandler::HandleListCreatureCommand(char* args) }; // query creature - result.reset(WorldDatabase.PQuery( + result = WorldDatabase.PQuery( "SELECT guid, position_x, position_y, position_z, map " "FROM creature " "WHERE id = '%u'", - cr_id)); + cr_id); if (result) player ? AddPlayerData() : AddSimpleData(); // query gameobject_spawn_entry queryTableNameIndex = 1; - result.reset(WorldDatabase.PQuery( + result = WorldDatabase.PQuery( "SELECT a.guid, b.position_x, b.position_y, b.position_z, b.map " "FROM creature_spawn_entry a LEFT JOIN creature b ON a.guid = b.guid " "WHERE a.entry = '%u'", - cr_id)); + cr_id); if (result) player ? AddPlayerData() : AddSimpleData(); // query spawn_group_entry queryTableNameIndex = 2; - result.reset(WorldDatabase.PQuery( + result = WorldDatabase.PQuery( "SELECT d.guid, d.position_x, d.position_y, d.position_z, d.map " "FROM spawn_group_entry a LEFT JOIN spawn_group b ON a.Id = b.Id LEFT JOIN spawn_group_spawn c ON a.ID = c.Id LEFT JOIN creature d ON c.Guid = d.guid " "WHERE a.Entry = '%u' AND b.Type = 0", - cr_id)); + cr_id); if (result) player ? AddPlayerData() : AddSimpleData(); @@ -5792,9 +5778,9 @@ bool ChatHandler::HandleBanInfoCharacterCommand(char* args) bool ChatHandler::HandleBanInfoHelper(uint32 accountid, char const* accountname) { - QueryResult* result = LoginDatabase.PQuery("SELECT FROM_UNIXTIME(banned_at),expires_at-banned_at,active,expires_at,reason,banned_by,unbanned_at,unbanned_by " - "FROM account_banned WHERE account_id = '%u' ORDER BY banned_at ASC", accountid); - if (!result) + auto queryResult = LoginDatabase.PQuery("SELECT FROM_UNIXTIME(banned_at),expires_at-banned_at,active,expires_at,reason,banned_by,unbanned_at,unbanned_by " + "FROM account_banned WHERE account_id = '%u' ORDER BY banned_at ASC", accountid); + if (!queryResult) { PSendSysMessage(LANG_BANINFO_NOACCOUNTBAN, accountname); return true; @@ -5803,7 +5789,7 @@ bool ChatHandler::HandleBanInfoHelper(uint32 accountid, char const* accountname) PSendSysMessage(LANG_BANINFO_BANHISTORY, accountname); do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); time_t expiresAt = time_t(fields[3].GetUInt64()); bool active = false; @@ -5823,9 +5809,8 @@ bool ChatHandler::HandleBanInfoHelper(uint32 accountid, char const* accountname) PSendSysMessage(LANG_BANINFO_HISTORYENTRY, fields[0].GetString(), bantime.c_str(), active ? GetMangosString(LANG_BANINFO_YES) : GetMangosString(LANG_BANINFO_NO), fields[4].GetString(), fields[5].GetString()); } - while (result->NextRow()); + while (queryResult->NextRow()); - delete result; return true; } @@ -5844,20 +5829,19 @@ bool ChatHandler::HandleBanInfoIPCommand(char* args) std::string IP = cIP; LoginDatabase.escape_string(IP); - QueryResult* result = LoginDatabase.PQuery("SELECT ip, FROM_UNIXTIME(banned_at), FROM_UNIXTIME(expires_at), expires_at-UNIX_TIMESTAMP(), reason,banned_by,expires_at-banned_at" - "FROM ip_banned WHERE ip = '%s'", IP.c_str()); - if (!result) + auto queryResult = LoginDatabase.PQuery("SELECT ip, FROM_UNIXTIME(banned_at), FROM_UNIXTIME(expires_at), expires_at-UNIX_TIMESTAMP(), reason,banned_by,expires_at-banned_at" + "FROM ip_banned WHERE ip = '%s'", IP.c_str()); + if (!queryResult) { PSendSysMessage(LANG_BANINFO_NOIP); return true; } - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); bool permanent = !fields[6].GetUInt64(); PSendSysMessage(LANG_BANINFO_IPENTRY, fields[0].GetString(), fields[1].GetString(), permanent ? GetMangosString(LANG_BANINFO_NEVER) : fields[2].GetString(), permanent ? GetMangosString(LANG_BANINFO_INFINITE) : secsToTimeString(fields[3].GetUInt64(), true).c_str(), fields[4].GetString(), fields[5].GetString()); - delete result; return true; } @@ -5871,14 +5855,14 @@ bool ChatHandler::HandleBanListCharacterCommand(char* args) std::string filter = cFilter; LoginDatabase.escape_string(filter); - std::unique_ptr result(CharacterDatabase.PQuery("SELECT account FROM characters WHERE name " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'"), filter.c_str())); - if (!result) + auto queryResult = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'"), filter.c_str()); + if (!queryResult) { PSendSysMessage(LANG_BANLIST_NOCHARACTER); return true; } - return HandleBanListHelper(std::move(result)); + return HandleBanListHelper(std::move(queryResult)); } bool ChatHandler::HandleBanListAccountCommand(char* args) @@ -5898,9 +5882,9 @@ bool ChatHandler::HandleBanListAccountCommand(char* args) } else { - queryResult.reset(LoginDatabase.PQuery("SELECT account.id, username FROM account, account_banned" - " WHERE account.id = account_banned.account_id AND active = 1 AND username " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'")" GROUP BY account.id", - filter.c_str())); + queryResult = LoginDatabase.PQuery("SELECT account.id, username FROM account, account_banned" + " WHERE account.id = account_banned.account_id AND active = 1 AND username " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'")" GROUP BY account.id", + filter.c_str()); } if (!queryResult) @@ -5924,12 +5908,11 @@ bool ChatHandler::HandleBanListHelper(std::unique_ptr queryResult) Field* fields = queryResult->Fetch(); uint32 accountid = fields[0].GetUInt32(); - QueryResult* banresult = LoginDatabase.PQuery("SELECT account.username FROM account,account_banned WHERE account_banned.account_id='%u' AND account_banned.account_id=account.id", accountid); + auto banresult = LoginDatabase.PQuery("SELECT account.username FROM account,account_banned WHERE account_banned.account_id='%u' AND account_banned.account_id=account.id", accountid); if (banresult) { Field* fields2 = banresult->Fetch(); PSendSysMessage("%s", fields2[0].GetString()); - delete banresult; } } while (queryResult->NextRow()); @@ -5956,7 +5939,7 @@ bool ChatHandler::HandleBanListHelper(std::unique_ptr queryResult) sAccountMgr.GetName(account_id, account_name); // No SQL injection. id is uint32. - QueryResult* banInfo = LoginDatabase.PQuery("SELECT banned_at,expires_at,banned_by,reason,unbanned_at,unbanned_by FROM account_banned WHERE account_id = %u ORDER BY expires_at", account_id); + auto banInfo = LoginDatabase.PQuery("SELECT banned_at,expires_at,banned_by,reason,unbanned_at,unbanned_by FROM account_banned WHERE account_id = %u ORDER BY expires_at", account_id); if (banInfo) { Field* fields2 = banInfo->Fetch(); @@ -5982,7 +5965,6 @@ bool ChatHandler::HandleBanListHelper(std::unique_ptr queryResult) } } while (banInfo->NextRow()); - delete banInfo; } } while (queryResult->NextRow()); @@ -6010,9 +5992,9 @@ bool ChatHandler::HandleBanListIPCommand(char* args) } else { - queryResult.reset(LoginDatabase.PQuery("SELECT ip,banned_at,expires_at,banned_by,reason FROM ip_banned" - " WHERE (banned_at=expires_at OR expires_at>UNIX_TIMESTAMP()) AND ip " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'") - " ORDER BY expires_at", filter.c_str())); + queryResult = LoginDatabase.PQuery("SELECT ip,banned_at,expires_at,banned_by,reason FROM ip_banned" + " WHERE (banned_at=expires_at OR expires_at>UNIX_TIMESTAMP()) AND ip " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'") + " ORDER BY expires_at", filter.c_str()); } if (!queryResult) @@ -6842,9 +6824,9 @@ bool ChatHandler::HandleServerSetMotdCommand(char* args) return true; } -bool ChatHandler::ShowPlayerListHelper(QueryResult* result, uint32* limit, bool title, bool error) +bool ChatHandler::ShowPlayerListHelper(std::unique_ptr queryResult, uint32* limit, bool title, bool error) { - if (!result) + if (!queryResult) { if (error) { @@ -6861,7 +6843,7 @@ bool ChatHandler::ShowPlayerListHelper(QueryResult* result, uint32* limit, bool SendSysMessage(LANG_CHARACTERS_LIST_BAR); } - if (result) + if (queryResult) { ///- Circle through them. Display username and GM level do @@ -6874,7 +6856,7 @@ bool ChatHandler::ShowPlayerListHelper(QueryResult* result, uint32* limit, bool --*limit; } - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 guid = fields[0].GetUInt32(); std::string name = fields[1].GetCppString(); uint8 race = fields[2].GetUInt8(); @@ -6892,9 +6874,7 @@ bool ChatHandler::ShowPlayerListHelper(QueryResult* result, uint32* limit, bool else PSendSysMessage(LANG_CHARACTERS_LIST_LINE_CHAT, guid, name.c_str(), name.c_str(), race_name, class_name, level); } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); } if (!m_session) @@ -6914,9 +6894,9 @@ bool ChatHandler::HandleAccountCharactersCommand(char* args) return false; ///- Get the characters for account id - QueryResult* result = CharacterDatabase.PQuery("SELECT guid, name, race, class, level FROM characters WHERE account = %u", account_id); + auto queryResult = CharacterDatabase.PQuery("SELECT guid, name, race, class, level FROM characters WHERE account = %u", account_id); - return ShowPlayerListHelper(result); + return ShowPlayerListHelper(std::move(queryResult)); } /// Set/Unset the expansion level for an account @@ -7528,12 +7508,11 @@ bool ChatHandler::HandleLinkAddCommand(char* args) if (!ExtractUInt32(&args, flags)) return false; - if (QueryResult* result = WorldDatabase.PQuery("SELECT flag FROM creature_linking WHERE guid = '%u' AND master_guid = '%u'", player->GetSelectionGuid().GetCounter(), masterCounter)) + if (auto queryResult = WorldDatabase.PQuery("SELECT flag FROM creature_linking WHERE guid = '%u' AND master_guid = '%u'", player->GetSelectionGuid().GetCounter(), masterCounter)) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 flag = fields[0].GetUInt32(); PSendSysMessage("Link already exists with flag = %u", flag); - delete result; } else { @@ -7559,9 +7538,8 @@ bool ChatHandler::HandleLinkRemoveCommand(char* args) if (!ExtractUInt32(&args, masterCounter)) return false; - if (QueryResult* result = WorldDatabase.PQuery("SELECT flag FROM creature_linking WHERE guid = '%u' AND master_guid = '%u'", player->GetSelectionGuid().GetCounter(), masterCounter)) + if (auto queryResult = WorldDatabase.PQuery("SELECT flag FROM creature_linking WHERE guid = '%u' AND master_guid = '%u'", player->GetSelectionGuid().GetCounter(), masterCounter)) { - delete result; WorldDatabase.PExecute("DELETE FROM creature_linking WHERE guid = '%u' AND master_guid = '%u'", player->GetSelectionGuid().GetCounter(), masterCounter); PSendSysMessage("Deleted link for guid = %u and master_guid = %u", player->GetSelectionGuid().GetCounter(), masterCounter); } @@ -7590,10 +7568,8 @@ bool ChatHandler::HandleLinkEditCommand(char* args) if (!ExtractUInt32(&args, flags)) return false; - if (QueryResult* result = WorldDatabase.PQuery("SELECT flag FROM creature_linking WHERE guid = '%u' AND master_guid = '%u'", player->GetSelectionGuid().GetCounter(), masterCounter)) + if (auto queryResult = WorldDatabase.PQuery("SELECT flag FROM creature_linking WHERE guid = '%u' AND master_guid = '%u'", player->GetSelectionGuid().GetCounter(), masterCounter)) { - delete result; - if (flags) { WorldDatabase.PExecute("UPDATE creature_linking SET flags = flags | '%u' WHERE guid = '%u' AND master_guid = '%u'", flags, player->GetSelectionGuid().GetCounter(), masterCounter); @@ -7642,9 +7618,8 @@ bool ChatHandler::HandleLinkToggleCommand(char* args) if (!ExtractUInt32(&args, toggle)) return false; - if (QueryResult* result = WorldDatabase.PQuery("SELECT flag FROM creature_linking WHERE guid = '%u' AND master_guid = '%u'", player->GetSelectionGuid().GetCounter(), masterCounter)) + if (auto queryResult = WorldDatabase.PQuery("SELECT flag FROM creature_linking WHERE guid = '%u' AND master_guid = '%u'", player->GetSelectionGuid().GetCounter(), masterCounter)) { - delete result; if (toggle) { WorldDatabase.PExecute("UPDATE creature_linking SET flags = flags &~ '%u' WHERE guid = '%u' AND master_guid = '%u'", flags, player->GetSelectionGuid().GetCounter(), masterCounter); @@ -7687,21 +7662,19 @@ bool ChatHandler::HandleLinkCheckCommand(char* args) bool found = false; - if (QueryResult* result = WorldDatabase.PQuery("SELECT flag FROM creature_linking WHERE guid = '%u' AND master_guid = '%u'", player->GetSelectionGuid().GetCounter(), masterCounter)) + if (auto queryResult = WorldDatabase.PQuery("SELECT flag FROM creature_linking WHERE guid = '%u' AND master_guid = '%u'", player->GetSelectionGuid().GetCounter(), masterCounter)) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 flags = fields[0].GetUInt32(); PSendSysMessage("Link for guid = %u , master_guid = %u has flags = %u", player->GetSelectionGuid().GetCounter(), masterCounter, flags); - delete result; found = true; } - if (QueryResult* result = WorldDatabase.PQuery("SELECT flag FROM creature_linking WHERE guid = '%u' AND master_guid = '%u'", masterCounter, player->GetSelectionGuid().GetCounter())) + if (auto queryResult = WorldDatabase.PQuery("SELECT flag FROM creature_linking WHERE guid = '%u' AND master_guid = '%u'", masterCounter, player->GetSelectionGuid().GetCounter())) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 flags = fields[0].GetUInt32(); PSendSysMessage("Link for guid = %u , master_guid = %u has flags = %u", masterCounter, player->GetSelectionGuid().GetCounter(), flags); - delete result; found = true; } diff --git a/src/game/DBScripts/ScriptMgr.cpp b/src/game/DBScripts/ScriptMgr.cpp index ab0d912c365..47f124321a9 100644 --- a/src/game/DBScripts/ScriptMgr.cpp +++ b/src/game/DBScripts/ScriptMgr.cpp @@ -113,12 +113,12 @@ void ScriptMgr::LoadScripts(ScriptMapType scriptType) scripts.first = tablename; scripts.second.clear(); // need for reload support - // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 - std::unique_ptr result(WorldDatabase.PQuery("SELECT id, delay, command, datalong, datalong2, datalong3, buddy_entry, search_radius, data_flags, dataint, dataint2, dataint3, dataint4, datafloat, x, y, z, o, speed, condition_id FROM %s ORDER BY priority", tablename)); + // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 + auto queryResult = WorldDatabase.PQuery("SELECT id, delay, command, datalong, datalong2, datalong3, buddy_entry, search_radius, data_flags, dataint, dataint2, dataint3, dataint4, datafloat, x, y, z, o, speed, condition_id FROM %s ORDER BY priority", tablename); uint32 count = 0; - if (!result) + if (!queryResult) { BarGoLink bar(1); bar.step(); @@ -127,13 +127,13 @@ void ScriptMgr::LoadScripts(ScriptMapType scriptType) return; } - BarGoLink bar(result->GetRowCount()); + BarGoLink bar(queryResult->GetRowCount()); do { bar.step(); - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); ScriptInfo tmp; tmp.id = fields[0].GetUInt32(); @@ -964,7 +964,7 @@ void ScriptMgr::LoadScripts(ScriptMapType scriptType) ++count; } - while (result->NextRow()); + while (queryResult->NextRow()); m_scriptMaps[scriptType] = std::make_shared(scripts); diff --git a/src/game/Entities/CharacterHandler.cpp b/src/game/Entities/CharacterHandler.cpp index fcf30b237b7..430472a8ec9 100644 --- a/src/game/Entities/CharacterHandler.cpp +++ b/src/game/Entities/CharacterHandler.cpp @@ -333,12 +333,11 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket& recv_data) return; } - QueryResult* resultacct = LoginDatabase.PQuery("SELECT SUM(numchars) FROM realmcharacters WHERE acctid = '%u'", GetAccountId()); + auto resultacct = LoginDatabase.PQuery("SELECT SUM(numchars) FROM realmcharacters WHERE acctid = '%u'", GetAccountId()); if (resultacct) { Field* fields = resultacct->Fetch(); uint32 acctcharcount = fields[0].GetUInt32(); - delete resultacct; if (acctcharcount >= sWorld.getConfig(CONFIG_UINT32_CHARACTERS_PER_ACCOUNT)) { @@ -348,13 +347,12 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket& recv_data) } } - QueryResult* result = CharacterDatabase.PQuery("SELECT COUNT(guid) FROM characters WHERE account = '%u'", GetAccountId()); + auto queryResult = CharacterDatabase.PQuery("SELECT COUNT(guid) FROM characters WHERE account = '%u'", GetAccountId()); uint8 charcount = 0; - if (result) + if (queryResult) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); charcount = fields[0].GetUInt8(); - delete result; if (charcount >= sWorld.getConfig(CONFIG_UINT32_CHARACTERS_PER_REALM)) { @@ -392,13 +390,13 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket& recv_data) if (!AllowTwoSideAccounts || skipCinematics == CINEMATICS_SKIP_SAME_RACE || class_ == CLASS_DEATH_KNIGHT) { - QueryResult* result2 = CharacterDatabase.PQuery("SELECT level,race,class FROM characters WHERE account = '%u' %s", + auto queryResult2 = CharacterDatabase.PQuery("SELECT level,race,class FROM characters WHERE account = '%u' %s", GetAccountId(), (skipCinematics == CINEMATICS_SKIP_SAME_RACE || class_ == CLASS_DEATH_KNIGHT) ? "" : "LIMIT 1"); - if (result2) + if (queryResult2) { Team team_ = Player::TeamForRace(race_); - Field* field = result2->Fetch(); + Field* field = queryResult2->Fetch(); uint8 acc_race = field[1].GetUInt32(); if (GetSecurity() == SEC_PLAYER && class_ == CLASS_DEATH_KNIGHT) @@ -413,7 +411,6 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket& recv_data) { data << (uint8)CHAR_CREATE_UNIQUE_CLASS_LIMIT; SendPacket(data); - delete result2; return; } } @@ -434,7 +431,6 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket& recv_data) { data << (uint8)CHAR_CREATE_PVP_TEAMS_VIOLATION; SendPacket(data); - delete result2; return; } } @@ -443,10 +439,10 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket& recv_data) // TODO: check if cinematic already shown? (already logged in?; cinematic field) while ((skipCinematics == CINEMATICS_SKIP_SAME_RACE && !have_same_race) || class_ == CLASS_DEATH_KNIGHT) { - if (!result2->NextRow()) + if (!queryResult2->NextRow()) break; - field = result2->Fetch(); + field = queryResult2->Fetch(); acc_race = field[1].GetUInt32(); if (!have_same_race) @@ -464,7 +460,6 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket& recv_data) { data << (uint8)CHAR_CREATE_UNIQUE_CLASS_LIMIT; SendPacket(data); - delete result2; return; } } @@ -477,7 +472,6 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket& recv_data) } } } - delete result2; } } @@ -554,13 +548,12 @@ void WorldSession::HandleCharDeleteOpcode(WorldPacket& recv_data) uint32 lowguid = guid.GetCounter(); - QueryResult* result = CharacterDatabase.PQuery("SELECT account,name FROM characters WHERE guid='%u'", lowguid); - if (result) + auto queryResult = CharacterDatabase.PQuery("SELECT account,name FROM characters WHERE guid='%u'", lowguid); + if (queryResult) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); accountId = fields[0].GetUInt32(); name = fields[1].GetCppString(); - delete result; } // prevent deleting other players' characters using cheating tools @@ -1428,8 +1421,8 @@ void WorldSession::HandleCharCustomizeOpcode(WorldPacket& recv_data) uint8 gender, skin, face, hairStyle, hairColor, facialHair; recv_data >> gender >> skin >> hairColor >> hairStyle >> facialHair >> face; - QueryResult* result = CharacterDatabase.PQuery("SELECT at_login FROM characters WHERE guid ='%u'", guid.GetCounter()); - if (!result) + auto queryResult = CharacterDatabase.PQuery("SELECT at_login FROM characters WHERE guid ='%u'", guid.GetCounter()); + if (!queryResult) { WorldPacket data(SMSG_CHAR_CUSTOMIZE, 1); data << uint8(CHAR_CREATE_ERROR); @@ -1437,9 +1430,8 @@ void WorldSession::HandleCharCustomizeOpcode(WorldPacket& recv_data) return; } - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 at_loginFlags = fields[0].GetUInt32(); - delete result; if (!(at_loginFlags & AT_LOGIN_CUSTOMIZE)) { diff --git a/src/game/Entities/CreatureLinkingMgr.cpp b/src/game/Entities/CreatureLinkingMgr.cpp index 3fc1378268e..58a4105ddbc 100644 --- a/src/game/Entities/CreatureLinkingMgr.cpp +++ b/src/game/Entities/CreatureLinkingMgr.cpp @@ -233,22 +233,20 @@ bool CreatureLinkingMgr::IsLinkingEntryValid(uint32 slaveEntry, CreatureLinkingI // Check for uniqueness of mob whom is followed, on whom spawning is dependend if (pTmp->searchRange == 0 && pTmp->linkingFlag & (FLAG_FOLLOW | FLAG_CANT_SPAWN_IF_BOSS_DEAD | FLAG_CANT_SPAWN_IF_BOSS_ALIVE)) { - QueryResult* result = WorldDatabase.PQuery("SELECT guid FROM creature WHERE id=%u AND map=%u LIMIT 2", pTmp->masterId, pTmp->mapId); - if (!result) + auto queryResult = WorldDatabase.PQuery("SELECT guid FROM creature WHERE id=%u AND map=%u LIMIT 2", pTmp->masterId, pTmp->mapId); + if (!queryResult) { sLog.outErrorDb("`creature_linking_template` has FLAG_FOLLOW, but no master, (entry: %u, map: %u, master: %u)", slaveEntry, pTmp->mapId, pTmp->masterId); return false; } - if (result->GetRowCount() > 1) + if (queryResult->GetRowCount() > 1) { sLog.outErrorDb("`creature_linking_template` has FLAG_FOLLOW, but non unique master, (entry: %u, map: %u, master: %u)", slaveEntry, pTmp->mapId, pTmp->masterId); - delete result; return false; } - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); pTmp->masterDBGuid = fields[0].GetUInt32(); - delete result; } } diff --git a/src/game/Entities/MiscHandler.cpp b/src/game/Entities/MiscHandler.cpp index 2596cb5f9d8..3d17253d036 100644 --- a/src/game/Entities/MiscHandler.cpp +++ b/src/game/Entities/MiscHandler.cpp @@ -1098,14 +1098,14 @@ void WorldSession::HandleWhoisOpcode(WorldPacket& recv_data) uint32 accid = plr->GetSession()->GetAccountId(); - QueryResult* result = LoginDatabase.PQuery("SELECT username,email,ip FROM account a JOIN account_logons b ON(a.id=b.accountId) WHERE a.id=%u ORDER BY loginTime DESC LIMIT 1", accid); - if (!result) + auto queryResult = LoginDatabase.PQuery("SELECT username,email,ip FROM account a JOIN account_logons b ON(a.id=b.accountId) WHERE a.id=%u ORDER BY loginTime DESC LIMIT 1", accid); + if (!queryResult) { SendNotification(LANG_ACCOUNT_FOR_PLAYER_NOT_FOUND, charname.c_str()); return; } - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); std::string acc = fields[0].GetCppString(); if (acc.empty()) acc = "Unknown"; @@ -1122,8 +1122,6 @@ void WorldSession::HandleWhoisOpcode(WorldPacket& recv_data) data << msg; _player->GetSession()->SendPacket(data); - delete result; - DEBUG_LOG("Received whois command from player %s for character %s", GetPlayer()->GetName(), charname.c_str()); } diff --git a/src/game/Entities/NPCHandler.cpp b/src/game/Entities/NPCHandler.cpp index 2ba700220dc..042498bdad2 100644 --- a/src/game/Entities/NPCHandler.cpp +++ b/src/game/Entities/NPCHandler.cpp @@ -528,14 +528,14 @@ void WorldSession::SendStablePet(ObjectGuid guid) const firstSlot = PET_SAVE_AS_CURRENT; else { - QueryResult* result = CharacterDatabase.PQuery("SELECT owner, id, entry, level, name FROM character_pet WHERE owner = '%u' AND slot = '%u' ORDER BY slot", + auto queryResult = CharacterDatabase.PQuery("SELECT owner, id, entry, level, name FROM character_pet WHERE owner = '%u' AND slot = '%u' ORDER BY slot", _player->GetGUIDLow(), uint32(PET_SAVE_NOT_IN_SLOT)); - if (result) // dismissed pet + if (queryResult) // dismissed pet { do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); data << uint32(fields[1].GetUInt32()); // petnumber data << uint32(fields[2].GetUInt32()); // creature entry @@ -544,22 +544,20 @@ void WorldSession::SendStablePet(ObjectGuid guid) const data << uint8(0x01); // active ++num; - } while (result->NextRow()); - - delete result; + } while (queryResult->NextRow()); } } } - // 0 1 2 3 4 5 - QueryResult* result = CharacterDatabase.PQuery("SELECT owner, slot, id, entry, level, name FROM character_pet WHERE owner = '%u' AND slot >= '%u' AND slot <= '%u' ORDER BY slot", + // 0 1 2 3 4 5 + auto queryResult = CharacterDatabase.PQuery("SELECT owner, slot, id, entry, level, name FROM character_pet WHERE owner = '%u' AND slot >= '%u' AND slot <= '%u' ORDER BY slot", _player->GetGUIDLow(), uint32(firstSlot), uint32(PET_SAVE_LAST_STABLE_SLOT)); - if (result) + if (queryResult) { do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); data << uint32(fields[2].GetUInt32()); // petnumber data << uint32(fields[3].GetUInt32()); // creature entry @@ -569,9 +567,7 @@ void WorldSession::SendStablePet(ObjectGuid guid) const ++num; } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); } data.put(wpos, num); // set real data to placeholder @@ -671,13 +667,13 @@ void WorldSession::HandleStablePet(WorldPacket& recv_data) uint32 free_slot = 1; - QueryResult* result = CharacterDatabase.PQuery("SELECT owner,slot,id FROM character_pet WHERE owner = '%u' AND slot >= '%u' AND slot <= '%u' ORDER BY slot ", + auto queryResult = CharacterDatabase.PQuery("SELECT owner,slot,id FROM character_pet WHERE owner = '%u' AND slot >= '%u' AND slot <= '%u' ORDER BY slot ", _player->GetGUIDLow(), PET_SAVE_FIRST_STABLE_SLOT, PET_SAVE_LAST_STABLE_SLOT); - if (result) + if (queryResult) { do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 slot = fields[1].GetUInt32(); @@ -688,9 +684,7 @@ void WorldSession::HandleStablePet(WorldPacket& recv_data) // this slot not free, skip ++free_slot; } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); } if (free_slot > 0 && free_slot <= GetPlayer()->m_stableSlots) @@ -730,14 +724,13 @@ void WorldSession::HandleUnstablePet(WorldPacket& recv_data) uint32 creature_id = 0; uint32 slot = 0; - QueryResult* result = CharacterDatabase.PQuery("SELECT entry, slot FROM character_pet WHERE owner = '%u' AND id = '%u' AND slot >='%u' AND slot <= '%u'", + auto queryResult = CharacterDatabase.PQuery("SELECT entry, slot FROM character_pet WHERE owner = '%u' AND id = '%u' AND slot >='%u' AND slot <= '%u'", _player->GetGUIDLow(), petnumber, PET_SAVE_FIRST_STABLE_SLOT, PET_SAVE_LAST_STABLE_SLOT); - if (result) + if (queryResult) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); creature_id = fields[0].GetUInt32(); slot = fields[1].GetUInt32(); - delete result; } if (!creature_id) @@ -924,19 +917,18 @@ void WorldSession::HandleStableSwapPet(WorldPacket& recv_data) } // find swapped pet slot in stable - QueryResult* result = CharacterDatabase.PQuery("SELECT slot,entry FROM character_pet WHERE owner = '%u' AND id = '%u'", + auto queryResult = CharacterDatabase.PQuery("SELECT slot,entry FROM character_pet WHERE owner = '%u' AND id = '%u'", _player->GetGUIDLow(), pet_number); - if (!result) + if (!queryResult) { SendStableResult(STABLE_ERR_STABLE); return; } - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 slot = fields[0].GetUInt32(); uint32 creature_id = fields[1].GetUInt32(); - delete result; if (!creature_id) { diff --git a/src/game/Entities/Pet.cpp b/src/game/Entities/Pet.cpp index 6e1fc4f7ebe..d3c911967b8 100644 --- a/src/game/Entities/Pet.cpp +++ b/src/game/Entities/Pet.cpp @@ -92,20 +92,18 @@ SpellCastResult Pet::TryLoadFromDB(Unit* owner, uint32 petentry /*= 0*/, uint32 // any current or other non-stabled pet (for hunter "call pet") request << "FROM character_pet WHERE owner = '" << ownerid << "' AND (slot = '" << uint32(PET_SAVE_AS_CURRENT) << "' OR slot > '" << uint32(PET_SAVE_LAST_STABLE_SLOT) << "')"; - QueryResult* result = CharacterDatabase.PQuery("%s", request.str().c_str()); + auto queryResult = CharacterDatabase.PQuery("%s", request.str().c_str()); - if (!result) + if (!queryResult) return SPELL_FAILED_NO_PET; - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); petentry = fields[0].GetUInt32(); uint32 savedHealth = fields[1].GetUInt32(); uint32 summon_spell_id = fields[2].GetUInt32(); PetType petType = PetType(fields[3].GetUInt8()); - delete result; - // update for case of current pet "slot = 0" if (!petentry) return SPELL_FAILED_NO_PET; @@ -147,41 +145,40 @@ bool Pet::LoadPetFromDB(Player* owner, Position const& spawnPos, uint32 petentry uint32 ownerid = owner->GetGUIDLow(); - QueryResult* result; + std::unique_ptr queryResult; if (petnumber) // known petnumber entry 0 1 2(?) 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 - result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, slot, name, renamed, curhealth, curmana, curhappiness, abdata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType " + queryResult = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, slot, name, renamed, curhealth, curmana, curhappiness, abdata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType " "FROM character_pet WHERE owner = '%u' AND id = '%u'", ownerid, petnumber); else if (current) // current pet (slot 0) 0 1 2(?) 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 - result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, slot, name, renamed, curhealth, curmana, curhappiness, abdata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType " + queryResult = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, slot, name, renamed, curhealth, curmana, curhappiness, abdata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType " "FROM character_pet WHERE owner = '%u' AND slot = '%u'", ownerid, PET_SAVE_AS_CURRENT); else if (petentry) // known petentry entry (unique for summoned pet, but non unique for hunter pet (only from current or not stabled pets) // 0 1 2(?) 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 - result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, slot, name, renamed, curhealth, curmana, curhappiness, abdata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType " + queryResult = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, slot, name, renamed, curhealth, curmana, curhappiness, abdata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType " "FROM character_pet WHERE owner = '%u' AND entry = '%u' AND (slot = '%u' OR slot > '%u') ", ownerid, petentry, PET_SAVE_AS_CURRENT, PET_SAVE_LAST_STABLE_SLOT); else // any current or other non-stabled pet (for hunter "call pet") // 0 1 2(?) 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 - result = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, slot, name, renamed, curhealth, curmana, curhappiness, abdata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType " + queryResult = CharacterDatabase.PQuery("SELECT id, entry, owner, modelid, level, exp, Reactstate, slot, name, renamed, curhealth, curmana, curhappiness, abdata, savetime, resettalents_cost, resettalents_time, CreatedBySpell, PetType " "FROM character_pet WHERE owner = '%u' AND (slot = '%u' OR slot > '%u') ", ownerid, PET_SAVE_AS_CURRENT, PET_SAVE_LAST_STABLE_SLOT); - if (!result) + if (!queryResult) return false; - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); // update for case of current pet "slot = 0" petentry = fields[1].GetUInt32(); if (!petentry) { - delete result; return false; } @@ -189,7 +186,6 @@ bool Pet::LoadPetFromDB(Player* owner, Position const& spawnPos, uint32 petentry if (!creatureInfo) { sLog.outError("Pet entry %u does not exist but used at pet load (owner: %s).", petentry, owner->GetGuidStr().c_str()); - delete result; return false; } @@ -198,7 +194,6 @@ bool Pet::LoadPetFromDB(Player* owner, Position const& spawnPos, uint32 petentry if (permanentOnly && spellInfo && GetSpellDuration(spellInfo) > 0) { - delete result; return false; } @@ -207,7 +202,6 @@ bool Pet::LoadPetFromDB(Player* owner, Position const& spawnPos, uint32 petentry { if (!creatureInfo->isTameable(owner->CanTameExoticPets())) { - delete result; return false; } } @@ -228,7 +222,6 @@ bool Pet::LoadPetFromDB(Player* owner, Position const& spawnPos, uint32 petentry ChangePetSlot.PExecute(uint32(PET_SAVE_AS_CURRENT), pet_number); CharacterDatabase.CommitTransaction(); - delete result; return false; } owner->SetTemporaryUnsummonedPetNumber(0); @@ -240,7 +233,6 @@ bool Pet::LoadPetFromDB(Player* owner, Position const& spawnPos, uint32 petentry uint32 guid = pos.GetMap()->GenerateLocalLowGuid(HIGHGUID_PET); if (!Create(guid, pos, creatureInfo, pet_number)) { - delete result; return false; } @@ -249,7 +241,6 @@ bool Pet::LoadPetFromDB(Player* owner, Position const& spawnPos, uint32 petentry { Position pos = Pet::GetPetSpawnPosition(owner); owner->CastSpell(pos.x, pos.y, pos.z, summon_spell_id, TRIGGERED_IGNORE_GCD | TRIGGERED_IGNORE_COOLDOWNS); - delete result; return false; } @@ -263,7 +254,6 @@ bool Pet::LoadPetFromDB(Player* owner, Position const& spawnPos, uint32 petentry { pos.GetMap()->Add((Creature*)this); AIM_Initialize(); - delete result; return true; } @@ -385,18 +375,16 @@ bool Pet::LoadPetFromDB(Player* owner, Position const& spawnPos, uint32 petentry if (getPetType() == HUNTER_PET) { - result = CharacterDatabase.PQuery("SELECT genitive, dative, accusative, instrumental, prepositional FROM character_pet_declinedname WHERE owner = '%u' AND id = '%u'", owner->GetGUIDLow(), GetCharmInfo()->GetPetNumber()); + queryResult = CharacterDatabase.PQuery("SELECT genitive, dative, accusative, instrumental, prepositional FROM character_pet_declinedname WHERE owner = '%u' AND id = '%u'", owner->GetGUIDLow(), GetCharmInfo()->GetPetNumber()); - if (result) + if (queryResult) { delete m_declinedname; m_declinedname = new DeclinedName; - Field* fields2 = result->Fetch(); + Field* fields2 = queryResult->Fetch(); for (int i = 0; i < MAX_DECLINED_NAME_CASES; ++i) m_declinedname->name[i] = fields2[i].GetCppString(); - - delete result; } } @@ -571,16 +559,14 @@ void Pet::DeleteFromDB(uint32 guidlow, bool separate_transaction) void Pet::DeleteFromDB(Unit* owner, PetSaveMode slot) { - QueryResult* result = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u' AND slot = '%u' ", owner->GetGUIDLow(), uint32(slot)); - if (result) + auto queryResult = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u' AND slot = '%u' ", owner->GetGUIDLow(), uint32(slot)); + if (queryResult) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 petNumber = fields[0].GetUInt32(); if (petNumber) DeleteFromDB(petNumber); - - delete result; } } @@ -1322,16 +1308,16 @@ uint32 Pet::GetCurrentFoodBenefitLevel(uint32 itemlevel) const void Pet::_LoadSpellCooldowns() { - QueryResult* result = CharacterDatabase.PQuery("SELECT spell,time FROM pet_spell_cooldown WHERE guid = '%u'", m_charmInfo->GetPetNumber()); + auto queryResult = CharacterDatabase.PQuery("SELECT spell,time FROM pet_spell_cooldown WHERE guid = '%u'", m_charmInfo->GetPetNumber()); ByteBuffer cdData; uint32 cdCount = 0; - if (result) + if (queryResult) { auto curTime = GetMap()->GetCurrentClockTime(); do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 spell_id = fields[0].GetUInt32(); uint64 spell_time = fields[1].GetUInt64(); @@ -1362,9 +1348,7 @@ void Pet::_LoadSpellCooldowns() sLog.outDebug("Adding spell cooldown to %s, SpellID(%u), recDuration(%us).", GetGuidStr().c_str(), spell_id, spellCDDuration); #endif } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); if (cdCount && GetOwner() && GetOwner()->GetTypeId() == TYPEID_PLAYER) { @@ -1408,19 +1392,17 @@ void Pet::_SaveSpellCooldowns() bool Pet::_LoadSpells() { - std::unique_ptr result(CharacterDatabase.PQuery("SELECT spell,active FROM pet_spell WHERE guid = '%u'", m_charmInfo->GetPetNumber())); + auto queryResult = CharacterDatabase.PQuery("SELECT spell,active FROM pet_spell WHERE guid = '%u'", m_charmInfo->GetPetNumber()); - if (result) + if (queryResult) { do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); addSpell(fields[0].GetUInt32(), ActiveStates(fields[1].GetUInt8()), PETSPELL_UNCHANGED); } - while (result->NextRow()); - - return true; + while (queryResult->NextRow()); } return false; @@ -1488,13 +1470,13 @@ bool Pet::_LoadGuardianPetNumber() void Pet::_LoadAuras(uint32 timediff) { - QueryResult* result = CharacterDatabase.PQuery("SELECT caster_guid,item_guid,spell,stackcount,remaincharges,basepoints0,basepoints1,basepoints2,periodictime0,periodictime1,periodictime2,maxduration,remaintime,effIndexMask FROM pet_aura WHERE guid = '%u'", m_charmInfo->GetPetNumber()); + auto queryResult = CharacterDatabase.PQuery("SELECT caster_guid,item_guid,spell,stackcount,remaincharges,basepoints0,basepoints1,basepoints2,periodictime0,periodictime1,periodictime2,maxduration,remaintime,effIndexMask FROM pet_aura WHERE guid = '%u'", m_charmInfo->GetPetNumber()); - if (result) + if (queryResult) { do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); ObjectGuid casterGuid = ObjectGuid(fields[0].GetUInt64()); uint32 item_lowguid = fields[1].GetUInt32(); uint32 spellid = fields[2].GetUInt32(); @@ -1577,9 +1559,7 @@ void Pet::_LoadAuras(uint32 timediff) else delete holder; } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); } } @@ -2026,7 +2006,7 @@ void Pet::resetTalentsForAllPetsOf(Player* owner, Pet* online_pet /*= nullptr*/) // now need only reset for offline pets (all pets except online case) uint32 except_petnumber = online_pet ? online_pet->GetCharmInfo()->GetPetNumber() : 0; - QueryResult* resultPets = CharacterDatabase.PQuery( + auto resultPets = CharacterDatabase.PQuery( "SELECT id FROM character_pet WHERE owner = '%u' AND id <> '%u'", owner->GetGUIDLow(), except_petnumber); @@ -2034,14 +2014,13 @@ void Pet::resetTalentsForAllPetsOf(Player* owner, Pet* online_pet /*= nullptr*/) if (!resultPets) return; - QueryResult* result = CharacterDatabase.PQuery( + auto queryResult = CharacterDatabase.PQuery( "SELECT DISTINCT pet_spell.spell FROM pet_spell, character_pet " "WHERE character_pet.owner = '%u' AND character_pet.id = pet_spell.guid AND character_pet.id <> %u", owner->GetGUIDLow(), except_petnumber); - if (!result) + if (!queryResult) { - delete resultPets; return; } @@ -2064,14 +2043,12 @@ void Pet::resetTalentsForAllPetsOf(Player* owner, Pet* online_pet /*= nullptr*/) } while (resultPets->NextRow()); - delete resultPets; - ss << ") AND spell IN ("; bool need_execute = false; do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 spell = fields[0].GetUInt32(); @@ -2085,9 +2062,7 @@ void Pet::resetTalentsForAllPetsOf(Player* owner, Pet* online_pet /*= nullptr*/) need_execute = true; } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); if (!need_execute) return; diff --git a/src/game/Entities/PetitionsHandler.cpp b/src/game/Entities/PetitionsHandler.cpp index b364fe769d9..49d3334a4b1 100644 --- a/src/game/Entities/PetitionsHandler.cpp +++ b/src/game/Entities/PetitionsHandler.cpp @@ -210,20 +210,18 @@ void WorldSession::HandlePetitionBuyOpcode(WorldPacket& recv_data) // a petition is invalid, if both the owner and the type matches // we checked above, if this player is in an arenateam, so this must be data corruption - QueryResult* result = CharacterDatabase.PQuery("SELECT petitionguid FROM petition WHERE ownerguid = '%u' AND type = '%u'", _player->GetGUIDLow(), type); + auto queryResult = CharacterDatabase.PQuery("SELECT petitionguid FROM petition WHERE ownerguid = '%u' AND type = '%u'", _player->GetGUIDLow(), type); std::ostringstream ssInvalidPetitionGUIDs; - if (result) + if (queryResult) { do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); ssInvalidPetitionGUIDs << "'" << fields[0].GetUInt32() << "' , "; } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); } // delete petitions with the same guid as this one @@ -252,25 +250,24 @@ void WorldSession::HandlePetitionShowSignOpcode(WorldPacket& recv_data) // solve (possible) some strange compile problems with explicit use GUID_LOPART(petitionguid) at some GCC versions (wrong code optimization in compiler?) uint32 petitionguid_low = petitionguid.GetCounter(); - QueryResult* result = CharacterDatabase.PQuery("SELECT type FROM petition WHERE petitionguid = '%u'", petitionguid_low); - if (!result) + auto queryResult = CharacterDatabase.PQuery("SELECT type FROM petition WHERE petitionguid = '%u'", petitionguid_low); + if (!queryResult) { sLog.outError("any petition on server..."); return; } - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 type = fields[0].GetUInt32(); - delete result; // if guild petition and has guild => error, return; if (type == 9 && _player->GetGuildId()) return; - result = CharacterDatabase.PQuery("SELECT playerguid FROM petition_sign WHERE petitionguid = '%u'", petitionguid_low); + queryResult = CharacterDatabase.PQuery("SELECT playerguid FROM petition_sign WHERE petitionguid = '%u'", petitionguid_low); - // result==nullptr also correct in case no sign yet - if (result) - signs = (uint8)result->GetRowCount(); + // queryResult==nullptr also correct in case no sign yet + if (queryResult) + signs = (uint8)queryResult->GetRowCount(); DEBUG_LOG("CMSG_PETITION_SHOW_SIGNATURES petition: %s", petitionguid.GetString().c_str()); @@ -282,15 +279,14 @@ void WorldSession::HandlePetitionShowSignOpcode(WorldPacket& recv_data) for (uint8 i = 1; i <= signs; ++i) { - Field* fields2 = result->Fetch(); + Field* fields2 = queryResult->Fetch(); ObjectGuid signerGuid = ObjectGuid(HIGHGUID_PLAYER, fields2[0].GetUInt32()); data << ObjectGuid(signerGuid); // Player GUID data << uint32(0); // there 0 ... - result->NextRow(); + queryResult->NextRow(); } - delete result; SendPacket(data); } @@ -312,24 +308,23 @@ void WorldSession::SendPetitionQueryOpcode(ObjectGuid petitionguid) const { uint32 petitionLowGuid = petitionguid.GetCounter(); - QueryResult* result = CharacterDatabase.PQuery( + auto queryResult = CharacterDatabase.PQuery( "SELECT ownerguid, name, " " (SELECT COUNT(playerguid) FROM petition_sign WHERE petition_sign.petitionguid = '%u') AS signs, " " type " "FROM petition WHERE petitionguid = '%u'", petitionLowGuid, petitionLowGuid); - if (!result) + if (!queryResult) { DEBUG_LOG("CMSG_PETITION_QUERY failed for petition (GUID: %u)", petitionLowGuid); return; } - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); ObjectGuid ownerGuid = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32()); std::string name = fields[1].GetCppString(); //uint8 signs = fields[2].GetUInt8(); uint32 type = fields[3].GetUInt32(); - delete result; WorldPacket data(SMSG_PETITION_QUERY_RESPONSE, (4 + 8 + name.size() + 1 + 1 + 4 * 12 + 2 + 10)); data << uint32(petitionLowGuid); // guild/team guid (in mangos always same as GUID_LOPART(petition guid) @@ -386,13 +381,12 @@ void WorldSession::HandlePetitionRenameOpcode(WorldPacket& recv_data) if (!item) return; - QueryResult* result = CharacterDatabase.PQuery("SELECT type FROM petition WHERE petitionguid = '%u'", petitionGuid.GetCounter()); + auto queryResult = CharacterDatabase.PQuery("SELECT type FROM petition WHERE petitionguid = '%u'", petitionGuid.GetCounter()); - if (result) + if (queryResult) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); type = fields[0].GetUInt32(); - delete result; } else { @@ -452,26 +446,24 @@ void WorldSession::HandlePetitionSignOpcode(WorldPacket& recv_data) uint32 petitionLowGuid = petitionGuid.GetCounter(); - QueryResult* result = CharacterDatabase.PQuery( + auto queryResult = CharacterDatabase.PQuery( "SELECT ownerguid, " " (SELECT COUNT(playerguid) FROM petition_sign WHERE petition_sign.petitionguid = '%u') AS signs, " " type " "FROM petition WHERE petitionguid = '%u'", petitionLowGuid, petitionLowGuid); - if (!result) + if (!queryResult) { sLog.outError("any petition on server..."); return; } - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 ownerLowGuid = fields[0].GetUInt32(); ObjectGuid ownerGuid = ObjectGuid(HIGHGUID_PLAYER, ownerLowGuid); uint8 signs = fields[1].GetUInt8(); uint32 type = fields[2].GetUInt32(); - delete result; - if (ownerGuid == _player->GetObjectGuid()) return; @@ -532,11 +524,10 @@ void WorldSession::HandlePetitionSignOpcode(WorldPacket& recv_data) // client doesn't allow to sign petition two times by one character, but not check sign by another character from same account // not allow sign another player from already sign player account - result = CharacterDatabase.PQuery("SELECT playerguid FROM petition_sign WHERE player_account = '%u' AND petitionguid = '%u'", GetAccountId(), petitionLowGuid); + queryResult = CharacterDatabase.PQuery("SELECT playerguid FROM petition_sign WHERE player_account = '%u' AND petitionguid = '%u'", GetAccountId(), petitionLowGuid); - if (result) + if (queryResult) { - delete result; WorldPacket data(SMSG_PETITION_SIGN_RESULTS, (8 + 8 + 4)); data << ObjectGuid(petitionGuid); data << ObjectGuid(_player->GetObjectGuid()); @@ -586,13 +577,12 @@ void WorldSession::HandlePetitionDeclineOpcode(WorldPacket& recv_data) uint32 petitionLowGuid = petitionGuid.GetCounter(); - QueryResult* result = CharacterDatabase.PQuery("SELECT ownerguid FROM petition WHERE petitionguid = '%u'", petitionLowGuid); - if (!result) + auto queryResult = CharacterDatabase.PQuery("SELECT ownerguid FROM petition WHERE petitionguid = '%u'", petitionLowGuid); + if (!queryResult) return; - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); ObjectGuid ownerguid = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32()); - delete result; Player* owner = sObjectMgr.GetPlayer(ownerguid); if (owner) // petition owner online @@ -620,13 +610,12 @@ void WorldSession::HandleOfferPetitionOpcode(WorldPacket& recv_data) return; /// Get petition type and check - QueryResult* result = CharacterDatabase.PQuery("SELECT type FROM petition WHERE petitionguid = '%u'", petitionGuid.GetCounter()); - if (!result) + auto queryResult = CharacterDatabase.PQuery("SELECT type FROM petition WHERE petitionguid = '%u'", petitionGuid.GetCounter()); + if (!queryResult) return; - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 type = fields[0].GetUInt32(); - delete result; DEBUG_LOG("OFFER PETITION: type %u petition %s to %s", type, petitionGuid.GetString().c_str(), playerGuid.GetString().c_str()); @@ -685,10 +674,10 @@ void WorldSession::HandleOfferPetitionOpcode(WorldPacket& recv_data) /// Get petition signs count uint8 signs = 0; - result = CharacterDatabase.PQuery("SELECT playerguid FROM petition_sign WHERE petitionguid = '%u'", petitionGuid.GetCounter()); - // result==nullptr also correct charter without signs - if (result) - signs = (uint8)result->GetRowCount(); + queryResult = CharacterDatabase.PQuery("SELECT playerguid FROM petition_sign WHERE petitionguid = '%u'", petitionGuid.GetCounter()); + // queryResult==nullptr also correct charter without signs + if (queryResult) + signs = (uint8)queryResult->GetRowCount(); /// Send response WorldPacket data(SMSG_PETITION_SHOW_SIGNATURES, (8 + 8 + 4 + signs + signs * 12)); @@ -699,16 +688,15 @@ void WorldSession::HandleOfferPetitionOpcode(WorldPacket& recv_data) for (uint8 i = 1; i <= signs; ++i) { - Field* fields2 = result->Fetch(); + Field* fields2 = queryResult->Fetch(); ObjectGuid signerGuid = ObjectGuid(HIGHGUID_PLAYER, fields2[0].GetUInt32()); data << ObjectGuid(signerGuid); // Player GUID data << uint32(0); // there 0 ... - result->NextRow(); + queryResult->NextRow(); } - delete result; player->GetSession()->SendPacket(data); } @@ -729,14 +717,13 @@ void WorldSession::HandleTurnInPetitionOpcode(WorldPacket& recv_data) std::string name; // data - QueryResult* result = CharacterDatabase.PQuery("SELECT ownerguid, name, type FROM petition WHERE petitionguid = '%u'", petitionGuid.GetCounter()); - if (result) + auto queryResult = CharacterDatabase.PQuery("SELECT ownerguid, name, type FROM petition WHERE petitionguid = '%u'", petitionGuid.GetCounter()); + if (queryResult) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); ownerGuid = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32()); name = fields[1].GetCppString(); type = fields[2].GetUInt32(); - delete result; } else { @@ -777,8 +764,8 @@ void WorldSession::HandleTurnInPetitionOpcode(WorldPacket& recv_data) return; // signs - result = CharacterDatabase.PQuery("SELECT playerguid FROM petition_sign WHERE petitionguid = '%u'", petitionGuid.GetCounter()); - uint8 signs = result ? (uint8)result->GetRowCount() : 0; + queryResult = CharacterDatabase.PQuery("SELECT playerguid FROM petition_sign WHERE petitionguid = '%u'", petitionGuid.GetCounter()); + uint8 signs = queryResult ? (uint8)queryResult->GetRowCount() : 0; uint32 count = type == 9 ? sWorld.getConfig(CONFIG_UINT32_MIN_PETITION_SIGNS) : type - 1; if (signs < count) @@ -786,7 +773,6 @@ void WorldSession::HandleTurnInPetitionOpcode(WorldPacket& recv_data) WorldPacket data(SMSG_TURN_IN_PETITION_RESULTS, 4); data << uint32(PETITION_TURN_NEED_MORE_SIGNATURES); // need more signatures... SendPacket(data); - delete result; return; } @@ -795,7 +781,6 @@ void WorldSession::HandleTurnInPetitionOpcode(WorldPacket& recv_data) if (sGuildMgr.GetGuildByName(name)) { SendGuildCommandResult(GUILD_CREATE_S, name, ERR_GUILD_NAME_EXISTS_S); - delete result; return; } } @@ -804,7 +789,6 @@ void WorldSession::HandleTurnInPetitionOpcode(WorldPacket& recv_data) if (sObjectMgr.GetArenaTeamByName(name)) { SendArenaTeamCommandResult(ERR_ARENA_TEAM_CREATE_S, name, "", ERR_ARENA_TEAM_NAME_EXISTS_S); - delete result; return; } } @@ -813,7 +797,6 @@ void WorldSession::HandleTurnInPetitionOpcode(WorldPacket& recv_data) Item* item = _player->GetItemByGuid(petitionGuid); if (!item) { - delete result; return; } @@ -828,7 +811,6 @@ void WorldSession::HandleTurnInPetitionOpcode(WorldPacket& recv_data) if (!guild->Create(_player, name)) { delete guild; - delete result; return; } @@ -842,7 +824,7 @@ void WorldSession::HandleTurnInPetitionOpcode(WorldPacket& recv_data) // add members for (uint8 i = 0; i < signs; ++i) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); ObjectGuid signGuid = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32()); if (!signGuid) @@ -860,7 +842,7 @@ void WorldSession::HandleTurnInPetitionOpcode(WorldPacket& recv_data) session->SendGuildCommandResult(GUILD_FOUNDER_S, name, 0); } - result->NextRow(); + queryResult->NextRow(); } } else // or arena team @@ -870,7 +852,6 @@ void WorldSession::HandleTurnInPetitionOpcode(WorldPacket& recv_data) { sLog.outError("PetitionsHandler: arena team create failed."); delete at; - delete result; return; } @@ -886,19 +867,17 @@ void WorldSession::HandleTurnInPetitionOpcode(WorldPacket& recv_data) // add members for (uint8 i = 0; i < signs; ++i) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); ObjectGuid memberGUID = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32()); if (!memberGUID) continue; DEBUG_LOG("PetitionsHandler: adding arena member %s", memberGUID.GetString().c_str()); at->AddMember(memberGUID); - result->NextRow(); + queryResult->NextRow(); } } - delete result; - CharacterDatabase.BeginTransaction(); CharacterDatabase.PExecute("DELETE FROM petition WHERE petitionguid = '%u'", petitionGuid.GetCounter()); CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE petitionguid = '%u'", petitionGuid.GetCounter()); diff --git a/src/game/Entities/Player.cpp b/src/game/Entities/Player.cpp index f081ed43e5b..19d8ddd3f9d 100644 --- a/src/game/Entities/Player.cpp +++ b/src/game/Entities/Player.cpp @@ -4497,11 +4497,10 @@ void Player::DeleteFromDB(ObjectGuid playerguid, uint32 accountId, bool updateRe LeaveAllArenaTeams(playerguid); // the player was uninvited already on logout so just remove from group - QueryResult* resultGroup = CharacterDatabase.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", lowguid); + auto resultGroup = CharacterDatabase.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", lowguid); if (resultGroup) { uint32 groupId = (*resultGroup)[0].GetUInt32(); - delete resultGroup; if (Group* group = sObjectMgr.GetGroupById(groupId)) RemoveFromGroup(group, playerguid); } @@ -4514,8 +4513,8 @@ void Player::DeleteFromDB(ObjectGuid playerguid, uint32 accountId, bool updateRe // completely remove from the database case 0: { - // return back all mails with COD and Item 0 1 2 3 4 5 6 7 - QueryResult* resultMail = CharacterDatabase.PQuery("SELECT id,messageType,mailTemplateId,sender,subject,body,money,has_items FROM mail WHERE receiver='%u' AND has_items<>0 AND cod<>0", lowguid); + // return back all mails with COD and Item 0 1 2 3 4 5 6 7 + auto resultMail = CharacterDatabase.PQuery("SELECT id,messageType,mailTemplateId,sender,subject,body,money,has_items FROM mail WHERE receiver='%u' AND has_items<>0 AND cod<>0", lowguid); if (resultMail) { do @@ -4552,8 +4551,8 @@ void Player::DeleteFromDB(ObjectGuid playerguid, uint32 accountId, bool updateRe if (has_items) { // data needs to be at first place for Item::LoadFromDB - // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 - QueryResult* resultItems = CharacterDatabase.PQuery("SELECT itemEntry, creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, playedTime, text, item_guid, item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail_id); + // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 + auto resultItems = CharacterDatabase.PQuery("SELECT itemEntry, creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, playedTime, text, item_guid, item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail_id); if (resultItems) { do @@ -4581,8 +4580,6 @@ void Player::DeleteFromDB(ObjectGuid playerguid, uint32 accountId, bool updateRe draft.AddItem(pItem); } while (resultItems->NextRow()); - - delete resultItems; } } @@ -4593,16 +4590,14 @@ void Player::DeleteFromDB(ObjectGuid playerguid, uint32 accountId, bool updateRe draft.SetMoney(money).SendReturnToSender(pl_account, playerguid, ObjectGuid(HIGHGUID_PLAYER, sender)); } while (resultMail->NextRow()); - - delete resultMail; } // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet. // Get guids of character's pets, will deleted in transaction - QueryResult* resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'", lowguid); + auto resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'", lowguid); // delete char from friends list when selected chars is online (non existing - error) - QueryResult* resultFriend = CharacterDatabase.PQuery("SELECT DISTINCT guid FROM character_social WHERE friend = '%u'", lowguid); + auto resultFriend = CharacterDatabase.PQuery("SELECT DISTINCT guid FROM character_social WHERE friend = '%u'", lowguid); // NOW we can finally clear other DB data related to character CharacterDatabase.BeginTransaction(); @@ -4616,7 +4611,6 @@ void Player::DeleteFromDB(ObjectGuid playerguid, uint32 accountId, bool updateRe Pet::DeleteFromDB(petguidlow, false); } while (resultPets->NextRow()); - delete resultPets; } // cleanup friends for online players, offline case will cleanup later in code @@ -4635,7 +4629,6 @@ void Player::DeleteFromDB(ObjectGuid playerguid, uint32 accountId, bool updateRe } } while (resultFriend->NextRow()); - delete resultFriend; } CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'", lowguid); @@ -4709,7 +4702,7 @@ void Player::DeleteOldCharacters(uint32 keepDays) { sLog.outString("Player::DeleteOldChars: Deleting all characters which have been deleted %u days before...", keepDays); - QueryResult* resultChars = CharacterDatabase.PQuery("SELECT guid, deleteInfos_Account FROM characters WHERE deleteDate IS NOT NULL AND deleteDate < '" UI64FMTD "'", uint64(time(nullptr) - time_t(keepDays * DAY))); + auto resultChars = CharacterDatabase.PQuery("SELECT guid, deleteInfos_Account FROM characters WHERE deleteDate IS NOT NULL AND deleteDate < '" UI64FMTD "'", uint64(time(nullptr) - time_t(keepDays * DAY))); if (resultChars) { sLog.outString("Player::DeleteOldChars: Found %u character(s) to delete", uint32(resultChars->GetRowCount())); @@ -4720,7 +4713,6 @@ void Player::DeleteOldCharacters(uint32 keepDays) Player::DeleteFromDB(guid, charFields[1].GetUInt32(), true, true); } while (resultChars->NextRow()); - delete resultChars; } sLog.outString(); } @@ -7349,22 +7341,20 @@ uint32 Player::GetGuildIdFromDB(ObjectGuid guid) { uint32 lowguid = guid.GetCounter(); - QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", lowguid); - if (!result) + auto queryResult = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", lowguid); + if (!queryResult) return 0; - uint32 id = result->Fetch()[0].GetUInt32(); - delete result; + uint32 id = queryResult->Fetch()[0].GetUInt32(); return id; } uint32 Player::GetRankFromDB(ObjectGuid guid) { - QueryResult* result = CharacterDatabase.PQuery("SELECT `rank` FROM guild_member WHERE guid='%u'", guid.GetCounter()); - if (result) + auto queryResult = CharacterDatabase.PQuery("SELECT `rank` FROM guild_member WHERE guid='%u'", guid.GetCounter()); + if (queryResult) { - uint32 v = result->Fetch()[0].GetUInt32(); - delete result; + uint32 v = queryResult->Fetch()[0].GetUInt32(); return v; } return 0; @@ -7372,37 +7362,34 @@ uint32 Player::GetRankFromDB(ObjectGuid guid) uint32 Player::GetArenaTeamIdFromDB(ObjectGuid guid, ArenaType type) { - QueryResult* result = CharacterDatabase.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u' AND type='%u' LIMIT 1", guid.GetCounter(), type); - if (!result) + auto queryResult = CharacterDatabase.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u' AND type='%u' LIMIT 1", guid.GetCounter(), type); + if (!queryResult) return 0; - uint32 id = (*result)[0].GetUInt32(); - delete result; + uint32 id = (*queryResult)[0].GetUInt32(); return id; } uint32 Player::GetZoneIdFromDB(ObjectGuid guid) { uint32 lowguid = guid.GetCounter(); - QueryResult* result = CharacterDatabase.PQuery("SELECT zone FROM characters WHERE guid='%u'", lowguid); - if (!result) + auto queryResult = CharacterDatabase.PQuery("SELECT zone FROM characters WHERE guid='%u'", lowguid); + if (!queryResult) return 0; - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 zone = fields[0].GetUInt32(); - delete result; if (!zone) { // stored zone is zero, use generic and slow zone detection - result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", lowguid); - if (!result) + queryResult = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", lowguid); + if (!queryResult) return 0; - fields = result->Fetch(); + fields = queryResult->Fetch(); uint32 map = fields[0].GetUInt32(); float posx = fields[1].GetFloat(); float posy = fields[2].GetFloat(); float posz = fields[3].GetFloat(); - delete result; zone = sTerrainMgr.GetZoneId(map, posx, posy, posz); @@ -7417,13 +7404,12 @@ uint32 Player::GetLevelFromDB(ObjectGuid guid) { uint32 lowguid = guid.GetCounter(); - QueryResult* result = CharacterDatabase.PQuery("SELECT level FROM characters WHERE guid='%u'", lowguid); - if (!result) + auto queryResult = CharacterDatabase.PQuery("SELECT level FROM characters WHERE guid='%u'", lowguid); + if (!queryResult) return 0; - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 level = fields[0].GetUInt32(); - delete result; return level; } @@ -13723,7 +13709,7 @@ void Player::OnGossipSelect(WorldObject* pSource, uint32 gossipListId, uint32 me } else if (GetPlayerbotMgr()->GetPlayerBot(ObjectGuid(HIGHGUID_PLAYER, guidlo)) == nullptr) { - QueryResult* resultchar = CharacterDatabase.PQuery("SELECT COUNT(*) FROM characters WHERE online = '1' AND account = '%u'", m_session->GetAccountId()); + auto resultchar = CharacterDatabase.PQuery("SELECT COUNT(*) FROM characters WHERE online = '1' AND account = '%u'", m_session->GetAccountId()); if (resultchar) { Field* fields = resultchar->Fetch(); @@ -13733,13 +13719,11 @@ void Player::OnGossipSelect(WorldObject* pSource, uint32 gossipListId, uint32 me if (acctcharcount > maxnum) { ChatHandler(this).PSendSysMessage("|cffff0000You cannot summon anymore bots. (Current Max: |cffffffff%u|cffff0000)", maxnum); - delete resultchar; return; } } - delete resultchar; - QueryResult* resultlvl = CharacterDatabase.PQuery("SELECT level,name FROM characters WHERE guid = '%u'", guidlo); + auto resultlvl = CharacterDatabase.PQuery("SELECT level,name FROM characters WHERE guid = '%u'", guidlo); if (resultlvl) { Field* fields = resultlvl->Fetch(); @@ -13749,11 +13733,9 @@ void Player::OnGossipSelect(WorldObject* pSource, uint32 gossipListId, uint32 me if (charlvl > maxlvl) { ChatHandler(this).PSendSysMessage("|cffff0000You cannot summon |cffffffff[%s]|cffff0000, it's level is too high. (Current Max:lvl |cffffffff%u|cffff0000)", fields[1].GetString(), maxlvl); - delete resultlvl; return; } } - delete resultlvl; GetPlayerbotMgr()->LoginPlayerBot(ObjectGuid(HIGHGUID_PLAYER, guidlo)); this->ModifyMoney(-(int32)cost); @@ -16169,11 +16151,11 @@ void Player::_LoadBGData(QueryResult* result) bool Player::LoadPositionFromDB(ObjectGuid guid, uint32& mapid, float& x, float& y, float& z, float& o, bool& in_flight) { - QueryResult* result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'", guid.GetCounter()); - if (!result) + auto queryResult = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'", guid.GetCounter()); + if (!queryResult) return false; - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); x = fields[0].GetFloat(); y = fields[1].GetFloat(); @@ -16182,7 +16164,6 @@ bool Player::LoadPositionFromDB(ObjectGuid guid, uint32& mapid, float& x, float& mapid = fields[4].GetUInt32(); in_flight = !fields[5].GetCppString().empty(); - delete result; return true; } @@ -19061,19 +19042,17 @@ void Player::SetUInt32ValueInArray(Tokens& tokens, uint16 index, uint32 value) void Player::Customize(ObjectGuid guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair) { // 0 - QueryResult* result = CharacterDatabase.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", guid.GetCounter()); - if (!result) + auto queryResult = CharacterDatabase.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", guid.GetCounter()); + if (!queryResult) return; - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 player_bytes2 = fields[0].GetUInt32(); player_bytes2 &= ~0xFF; player_bytes2 |= facialHair; CharacterDatabase.PExecute("UPDATE characters SET gender = '%u', playerBytes = '%u', playerBytes2 = '%u' WHERE guid = '%u'", gender, skin | (face << 8) | (hairStyle << 16) | (hairColor << 24), player_bytes2, guid.GetCounter()); - - delete result; } void Player::SendAttackSwingDeadTarget() const @@ -19754,18 +19733,18 @@ void Player::RemovePetitionsAndSigns(ObjectGuid guid, uint32 type) { uint32 lowguid = guid.GetCounter(); - QueryResult* result; + std::unique_ptr queryResult; if (type == 10) - result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", lowguid); + queryResult = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", lowguid); else - result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", lowguid, type); + queryResult = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", lowguid, type); - if (result) + if (queryResult) { do // this part effectively does nothing, since the deletion / modification only takes place _after_ the PetitionQuery. Though I don't know if the result remains intact if I execute the delete query beforehand. { // and SendPetitionQueryOpcode reads data from the DB - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); ObjectGuid ownerguid = ObjectGuid(HIGHGUID_PLAYER, fields[0].GetUInt32()); ObjectGuid petitionguid = ObjectGuid(HIGHGUID_ITEM, fields[1].GetUInt32()); @@ -19774,9 +19753,7 @@ void Player::RemovePetitionsAndSigns(ObjectGuid guid, uint32 type) if (owner) owner->GetSession()->SendPetitionQueryOpcode(petitionguid); } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); if (type == 10) CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", lowguid); @@ -19801,20 +19778,18 @@ void Player::RemovePetitionsAndSigns(ObjectGuid guid, uint32 type) void Player::LeaveAllArenaTeams(ObjectGuid guid) { uint32 lowguid = guid.GetCounter(); - QueryResult* result = CharacterDatabase.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u'", lowguid); - if (!result) + auto queryResult = CharacterDatabase.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u'", lowguid); + if (!queryResult) return; do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); if (uint32 at_id = fields[0].GetUInt32()) if (ArenaTeam* at = sObjectMgr.GetArenaTeamById(at_id)) at->DelMember(guid); } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); } Difficulty Player::GetDifficulty(bool isRaid) const @@ -25175,12 +25150,12 @@ void Player::AddNewInstanceId(uint32 instanceId) void Player::_LoadCreatedInstanceTimers() { // 0 1 - QueryResult* result = CharacterDatabase.PQuery("SELECT ExpireTime, InstanceId FROM account_instances_entered WHERE AccountId = '%u'", m_session->GetAccountId()); - if (result) + auto queryResult = CharacterDatabase.PQuery("SELECT ExpireTime, InstanceId FROM account_instances_entered WHERE AccountId = '%u'", m_session->GetAccountId()); + if (queryResult) { do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); TimePoint expireTime = std::chrono::time_point_cast(Clock::from_time_t(fields[0].GetUInt64())); uint32 instanceId = fields[1].GetUInt32(); @@ -25188,9 +25163,7 @@ void Player::_LoadCreatedInstanceTimers() m_enteredInstances.emplace(instanceId, expireTime); } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); } } diff --git a/src/game/Globals/ObjectMgr.cpp b/src/game/Globals/ObjectMgr.cpp index 622c8daf6dd..52cd29dd6a5 100644 --- a/src/game/Globals/ObjectMgr.cpp +++ b/src/game/Globals/ObjectMgr.cpp @@ -2469,7 +2469,7 @@ void ObjectMgr::LoadGameObjects() sLog.outString(">> Loaded " SIZEFMTD " gameobjects", mGameObjectDataMap.size()); sLog.outString(); - queryResult.reset(WorldDatabase.PQuery("SELECT guid, animprogress, state, stringId, path_rotation0, path_rotation1, path_rotation2, path_rotation3 FROM gameobject_addon")); + queryResult = WorldDatabase.PQuery("SELECT guid, animprogress, state, stringId, path_rotation0, path_rotation1, path_rotation2, path_rotation3 FROM gameobject_addon"); do { Field* fields = queryResult->Fetch(); @@ -2648,12 +2648,11 @@ int32 ObjectMgr::GetPlayerMapIdByGUID(ObjectGuid const& guid) const if (Player* player = GetPlayer(guid)) return int32(player->GetMapId()); - QueryResult* result = CharacterDatabase.PQuery("SELECT map FROM characters WHERE guid = '%u'", guid.GetCounter()); + auto queryResult = CharacterDatabase.PQuery("SELECT map FROM characters WHERE guid = '%u'", guid.GetCounter()); - if (result) + if (queryResult) { - uint32 mapId = (*result)[0].GetUInt32(); - delete result; + uint32 mapId = (*queryResult)[0].GetUInt32(); return int32(mapId); } @@ -2668,12 +2667,10 @@ ObjectGuid ObjectMgr::GetPlayerGuidByName(std::string name) const CharacterDatabase.escape_string(name); // Player name safe to sending to DB (checked at login) and this function using - QueryResult* result = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str()); - if (result) + auto queryResult = CharacterDatabase.PQuery("SELECT guid FROM characters WHERE name = '%s'", name.c_str()); + if (queryResult) { - guid = ObjectGuid(HIGHGUID_PLAYER, (*result)[0].GetUInt32()); - - delete result; + guid = ObjectGuid(HIGHGUID_PLAYER, (*queryResult)[0].GetUInt32()); } return guid; @@ -2690,12 +2687,11 @@ bool ObjectMgr::GetPlayerNameByGUID(ObjectGuid guid, std::string& name) const uint32 lowguid = guid.GetCounter(); - QueryResult* result = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", lowguid); + auto queryResult = CharacterDatabase.PQuery("SELECT name FROM characters WHERE guid = '%u'", lowguid); - if (result) + if (queryResult) { - name = (*result)[0].GetCppString(); - delete result; + name = (*queryResult)[0].GetCppString(); return true; } @@ -2710,12 +2706,11 @@ Team ObjectMgr::GetPlayerTeamByGUID(ObjectGuid guid) const uint32 lowguid = guid.GetCounter(); - QueryResult* result = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", lowguid); + auto queryResult = CharacterDatabase.PQuery("SELECT race FROM characters WHERE guid = '%u'", lowguid); - if (result) + if (queryResult) { - uint8 race = (*result)[0].GetUInt8(); - delete result; + uint8 race = (*queryResult)[0].GetUInt8(); return Player::TeamForRace(race); } @@ -2733,11 +2728,10 @@ uint32 ObjectMgr::GetPlayerAccountIdByGUID(ObjectGuid guid) const uint32 lowguid = guid.GetCounter(); - QueryResult* result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", lowguid); - if (result) + auto queryResult = CharacterDatabase.PQuery("SELECT account FROM characters WHERE guid = '%u'", lowguid); + if (queryResult) { - uint32 acc = (*result)[0].GetUInt32(); - delete result; + uint32 acc = (*queryResult)[0].GetUInt32(); return acc; } @@ -2746,11 +2740,10 @@ uint32 ObjectMgr::GetPlayerAccountIdByGUID(ObjectGuid guid) const uint32 ObjectMgr::GetPlayerAccountIdByPlayerName(const std::string& name) const { - QueryResult* result = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str()); - if (result) + auto queryResult = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'", name.c_str()); + if (queryResult) { - uint32 acc = (*result)[0].GetUInt32(); - delete result; + uint32 acc = (*queryResult)[0].GetUInt32(); return acc; } @@ -6396,9 +6389,9 @@ void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp) // delete all old mails without item and without body immediately, if starting server if (!serverUp) CharacterDatabase.PExecute("DELETE FROM mail WHERE expire_time < '" UI64FMTD "' AND has_items = '0' AND body = ''", (uint64)basetime); - // 0 1 2 3 4 5 6 7 8 - QueryResult* result = CharacterDatabase.PQuery("SELECT id,messageType,sender,receiver,has_items,expire_time,cod,checked,mailTemplateId FROM mail WHERE expire_time < '" UI64FMTD "'", (uint64)basetime); - if (!result) + // 0 1 2 3 4 5 6 7 8 + auto queryResult = CharacterDatabase.PQuery("SELECT id,messageType,sender,receiver,has_items,expire_time,cod,checked,mailTemplateId FROM mail WHERE expire_time < '" UI64FMTD "'", (uint64)basetime); + if (!queryResult) { BarGoLink bar(1); bar.step(); @@ -6412,14 +6405,14 @@ void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp) // delitems << "DELETE FROM item_instance WHERE guid IN ( "; // delmails << "DELETE FROM mail WHERE id IN ( " - BarGoLink bar(result->GetRowCount()); + BarGoLink bar(queryResult->GetRowCount()); uint32 count = 0; do { bar.step(); - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); Mail* m = new Mail; m->messageID = fields[0].GetUInt32(); m->messageType = fields[1].GetUInt8(); @@ -6445,7 +6438,7 @@ void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp) // delete or return mail: if (has_items) { - QueryResult* resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID); + auto resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", m->messageID); if (resultItems) { do @@ -6458,8 +6451,6 @@ void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp) m->AddItem(item_guid_low, item_template); } while (resultItems->NextRow()); - - delete resultItems; } // if it is mail from non-player, or if it's already return mail, it shouldn't be returned, but deleted if (m->messageType != MAIL_NORMAL || (m->checked & (MAIL_CHECK_MASK_COD_PAYMENT | MAIL_CHECK_MASK_RETURNED))) @@ -6490,8 +6481,7 @@ void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp) delete m; ++count; } - while (result->NextRow()); - delete result; + while (queryResult->NextRow()); sLog.outString(">> Loaded %u mails", count); sLog.outString(); @@ -8522,9 +8512,9 @@ void ObjectMgr::LoadQuestRelationsHelper(QuestRelationsMap& map, char const* tab uint32 count = 0; - QueryResult* result = WorldDatabase.PQuery("SELECT id,quest FROM %s", table); + auto queryResult = WorldDatabase.PQuery("SELECT id,quest FROM %s", table); - if (!result) + if (!queryResult) { BarGoLink bar(1); @@ -8535,11 +8525,11 @@ void ObjectMgr::LoadQuestRelationsHelper(QuestRelationsMap& map, char const* tab return; } - BarGoLink bar(result->GetRowCount()); + BarGoLink bar(queryResult->GetRowCount()); do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); bar.step(); uint32 id = fields[0].GetUInt32(); @@ -8555,9 +8545,7 @@ void ObjectMgr::LoadQuestRelationsHelper(QuestRelationsMap& map, char const* tab ++count; } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); sLog.outString(); sLog.outString(">> Loaded %u quest relations from %s", count, table); @@ -9012,10 +9000,10 @@ bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min sLog.outString("Loading texts from %s%s", table, extra_content ? ", with additional data" : ""); - QueryResult* result = db.PQuery("SELECT entry,content_default,content_loc1,content_loc2,content_loc3,content_loc4,content_loc5,content_loc6,content_loc7,content_loc8 %s FROM %s", + auto queryResult = db.PQuery("SELECT entry,content_default,content_loc1,content_loc2,content_loc3,content_loc4,content_loc5,content_loc6,content_loc7,content_loc8 %s FROM %s", extra_content ? ",sound,type,language,emote,broadcast_text_id" : "", table); - if (!result) + if (!queryResult) { BarGoLink bar(1); @@ -9031,11 +9019,11 @@ bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min uint32 count = 0; - BarGoLink bar(result->GetRowCount()); + BarGoLink bar(queryResult->GetRowCount()); do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); bar.step(); int32 entry = fields[0].GetInt32(); @@ -9124,9 +9112,7 @@ bool ObjectMgr::LoadMangosStrings(DatabaseType& db, char const* table, int32 min } } } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); if (min_value == MIN_MANGOS_STRING_ID) sLog.outString(">> Loaded %u MaNGOS strings from table %s", count, table); @@ -9477,9 +9463,9 @@ void ObjectMgr::LoadTrainers(char const* tableName, bool isTemplates) std::set skip_trainers; - std::unique_ptr result(WorldDatabase.PQuery("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel,ReqAbility1,ReqAbility2,ReqAbility3,condition_id FROM %s", tableName)); + auto queryResult = WorldDatabase.PQuery("SELECT entry, spell,spellcost,reqskill,reqskillvalue,reqlevel,ReqAbility1,ReqAbility2,ReqAbility3,condition_id FROM %s", tableName); - if (!result) + if (!queryResult) { BarGoLink bar(1); bar.step(); @@ -9488,7 +9474,7 @@ void ObjectMgr::LoadTrainers(char const* tableName, bool isTemplates) return; } - BarGoLink bar(result->GetRowCount()); + BarGoLink bar(queryResult->GetRowCount()); std::set talentIds; @@ -9497,7 +9483,7 @@ void ObjectMgr::LoadTrainers(char const* tableName, bool isTemplates) { bar.step(); - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 entry = fields[0].GetUInt32(); uint32 spell = fields[1].GetUInt32(); @@ -9631,7 +9617,7 @@ void ObjectMgr::LoadTrainers(char const* tableName, bool isTemplates) ++count; } - while (result->NextRow()); + while (queryResult->NextRow()); sLog.outString(">> Loaded %d trainer %sspells", count, isTemplates ? "template " : ""); sLog.outString(); @@ -9681,8 +9667,8 @@ void ObjectMgr::LoadVendors(char const* tableName, bool isTemplates) itr.second.Clear(); vendorList.clear(); - QueryResult* result = WorldDatabase.PQuery("SELECT entry, item, maxcount, incrtime, ExtendedCost, condition_id FROM %s ORDER BY slot", tableName); - if (!result) + auto queryResult = WorldDatabase.PQuery("SELECT entry, item, maxcount, incrtime, ExtendedCost, condition_id FROM %s ORDER BY slot", tableName); + if (!queryResult) { BarGoLink bar(1); @@ -9693,13 +9679,13 @@ void ObjectMgr::LoadVendors(char const* tableName, bool isTemplates) return; } - BarGoLink bar(result->GetRowCount()); + BarGoLink bar(queryResult->GetRowCount()); uint32 count = 0; do { bar.step(); - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 entry = fields[0].GetUInt32(); uint32 item_id = fields[1].GetUInt32(); @@ -9716,9 +9702,7 @@ void ObjectMgr::LoadVendors(char const* tableName, bool isTemplates) vList.AddItem(item_id, maxcount, incrtime, ExtendedCost, conditionId); ++count; } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); sLog.outString(">> Loaded %u vendor %sitems", count, isTemplates ? "template " : ""); sLog.outString(); diff --git a/src/game/Guilds/Guild.cpp b/src/game/Guilds/Guild.cpp index e949cf9a1d6..fb38dc89b07 100644 --- a/src/game/Guilds/Guild.cpp +++ b/src/game/Guilds/Guild.cpp @@ -205,18 +205,17 @@ bool Guild::AddMember(ObjectGuid plGuid, uint32 plRank) else { // 0 1 2 3 4 5 - QueryResult* result = CharacterDatabase.PQuery("SELECT name,level,class,gender,zone,account FROM characters WHERE guid = '%u'", lowguid); - if (!result) + auto queryResult = CharacterDatabase.PQuery("SELECT name,level,class,gender,zone,account FROM characters WHERE guid = '%u'", lowguid); + if (!queryResult) return false; // player doesn't exist - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); newmember.Name = fields[0].GetCppString(); newmember.Level = fields[1].GetUInt8(); newmember.Class = fields[2].GetUInt8(); newmember.Gender_ = fields[3].GetUInt8(); newmember.ZoneId = fields[4].GetUInt32(); newmember.accountId = fields[5].GetInt32(); - delete result; if (newmember.Level < 1 || newmember.Class < 1 || !((1 << (newmember.Class - 1)) & CLASSMASK_ALL_PLAYABLE)) @@ -924,15 +923,15 @@ void Guild::DisplayGuildEventLog(WorldSession* session) void Guild::LoadGuildEventLogFromDB() { // 0 1 2 3 4 5 - QueryResult* result = CharacterDatabase.PQuery("SELECT LogGuid, EventType, PlayerGuid1, PlayerGuid2, NewRank, TimeStamp FROM guild_eventlog WHERE guildid=%u ORDER BY TimeStamp DESC,LogGuid DESC LIMIT %u", m_Id, GUILD_EVENTLOG_MAX_RECORDS); - if (!result) + auto queryResult = CharacterDatabase.PQuery("SELECT LogGuid, EventType, PlayerGuid1, PlayerGuid2, NewRank, TimeStamp FROM guild_eventlog WHERE guildid=%u ORDER BY TimeStamp DESC,LogGuid DESC LIMIT %u", m_Id, GUILD_EVENTLOG_MAX_RECORDS); + if (!queryResult) return; bool isNextLogGuidSet = false; // uint32 configCount = sWorld.getConfig(CONFIG_UINT32_GUILD_EVENT_LOG_COUNT); // First event in list will be the oldest and the latest event is last event in list do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); if (!isNextLogGuidSet) { m_GuildEventLogNextGuid = fields[0].GetUInt32(); @@ -953,8 +952,7 @@ void Guild::LoadGuildEventLogFromDB() // Add entry to list m_GuildEventLog.push_front(NewEvent); } - while (result->NextRow()); - delete result; + while (queryResult->NextRow()); } // Add entry to guild eventlog @@ -1179,8 +1177,8 @@ uint32 Guild::GetBankRights(uint32 rankId, uint8 TabId) const void Guild::LoadGuildBankFromDB() { // 0 1 2 3 - QueryResult* result = CharacterDatabase.PQuery("SELECT TabId, TabName, TabIcon, TabText FROM guild_bank_tab WHERE guildid='%u' ORDER BY TabId", m_Id); - if (!result) + auto queryResult = CharacterDatabase.PQuery("SELECT TabId, TabName, TabIcon, TabText FROM guild_bank_tab WHERE guildid='%u' ORDER BY TabId", m_Id); + if (!queryResult) { m_TabList.clear(); return; @@ -1188,7 +1186,7 @@ void Guild::LoadGuildBankFromDB() do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint8 tabId = fields[0].GetUInt8(); if (tabId >= GetPurchasedTabs()) { @@ -1200,19 +1198,17 @@ void Guild::LoadGuildBankFromDB() m_TabList[tabId].Icon = fields[2].GetCppString(); m_TabList[tabId].Text = fields[3].GetCppString(); } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); // data needs to be at first place for Item::LoadFromDB // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 - result = CharacterDatabase.PQuery("SELECT itemEntry, creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, playedTime, text, TabId, SlotId, item_guid, item_entry FROM guild_bank_item JOIN item_instance ON item_guid = guid WHERE guildid='%u' ORDER BY TabId", m_Id); - if (!result) + queryResult = CharacterDatabase.PQuery("SELECT itemEntry, creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, playedTime, text, TabId, SlotId, item_guid, item_entry FROM guild_bank_item JOIN item_instance ON item_guid = guid WHERE guildid='%u' ORDER BY TabId", m_Id); + if (!queryResult) return; do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint8 TabId = fields[12].GetUInt8(); uint8 SlotId = fields[13].GetUInt8(); uint32 ItemGuid = fields[14].GetUInt32(); @@ -1250,9 +1246,7 @@ void Guild::LoadGuildBankFromDB() pItem->AddToWorld(); m_TabList[TabId].Slots[SlotId] = pItem; } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); } // ************************************************* @@ -1501,15 +1495,15 @@ void Guild::LoadGuildBankEventLogFromDB() // cycle through all purchased guild bank item tabs for (uint32 tabId = 0; tabId < uint32(GetPurchasedTabs()); ++tabId) { - // 0 1 2 3 4 5 6 - QueryResult* result = CharacterDatabase.PQuery("SELECT LogGuid, EventType, PlayerGuid, ItemOrMoney, ItemStackCount, DestTabId, TimeStamp FROM guild_bank_eventlog WHERE guildid='%u' AND TabId='%u' ORDER BY TimeStamp DESC,LogGuid DESC LIMIT %u", m_Id, tabId, GUILD_BANK_MAX_LOGS); - if (!result) + // 0 1 2 3 4 5 6 + auto queryResult = CharacterDatabase.PQuery("SELECT LogGuid, EventType, PlayerGuid, ItemOrMoney, ItemStackCount, DestTabId, TimeStamp FROM guild_bank_eventlog WHERE guildid='%u' AND TabId='%u' ORDER BY TimeStamp DESC,LogGuid DESC LIMIT %u", m_Id, tabId, GUILD_BANK_MAX_LOGS); + if (!queryResult) continue; bool isNextLogGuidSet = false; do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); GuildBankEventLogEntry NewEvent; NewEvent.EventType = fields[1].GetUInt8(); @@ -1538,20 +1532,19 @@ void Guild::LoadGuildBankEventLogFromDB() isNextLogGuidSet = true; } } - while (result->NextRow()); - delete result; + while (queryResult->NextRow()); } // special handle for guild bank money log - // 0 1 2 3 4 5 6 - QueryResult* result = CharacterDatabase.PQuery("SELECT LogGuid, EventType, PlayerGuid, ItemOrMoney, ItemStackCount, DestTabId, TimeStamp FROM guild_bank_eventlog WHERE guildid='%u' AND TabId='%u' ORDER BY TimeStamp DESC,LogGuid DESC LIMIT %u", m_Id, GUILD_BANK_MONEY_LOGS_TAB, GUILD_BANK_MAX_LOGS); - if (!result) + // 0 1 2 3 4 5 6 + auto queryResult = CharacterDatabase.PQuery("SELECT LogGuid, EventType, PlayerGuid, ItemOrMoney, ItemStackCount, DestTabId, TimeStamp FROM guild_bank_eventlog WHERE guildid='%u' AND TabId='%u' ORDER BY TimeStamp DESC,LogGuid DESC LIMIT %u", m_Id, GUILD_BANK_MONEY_LOGS_TAB, GUILD_BANK_MAX_LOGS); + if (!queryResult) return; bool isNextMoneyLogGuidSet = false; do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); if (!isNextMoneyLogGuidSet) { m_GuildBankEventLogNextGuid_Money = fields[0].GetUInt32(); @@ -1575,8 +1568,7 @@ void Guild::LoadGuildBankEventLogFromDB() // events are ordered from oldest (in beginning) to latest (in the end) m_GuildBankEventLog_Money.push_front(NewEvent); } - while (result->NextRow()); - delete result; + while (queryResult->NextRow()); } void Guild::DisplayGuildBankLogs(WorldSession* session, uint8 TabId) diff --git a/src/game/Loot/LootMgr.cpp b/src/game/Loot/LootMgr.cpp index 9f800a94251..e29ccd0b7ef 100644 --- a/src/game/Loot/LootMgr.cpp +++ b/src/game/Loot/LootMgr.cpp @@ -105,15 +105,15 @@ void LootStore::LoadLootTable() Clear(); // 0 1 2 3 4 5 6 - QueryResult* result = WorldDatabase.PQuery("SELECT entry, item, ChanceOrQuestChance, groupid, mincountOrRef, maxcount, condition_id FROM %s", GetName()); + auto queryResult = WorldDatabase.PQuery("SELECT entry, item, ChanceOrQuestChance, groupid, mincountOrRef, maxcount, condition_id FROM %s", GetName()); - if (result) + if (queryResult) { - BarGoLink bar(result->GetRowCount()); + BarGoLink bar(queryResult->GetRowCount()); do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); bar.step(); uint32 entry = fields[0].GetUInt32(); @@ -170,9 +170,7 @@ void LootStore::LoadLootTable() tab->second->AddEntry(storeitem); ++count; } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); Verify(); // Checks validity of the loot store diff --git a/src/game/Mails/MailHandler.cpp b/src/game/Mails/MailHandler.cpp index 419fea07c17..ea5106b7340 100644 --- a/src/game/Mails/MailHandler.cpp +++ b/src/game/Mails/MailHandler.cpp @@ -207,11 +207,10 @@ void WorldSession::HandleSendMail(WorldPacket& recv_data) else { rc_team = sObjectMgr.GetPlayerTeamByGUID(rc); - if (QueryResult* result = CharacterDatabase.PQuery("SELECT COUNT(*) FROM mail WHERE receiver = '%u'", rc.GetCounter())) + if (auto queryResult = CharacterDatabase.PQuery("SELECT COUNT(*) FROM mail WHERE receiver = '%u'", rc.GetCounter())) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); mails_count = fields[0].GetUInt32(); - delete result; } } diff --git a/src/game/Maps/Map.cpp b/src/game/Maps/Map.cpp index 68d15e6d06d..240276d74cc 100644 --- a/src/game/Maps/Map.cpp +++ b/src/game/Maps/Map.cpp @@ -1633,24 +1633,22 @@ void Map::CreateInstanceData(bool load) if (load) { - // TODO: make a global storage for this - QueryResult* result; + std::unique_ptr queryResult; if (Instanceable()) - result = CharacterDatabase.PQuery("SELECT data FROM instance WHERE id = '%u'", i_InstanceId); + queryResult = CharacterDatabase.PQuery("SELECT data FROM instance WHERE id = '%u'", i_InstanceId); else - result = CharacterDatabase.PQuery("SELECT data FROM world WHERE map = '%u'", GetId()); + queryResult = CharacterDatabase.PQuery("SELECT data FROM world WHERE map = '%u'", GetId()); - if (result) + if (queryResult) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); const char* data = fields[0].GetString(); if (data) { DEBUG_LOG("Loading instance data for `%s` (Map: %u Instance: %u)", sScriptDevAIMgr.GetScriptName(i_script_id), GetId(), i_InstanceId); i_data->Load(data); } - delete result; } else { diff --git a/src/game/Maps/MapPersistentStateMgr.cpp b/src/game/Maps/MapPersistentStateMgr.cpp index 241011d2bb7..5a7c59c52d1 100644 --- a/src/game/Maps/MapPersistentStateMgr.cpp +++ b/src/game/Maps/MapPersistentStateMgr.cpp @@ -778,12 +778,12 @@ void MapPersistentStateManager::_DelHelper(DatabaseType& db, const char* fields, vsnprintf(szQueryTail, MAX_QUERY_LEN, queryTail, ap); va_end(ap); - QueryResult* result = db.PQuery("SELECT %s FROM %s %s", fields, table, szQueryTail); - if (result) + auto queryResult = db.PQuery("SELECT %s FROM %s %s", fields, table, szQueryTail); + if (queryResult) { do { - Field* resultFields = result->Fetch(); + Field* resultFields = queryResult->Fetch(); std::ostringstream ss; for (size_t i = 0; i < fieldTokens.size(); ++i) { @@ -793,8 +793,7 @@ void MapPersistentStateManager::_DelHelper(DatabaseType& db, const char* fields, } db.PExecute("DELETE FROM %s WHERE %s", table, ss.str().c_str()); } - while (result->NextRow()); - delete result; + while (queryResult->NextRow()); } } diff --git a/src/game/MotionGenerators/WaypointManager.cpp b/src/game/MotionGenerators/WaypointManager.cpp index fd5f76b4830..16e9f1a278d 100644 --- a/src/game/MotionGenerators/WaypointManager.cpp +++ b/src/game/MotionGenerators/WaypointManager.cpp @@ -243,10 +243,10 @@ void WaypointManager::Load() // prevent using invalid coordinates if (!MaNGOS::IsValidMapCoord(node.x, node.y, node.z, node.orientation)) { - QueryResult* result1 = WorldDatabase.PQuery("SELECT id, map FROM creature WHERE guid = '%u'", id); - if (result1) + auto queryResult1 = WorldDatabase.PQuery("SELECT id, map FROM creature WHERE guid = '%u'", id); + if (queryResult1) sLog.outErrorDb("Creature (guidlow %d, entry %d) have invalid coordinates in his waypoint %d (X: %f, Y: %f).", - id, result1->Fetch()[0].GetUInt32(), point, node.x, node.y); + id, queryResult1->Fetch()[0].GetUInt32(), point, node.x, node.y); else sLog.outErrorDb("Waypoint path %d, have invalid coordinates in his waypoint %d (X: %f, Y: %f).", id, point, node.x, node.y); @@ -254,10 +254,9 @@ void WaypointManager::Load() MaNGOS::NormalizeMapCoord(node.x); MaNGOS::NormalizeMapCoord(node.y); - if (result1) + if (queryResult1) { - node.z = sTerrainMgr.LoadTerrain(result1->Fetch()[1].GetUInt32())->GetHeightStatic(node.x, node.y, node.z); - delete result1; + node.z = sTerrainMgr.LoadTerrain(queryResult1->Fetch()[1].GetUInt32())->GetHeightStatic(node.x, node.y, node.z); } WorldDatabase.PExecute("UPDATE creature_movement SET PositionX = '%f', PositionY = '%f', PositionZ = '%f' WHERE Id = '%u' AND Point = '%u'", node.x, node.y, node.z, id, point); diff --git a/src/game/PlayerBot/Base/PlayerbotAI.cpp b/src/game/PlayerBot/Base/PlayerbotAI.cpp index c1233acfcac..7a824e4bc56 100644 --- a/src/game/PlayerBot/Base/PlayerbotAI.cpp +++ b/src/game/PlayerBot/Base/PlayerbotAI.cpp @@ -3720,18 +3720,17 @@ void PlayerbotAI::SetQuestNeedItems() continue; // TODO: find faster way to handle this look up instead of using SQL lookup for each item - QueryResult* result; // determine if GOs are needed - result = WorldDatabase.PQuery("SELECT entry FROM gameobject_template WHERE questitem1='%u' " + auto queryResult = WorldDatabase.PQuery("SELECT entry FROM gameobject_template WHERE questitem1='%u' " "OR questitem2='%u' OR questitem3='%u' OR questitem4='%u' OR questitem5='%u' OR questitem6='%u'", qInfo->ReqItemId[i], qInfo->ReqItemId[i], qInfo->ReqItemId[i], qInfo->ReqItemId[i], qInfo->ReqItemId[i], qInfo->ReqItemId[i]); - if (result) + if (queryResult) { do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 entry = fields[0].GetUInt32(); GameObjectInfo const* gInfo = ObjectMgr::GetGameObjectInfo(entry); @@ -3746,9 +3745,7 @@ void PlayerbotAI::SetQuestNeedItems() m_collectObjects.unique(); } } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); } } } @@ -4555,9 +4552,9 @@ Unit* PlayerbotAI::FindAttacker(ATTACKERINFOTYPE ait, Unit* victim) */ void PlayerbotAI::BotDataRestore() { - QueryResult* result = CharacterDatabase.PQuery("SELECT combat_delay,autoequip FROM playerbot_saved_data WHERE guid = '%u'", m_bot->GetGUIDLow()); + auto queryResult = CharacterDatabase.PQuery("SELECT combat_delay,autoequip FROM playerbot_saved_data WHERE guid = '%u'", m_bot->GetGUIDLow()); - if (!result) + if (!queryResult) { sLog.outString(); sLog.outString(">> [BotDataRestore()] Loaded `playerbot_saved_data`, found no match for guid %u.", m_bot->GetGUIDLow()); @@ -4566,10 +4563,9 @@ void PlayerbotAI::BotDataRestore() } else { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); m_DelayAttack = fields[0].GetUInt8(); m_AutoEquipToggle = fields[1].GetBool(); - delete result; } } @@ -4580,9 +4576,9 @@ void PlayerbotAI::BotDataRestore() */ void PlayerbotAI::CombatOrderRestore() { - QueryResult* result = CharacterDatabase.PQuery("SELECT combat_order,primary_target,secondary_target,pname,sname,combat_delay,auto_follow FROM playerbot_saved_data WHERE guid = '%u'", m_bot->GetGUIDLow()); + auto queryResult = CharacterDatabase.PQuery("SELECT combat_order,primary_target,secondary_target,pname,sname,combat_delay,auto_follow FROM playerbot_saved_data WHERE guid = '%u'", m_bot->GetGUIDLow()); - if (!result) + if (!queryResult) { sLog.outString(); sLog.outString(">> [CombatOrderRestore()] Loaded `playerbot_saved_data`, found no match for guid %u.", m_bot->GetGUIDLow()); @@ -4590,7 +4586,7 @@ void PlayerbotAI::CombatOrderRestore() return; } - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); CombatOrderType combatOrders = (CombatOrderType)fields[0].GetUInt32(); ObjectGuid PrimtargetGUID = ObjectGuid(fields[1].GetUInt64()); ObjectGuid SectargetGUID = ObjectGuid(fields[2].GetUInt64()); @@ -4600,7 +4596,6 @@ void PlayerbotAI::CombatOrderRestore() m_FollowAutoGo = fields[6].GetUInt8(); gPrimtarget = ObjectAccessor::GetUnit(*m_bot->GetMap()->GetWorldObject(PrimtargetGUID), PrimtargetGUID); gSectarget = ObjectAccessor::GetUnit(*m_bot->GetMap()->GetWorldObject(SectargetGUID), SectargetGUID); - delete result; //Unit* target = nullptr; //ObjectGuid NoTargetGUID = m_bot->GetObjectGuid(); @@ -6356,9 +6351,9 @@ uint32 PlayerbotAI::GetTalentSpecsAmount() uint32 PlayerbotAI::GetTalentSpecsAmount(long specClass) { - QueryResult* result = CharacterDatabase.PQuery("SELECT COUNT(*) FROM playerbot_talentspec WHERE class = '%li'", specClass); + auto queryResult = CharacterDatabase.PQuery("SELECT COUNT(*) FROM playerbot_talentspec WHERE class = '%li'", specClass); - if (!result) + if (!queryResult) { sLog.outString(); sLog.outString(">> Loaded `playerbot_talentspec`, found no talentspecs for class %li.", specClass); @@ -6366,11 +6361,10 @@ uint32 PlayerbotAI::GetTalentSpecsAmount(long specClass) return 0; } - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 count = fields[0].GetUInt32(); - delete result; return count; } @@ -6384,9 +6378,9 @@ std::list PlayerbotAI::GetTalentSpecs(long specClass) TalentSpec ts; std::list tsList; - QueryResult* result = CharacterDatabase.PQuery("SELECT * FROM playerbot_talentspec WHERE class = %li ORDER BY talentspec_id ASC", specClass); + auto queryResult = CharacterDatabase.PQuery("SELECT * FROM playerbot_talentspec WHERE class = %li ORDER BY talentspec_id ASC", specClass); - if (!result) + if (!queryResult) { sLog.outString(); sLog.outString(">> Loaded `playerbot_talentspec`, found no talentspecs for class %li.", specClass); @@ -6403,7 +6397,7 @@ std::list PlayerbotAI::GetTalentSpecs(long specClass) 4 to 74 talent_10 to 71 75 to 80 major_glyph_15, 30, 80, minor_glyph_15, 50, 70 */ - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); /* ts_id = fields[0].GetUInt32(); // not used if (!ts_id) // Nice bit of paranoia: ts_id is an AUTO_INCREMENT value @@ -6439,9 +6433,8 @@ std::list PlayerbotAI::GetTalentSpecs(long specClass) tsList.push_back(ts); } - while (result->NextRow()); + while (queryResult->NextRow()); - delete result; return tsList; } @@ -6465,14 +6458,13 @@ TalentSpec PlayerbotAI::GetTalentSpec(long specClass, long choice) // Weed out invalid choice - ts has been zero'd out anyway if (0 >= choice || (long) GetTalentSpecsAmount(specClass) < choice) return ts; - QueryResult* result = CharacterDatabase.PQuery("SELECT * FROM playerbot_talentspec WHERE class = %li ORDER BY talentspec_id ASC", specClass); + auto queryResult = CharacterDatabase.PQuery("SELECT * FROM playerbot_talentspec WHERE class = %li ORDER BY talentspec_id ASC", specClass); - if (!result) + if (!queryResult) { sLog.outString(); sLog.outString(">> Loaded `playerbot_talentspec`, found no talentspecs for class %li.", specClass); - delete result; return ts; // empty } @@ -6489,7 +6481,7 @@ TalentSpec PlayerbotAI::GetTalentSpec(long specClass, long choice) 4 to 74 talent_10 to 71 75 to 80 major_glyph_15, 30, 80, minor_glyph_15, 50, 70 */ - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); /* ts_id = fields[0].GetUInt32(); // not used if (!ts_id) // Nice bit of paranoia: ts_id is an AUTO_INCREMENT value @@ -6505,7 +6497,6 @@ TalentSpec PlayerbotAI::GetTalentSpec(long specClass, long choice) ts.specName = ""; ts.specClass = 0; - delete result; return ts; } @@ -6526,15 +6517,13 @@ TalentSpec PlayerbotAI::GetTalentSpec(long specClass, long choice) ts.glyphIdMajor[i] = fields[i + 78].GetUInt16(); } - delete result; return ts; } // TODO: okay, this won't bog down the system, but it's still a waste. Figure out a better way. - result->NextRow(); + queryResult->NextRow(); } - delete result; return ts; } @@ -8363,14 +8352,14 @@ void PlayerbotAI::Repair(const uint32 itemid, Creature* rCreature) bool PlayerbotAI::RemoveAuction(const uint32 auctionid) { - QueryResult* result = CharacterDatabase.PQuery( + auto queryResult = CharacterDatabase.PQuery( "SELECT houseid,itemguid,item_template,itemowner,buyoutprice,time,buyguid,lastbid,startbid,deposit FROM auction WHERE id = '%u'", auctionid); AuctionEntry* auction; - if (result) + if (queryResult) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); auction = new AuctionEntry; auction->Id = auctionid; @@ -8394,7 +8383,6 @@ bool PlayerbotAI::RemoveAuction(const uint32 auctionid) auction->DeleteFromDB(); sLog.outError("Auction %u has not a existing item : %u, deleted", auction->Id, auction->itemGuidLow); delete auction; - delete result; return false; } @@ -8415,7 +8403,6 @@ bool PlayerbotAI::RemoveAuction(const uint32 auctionid) auction->DeleteFromDB(); delete auction; - delete result; } return true; } @@ -8610,14 +8597,14 @@ void PlayerbotAI::ListAuctions() { std::ostringstream report; - QueryResult* result = CharacterDatabase.PQuery( + auto queryResult = CharacterDatabase.PQuery( "SELECT id,itemguid,item_template,time,buyguid,lastbid FROM auction WHERE itemowner = '%u'", m_bot->GetObjectGuid().GetCounter()); - if (result) + if (queryResult) { report << "My active auctions are: \n"; do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 Id = fields[0].GetUInt32(); uint32 itemGuidLow = fields[1].GetUInt32(); @@ -8659,9 +8646,8 @@ void PlayerbotAI::ListAuctions() report << " ends: " << aTm->tm_hour << "|cff0070dd|hH|h|r " << aTm->tm_min << "|cff0070dd|hmin|h|r"; } } - while (result->NextRow()); + while (queryResult->NextRow()); - delete result; TellMaster(report.str().c_str()); } } @@ -9341,11 +9327,9 @@ void PlayerbotAI::_HandleCommandOrders(std::string& text, Player& fromPlayer) return; } - QueryResult* resultlvl = CharacterDatabase.PQuery("SELECT guid FROM playerbot_saved_data WHERE guid = '%u'", m_bot->GetObjectGuid().GetCounter()); + auto resultlvl = CharacterDatabase.PQuery("SELECT guid FROM playerbot_saved_data WHERE guid = '%u'", m_bot->GetObjectGuid().GetCounter()); if (!resultlvl) CharacterDatabase.DirectPExecute("INSERT INTO playerbot_saved_data (guid,combat_order,primary_target,secondary_target,pname,sname,combat_delay,auto_follow,autoequip) VALUES ('%u',0,0,0,'','',0,0,false)", m_bot->GetObjectGuid().GetCounter()); - else - delete resultlvl; size_t protect = text.find("protect"); size_t assist = text.find("assist"); @@ -11031,8 +11015,8 @@ void PlayerbotAI::_HandleCommandQuest(std::string& text, Player& fromPlayer) // Compare quest entry from [Quest Link] with quest ids listed DB table // if found the quest is autocompleted - QueryResult* result = CharacterDatabase.PQuery("SELECT * FROM playerbot_quest_data WHERE autocomplete='%u'", entry); - if (!result) + auto queryResult = CharacterDatabase.PQuery("SELECT * FROM playerbot_quest_data WHERE autocomplete='%u'", entry); + if (!queryResult) { MakeQuestLink(pQuest, msg); msg << " can't be autocompleted\n"; @@ -11115,7 +11099,6 @@ void PlayerbotAI::_HandleCommandQuest(std::string& text, Player& fromPlayer) MakeQuestLink(pQuest, msg); msg << "\n"; } - delete result; } } ch.SendSysMessage(msg.str().c_str()); @@ -11449,7 +11432,6 @@ void PlayerbotAI::_HandleCommandSurvey(std::string& /*text*/, Player& fromPlayer { uint32 count = 0; std::ostringstream detectout; - QueryResult* result; GameEventMgr::ActiveEvents const& activeEventsList = sGameEventMgr.GetActiveEventList(); std::ostringstream eventFilter; eventFilter << " AND (event IS NULL "; @@ -11471,16 +11453,16 @@ void PlayerbotAI::_HandleCommandSurvey(std::string& /*text*/, Player& fromPlayer else eventFilter << ")"; - result = WorldDatabase.PQuery("SELECT gameobject.guid, id, position_x, position_y, position_z, map, " - "(POW(position_x - %f, 2) + POW(position_y - %f, 2) + POW(position_z - %f, 2)) AS order_ FROM gameobject " - "LEFT OUTER JOIN game_event_gameobject on gameobject.guid=game_event_gameobject.guid WHERE map = '%i' %s ORDER BY order_ ASC LIMIT 10", - m_bot->GetPositionX(), m_bot->GetPositionY(), m_bot->GetPositionZ(), m_bot->GetMapId(), eventFilter.str().c_str()); + auto queryResult = WorldDatabase.PQuery("SELECT gameobject.guid, id, position_x, position_y, position_z, map, " + "(POW(position_x - %f, 2) + POW(position_y - %f, 2) + POW(position_z - %f, 2)) AS order_ FROM gameobject " + "LEFT OUTER JOIN game_event_gameobject on gameobject.guid=game_event_gameobject.guid WHERE map = '%i' %s ORDER BY order_ ASC LIMIT 10", + m_bot->GetPositionX(), m_bot->GetPositionY(), m_bot->GetPositionZ(), m_bot->GetMapId(), eventFilter.str().c_str()); - if (result) + if (queryResult) { do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 guid = fields[0].GetUInt32(); uint32 entry = fields[1].GetUInt32(); @@ -11494,9 +11476,8 @@ void PlayerbotAI::_HandleCommandSurvey(std::string& /*text*/, Player& fromPlayer detectout << "|cFFFFFF00|Hfound:" << guid << ":" << entry << ":" << "|h[" << go->GetGOInfo()->name << "]|h|r"; ++count; } - while (result->NextRow()); + while (queryResult->NextRow()); - delete result; } SendWhisper(detectout.str().c_str(), fromPlayer); } @@ -11915,11 +11896,11 @@ void PlayerbotAI::_HandleCommandGM(std::string& text, Player& fromPlayer) } //check whether entry is already in database - QueryResult* result = CharacterDatabase.PQuery("SELECT * FROM playerbot_quest_data WHERE autocomplete='%u'", entry); + auto queryResult = CharacterDatabase.PQuery("SELECT * FROM playerbot_quest_data WHERE autocomplete='%u'", entry); if (add != std::string::npos) { - if (!result) + if (!queryResult) { // add new entry out << "adding quest "; @@ -11932,20 +11913,18 @@ void PlayerbotAI::_HandleCommandGM(std::string& text, Player& fromPlayer) // entry found in table MakeQuestLink(pQuest, out); out << " already in table\n"; - delete result; continue; } } else if (del != std::string::npos) { - if (result) + if (queryResult) { // delete entry out << "deleting "; MakeQuestLink(pQuest, out); out << " from table\n"; CharacterDatabase.DirectPExecute("DELETE FROM playerbot_quest_data WHERE autocomplete='%u'", entry); - delete result; } else { diff --git a/src/game/PlayerBot/Base/PlayerbotMgr.cpp b/src/game/PlayerBot/Base/PlayerbotMgr.cpp index 5708883f95e..8ec048c0954 100644 --- a/src/game/PlayerBot/Base/PlayerbotMgr.cpp +++ b/src/game/PlayerBot/Base/PlayerbotMgr.cpp @@ -108,12 +108,11 @@ void PlayerbotMgr::HandleMasterIncomingPacket(const WorldPacket& packet) uint32 petitionLowGuid = petitionGuid.GetCounter(); - QueryResult* result = CharacterDatabase.PQuery("SELECT * FROM petition_sign WHERE playerguid = '%u' AND petitionguid = '%u'", player->GetGUIDLow(), petitionLowGuid); + auto queryResult = CharacterDatabase.PQuery("SELECT * FROM petition_sign WHERE playerguid = '%u' AND petitionguid = '%u'", player->GetGUIDLow(), petitionLowGuid); - if (result) + if (queryResult) { ChatHandler(m_master).PSendSysMessage("%s has already signed the petition", player->GetName()); - delete result; return; } @@ -981,10 +980,10 @@ void Creature::LoadBotMenu(Player* pPlayer) if (pPlayer->GetPlayerbotAI()) return; ObjectGuid guid = pPlayer->GetObjectGuid(); uint32 accountId = sObjectMgr.GetPlayerAccountIdByGUID(guid); - QueryResult* result = CharacterDatabase.PQuery("SELECT guid, name FROM characters WHERE account='%d'", accountId); + auto queryResult = CharacterDatabase.PQuery("SELECT guid, name FROM characters WHERE account='%d'", accountId); do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); ObjectGuid guidlo = ObjectGuid(fields[0].GetUInt64()); std::string name = fields[1].GetString(); std::string word = ""; @@ -1015,8 +1014,7 @@ void Creature::LoadBotMenu(Player* pPlayer) } } } - while (result->NextRow()); - delete result; + while (queryResult->NextRow()); } void Player::skill(std::list& m_spellsToLearn) @@ -1273,7 +1271,7 @@ bool ChatHandler::HandlePlayerbotCommand(char* args) return false; } - QueryResult* resultchar = CharacterDatabase.PQuery("SELECT COUNT(*) FROM characters WHERE online = '1' AND account = '%u'", m_session->GetAccountId()); + auto resultchar = CharacterDatabase.PQuery("SELECT COUNT(*) FROM characters WHERE online = '1' AND account = '%u'", m_session->GetAccountId()); if (resultchar) { Field* fields = resultchar->Fetch(); @@ -1284,13 +1282,11 @@ bool ChatHandler::HandlePlayerbotCommand(char* args) { PSendSysMessage("|cffff0000You cannot summon anymore bots.(Current Max: |cffffffff%u)", maxnum); SetSentErrorMessage(true); - delete resultchar; return false; } - delete resultchar; } - QueryResult* resultlvl = CharacterDatabase.PQuery("SELECT level, name, race, class, map FROM characters WHERE guid = '%u'", guid.GetCounter()); + auto resultlvl = CharacterDatabase.PQuery("SELECT level, name, race, class, map FROM characters WHERE guid = '%u'", guid.GetCounter()); if (resultlvl) { Field* fields = resultlvl->Fetch(); @@ -1309,7 +1305,6 @@ bool ChatHandler::HandlePlayerbotCommand(char* args) { PSendSysMessage("|cffff0000You cannot summon |cffffffff[%s]|cffff0000, it's level is too high.(Current Max:lvl |cffffffff%u)", fields[1].GetString(), maxlvl); SetSentErrorMessage(true); - delete resultlvl; return false; } @@ -1318,7 +1313,6 @@ bool ChatHandler::HandlePlayerbotCommand(char* args) { PSendSysMessage("|cffff0000You cannot summon |cffffffff[%s]|cffff0000, the Death Knight is not free of the Lich King.", fields[1].GetString()); SetSentErrorMessage(true); - delete resultlvl; return false; } @@ -1327,11 +1321,9 @@ bool ChatHandler::HandlePlayerbotCommand(char* args) { PSendSysMessage("|cffff0000You cannot summon |cffffffff[%s]|cffff0000, a member of the enemy side", fields[1].GetString()); SetSentErrorMessage(true); - delete resultlvl; return false; } } - delete resultlvl; } // end of gmconfig patch if (cmdStr == "add" || cmdStr == "login") diff --git a/src/game/Server/WorldSession.cpp b/src/game/Server/WorldSession.cpp index 51a17b9b7a3..2e37e97da23 100644 --- a/src/game/Server/WorldSession.cpp +++ b/src/game/Server/WorldSession.cpp @@ -961,7 +961,7 @@ void WorldSession::SendAuthWaitQue(uint32 position) const void WorldSession::LoadGlobalAccountData() { LoadAccountData( - CharacterDatabase.PQuery("SELECT type, time, data FROM account_data WHERE account='%u'", GetAccountId()), + CharacterDatabase.PQuery("SELECT type, time, data FROM account_data WHERE account='%u'", GetAccountId()).release(), GLOBAL_CACHE_MASK ); } @@ -1062,9 +1062,9 @@ void WorldSession::LoadTutorialsData() for (unsigned int& m_Tutorial : m_Tutorials) m_Tutorial = 0; - QueryResult* result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u'", GetAccountId()); + auto queryResult = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u'", GetAccountId()); - if (!result) + if (!queryResult) { m_tutorialState = TUTORIALDATA_NEW; return; @@ -1072,14 +1072,12 @@ void WorldSession::LoadTutorialsData() do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); for (int iI = 0; iI < 8; ++iI) m_Tutorials[iI] = fields[iI].GetUInt32(); } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); m_tutorialState = TUTORIALDATA_UNCHANGED; } diff --git a/src/game/Server/WorldSocket.cpp b/src/game/Server/WorldSocket.cpp index c9f99c253af..211e17a5955 100644 --- a/src/game/Server/WorldSocket.cpp +++ b/src/game/Server/WorldSocket.cpp @@ -361,7 +361,7 @@ bool WorldSocket::HandleAuthSession(WorldPacket& recvPacket) LoginDatabase.escape_string(safe_account); // No SQL injection, username escaped. - QueryResult* result = + auto queryResult = LoginDatabase.PQuery("SELECT " "a.id, " //0 "gmlevel, " //1 @@ -381,7 +381,7 @@ bool WorldSocket::HandleAuthSession(WorldPacket& recvPacket) safe_account.c_str()); // Stop if the account is not found - if (!result) + if (!queryResult) { packet.Initialize(SMSG_AUTH_RESPONSE, 1); packet << uint8(AUTH_UNKNOWN_ACCOUNT); @@ -392,7 +392,7 @@ bool WorldSocket::HandleAuthSession(WorldPacket& recvPacket) return false; } - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); N.SetHexStr("894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7"); g.SetDword(7); @@ -420,7 +420,6 @@ bool WorldSocket::HandleAuthSession(WorldPacket& recvPacket) packet << uint8(AUTH_FAILED); SendPacket(packet); - delete result; BASIC_LOG("WorldSocket::HandleAuthSession: Sent Auth Response (Account IP differs)."); return false; } @@ -451,10 +450,8 @@ bool WorldSocket::HandleAuthSession(WorldPacket& recvPacket) uint32 accountFlags = fields[11].GetUInt32(); std::string platform = fields[12].GetString(); - delete result; - // Re-check account ban (same check as in realmd) - QueryResult* banresult = + auto banresult = LoginDatabase.PQuery("SELECT 1 FROM account_banned WHERE account_id = %u AND active = 1 AND (expires_at > UNIX_TIMESTAMP() OR expires_at = banned_at)" "UNION " "SELECT 1 FROM ip_banned WHERE (expires_at = banned_at OR expires_at > UNIX_TIMESTAMP()) AND ip = '%s'", @@ -466,8 +463,6 @@ bool WorldSocket::HandleAuthSession(WorldPacket& recvPacket) packet << uint8(AUTH_BANNED); SendPacket(packet); - delete banresult; - sLog.outError("WorldSocket::HandleAuthSession: Sent Auth Response (Account banned)."); return false; } diff --git a/src/game/Spells/SpellHandler.cpp b/src/game/Spells/SpellHandler.cpp index fbead57bd36..4ed5a58ed29 100644 --- a/src/game/Spells/SpellHandler.cpp +++ b/src/game/Spells/SpellHandler.cpp @@ -250,10 +250,10 @@ void WorldSession::HandleOpenItemOpcode(WorldPacket& recvPacket) if (pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_WRAPPED))// wrapped? { - QueryResult* result = CharacterDatabase.PQuery("SELECT entry, flags FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow()); - if (result) + auto queryResult = CharacterDatabase.PQuery("SELECT entry, flags FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow()); + if (queryResult) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 entry = fields[0].GetUInt32(); uint32 flags = fields[1].GetUInt32(); @@ -261,7 +261,6 @@ void WorldSession::HandleOpenItemOpcode(WorldPacket& recvPacket) pItem->SetEntry(entry); pItem->SetUInt32Value(ITEM_FIELD_FLAGS, flags); pItem->SetState(ITEM_CHANGED, pUser); - delete result; } else { diff --git a/src/game/Spells/SpellMgr.cpp b/src/game/Spells/SpellMgr.cpp index 012943d7471..c3532cedb1b 100644 --- a/src/game/Spells/SpellMgr.cpp +++ b/src/game/Spells/SpellMgr.cpp @@ -3027,9 +3027,9 @@ void SpellMgr::CheckUsedSpells(char const* table) const uint32 countMasks = 0; // 0 1 2 3 4 5 6 7 8 9 10 11 - QueryResult* result = WorldDatabase.PQuery("SELECT spellid,SpellFamilyName,SpellFamilyMaskA,SpellFamilyMaskB,SpellIcon,SpellVisual,SpellCategory,EffectType,EffectAura,EffectIdx,Name,Code FROM %s", table); + auto queryResult = WorldDatabase.PQuery("SELECT spellid,SpellFamilyName,SpellFamilyMaskA,SpellFamilyMaskB,SpellIcon,SpellVisual,SpellCategory,EffectType,EffectAura,EffectIdx,Name,Code FROM %s", table); - if (!result) + if (!queryResult) { BarGoLink bar(1); @@ -3040,11 +3040,11 @@ void SpellMgr::CheckUsedSpells(char const* table) const return; } - BarGoLink bar(result->GetRowCount()); + BarGoLink bar(queryResult->GetRowCount()); do { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); bar.step(); @@ -3262,9 +3262,7 @@ void SpellMgr::CheckUsedSpells(char const* table) const } } } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); sLog.outString(); sLog.outString(">> Checked %u spells and %u spell masks", countSpells, countMasks); diff --git a/src/game/Tools/CharacterDatabaseCleaner.cpp b/src/game/Tools/CharacterDatabaseCleaner.cpp index bc0f188f2ee..3534c844237 100644 --- a/src/game/Tools/CharacterDatabaseCleaner.cpp +++ b/src/game/Tools/CharacterDatabaseCleaner.cpp @@ -33,11 +33,10 @@ void CharacterDatabaseCleaner::CleanDatabase() sLog.outString("Cleaning character database..."); // check flags which clean ups are necessary - QueryResult* result = CharacterDatabase.PQuery("SELECT cleaning_flags FROM saved_variables"); - if (!result) + auto queryResult = CharacterDatabase.PQuery("SELECT cleaning_flags FROM saved_variables"); + if (!queryResult) return; - uint32 flags = (*result)[0].GetUInt32(); - delete result; + uint32 flags = (*queryResult)[0].GetUInt32(); // clean up if (flags & CLEANING_FLAG_ACHIEVEMENT_PROGRESS) @@ -53,8 +52,8 @@ void CharacterDatabaseCleaner::CleanDatabase() void CharacterDatabaseCleaner::CheckUnique(const char* column, const char* table, bool (*check)(uint32)) { - QueryResult* result = CharacterDatabase.PQuery("SELECT DISTINCT %s FROM %s", column, table); - if (!result) + auto queryResult = CharacterDatabase.PQuery("SELECT DISTINCT %s FROM %s", column, table); + if (!queryResult) { sLog.outString("Table %s is empty.", table); return; @@ -62,12 +61,12 @@ void CharacterDatabaseCleaner::CheckUnique(const char* column, const char* table bool found = false; std::ostringstream ss; - BarGoLink bar(result->GetRowCount()); + BarGoLink bar(queryResult->GetRowCount()); do { bar.step(); - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); uint32 id = fields[0].GetUInt32(); @@ -83,8 +82,7 @@ void CharacterDatabaseCleaner::CheckUnique(const char* column, const char* table ss << id; } } - while (result->NextRow()); - delete result; + while (queryResult->NextRow()); if (found) { diff --git a/src/game/Tools/PlayerDump.cpp b/src/game/Tools/PlayerDump.cpp index d7ee683fff5..46567ac778c 100644 --- a/src/game/Tools/PlayerDump.cpp +++ b/src/game/Tools/PlayerDump.cpp @@ -314,8 +314,8 @@ void PlayerDumpWriter::DumpTableContent(std::string& dump, uint32 guid, char con else // not set case, get single guid string wherestr = GenerateWhereStr(fieldname, guid); - QueryResult* result = CharacterDatabase.PQuery("SELECT * FROM %s WHERE %s", tableFrom, wherestr.c_str()); - if (!result) + auto queryResult = CharacterDatabase.PQuery("SELECT * FROM %s WHERE %s", tableFrom, wherestr.c_str()); + if (!queryResult) return; do @@ -324,22 +324,20 @@ void PlayerDumpWriter::DumpTableContent(std::string& dump, uint32 guid, char con switch (type) { case DTT_INVENTORY: - StoreGUID(result, 3, items); break; // item guid collection (character_inventory.item) + StoreGUID(queryResult.get(), 3, items); break; // item guid collection (character_inventory.item) case DTT_PET: - StoreGUID(result, 0, pets); break; // pet petnumber collection (character_pet.id) + StoreGUID(queryResult.get(), 0, pets); break; // pet petnumber collection (character_pet.id) case DTT_MAIL: - StoreGUID(result, 0, mails); // mail id collection (mail.id) + StoreGUID(queryResult.get(), 0, mails); // mail id collection (mail.id) case DTT_MAIL_ITEM: - StoreGUID(result, 1, items); break; // item guid collection (mail_items.item_guid) + StoreGUID(queryResult.get(), 1, items); break; // item guid collection (mail_items.item_guid) default: break; } - dump += CreateDumpString(tableTo, result); + dump += CreateDumpString(tableTo, queryResult.get()); dump += "\n"; } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); } while (guids && guids_itr != guids->end()); // not set case iterate single time, set case iterate for all guids } @@ -417,18 +415,16 @@ DumpReturn PlayerDumpReader::LoadDump(const std::string& file, uint32 account, s if (!fin) return DUMP_FILE_OPEN_ERROR; - QueryResult* result; char newguid[20], chraccount[20], newpetid[20], currpetid[20], lastpetid[20]; // make sure the same guid doesn't already exist and is safe to use bool incHighest = true; if (guid != 0 && guid < sObjectMgr.m_CharGuids.GetNextAfterMaxUsed()) { - result = CharacterDatabase.PQuery("SELECT * FROM characters WHERE guid = '%u'", guid); - if (result) + auto queryResult = CharacterDatabase.PQuery("SELECT * FROM characters WHERE guid = '%u'", guid); + if (queryResult) { guid = sObjectMgr.m_CharGuids.GetNextAfterMaxUsed(); - delete result; } else incHighest = false; } @@ -442,11 +438,10 @@ DumpReturn PlayerDumpReader::LoadDump(const std::string& file, uint32 account, s if (ObjectMgr::CheckPlayerName(name, true) == CHAR_NAME_SUCCESS) { CharacterDatabase.escape_string(name); // for safe, we use name only for sql quearies anyway - result = CharacterDatabase.PQuery("SELECT * FROM characters WHERE name = '%s'", name.c_str()); - if (result) + auto queryResult = CharacterDatabase.PQuery("SELECT * FROM characters WHERE name = '%s'", name.c_str()); + if (queryResult) { name.clear(); // use the one from the dump - delete result; } } else @@ -557,11 +552,9 @@ DumpReturn PlayerDumpReader::LoadDump(const std::string& file, uint32 account, s name = getnth(line, 3); // characters.name CharacterDatabase.escape_string(name); - result = CharacterDatabase.PQuery("SELECT * FROM characters WHERE name = '%s'", name.c_str()); - if (result) + auto queryResult = CharacterDatabase.PQuery("SELECT * FROM characters WHERE name = '%s'", name.c_str()); + if (queryResult) { - delete result; - if (!changenth(line, 36, "1")) // characters.at_login set to "rename on login" ROLLBACK(DUMP_FILE_BROKEN); diff --git a/src/game/World/World.cpp b/src/game/World/World.cpp index e31392560fe..979f54f45ce 100644 --- a/src/game/World/World.cpp +++ b/src/game/World/World.cpp @@ -2014,7 +2014,7 @@ BanReturn World::BanAccount(BanMode mode, std::string nameOrIP, uint32 duration_ std::string safe_author = author; LoginDatabase.escape_string(safe_author); - QueryResult* resultAccounts; // used for kicking + std::unique_ptr resultAccounts; // used for kicking ///- Update the database with ban information switch (mode) @@ -2063,7 +2063,6 @@ BanReturn World::BanAccount(BanMode mode, std::string nameOrIP, uint32 duration_ } while (resultAccounts->NextRow()); - delete resultAccounts; return BAN_SUCCESS; } diff --git a/src/mangosd/CliRunnable.cpp b/src/mangosd/CliRunnable.cpp index b503d3c9df4..2497b95e48b 100644 --- a/src/mangosd/CliRunnable.cpp +++ b/src/mangosd/CliRunnable.cpp @@ -118,14 +118,14 @@ bool ChatHandler::GetDeletedCharacterInfoList(DeletedInfoList& foundList, std::s { // search by GUID if (isNumeric(searchString)) - resultChar.reset(CharacterDatabase.PQuery("SELECT guid, deleteInfos_Name, deleteInfos_Account, deleteDate FROM characters WHERE deleteDate IS NOT NULL AND guid = %u", uint32(atoi(searchString.c_str())))); + resultChar = CharacterDatabase.PQuery("SELECT guid, deleteInfos_Name, deleteInfos_Account, deleteDate FROM characters WHERE deleteDate IS NOT NULL AND guid = %u", uint32(atoi(searchString.c_str()))); // search by name else { if (!normalizePlayerName(searchString)) return false; - resultChar.reset(CharacterDatabase.PQuery("SELECT guid, deleteInfos_Name, deleteInfos_Account, deleteDate FROM characters WHERE deleteDate IS NOT NULL AND deleteInfos_Name " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'"), searchString.c_str())); + resultChar = CharacterDatabase.PQuery("SELECT guid, deleteInfos_Name, deleteInfos_Account, deleteDate FROM characters WHERE deleteDate IS NOT NULL AND deleteInfos_Name " _LIKE_ " " _CONCAT3_("'%%'", "'%s'", "'%%'"), searchString.c_str()); } } else @@ -473,10 +473,10 @@ bool ChatHandler::HandleAccountOnlineListCommand(char* args) return false; ///- Get the list of accounts ID logged to the realm - // 0 1 2 3 4 - QueryResult* result = LoginDatabase.PQuery("SELECT distinct a.id, username, ip, gmlevel, expansion FROM account a join account_logons b on(a.id=b.accountId) WHERE active_realm_id = %u", realmID); + // 0 1 2 3 4 + auto queryResult = LoginDatabase.PQuery("SELECT distinct a.id, username, ip, gmlevel, expansion FROM account a join account_logons b on(a.id=b.accountId) WHERE active_realm_id = %u", realmID); - return ShowAccountListHelper(result, &limit); + return ShowAccountListHelper(std::move(queryResult), &limit); } /// Create an account diff --git a/src/realmd/AuthSocket.cpp b/src/realmd/AuthSocket.cpp index 92ae7cea48f..1821e054de4 100644 --- a/src/realmd/AuthSocket.cpp +++ b/src/realmd/AuthSocket.cpp @@ -393,10 +393,10 @@ bool AuthSocket::_HandleLogonChallenge() { ///- Get the account details from the account table // No SQL injection (escaped user name) - QueryResult* result = LoginDatabase.PQuery("SELECT id,locked,lockedIp,gmlevel,v,s,token FROM account WHERE username = '%s'", _safelogin.c_str()); - if (result) + auto queryResult = LoginDatabase.PQuery("SELECT id,locked,lockedIp,gmlevel,v,s,token FROM account WHERE username = '%s'", _safelogin.c_str()); + if (queryResult) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); ///- If the IP is 'locked', check that the player comes indeed from the correct IP address bool locked = false; @@ -430,7 +430,7 @@ bool AuthSocket::_HandleLogonChallenge() if (!locked && !broken) { ///- If the account is banned, reject the logon attempt - QueryResult* banresult = LoginDatabase.PQuery("SELECT banned_at,expires_at FROM account_banned WHERE " + auto banresult = LoginDatabase.PQuery("SELECT banned_at,expires_at FROM account_banned WHERE " "account_id = %u AND active = 1 AND (expires_at > UNIX_TIMESTAMP() OR expires_at = banned_at)", fields[0].GetUInt32()); if (banresult) { @@ -444,8 +444,6 @@ bool AuthSocket::_HandleLogonChallenge() pkt << uint8(AUTH_LOGON_FAILED_SUSPENDED); BASIC_LOG("[AuthChallenge] Temporarily banned account %s tries to login!", _login.c_str()); } - - delete banresult; } else { @@ -501,7 +499,6 @@ bool AuthSocket::_HandleLogonChallenge() _status = STATUS_LOGON_PROOF; } } - delete result; } else // no account pkt << uint8(AUTH_LOGON_FAILED_UNKNOWN_ACCOUNT); @@ -632,7 +629,7 @@ bool AuthSocket::_HandleLogonProof() // Increment number of failed logins by one and if it reaches the limit temporarily ban that account or IP LoginDatabase.PExecute("UPDATE account SET failed_logins = failed_logins + 1 WHERE username = '%s'", _safelogin.c_str()); - if (QueryResult* loginfail = LoginDatabase.PQuery("SELECT id, failed_logins FROM account WHERE username = '%s'", _safelogin.c_str())) + if (auto loginfail = LoginDatabase.PQuery("SELECT id, failed_logins FROM account WHERE username = '%s'", _safelogin.c_str())) { Field* fields = loginfail->Fetch(); uint32 failed_logins = fields[1].GetUInt32(); @@ -661,7 +658,6 @@ bool AuthSocket::_HandleLogonProof() current_ip.c_str(), WrongPassBanTime, _login.c_str(), failed_logins); } } - delete loginfail; } } } @@ -711,19 +707,18 @@ bool AuthSocket::_HandleReconnectChallenge() EndianConvert(ch->build); _build = ch->build; - QueryResult* result = LoginDatabase.PQuery("SELECT sessionkey FROM account WHERE username = '%s'", _safelogin.c_str()); + auto queryResult = LoginDatabase.PQuery("SELECT sessionkey FROM account WHERE username = '%s'", _safelogin.c_str()); // Stop if the account is not found - if (!result) + if (!queryResult) { sLog.outError("[ERROR] user %s tried to login and we cannot find his session key in the database.", _login.c_str()); Close(); return false; } - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); srp.SetStrongSessionKey(fields[0].GetString()); - delete result; ///- All good, await client's proof _status = STATUS_RECON_PROOF; @@ -803,17 +798,16 @@ bool AuthSocket::_HandleRealmList() ///- Get the user id (else close the connection) // No SQL injection (escaped user name) - QueryResult* result = LoginDatabase.PQuery("SELECT id, gmlevel FROM account WHERE username = '%s'", _safelogin.c_str()); - if (!result) + auto queryResult = LoginDatabase.PQuery("SELECT id, gmlevel FROM account WHERE username = '%s'", _safelogin.c_str()); + if (!queryResult) { sLog.outError("[ERROR] user %s tried to login and we cannot find him in the database.", _login.c_str()); Close(); return false; } - uint32 id = (*result)[0].GetUInt32(); - uint8 accountSecurityLevel = (*result)[1].GetUInt8(); - delete result; + uint32 id = (*queryResult)[0].GetUInt32(); + uint8 accountSecurityLevel = (*queryResult)[1].GetUInt8(); ///- Update realm list if need sRealmList.UpdateIfNeed(); @@ -847,12 +841,11 @@ void AuthSocket::LoadRealmlist(ByteBuffer& pkt, uint32 acctid, uint8 securityLev uint8 AmountOfCharacters; // No SQL injection. id of realm is controlled by the database. - QueryResult* result = LoginDatabase.PQuery("SELECT numchars FROM realmcharacters WHERE realmid = '%d' AND acctid='%u'", i.second.m_ID, acctid); - if (result) + auto queryResult = LoginDatabase.PQuery("SELECT numchars FROM realmcharacters WHERE realmid = '%d' AND acctid='%u'", i.second.m_ID, acctid); + if (queryResult) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); AmountOfCharacters = fields[0].GetUInt8(); - delete result; } else AmountOfCharacters = 0; @@ -912,12 +905,11 @@ void AuthSocket::LoadRealmlist(ByteBuffer& pkt, uint32 acctid, uint8 securityLev uint8 AmountOfCharacters; // No SQL injection. id of realm is controlled by the database. - QueryResult* result = LoginDatabase.PQuery("SELECT numchars FROM realmcharacters WHERE realmid = '%d' AND acctid='%u'", i.second.m_ID, acctid); - if (result) + auto queryResult = LoginDatabase.PQuery("SELECT numchars FROM realmcharacters WHERE realmid = '%d' AND acctid='%u'", i.second.m_ID, acctid); + if (queryResult) { - Field* fields = result->Fetch(); + Field* fields = queryResult->Fetch(); AmountOfCharacters = fields[0].GetUInt8(); - delete result; } else AmountOfCharacters = 0; diff --git a/src/shared/Database/Database.cpp b/src/shared/Database/Database.cpp index 5941a2f8867..305e1600491 100644 --- a/src/shared/Database/Database.cpp +++ b/src/shared/Database/Database.cpp @@ -283,9 +283,10 @@ bool Database::PExecuteLog(const char* format, ...) return Execute(szQuery); } -QueryResult* Database::PQuery(const char* format, ...) +std::unique_ptr Database::PQuery(const char* format, ...) { - if (!format) return nullptr; + if (!format) + return {}; va_list ap; char szQuery [MAX_QUERY_LEN]; @@ -296,10 +297,10 @@ QueryResult* Database::PQuery(const char* format, ...) if (res == -1) { sLog.outError("SQL Query truncated (and not execute) for format: %s", format); - return nullptr; + return {}; } - return Query(szQuery).release(); + return Query(szQuery); } QueryNamedResult* Database::PQueryNamed(const char* format, ...) @@ -446,10 +447,9 @@ bool Database::RollbackTransaction() bool Database::CheckRequiredField(char const* table_name, char const* required_name) { // check required field - QueryResult* result = PQuery("SELECT %s FROM %s LIMIT 1", required_name, table_name); - if (result) + auto queryResult = PQuery("SELECT %s FROM %s LIMIT 1", required_name, table_name); + if (queryResult) { - delete result; return true; } diff --git a/src/shared/Database/Database.h b/src/shared/Database/Database.h index ecabede6bce..80941aaeac6 100644 --- a/src/shared/Database/Database.h +++ b/src/shared/Database/Database.h @@ -124,7 +124,7 @@ class Database return guard->QueryNamed(sql); } - QueryResult* PQuery(const char* format, ...) ATTR_PRINTF(2, 3); + std::unique_ptr PQuery(const char* format, ...) ATTR_PRINTF(2, 3); QueryNamedResult* PQueryNamed(const char* format, ...) ATTR_PRINTF(2, 3); bool DirectExecute(const char* sql) const diff --git a/src/shared/Database/SQLStorageImpl.h b/src/shared/Database/SQLStorageImpl.h index 1a2ad24a979..273bc12eb5b 100644 --- a/src/shared/Database/SQLStorageImpl.h +++ b/src/shared/Database/SQLStorageImpl.h @@ -306,30 +306,28 @@ template void SQLStorageLoaderBase::Load(StorageClass& store, bool error_at_empty /*= true*/) { Field* fields = nullptr; - QueryResult* result = WorldDatabase.PQuery("SELECT MAX(%s) FROM %s", store.EntryFieldName(), store.GetTableName()); - if (!result) + auto queryResult = WorldDatabase.PQuery("SELECT MAX(%s) FROM %s", store.EntryFieldName(), store.GetTableName()); + if (!queryResult) { sLog.outError("Error loading %s table (not exist?)\n", store.GetTableName()); Log::WaitBeforeContinueIfNeed(); exit(1); // Stop server at loading non exited table or not accessable table } - uint32 maxRecordId = (*result)[0].GetUInt32() + 1; + uint32 maxRecordId = (*queryResult)[0].GetUInt32() + 1; uint32 recordCount = 0; uint32 recordsize = 0; - delete result; - result = WorldDatabase.PQuery("SELECT COUNT(*) FROM %s", store.GetTableName()); - if (result) + queryResult = WorldDatabase.PQuery("SELECT COUNT(*) FROM %s", store.GetTableName()); + if (queryResult) { - fields = result->Fetch(); + fields = queryResult->Fetch(); recordCount = fields[0].GetUInt32(); - delete result; } - result = WorldDatabase.PQuery("SELECT * FROM %s", store.GetTableName()); + queryResult = WorldDatabase.PQuery("SELECT * FROM %s", store.GetTableName()); - if (!result) + if (!queryResult) { if (error_at_empty) sLog.outError("%s table is empty!\n", store.GetTableName()); @@ -340,11 +338,10 @@ void SQLStorageLoaderBase::Load(StorageClass& store return; } - if (store.GetSrcFieldCount() != result->GetFieldCount()) + if (store.GetSrcFieldCount() != queryResult->GetFieldCount()) { recordCount = 0; sLog.outError("Error in %s table, probably sql file format was updated (there should be %d fields in sql).\n", store.GetTableName(), store.GetSrcFieldCount()); - delete result; Log::WaitBeforeContinueIfNeed(); exit(1); // Stop server at loading broken or non-compatible table. } @@ -391,7 +388,7 @@ void SQLStorageLoaderBase::Load(StorageClass& store BarGoLink bar(recordCount); do { - fields = result->Fetch(); + fields = queryResult->Fetch(); bar.step(); char* record = store.createRecord(fields[0].GetUInt32()); @@ -442,9 +439,7 @@ void SQLStorageLoaderBase::Load(StorageClass& store ++y; } } - while (result->NextRow()); - - delete result; + while (queryResult->NextRow()); } #endif