diff --git a/src/common/Threading/PCQueue.h b/src/common/Threading/PCQueue.h index 6484053655e0b6..7ced25475262b8 100644 --- a/src/common/Threading/PCQueue.h +++ b/src/common/Threading/PCQueue.h @@ -28,31 +28,37 @@ template class ProducerConsumerQueue { private: - std::mutex _queueLock; + mutable std::mutex _queueLock; std::queue _queue; std::condition_variable _condition; - std::atomic _shutdown; + std::atomic _shutdown{ false }; public: - ProducerConsumerQueue() : _shutdown(false) { } + ProducerConsumerQueue() = default; - void Push(const T& value) + void Push(T const& value) { std::lock_guard lock(_queueLock); - _queue.push(std::move(value)); - + _queue.push(value); _condition.notify_one(); } - bool Empty() + void Push(T&& value) { std::lock_guard lock(_queueLock); + _queue.push(std::move(value)); + _condition.notify_one(); + } + bool Empty() const + { + std::lock_guard lock(_queueLock); return _queue.empty(); } - [[nodiscard]] size_t Size() const + std::size_t Size() const { + std::lock_guard lock(_queueLock); return _queue.size(); } @@ -61,14 +67,10 @@ class ProducerConsumerQueue std::lock_guard lock(_queueLock); if (_queue.empty() || _shutdown) - { return false; - } - - value = _queue.front(); + value = std::move(_queue.front()); _queue.pop(); - return true; } @@ -79,17 +81,28 @@ class ProducerConsumerQueue // we could be using .wait(lock, predicate) overload here but it is broken // https://connect.microsoft.com/VisualStudio/feedback/details/1098841 while (_queue.empty() && !_shutdown) - { _condition.wait(lock); - } if (_queue.empty() || _shutdown) - { return; - } value = _queue.front(); + _queue.pop(); + } + + void WaitAndPop(T& value, std::atomic const& customCancel) + { + std::unique_lock lock(_queueLock); + + // we could be using .wait(lock, predicate) overload here but it is broken + // https://connect.microsoft.com/VisualStudio/feedback/details/1098841 + while (_queue.empty() && !_shutdown && !customCancel) + _condition.wait(lock); + + if (_queue.empty() || _shutdown || customCancel) + return; + value = _queue.front(); _queue.pop(); } @@ -101,22 +114,21 @@ class ProducerConsumerQueue { T& value = _queue.front(); - DeleteQueuedObject(value); + if constexpr (std::is_pointer_v) + delete value; _queue.pop(); } _shutdown = true; - _condition.notify_all(); } -private: - template - typename std::enable_if::value>::type DeleteQueuedObject(E& obj) { delete obj; } - - template - typename std::enable_if::value>::type DeleteQueuedObject(E const& /*packet*/) { } + void NotifyAll() + { + std::lock_guard lock(_queueLock); + _condition.notify_all(); + } }; #endif diff --git a/src/server/database/Database/MySQLThreading.cpp b/src/common/Utilities/FileUtil.cpp similarity index 51% rename from src/server/database/Database/MySQLThreading.cpp rename to src/common/Utilities/FileUtil.cpp index d15b1d70f6f273..e751c38dd08c02 100644 --- a/src/server/database/Database/MySQLThreading.cpp +++ b/src/common/Utilities/FileUtil.cpp @@ -15,20 +15,42 @@ * with this program. If not, see . */ -#include "MySQLThreading.h" -#include "MySQLWorkaround.h" +#include "FileUtil.h" +#include +#include -void MySQL::Library_Init() -{ - mysql_library_init(-1, nullptr, nullptr); -} +namespace fs = std::filesystem; -void MySQL::Library_End() +void Acore::File::CorrectDirPath(std::string& path) { - mysql_library_end(); + if (path.empty()) + { + path = fs::absolute(fs::current_path()).generic_string(); + return; + } + + std::replace(std::begin(path), std::end(path), '\\', '/'); + + if (path.at(path.length() - 1) != '/') + path.push_back('/'); } -uint32 MySQL::GetLibraryVersion() +bool Acore::File::CreateDirIfNeed(std::string_view path) { - return MYSQL_VERSION_ID; + if (path.empty()) + return true; + + fs::path dirPath{ path }; + + if (fs::exists(dirPath) && fs::is_directory(path)) + return true; + + try + { + return fs::create_directory(dirPath); + } + catch (...) + { + return false; + } } diff --git a/src/server/database/Database/MySQLThreading.h b/src/common/Utilities/FileUtil.h similarity index 78% rename from src/server/database/Database/MySQLThreading.h rename to src/common/Utilities/FileUtil.h index c14e6872eebe9d..8852826ba2807e 100644 --- a/src/server/database/Database/MySQLThreading.h +++ b/src/common/Utilities/FileUtil.h @@ -15,16 +15,16 @@ * with this program. If not, see . */ -#ifndef _MYSQLTHREADING_H -#define _MYSQLTHREADING_H +#ifndef AC_FILE_UTIL_H_ +#define AC_FILE_UTIL_H_ #include "Define.h" +#include -namespace MySQL +namespace Acore::File { - AC_DATABASE_API void Library_Init(); - AC_DATABASE_API void Library_End(); - AC_DATABASE_API uint32 GetLibraryVersion(); + AC_COMMON_API void CorrectDirPath(std::string& path); + AC_COMMON_API bool CreateDirIfNeed(std::string_view path); } #endif diff --git a/src/common/Utilities/StopWatch.h b/src/common/Utilities/StopWatch.h new file mode 100644 index 00000000000000..b1f0bc78a19375 --- /dev/null +++ b/src/common/Utilities/StopWatch.h @@ -0,0 +1,62 @@ +/* + * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU Affero General Public License as published by the + * Free Software Foundation; either version 3 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef AC_STOP_WATCH_H_ +#define AC_STOP_WATCH_H_ + +#include "Timer.h" +#include + +class StopWatch +{ + using clock = std::chrono::steady_clock; + +public: + explicit StopWatch(uint8 outCount = 3) + : _startTime{ clock::now() }, _outCount{ outCount } {} + + [[nodiscard]] Microseconds Elapsed() const + { + return std::chrono::duration_cast(clock::now() - _startTime); + } + + void Reset() + { + _startTime = clock::now(); + } + + [[nodiscard]] uint8 GetOutCount() const + { + return _outCount; + } + +private: + std::chrono::time_point _startTime; + uint8 _outCount; +}; + +template<> +struct fmt::formatter : formatter +{ + template + auto format(const StopWatch& sw, FormatContext& ctx) -> decltype(ctx.out()) + { + return formatter::format(Acore::Time::ToTimeString(sw.Elapsed(), sw.GetOutCount()), ctx); + } +}; + +#endif diff --git a/src/common/Utilities/StringFormat.cpp b/src/common/Utilities/StringFormat.cpp index c547a2d710e307..ffde23a205e22b 100644 --- a/src/common/Utilities/StringFormat.cpp +++ b/src/common/Utilities/StringFormat.cpp @@ -19,6 +19,8 @@ #include "Define.h" #include +constexpr char CHAR_WHITESPACE = ' '; + template AC_COMMON_API Str Acore::String::Trim(const Str& s, const std::locale& loc /*= std::locale()*/) { @@ -50,6 +52,22 @@ AC_COMMON_API Str Acore::String::Trim(const Str& s, const std::locale& loc /*= s return s; } +std::string_view Acore::String::TrimLeft(std::string_view str) +{ + while (!str.empty() && (str.front() == CHAR_WHITESPACE)) + str.remove_prefix(1); + + return str; +} + +std::string_view Acore::String::TrimRight(std::string_view str) +{ + while (!str.empty() && (str.back() == CHAR_WHITESPACE)) + str.remove_suffix(1); + + return str; +} + std::string Acore::String::TrimRightInPlace(std::string& str) { int pos = int(str.size()) - 1; @@ -71,7 +89,8 @@ std::string Acore::String::TrimRightInPlace(std::string& str) * @param suffix Character to add at the end of the str * @return std::string Suffixed string */ -std::string Acore::String::AddSuffixIfNotExists(std::string str, const char suffix) { +std::string Acore::String::AddSuffixIfNotExists(std::string& str, char suffix) +{ if (str.empty() || (str.at(str.length() - 1) != suffix)) str.push_back(suffix); diff --git a/src/common/Utilities/StringFormat.h b/src/common/Utilities/StringFormat.h index b91509181f3821..0cd3cf286901a3 100644 --- a/src/common/Utilities/StringFormat.h +++ b/src/common/Utilities/StringFormat.h @@ -71,9 +71,10 @@ namespace Acore::String template AC_COMMON_API Str Trim(const Str& s, const std::locale& loc = std::locale()); + AC_COMMON_API std::string_view TrimLeft(std::string_view str); + AC_COMMON_API std::string_view TrimRight(std::string_view str); AC_COMMON_API std::string TrimRightInPlace(std::string& str); - - AC_COMMON_API std::string AddSuffixIfNotExists(std::string str, const char suffix); + AC_COMMON_API std::string AddSuffixIfNotExists(std::string& str, char suffix); } #endif diff --git a/src/common/Utilities/Timer.cpp b/src/common/Utilities/Timer.cpp index e7cb691a1c826d..1baa6c9307fa72 100644 --- a/src/common/Utilities/Timer.cpp +++ b/src/common/Utilities/Timer.cpp @@ -17,6 +17,7 @@ #include "Timer.h" #include "StringFormat.h" +#include "StringConvert.h" #include #include @@ -72,6 +73,105 @@ AC_COMMON_API uint32 Acore::Time::TimeStringTo(std::string_view timestr return secs; } +std::string Acore::Time::ToTimeString(Microseconds durationTime, uint8 outCount /*= 3*/, TimeFormat timeFormat /*= TimeFormat::ShortText*/) +{ + uint64 microsecs = durationTime.count() % 1000; + uint64 millisecs = (durationTime.count() / TimeDiff::MILLISECONDS) % 1000; + uint64 secs = (durationTime.count() / TimeDiff::SECONDS) % 60; + uint64 minutes = (durationTime.count() / TimeDiff::MINUTES) % 60; + uint64 hours = (durationTime.count() / TimeDiff::HOURS) % 24; + uint64 days = durationTime.count() / TimeDiff::DAYS; + + std::string out; + uint8 count = 0; + bool isFirst = false; + + if (timeFormat == TimeFormat::Numeric) + { + auto AddOutNumerlic = [&isFirst, &out, &count, outCount](uint64 time) + { + if (count >= outCount) + return; + + if (!isFirst) + { + isFirst = true; + out.append(Acore::StringFormatFmt("{}:", time)); + } + else + out.append(Acore::StringFormatFmt("{:02}:", time)); + + count++; + }; + + if (days) + AddOutNumerlic(days); + + if (hours) + AddOutNumerlic(hours); + + if (minutes) + AddOutNumerlic(minutes); + + if (secs) + AddOutNumerlic(secs); + + if (millisecs) + AddOutNumerlic(millisecs); + + if (microsecs) + AddOutNumerlic(microsecs); + + // Delete last (:) + if (!out.empty()) + out.pop_back(); + + return out; + } + + auto AddOut = [&out, &count, timeFormat, outCount](uint32 timeCount, std::string_view shortText, std::string_view fullText1, std::string_view fullText) + { + if (count >= outCount) + return; + + out.append(Acore::ToString(timeCount)); + + switch (timeFormat) + { + case TimeFormat::ShortText: + out.append(shortText); + break; + case TimeFormat::FullText: + out.append(timeCount == 1 ? fullText1 : fullText); + break; + default: + out.append(""); + } + + count++; + }; + + if (days) + AddOut(days, "d ", " Day ", " Days "); + + if (hours) + AddOut(hours, "h ", " Hour ", " Hours "); + + if (minutes) + AddOut(minutes, "m ", " Minute ", " Minutes "); + + if (secs) + AddOut(secs, "s ", " Second ", " Seconds "); + + if (millisecs) + AddOut(millisecs, "ms ", " Millisecond ", " Milliseconds "); + + if (microsecs) + AddOut(microsecs, "us ", " Microsecond ", " Microseconds "); + + return std::string{ Acore::String::TrimRight(out) }; +} + template<> AC_COMMON_API std::string Acore::Time::ToTimeString(uint64 durationTime, TimeOutput timeOutput /*= TimeOutput::Seconds*/, TimeFormat timeFormat /*= TimeFormat::ShortText*/) { diff --git a/src/common/Utilities/Timer.h b/src/common/Utilities/Timer.h index e8d392439237d3..bcff11433c17d8 100644 --- a/src/common/Utilities/Timer.h +++ b/src/common/Utilities/Timer.h @@ -43,6 +43,8 @@ namespace Acore::Time template AC_COMMON_API uint32 TimeStringTo(std::string_view timeString); + AC_COMMON_API std::string ToTimeString(Microseconds durationTime, uint8 outCount = 3, TimeFormat timeFormat = TimeFormat::ShortText); + template AC_COMMON_API std::string ToTimeString(uint64 durationTime, TimeOutput timeOutput = TimeOutput::Seconds, TimeFormat timeFormat = TimeFormat::ShortText); diff --git a/src/server/apps/authserver/Main.cpp b/src/server/apps/authserver/Main.cpp index 4c110db7aaaf49..ae4c14eeba032c 100644 --- a/src/server/apps/authserver/Main.cpp +++ b/src/server/apps/authserver/Main.cpp @@ -28,13 +28,12 @@ #include "Banner.h" #include "Config.h" #include "DatabaseEnv.h" -#include "DatabaseLoader.h" +#include "DatabaseMgr.h" #include "DeadlineTimer.h" #include "GitRevision.h" #include "IPLocation.h" #include "IoContext.h" #include "Log.h" -#include "MySQLThreading.h" #include "OpenSSLCrypto.h" #include "ProcessPriority.h" #include "RealmList.h" @@ -61,7 +60,7 @@ namespace fs = std::filesystem; bool StartDB(); void StopDB(); void SignalHandler(std::weak_ptr ioContextRef, boost::system::error_code const& error, int signalNumber); -void KeepDatabaseAliveHandler(std::weak_ptr dbPingTimerRef, int32 dbPingInterval, boost::system::error_code const& error); +void DatabaseUpdateHandler(std::weak_ptr dbUpdateTimerRef, boost::system::error_code const& error); void BanExpiryHandler(std::weak_ptr banExpiryCheckTimerRef, int32 banExpiryCheckInterval, boost::system::error_code const& error); variables_map GetConsoleArguments(int argc, char** argv, fs::path& configFile); @@ -177,11 +176,10 @@ int main(int argc, char** argv) // Set process priority according to configuration settings SetProcessPriority("server.authserver", sConfigMgr->GetOption(CONFIG_PROCESSOR_AFFINITY, 0), sConfigMgr->GetOption(CONFIG_HIGH_PRIORITY, false)); - // Enabled a timed callback for handling the database keep alive ping - int32 dbPingInterval = sConfigMgr->GetOption("MaxPingTime", 30); - std::shared_ptr dbPingTimer = std::make_shared(*ioContext); - dbPingTimer->expires_from_now(boost::posix_time::minutes(dbPingInterval)); - dbPingTimer->async_wait(std::bind(&KeepDatabaseAliveHandler, std::weak_ptr(dbPingTimer), dbPingInterval, std::placeholders::_1)); + // Enabled a timed callback for handling the database update + std::shared_ptr dbUpdateTimer = std::make_shared(*ioContext); + dbUpdateTimer->expires_from_now(boost::posix_time::milliseconds(1)); + dbUpdateTimer->async_wait(std::bind(&DatabaseUpdateHandler, std::weak_ptr(dbUpdateTimer), std::placeholders::_1)); int32 banExpiryCheckInterval = sConfigMgr->GetOption("BanExpiryCheckInterval", 60); std::shared_ptr banExpiryCheckTimer = std::make_shared(*ioContext); @@ -192,7 +190,7 @@ int main(int argc, char** argv) ioContext->run(); banExpiryCheckTimer->cancel(); - dbPingTimer->cancel(); + dbUpdateTimer->cancel(); LOG_INFO("server.authserver", "Halting process..."); @@ -204,16 +202,8 @@ int main(int argc, char** argv) /// Initialize connection to the database bool StartDB() { - MySQL::Library_Init(); - - // Load databases - // NOTE: While authserver is singlethreaded you should keep synch_threads == 1. - // Increasing it is just silly since only 1 will be used ever. - DatabaseLoader loader("server.authserver"); - loader - .AddDatabase(LoginDatabase, "Login"); - - if (!loader.Load()) + sDatabaseMgr->AddDatabase(LoginDatabase, "Login"); + if (!sDatabaseMgr->Load()) return false; LOG_INFO("server.authserver", "Started auth database connection pool."); @@ -224,8 +214,7 @@ bool StartDB() /// Close the connection to the database void StopDB() { - LoginDatabase.Close(); - MySQL::Library_End(); + sDatabaseMgr->CloseAllConnections(); } void SignalHandler(std::weak_ptr ioContextRef, boost::system::error_code const& error, int /*signalNumber*/) @@ -239,17 +228,16 @@ void SignalHandler(std::weak_ptr ioContextRef, boost::sy } } -void KeepDatabaseAliveHandler(std::weak_ptr dbPingTimerRef, int32 dbPingInterval, boost::system::error_code const& error) +void DatabaseUpdateHandler(std::weak_ptr dbUpdateTimerRef, boost::system::error_code const& error) { if (!error) { - if (std::shared_ptr dbPingTimer = dbPingTimerRef.lock()) + if (std::shared_ptr dbUpdateTimer = dbUpdateTimerRef.lock()) { - LOG_INFO("server.authserver", "Ping MySQL to keep connection alive"); - LoginDatabase.KeepAlive(); + sDatabaseMgr->Update(0ms); - dbPingTimer->expires_from_now(boost::posix_time::minutes(dbPingInterval)); - dbPingTimer->async_wait(std::bind(&KeepDatabaseAliveHandler, dbPingTimerRef, dbPingInterval, std::placeholders::_1)); + dbUpdateTimer->expires_from_now(boost::posix_time::milliseconds(1)); + dbUpdateTimer->async_wait(std::bind(&DatabaseUpdateHandler, dbUpdateTimerRef, std::placeholders::_1)); } } } diff --git a/src/server/apps/authserver/Server/AuthSession.cpp b/src/server/apps/authserver/Server/AuthSession.cpp index b2ae2cab369f0c..b92a3c81830e19 100644 --- a/src/server/apps/authserver/Server/AuthSession.cpp +++ b/src/server/apps/authserver/Server/AuthSession.cpp @@ -173,7 +173,7 @@ void AuthSession::Start() std::string ip_address = GetRemoteIpAddress().to_string(); LOG_TRACE("session", "Accepted connection from {}", ip_address); - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_IP_INFO); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_IP_INFO); stmt->SetData(0, ip_address); _queryProcessor.AddCallback(LoginDatabase.AsyncQuery(stmt).WithPreparedCallback(std::bind(&AuthSession::CheckIpCallback, this, std::placeholders::_1))); @@ -309,7 +309,7 @@ bool AuthSession::HandleLogonChallenge() _localizationName[i] = challenge->country[4 - i - 1]; // Get the account details from the account table - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_LOGONCHALLENGE); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_LOGONCHALLENGE); stmt->SetData(0, GetRemoteIpAddress().to_string()); stmt->SetData(1, login); @@ -517,7 +517,7 @@ bool AuthSession::HandleLogonProof() // No SQL injection (escaped user name) and IP address as received by socket std::string address = sConfigMgr->GetOption("AllowLoggingIPAddressesInDatabase", true, true) ? GetRemoteIpAddress().to_string() : "0.0.0.0"; - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_LOGONPROOF); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_LOGONPROOF); stmt->SetData(0, _sessionKey); stmt->SetData(1, address); stmt->SetData(2, GetLocaleByName(_localizationName)); @@ -573,7 +573,7 @@ bool AuthSession::HandleLogonProof() // We can not include the failed account login hook. However, this is a workaround to still log this. if (sConfigMgr->GetOption("WrongPass.Logging", false)) { - LoginDatabasePreparedStatement* logstmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_FALP_IP_LOGGING); + LoginDatabasePreparedStatement logstmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_FALP_IP_LOGGING); logstmt->SetData(0, _accountInfo.Id); logstmt->SetData(1, GetRemoteIpAddress().to_string()); logstmt->SetData(2, "Login to WoW Failed - Incorrect Password"); @@ -584,7 +584,7 @@ bool AuthSession::HandleLogonProof() if (MaxWrongPassCount > 0) { //Increment number of failed logins by one and if it reaches the limit temporarily ban that account or IP - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_FAILEDLOGINS); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_FAILEDLOGINS); stmt->SetData(0, _accountInfo.Login); LoginDatabase.Execute(stmt); @@ -647,7 +647,7 @@ bool AuthSession::HandleReconnectChallenge() _localizationName[i] = challenge->country[4 - i - 1]; // Get the account details from the account table - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_RECONNECTCHALLENGE); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_RECONNECTCHALLENGE); stmt->SetData(0, GetRemoteIpAddress().to_string()); stmt->SetData(1, login); @@ -733,7 +733,7 @@ bool AuthSession::HandleRealmList() { LOG_DEBUG("server.authserver", "Entering _HandleRealmList"); - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_REALM_CHARACTER_COUNTS); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_REALM_CHARACTER_COUNTS); stmt->SetData(0, _accountInfo.Id); _queryProcessor.AddCallback(LoginDatabase.AsyncQuery(stmt).WithPreparedCallback(std::bind(&AuthSession::RealmListCallback, this, std::placeholders::_1))); diff --git a/src/server/apps/authserver/authserver.conf.dist b/src/server/apps/authserver/authserver.conf.dist index d11634cf76ebcf..192cee73b42187 100644 --- a/src/server/apps/authserver/authserver.conf.dist +++ b/src/server/apps/authserver/authserver.conf.dist @@ -1,7 +1,6 @@ ############################################### # AzerothCore Auth Server configuration file # ############################################### -[authserver] ################################################################################################### # SECTION INDEX @@ -234,22 +233,20 @@ Database.Reconnect.Seconds = 15 Database.Reconnect.Attempts = 20 # -# LoginDatabase.WorkerThreads -# Description: The amount of worker threads spawned to handle asynchronous (delayed) MySQL -# statements. Each worker thread is mirrored with its own connection to the -# Default: 1 +# MaxQueueSize +# Description: Max size queue before open new dynamic async connect for db +# Default: 10 +# -LoginDatabase.WorkerThreads = 1 +MaxQueueSize = 10 # -# LoginDatabase.SynchThreads -# Description: The amount of MySQL connections spawned to handle. -# Default: 1 - (LoginDatabase.WorkerThreads) +# MaxPingTime +# Description: Time (in minutes) between database pings. +# Default: 30 # -LoginDatabase.SynchThreads = 1 - -# +MaxPingTime = 30 ################################################################################################### ################################################################################################### diff --git a/src/server/apps/worldserver/Main.cpp b/src/server/apps/worldserver/Main.cpp index 01b9f56ab9d465..67415e0c2d12de 100644 --- a/src/server/apps/worldserver/Main.cpp +++ b/src/server/apps/worldserver/Main.cpp @@ -30,7 +30,7 @@ #include "Common.h" #include "Config.h" #include "DatabaseEnv.h" -#include "DatabaseLoader.h" +#include "DatabaseMgr.h" #include "DeadlineTimer.h" #include "GitRevision.h" #include "IoContext.h" @@ -38,7 +38,6 @@ #include "Metric.h" #include "ModuleMgr.h" #include "ModulesScriptLoader.h" -#include "MySQLThreading.h" #include "OpenSSLCrypto.h" #include "OutdoorPvPMgr.h" #include "ProcessPriority.h" @@ -288,9 +287,9 @@ int main(int argc, char** argv) sMetric->Initialize(realm.Name, *ioContext, []() { METRIC_VALUE("online_players", sWorld->GetPlayerCount()); - METRIC_VALUE("db_queue_login", uint64(LoginDatabase.QueueSize())); - METRIC_VALUE("db_queue_character", uint64(CharacterDatabase.QueueSize())); - METRIC_VALUE("db_queue_world", uint64(WorldDatabase.QueueSize())); + METRIC_VALUE("db_queue_login", uint64(LoginDatabase.GetQueueSize())); + METRIC_VALUE("db_queue_character", uint64(CharacterDatabase.GetQueueSize())); + METRIC_VALUE("db_queue_world", uint64(WorldDatabase.GetQueueSize())); }); METRIC_EVENT("events", "Worldserver started", ""); @@ -430,16 +429,15 @@ int main(int argc, char** argv) /// Initialize connection to the databases bool StartDB() { - MySQL::Library_Init(); + sDatabaseMgr->SetModuleList(AC_MODULES_LIST); // Load databases - DatabaseLoader loader("server.worldserver", DatabaseLoader::DATABASE_NONE, AC_MODULES_LIST); - loader - .AddDatabase(LoginDatabase, "Login") - .AddDatabase(CharacterDatabase, "Character") - .AddDatabase(WorldDatabase, "World"); + sDatabaseMgr->AddDatabase(LoginDatabase, "Login"); + sDatabaseMgr->AddDatabase(CharacterDatabase, "Character"); + sDatabaseMgr->AddDatabase(WorldDatabase, "World"); +// sDatabaseMgr->AddDatabase(DBCDatabase, "Dbc"); - if (!loader.Load()) + if (!sDatabaseMgr->Load()) return false; ///- Get the realm Id from the configuration file @@ -470,21 +468,15 @@ bool StartDB() WorldDatabase.Execute("UPDATE version SET core_version = '{}', core_revision = '{}'", GitRevision::GetFullVersion(), GitRevision::GetHash()); // One-time query sWorld->LoadDBVersion(); - LOG_INFO("server.loading", "> Version DB world: {}", sWorld->GetDBVersion()); - - sScriptMgr->OnAfterDatabasesLoaded(loader.GetUpdateFlags()); + sScriptMgr->OnAfterDatabasesLoaded(sDatabaseMgr->GetUpdateFlags()); return true; } void StopDB() { - CharacterDatabase.Close(); - WorldDatabase.Close(); - LoginDatabase.Close(); - - MySQL::Library_End(); + sDatabaseMgr->CloseAllConnections(); } /// Clear 'online' status for all accounts with characters in this realm diff --git a/src/server/apps/worldserver/RemoteAccess/RASession.cpp b/src/server/apps/worldserver/RemoteAccess/RASession.cpp index 4bbd1b53851766..90e589c305550b 100644 --- a/src/server/apps/worldserver/RemoteAccess/RASession.cpp +++ b/src/server/apps/worldserver/RemoteAccess/RASession.cpp @@ -125,7 +125,7 @@ bool RASession::CheckAccessLevel(const std::string& user) Utf8ToUpperOnlyLatin(safeUser); - auto* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_ACCESS); + auto stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_ACCESS); stmt->SetData(0, safeUser); PreparedQueryResult result = LoginDatabase.Query(stmt); @@ -161,8 +161,7 @@ bool RASession::CheckPassword(const std::string& user, const std::string& pass) Utf8ToUpperOnlyLatin(safe_pass); std::transform(safe_pass.begin(), safe_pass.end(), safe_pass.begin(), ::toupper); - auto* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_CHECK_PASSWORD_BY_NAME); - + auto stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_CHECK_PASSWORD_BY_NAME); stmt->SetData(0, safe_user); if (PreparedQueryResult result = LoginDatabase.Query(stmt)) diff --git a/src/server/apps/worldserver/worldserver.conf.dist b/src/server/apps/worldserver/worldserver.conf.dist index be7c50cf7d443c..c018deeb937d68 100644 --- a/src/server/apps/worldserver/worldserver.conf.dist +++ b/src/server/apps/worldserver/worldserver.conf.dist @@ -1,7 +1,6 @@ ################################################ # AzerothCore World Server configuration file # ################################################ -[worldserver] ################################################################################################### # SECTION INDEX @@ -123,37 +122,18 @@ Database.Reconnect.Seconds = 15 Database.Reconnect.Attempts = 20 # -# LoginDatabase.WorkerThreads -# WorldDatabase.WorkerThreads -# CharacterDatabase.WorkerThreads -# Description: The amount of worker threads spawned to handle asynchronous (delayed) MySQL -# statements. Each worker thread is mirrored with its own connection to the -# MySQL server and their own thread on the MySQL server. -# Default: 1 - (LoginDatabase.WorkerThreads) -# 1 - (WorldDatabase.WorkerThreads) -# 1 - (CharacterDatabase.WorkerThreads) - -LoginDatabase.WorkerThreads = 1 -WorldDatabase.WorkerThreads = 1 -CharacterDatabase.WorkerThreads = 1 - +# MaxQueueSize +# Description: Max size queue before open new dynamic async connect for db +# Default: 10 # -# LoginDatabase.SynchThreads -# WorldDatabase.SynchThreads -# CharacterDatabase.SynchThreads -# Description: The amount of MySQL connections spawned to handle. -# Default: 1 - (LoginDatabase.WorkerThreads) -# 1 - (WorldDatabase.WorkerThreads) -# 2 - (CharacterDatabase.WorkerThreads) -LoginDatabase.SynchThreads = 1 -WorldDatabase.SynchThreads = 1 -CharacterDatabase.SynchThreads = 2 +MaxQueueSize = 10 # # MaxPingTime # Description: Time (in minutes) between database pings. # Default: 30 +# MaxPingTime = 30 @@ -3954,6 +3934,11 @@ Logger.sql.sql=2,Console DBErrors Logger.sql=4,Console Server Logger.time.update=4,Console Server Logger.module=4,Console Server +Logger.db = 3,Console Server +Logger.db.query = 2,Console DBErrors +Logger.db.update = 4,Console Server +Logger.db.pool = 4,Console Server +Logger.db.connection = 4,Console Server #Logger.achievement=4,Console Server #Logger.addon=4,Console Server diff --git a/src/server/database/Database/AdhocStatement.cpp b/src/server/database/Database/AdhocStatement.cpp deleted file mode 100644 index cb39769cae85f6..00000000000000 --- a/src/server/database/Database/AdhocStatement.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* - * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU Affero General Public License as published by the - * Free Software Foundation; either version 3 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see . - */ - -#include "AdhocStatement.h" -#include "Errors.h" -#include "MySQLConnection.h" -#include "QueryResult.h" - -/*! Basic, ad-hoc queries. */ -BasicStatementTask::BasicStatementTask(std::string_view sql, bool async) : m_result(nullptr) -{ - m_sql = std::string(sql); - m_has_result = async; // If the operation is async, then there's a result - - if (async) - m_result = new QueryResultPromise(); -} - -BasicStatementTask::~BasicStatementTask() -{ - m_sql.clear(); - if (m_has_result && m_result) - delete m_result; -} - -bool BasicStatementTask::Execute() -{ - if (m_has_result) - { - ResultSet* result = m_conn->Query(m_sql); - if (!result || !result->GetRowCount() || !result->NextRow()) - { - delete result; - m_result->set_value(QueryResult(nullptr)); - return false; - } - - m_result->set_value(QueryResult(result)); - return true; - } - - return m_conn->Execute(m_sql); -} diff --git a/src/server/database/Database/AdhocStatement.h b/src/server/database/Database/AdhocStatement.h deleted file mode 100644 index 61469c6c28db08..00000000000000 --- a/src/server/database/Database/AdhocStatement.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU Affero General Public License as published by the - * Free Software Foundation; either version 3 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see . - */ - -#ifndef _ADHOCSTATEMENT_H -#define _ADHOCSTATEMENT_H - -#include "DatabaseEnvFwd.h" -#include "Define.h" -#include "SQLOperation.h" - -/*! Raw, ad-hoc query. */ -class AC_DATABASE_API BasicStatementTask : public SQLOperation -{ -public: - BasicStatementTask(std::string_view sql, bool async = false); - ~BasicStatementTask(); - - bool Execute() override; - QueryResultFuture GetFuture() const { return m_result->get_future(); } - -private: - std::string m_sql; //- Raw query to be executed - bool m_has_result; - QueryResultPromise* m_result; -}; - -#endif diff --git a/src/server/database/Database/DatabaseAsyncOperation.cpp b/src/server/database/Database/DatabaseAsyncOperation.cpp new file mode 100644 index 00000000000000..aa2d079e347c27 --- /dev/null +++ b/src/server/database/Database/DatabaseAsyncOperation.cpp @@ -0,0 +1,77 @@ +/* + * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU Affero General Public License as published by the + * Free Software Foundation; either version 3 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "DatabaseAsyncOperation.h" +#include "DatabaseWorkerPool.h" +#include "MySQLConnection.h" +#include "QueryResult.h" +#include + +BasicStatementTask::BasicStatementTask(std::string_view sql, bool isAsync /*= false*/) : + AsyncOperation(isAsync), _sql(sql) +{ + if (_hasResult) + _result = std::make_unique(); +} + +void BasicStatementTask::ExecuteQuery() +{ + if (_hasResult) + { + auto result = _connection->Query(_sql); + if (!result || !result->GetRowCount() || !result->NextRow()) + { + _result->set_value(QueryResult(nullptr)); + return; + } + + _result->set_value(result); + return; + } + + _connection->Execute(_sql); +} + +PreparedStatementTask::PreparedStatementTask(PreparedStatement stmt, bool isAsync /*= false*/) : + AsyncOperation(isAsync), _stmt(std::move(stmt)) +{ + if (_hasResult) + _result = std::make_unique(); +} + +void PreparedStatementTask::ExecuteQuery() +{ + if (_hasResult) + { + auto result = _connection->Query(_stmt); + if (!result || !result->GetRowCount()) + { + _result->set_value({ nullptr }); + return; + } + + _result->set_value(result); + return; + } + + _connection->Execute(_stmt); +} + +void CheckAsyncQueueTask::Execute() +{ + _dbPool->CheckAsyncQueue(); +} diff --git a/src/server/database/Database/DatabaseAsyncOperation.h b/src/server/database/Database/DatabaseAsyncOperation.h new file mode 100644 index 00000000000000..286939098382ed --- /dev/null +++ b/src/server/database/Database/DatabaseAsyncOperation.h @@ -0,0 +1,90 @@ +/* + * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU Affero General Public License as published by the + * Free Software Foundation; either version 3 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef _DATABASE_ASYNC_OPERATION_H_ +#define _DATABASE_ASYNC_OPERATION_H_ + +#include "DatabaseEnvFwd.h" + +class DatabaseWorkerPool; + +class AC_DATABASE_API AsyncOperation +{ +public: + explicit AsyncOperation(bool isAsync = false) : + _hasResult(isAsync) { } + + virtual ~AsyncOperation() = default; + + virtual void ExecuteQuery() = 0; + inline void SetConnection(MySQLConnection* connection) { _connection = connection; } + +protected: + MySQLConnection* _connection{ nullptr }; + bool _hasResult{}; + +private: + AsyncOperation(AsyncOperation const& right) = delete; + AsyncOperation& operator=(AsyncOperation const& right) = delete; +}; + +class AC_DATABASE_API BasicStatementTask : public AsyncOperation +{ +public: + explicit BasicStatementTask(std::string_view sql, bool isAsync = false); + ~BasicStatementTask() override = default; + + void ExecuteQuery() override; + [[nodiscard]] QueryResultFuture GetFuture() const { return _result->get_future(); } + +private: + std::string _sql; + std::unique_ptr _result; +}; + +class AC_DATABASE_API PreparedStatementTask : public AsyncOperation +{ +public: + explicit PreparedStatementTask(PreparedStatement stmt, bool isAsync = false); + ~PreparedStatementTask() override = default; + + void ExecuteQuery() override; + [[nodiscard]] PreparedQueryResultFuture GetFuture() const { return _result->get_future(); } + +private: + PreparedStatement _stmt; + std::unique_ptr _result; +}; + +class AC_DATABASE_API CheckAsyncQueueTask +{ +public: + explicit CheckAsyncQueueTask(DatabaseWorkerPool* dbPool) : + _dbPool(dbPool) { } + + virtual ~CheckAsyncQueueTask() = default; + + void Execute(); + +private: + DatabaseWorkerPool* _dbPool; + + CheckAsyncQueueTask(CheckAsyncQueueTask const& right) = delete; + CheckAsyncQueueTask& operator=(CheckAsyncQueueTask const& right) = delete; +}; + +#endif // _DATABASE_ASYNC_OPERATION_H_ diff --git a/src/server/database/Database/DatabaseAsyncQueueWorker.cpp b/src/server/database/Database/DatabaseAsyncQueueWorker.cpp new file mode 100644 index 00000000000000..718aa1d4e7485d --- /dev/null +++ b/src/server/database/Database/DatabaseAsyncQueueWorker.cpp @@ -0,0 +1,93 @@ +/* + * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU Affero General Public License as published by the + * Free Software Foundation; either version 3 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "DatabaseAsyncQueueWorker.h" +#include "DatabaseAsyncOperation.h" +#include "PCQueue.h" + +AsyncDBQueueWorker::AsyncDBQueueWorker(ProducerConsumerQueue* dbQueue, MySQLConnection* connection) +{ + _connection = connection; + _queue = dbQueue; + _thread = std::thread(&AsyncDBQueueWorker::ExecuteAsyncQueue, this); +} + +AsyncDBQueueWorker::~AsyncDBQueueWorker() +{ + _cancel = true; + _queue->NotifyAll(); + + if (_thread.joinable()) + _thread.join(); +} + +void AsyncDBQueueWorker::ExecuteAsyncQueue() +{ + if (!_queue) + return; + + for (;;) + { + AsyncOperation* operation{ nullptr }; + + _queue->WaitAndPop(operation, _cancel); + + if (_cancel) + break; + + if (!operation) + continue; + + operation->SetConnection(_connection); + operation->ExecuteQuery(); + delete operation; + } +} + +AsyncDBQueueChecker::AsyncDBQueueChecker(ProducerConsumerQueue* dbQueue) +{ + _queue = dbQueue; + _thread = std::thread(&AsyncDBQueueChecker::ExecuteThread, this); +} + +AsyncDBQueueChecker::~AsyncDBQueueChecker() +{ + _cancel = true; + _queue->Cancel(); + + if (_thread.joinable()) + _thread.join(); +} + +void AsyncDBQueueChecker::ExecuteThread() +{ + if (!_queue) + return; + + for (;;) + { + CheckAsyncQueueTask* operation{ nullptr }; + + _queue->WaitAndPop(operation); + + if (!operation || _cancel) + return; + + operation->Execute(); + delete operation; + } +} diff --git a/src/server/database/Database/DatabaseAsyncQueueWorker.h b/src/server/database/Database/DatabaseAsyncQueueWorker.h new file mode 100644 index 00000000000000..b14189ead2bf2e --- /dev/null +++ b/src/server/database/Database/DatabaseAsyncQueueWorker.h @@ -0,0 +1,69 @@ +/* + * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU Affero General Public License as published by the + * Free Software Foundation; either version 3 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#ifndef WARHEAD_ASYNC_DB_QUEUE_WORKER_H_ +#define WARHEAD_ASYNC_DB_QUEUE_WORKER_H_ + +#include "Define.h" +#include +#include + +template +class ProducerConsumerQueue; + +class AsyncOperation; +class CheckAsyncQueueTask; +class MySQLConnection; + +class AC_DATABASE_API AsyncDBQueueWorker +{ +public: + AsyncDBQueueWorker(ProducerConsumerQueue* dbQueue, MySQLConnection* connection); + ~AsyncDBQueueWorker(); + +private: + void ExecuteAsyncQueue(); + + ProducerConsumerQueue* _queue; + MySQLConnection* _connection; + + std::thread _thread; + std::atomic _cancel{ false }; + + AsyncDBQueueWorker(AsyncDBQueueWorker const& right) = delete; + AsyncDBQueueWorker& operator=(AsyncDBQueueWorker const& right) = delete; +}; + +class AC_DATABASE_API AsyncDBQueueChecker +{ +public: + AsyncDBQueueChecker(ProducerConsumerQueue* dbQueue); + ~AsyncDBQueueChecker(); + +private: + void ExecuteThread(); + + ProducerConsumerQueue* _queue; + + std::thread _thread; + std::atomic _cancel{ false }; + + AsyncDBQueueChecker(AsyncDBQueueChecker const& right) = delete; + AsyncDBQueueChecker& operator=(AsyncDBQueueChecker const& right) = delete; +}; + +#endif diff --git a/src/server/database/Database/DatabaseEnv.cpp b/src/server/database/Database/DatabaseEnv.cpp deleted file mode 100644 index e6bf6b082457e8..00000000000000 --- a/src/server/database/Database/DatabaseEnv.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/* - * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU Affero General Public License as published by the - * Free Software Foundation; either version 3 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see . - */ - -#include "DatabaseEnv.h" - -DatabaseWorkerPool WorldDatabase; -DatabaseWorkerPool CharacterDatabase; -DatabaseWorkerPool LoginDatabase; diff --git a/src/server/database/Database/DatabaseEnv.h b/src/server/database/Database/DatabaseEnv.h index eec79f00494ef6..379ab0c346a0ee 100644 --- a/src/server/database/Database/DatabaseEnv.h +++ b/src/server/database/Database/DatabaseEnv.h @@ -15,15 +15,8 @@ * with this program. If not, see . */ -#ifndef DATABASEENV_H -#define DATABASEENV_H - -#include "DatabaseWorkerPool.h" -#include "Define.h" - -#include "Implementation/CharacterDatabase.h" -#include "Implementation/LoginDatabase.h" -#include "Implementation/WorldDatabase.h" +#ifndef DATABASE_ENV_H +#define DATABASE_ENV_H #include "Field.h" #include "PreparedStatement.h" @@ -31,11 +24,9 @@ #include "QueryResult.h" #include "Transaction.h" -/// Accessor to the world database -AC_DATABASE_API extern DatabaseWorkerPool WorldDatabase; -/// Accessor to the character database -AC_DATABASE_API extern DatabaseWorkerPool CharacterDatabase; -/// Accessor to the realm/login database -AC_DATABASE_API extern DatabaseWorkerPool LoginDatabase; +// Impl include +#include "LoginDatabase.h" +#include "CharacterDatabase.h" +#include "WorldDatabase.h" #endif diff --git a/src/server/database/Database/DatabaseEnvFwd.h b/src/server/database/Database/DatabaseEnvFwd.h index 34a590c4562e6a..f5f153261b50fe 100644 --- a/src/server/database/Database/DatabaseEnvFwd.h +++ b/src/server/database/Database/DatabaseEnvFwd.h @@ -18,71 +18,76 @@ #ifndef DatabaseEnvFwd_h__ #define DatabaseEnvFwd_h__ +#include "Define.h" #include #include -struct QueryResultFieldMetadata; +template +class AsyncCallbackProcessor; + +enum class ConnectionFlags : uint8 +{ + Async = 0x1, + Sync = 0x2, + Both = Async | Sync +}; + +enum class DatabaseType : uint8 +{ + None, + Auth = 1, + Character = 2, + World = 4, +// Dbc = 8, + All = Auth | Character | World /*| Dbc*/ +}; + class Field; +class MySQLConnection; +class MySQLPreparedStatement; +class SQLQueryHolderBase; + +struct MySQLConnectionInfo; +struct QueryResultFieldMetadata; class ResultSet; using QueryResult = std::shared_ptr; using QueryResultFuture = std::future; using QueryResultPromise = std::promise; -class CharacterDatabaseConnection; -class LoginDatabaseConnection; -class WorldDatabaseConnection; - -class PreparedStatementBase; - -template -class PreparedStatement; - -using CharacterDatabasePreparedStatement = PreparedStatement; -using LoginDatabasePreparedStatement = PreparedStatement; -using WorldDatabasePreparedStatement = PreparedStatement; - class PreparedResultSet; using PreparedQueryResult = std::shared_ptr; using PreparedQueryResultFuture = std::future; using PreparedQueryResultPromise = std::promise; -class QueryCallback; - -template -class AsyncCallbackProcessor; - -using QueryCallbackProcessor = AsyncCallbackProcessor; - -class TransactionBase; +class PreparedStatementBase; +using PreparedStatement = std::shared_ptr; +using CharacterDatabasePreparedStatement = PreparedStatement; +using AuthDatabasePreparedStatement = PreparedStatement; +using WorldDatabasePreparedStatement = PreparedStatement; +class Transaction; using TransactionFuture = std::future; using TransactionPromise = std::promise; - -template -class Transaction; - -class TransactionCallback; - -template -using SQLTransaction = std::shared_ptr>; - -using CharacterDatabaseTransaction = SQLTransaction; -using LoginDatabaseTransaction = SQLTransaction; -using WorldDatabaseTransaction = SQLTransaction; +using SQLTransaction = std::shared_ptr; +using CharacterDatabaseTransaction = SQLTransaction; +using AuthDatabaseTransaction = SQLTransaction; +using WorldDatabaseTransaction = SQLTransaction; class SQLQueryHolderBase; using QueryResultHolderFuture = std::future; using QueryResultHolderPromise = std::promise; +using SQLQueryHolder = std::shared_ptr; +using CharacterDatabaseQueryHolder = SQLQueryHolderBase; +using AuthDatabaseQueryHolder = SQLQueryHolderBase; +using WorldDatabaseQueryHolder = SQLQueryHolderBase; -template -class SQLQueryHolder; - -using CharacterDatabaseQueryHolder = SQLQueryHolder; -using LoginDatabaseQueryHolder = SQLQueryHolder; -using WorldDatabaseQueryHolder = SQLQueryHolder; - +class QueryCallback; class SQLQueryHolderCallback; +class TransactionCallback; +using QueryCallbackProcessor = AsyncCallbackProcessor; +using TransactionCallbackProcessor = AsyncCallbackProcessor; +using QueryHolderCallbackProcessor = AsyncCallbackProcessor; // mysql struct MySQLHandle; @@ -91,4 +96,9 @@ struct MySQLField; struct MySQLBind; struct MySQLStmt; +// AC +using LoginDatabasePreparedStatement = PreparedStatement; +using LoginDatabaseTransaction = SQLTransaction; +using LoginDatabaseQueryHolder = SQLQueryHolderBase; + #endif // DatabaseEnvFwd_h__ diff --git a/src/server/database/Database/DatabaseLoader.cpp b/src/server/database/Database/DatabaseLoader.cpp deleted file mode 100644 index cfd0d6f0f87849..00000000000000 --- a/src/server/database/Database/DatabaseLoader.cpp +++ /dev/null @@ -1,221 +0,0 @@ -/* - * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU Affero General Public License as published by the - * Free Software Foundation; either version 3 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see . - */ - -#include "DatabaseLoader.h" -#include "Config.h" -#include "DBUpdater.h" -#include "DatabaseEnv.h" -#include "Duration.h" -#include "Log.h" -#include -#include -#include - -DatabaseLoader::DatabaseLoader(std::string const& logger, uint32 const defaultUpdateMask, std::string_view modulesList) - : _logger(logger), - _modulesList(modulesList), - _autoSetup(sConfigMgr->GetOption("Updates.AutoSetup", true)), - _updateFlags(sConfigMgr->GetOption("Updates.EnableDatabases", defaultUpdateMask)) { } - -template -DatabaseLoader& DatabaseLoader::AddDatabase(DatabaseWorkerPool& pool, std::string const& name) -{ - bool const updatesEnabledForThis = DBUpdater::IsEnabled(_updateFlags); - - _open.push([this, name, updatesEnabledForThis, &pool]() -> bool - { - std::string const dbString = sConfigMgr->GetOption(name + "DatabaseInfo", ""); - if (dbString.empty()) - { - LOG_ERROR(_logger, "Database {} not specified in configuration file!", name); - return false; - } - - uint8 const asyncThreads = sConfigMgr->GetOption(name + "Database.WorkerThreads", 1); - if (asyncThreads < 1 || asyncThreads > 32) - { - LOG_ERROR(_logger, "{} database: invalid number of worker threads specified. " - "Please pick a value between 1 and 32.", name); - return false; - } - - uint8 const synchThreads = sConfigMgr->GetOption(name + "Database.SynchThreads", 1); - - pool.SetConnectionInfo(dbString, asyncThreads, synchThreads); - - if (uint32 error = pool.Open()) - { - // Try reconnect - if (error == CR_CONNECTION_ERROR) - { - uint8 const attempts = sConfigMgr->GetOption("Database.Reconnect.Attempts", 20); - Seconds reconnectSeconds = Seconds(sConfigMgr->GetOption("Database.Reconnect.Seconds", 15)); - uint8 reconnectCount = 0; - - while (reconnectCount < attempts) - { - LOG_WARN(_logger, "> Retrying after {} seconds", static_cast(reconnectSeconds.count())); - std::this_thread::sleep_for(reconnectSeconds); - error = pool.Open(); - - if (error == CR_CONNECTION_ERROR) - { - reconnectCount++; - } - else - { - break; - } - } - } - - // Database does not exist - if ((error == ER_BAD_DB_ERROR) && updatesEnabledForThis && _autoSetup) - { - // Try to create the database and connect again if auto setup is enabled - if (DBUpdater::Create(pool) && (!pool.Open())) - { - error = 0; - } - } - - // If the error wasn't handled quit - if (error) - { - LOG_ERROR(_logger, "DatabasePool {} NOT opened. There were errors opening the MySQL connections. " - "Check your log file for specific errors", name); - - return false; - } - } - // Add the close operation - _close.push([&pool] - { - pool.Close(); - }); - - return true; - }); - - // Populate and update only if updates are enabled for this pool - if (updatesEnabledForThis) - { - _populate.push([this, name, &pool]() -> bool - { - if (!DBUpdater::Populate(pool)) - { - LOG_ERROR(_logger, "Could not populate the {} database, see log for details.", name); - return false; - } - - return true; - }); - - _update.push([this, name, &pool]() -> bool - { - if (!DBUpdater::Update(pool, _modulesList)) - { - LOG_ERROR(_logger, "Could not update the {} database, see log for details.", name); - return false; - } - - return true; - }); - } - - _prepare.push([this, name, &pool]() -> bool - { - if (!pool.PrepareStatements()) - { - LOG_ERROR(_logger, "Could not prepare statements of the {} database, see log for details.", name); - return false; - } - - return true; - }); - - return *this; -} - -bool DatabaseLoader::Load() -{ - if (!_updateFlags) - LOG_INFO("sql.updates", "Automatic database updates are disabled for all databases!"); - - if (!OpenDatabases()) - return false; - - if (!PopulateDatabases()) - return false; - - if (!UpdateDatabases()) - return false; - - if (!PrepareStatements()) - return false; - - return true; -} - -bool DatabaseLoader::OpenDatabases() -{ - return Process(_open); -} - -bool DatabaseLoader::PopulateDatabases() -{ - return Process(_populate); -} - -bool DatabaseLoader::UpdateDatabases() -{ - return Process(_update); -} - -bool DatabaseLoader::PrepareStatements() -{ - return Process(_prepare); -} - -bool DatabaseLoader::Process(std::queue& queue) -{ - while (!queue.empty()) - { - if (!queue.front()()) - { - // Close all open databases which have a registered close operation - while (!_close.empty()) - { - _close.top()(); - _close.pop(); - } - - return false; - } - - queue.pop(); - } - - return true; -} - -template AC_DATABASE_API -DatabaseLoader& DatabaseLoader::AddDatabase(DatabaseWorkerPool&, std::string const&); -template AC_DATABASE_API -DatabaseLoader& DatabaseLoader::AddDatabase(DatabaseWorkerPool&, std::string const&); -template AC_DATABASE_API -DatabaseLoader& DatabaseLoader::AddDatabase(DatabaseWorkerPool&, std::string const&); diff --git a/src/server/database/Database/DatabaseMgr.cpp b/src/server/database/Database/DatabaseMgr.cpp new file mode 100644 index 00000000000000..c6b28062144a32 --- /dev/null +++ b/src/server/database/Database/DatabaseMgr.cpp @@ -0,0 +1,251 @@ +/* + * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU Affero General Public License as published by the + * Free Software Foundation; either version 3 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "DatabaseMgr.h" +#include "Config.h" +#include "DBUpdater.h" +#include "DatabaseWorkerPool.h" +#include "Log.h" +#include "Timer.h" +#include +#include +#include + +DatabaseMgr::DatabaseMgr() +{ + mysql_library_init(0, nullptr, nullptr); + + _autoSetup = sConfigMgr->GetOption("Updates.AutoSetup", true); + _updateFlags = sConfigMgr->GetOption("Updates.EnableDatabases", 0); +} + +DatabaseMgr::~DatabaseMgr() +{ + mysql_library_end(); +} + +/*static*/ DatabaseMgr* DatabaseMgr::instance() +{ + static DatabaseMgr instance; + return &instance; +} + +void DatabaseMgr::AddDatabase(DatabaseWorkerPool& pool, std::string_view name) +{ + // #1. Set name for pool + pool.SetPoolName(name); + + // #2. Check option for enable auto update this pool + bool const updatesEnabledForThis = DBUpdater::IsEnabled(pool, _updateFlags); + + _open.emplace([this, name, updatesEnabledForThis, &pool]() -> bool + { + auto const dbString = sConfigMgr->GetOption(std::string(name) + "DatabaseInfo", ""); + if (dbString.empty()) + { + LOG_ERROR("db", "Database {} not specified in configuration file!", name); + return false; + } + + pool.SetConnectionInfo(dbString); + + if (uint32 error = pool.Open()) + { + // Try to reconnect + if (error == CR_CONNECTION_ERROR) + { + auto const attempts = sConfigMgr->GetOption("Database.Reconnect.Attempts", 20); + Seconds reconnectSeconds = Seconds(sConfigMgr->GetOption("Database.Reconnect.Seconds", 15)); + uint8 reconnectCount = 0; + + while (reconnectCount < attempts) + { + LOG_WARN("db", "> Retrying after {} seconds", reconnectSeconds.count()); + std::this_thread::sleep_for(reconnectSeconds); + error = pool.Open(); + + if (error == CR_CONNECTION_ERROR) + reconnectCount++; + else + break; + } + } + + // Database does not exist + if (error == ER_BAD_DB_ERROR && updatesEnabledForThis && _autoSetup) + { + // Try to create the database and connect again if auto setup is enabled + if (DBUpdater::Create(pool) && !pool.Open()) + error = 0; + } + + // If the error wasn't handled quit + if (error) + { + LOG_ERROR("db", "DatabasePool {} NOT opened. There were errors opening the MySQL connections. " + "Check your log file for specific errors", name); + + return false; + } + } + + // Add the close operation + _close.emplace([&pool] + { + pool.Close(); + }); + + return true; + }); + + // Populate and update only if updates are enabled for this pool + if (updatesEnabledForThis) + { + _populate.emplace([this, name, &pool]() -> bool + { + if (!DBUpdater::Populate(pool)) + { + LOG_ERROR("db", "Could not populate the {} database, see log for details.", name); + return false; + } + + return true; + }); + + _update.emplace([this, name, &pool]() -> bool + { + if (!DBUpdater::Update(pool, _modulesList)) + { + LOG_ERROR("db", "Could not update the {} database, see log for details.", name); + return false; + } + + return true; + }); + } + + _prepare.emplace([this, name, &pool]() -> bool + { + if (!pool.PrepareStatements()) + { + LOG_ERROR("db", "Could not prepare statements of the {} database, see log for details.", name); + return false; + } + + _poolList.emplace_back(&pool); + return true; + }); +} + +bool DatabaseMgr::Load() +{ + if (!_updateFlags) + LOG_INFO("db.update", "Automatic database updates are disabled for all databases!"); + + if (!OpenDatabases()) + return false; + + if (!PopulateDatabases()) + return false; + + if (!UpdateDatabases()) + return false; + + if (!PrepareStatements()) + return false; + + return true; +} + +bool DatabaseMgr::OpenDatabases() +{ + return Process(_open); +} + +bool DatabaseMgr::PopulateDatabases() +{ + return Process(_populate); +} + +bool DatabaseMgr::UpdateDatabases() +{ + return Process(_update); +} + +bool DatabaseMgr::PrepareStatements() +{ + return Process(_prepare); +} + +bool DatabaseMgr::Process(std::queue& queue) +{ + while (!queue.empty()) + { + if (!queue.front()()) + { + // Close all open databases which have a registered close operation + while (!_close.empty()) + { + _close.top()(); + _close.pop(); + } + + return false; + } + + queue.pop(); + } + + return true; +} + +void DatabaseMgr::CloseAllConnections() +{ + LOG_INFO("db", "> Close all database connections..."); + + // Close all open databases which have a registered close operation + while (!_close.empty()) + { + _close.top()(); + _close.pop(); + } +} + +void DatabaseMgr::Update(Milliseconds diff) +{ + if (_poolList.empty()) + return; + + for (auto const& pool : _poolList) + if (pool) + pool->Update(diff); +} + +uint32 DatabaseMgr::GetDatabaseLibraryVersion() +{ + return MYSQL_VERSION_ID; +} + +/*static*/ std::string_view DatabaseMgr::GetClientInfo() +{ + return { mysql_get_client_info() }; +} + +/*static*/ std::string_view DatabaseMgr::GetServerVersion() +{ + return { MYSQL_SERVER_VERSION }; +} diff --git a/src/server/database/Database/DatabaseLoader.h b/src/server/database/Database/DatabaseMgr.h similarity index 55% rename from src/server/database/Database/DatabaseLoader.h rename to src/server/database/Database/DatabaseMgr.h index 44aaca1992671e..9f310a49d2be01 100644 --- a/src/server/database/Database/DatabaseLoader.h +++ b/src/server/database/Database/DatabaseMgr.h @@ -15,68 +15,67 @@ * with this program. If not, see . */ -#ifndef DatabaseLoader_h__ -#define DatabaseLoader_h__ +#ifndef _DATABASE_MGR_H_ +#define _DATABASE_MGR_H_ -#include "Define.h" +#include "DatabaseEnvFwd.h" +#include "Duration.h" +#include #include #include #include -#include +#include -template class DatabaseWorkerPool; -// A helper class to initiate all database worker pools, -// handles updating, delays preparing of statements and cleans up on failure. -class AC_DATABASE_API DatabaseLoader +class AC_DATABASE_API DatabaseMgr { public: - DatabaseLoader(std::string const& logger, uint32 const defaultUpdateMask = 0, std::string_view modulesList = {}); + DatabaseMgr(); + ~DatabaseMgr(); - // Register a database to the loader (lazy implemented) - template - DatabaseLoader& AddDatabase(DatabaseWorkerPool& pool, std::string const& name); + static DatabaseMgr* instance(); - // Load all databases + void AddDatabase(DatabaseWorkerPool& pool, std::string_view name); + void Update(Milliseconds diff); bool Load(); + void CloseAllConnections(); - enum DatabaseTypeFlags - { - DATABASE_NONE = 0, + [[nodiscard]] uint32 GetUpdateFlags() const { return _updateFlags; } - DATABASE_LOGIN = 1, - DATABASE_CHARACTER = 2, - DATABASE_WORLD = 4, + static uint32 GetDatabaseLibraryVersion(); + static std::string_view GetClientInfo(); + static std::string_view GetServerVersion(); - DATABASE_MASK_ALL = DATABASE_LOGIN | DATABASE_CHARACTER | DATABASE_WORLD - }; - - [[nodiscard]] uint32 GetUpdateFlags() const - { - return _updateFlags; - } + void SetModuleList(std::string_view modulesList) { _modulesList = modulesList; } private: + using Predicate = std::function; + using Closer = std::function; + bool OpenDatabases(); bool PopulateDatabases(); bool UpdateDatabases(); bool PrepareStatements(); - using Predicate = std::function; - using Closer = std::function; - // Invokes all functions in the given queue and closes the databases on errors. // Returns false when there was an error. bool Process(std::queue& queue); - std::string const _logger; - std::string_view _modulesList; - bool const _autoSetup; - uint32 const _updateFlags; + std::string _modulesList; + bool _autoSetup{}; + uint32 _updateFlags{}; std::queue _open, _populate, _update, _prepare; std::stack _close; + std::vector _poolList; + + DatabaseMgr(DatabaseMgr const&) = delete; + DatabaseMgr(DatabaseMgr&&) = delete; + DatabaseMgr& operator=(DatabaseMgr const&) = delete; + DatabaseMgr& operator=(DatabaseMgr&&) = delete; }; -#endif // DatabaseLoader_h__ +#define sDatabaseMgr DatabaseMgr::instance() + +#endif diff --git a/src/server/database/Database/DatabaseWorker.cpp b/src/server/database/Database/DatabaseWorker.cpp deleted file mode 100644 index 527eb9b502b855..00000000000000 --- a/src/server/database/Database/DatabaseWorker.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/* - * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU Affero General Public License as published by the - * Free Software Foundation; either version 3 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see . - */ - -#include "DatabaseWorker.h" -#include "PCQueue.h" -#include "SQLOperation.h" - -DatabaseWorker::DatabaseWorker(ProducerConsumerQueue* newQueue, MySQLConnection* connection) -{ - _connection = connection; - _queue = newQueue; - _cancelationToken = false; - _workerThread = std::thread(&DatabaseWorker::WorkerThread, this); -} - -DatabaseWorker::~DatabaseWorker() -{ - _cancelationToken = true; - - _queue->Cancel(); - - _workerThread.join(); -} - -void DatabaseWorker::WorkerThread() -{ - if (!_queue) - return; - - for (;;) - { - SQLOperation* operation = nullptr; - - _queue->WaitAndPop(operation); - - if (_cancelationToken || !operation) - return; - - operation->SetConnection(_connection); - operation->call(); - - delete operation; - } -} diff --git a/src/server/database/Database/DatabaseWorker.h b/src/server/database/Database/DatabaseWorker.h deleted file mode 100644 index bc6724216d5352..00000000000000 --- a/src/server/database/Database/DatabaseWorker.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU Affero General Public License as published by the - * Free Software Foundation; either version 3 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see . - */ - -#ifndef _WORKERTHREAD_H -#define _WORKERTHREAD_H - -#include "Define.h" -#include -#include - -template -class ProducerConsumerQueue; - -class MySQLConnection; -class SQLOperation; - -class AC_DATABASE_API DatabaseWorker -{ -public: - DatabaseWorker(ProducerConsumerQueue* newQueue, MySQLConnection* connection); - ~DatabaseWorker(); - -private: - ProducerConsumerQueue* _queue; - MySQLConnection* _connection; - - void WorkerThread(); - std::thread _workerThread; - - std::atomic _cancelationToken; - - DatabaseWorker(DatabaseWorker const& right) = delete; - DatabaseWorker& operator=(DatabaseWorker const& right) = delete; -}; - -#endif diff --git a/src/server/database/Database/DatabaseWorkerPool.cpp b/src/server/database/Database/DatabaseWorkerPool.cpp index 4e0f466cf49162..dd22dbdaa33a90 100644 --- a/src/server/database/Database/DatabaseWorkerPool.cpp +++ b/src/server/database/Database/DatabaseWorkerPool.cpp @@ -16,11 +16,13 @@ */ #include "DatabaseWorkerPool.h" -#include "AdhocStatement.h" -#include "CharacterDatabase.h" +#include "DatabaseAsyncOperation.h" +#include "DatabaseAsyncQueueWorker.h" +#include "Config.h" #include "Errors.h" +#include "FileUtil.h" #include "Log.h" -#include "LoginDatabase.h" +#include "MySQLConnection.h" #include "MySQLPreparedStatement.h" #include "MySQLWorkaround.h" #include "PCQueue.h" @@ -28,108 +30,150 @@ #include "QueryCallback.h" #include "QueryHolder.h" #include "QueryResult.h" -#include "SQLOperation.h" +#include "TaskScheduler.h" #include "Transaction.h" -#include "WorldDatabase.h" -#include +#include +#include #include +#include +#include #ifdef ACORE_DEBUG #include #include #endif -#if MARIADB_VERSION_ID >= 100600 -#define MIN_MYSQL_SERVER_VERSION 100500u -#define MIN_MYSQL_CLIENT_VERSION 30203u +#if defined(LIBMARIADB) && MARIADB_VERSION_ID >= 100600 +#define MIN_DB_SERVER_VERSION 100500u +#define MIN_DB_CLIENT_VERSION 30203u #else -#define MIN_MYSQL_SERVER_VERSION 50700u -#define MIN_MYSQL_CLIENT_VERSION 50700u +#define MIN_DB_SERVER_VERSION 50700u +#define MIN_DB_CLIENT_VERSION 50700u #endif -class PingOperation : public SQLOperation +constexpr auto MAX_SYNC_CONNECTIONS = 32; +constexpr auto MAX_ASYNC_CONNECTIONS = 32; + +class PingOperation : public AsyncOperation { - //! Operation for idle delaythreads - bool Execute() override +public: + explicit PingOperation() : + AsyncOperation() { } + + //! Operation for idle delay threads + void ExecuteQuery() override { - m_conn->Ping(); - return true; + _connection->Ping(); } }; -template -DatabaseWorkerPool::DatabaseWorkerPool() : - _queue(new ProducerConsumerQueue()), - _async_threads(0), - _synch_threads(0) +DatabaseWorkerPool::DatabaseWorkerPool(DatabaseType type) : + _poolType(type) { - WPFatal(mysql_thread_safe(), "Used MySQL library isn't thread-safe."); + ASSERT(mysql_thread_safe(), "Used MySQL library isn't thread-safe"); -#if !defined(MARIADB_VERSION_ID) || MARIADB_VERSION_ID < 100600 - bool isSupportClientDB = mysql_get_client_version() >= MIN_MYSQL_CLIENT_VERSION; +#if !defined(LIBMARIADB) && MARIADB_VERSION_ID >= 100600 + bool isSupportClientDB = mysql_get_client_version() >= MIN_DB_CLIENT_VERSION; bool isSameClientDB = mysql_get_client_version() == MYSQL_VERSION_ID; #else // MariaDB 10.6+ - bool isSupportClientDB = mysql_get_client_version() >= MIN_MYSQL_CLIENT_VERSION; + bool isSupportClientDB = mysql_get_client_version() >= MIN_DB_CLIENT_VERSION; bool isSameClientDB = true; // Client version 3.2.3? #endif - WPFatal(isSupportClientDB, "AzerothCore does not support MySQL versions below 5.7 or MariaDB versions below 10.5.\n\nFound version: {} / {}. Server compiled with: {}.\nSearch the wiki for ACE00043 in Common Errors (https://www.azerothcore.org/wiki/common-errors#ace00043).", - mysql_get_client_info(), mysql_get_client_version(), MYSQL_VERSION_ID); - WPFatal(isSameClientDB, "Used MySQL library version ({} id {}) does not match the version id used to compile AzerothCore (id {}).\nSearch the wiki for ACE00046 in Common Errors (https://www.azerothcore.org/wiki/common-errors#ace00046).", - mysql_get_client_info(), mysql_get_client_version(), MYSQL_VERSION_ID); + ASSERT(isSupportClientDB, "AzerothCore does not support MySQL versions below 5.7 and MariaDB 10.3"); + ASSERT(isSameClientDB, "Used DB library version ({} id {}) does not match the version id used to compile AzerothCore (id {})", mysql_get_client_info(), mysql_get_client_version(), MYSQL_VERSION_ID); + + _scheduler = std::make_unique(); + _queue = std::make_unique>(); + _asyncQueueCheckQueue = std::make_unique>(); + _asyncQueueChecker = std::make_unique(_asyncQueueCheckQueue.get()); } -template -DatabaseWorkerPool::~DatabaseWorkerPool() +DatabaseWorkerPool::~DatabaseWorkerPool() { + _scheduler->CancelAll(); + _asyncQueueCheckQueue->Cancel(); _queue->Cancel(); } -template -void DatabaseWorkerPool::SetConnectionInfo(std::string_view infoString, uint8 const asyncThreads, uint8 const synchThreads) +void DatabaseWorkerPool::SetConnectionInfo(std::string_view infoString) { _connectionInfo = std::make_unique(infoString); - - _async_threads = asyncThreads; - _synch_threads = synchThreads; + MakeExtraFile(); } -template -uint32 DatabaseWorkerPool::Open() +void DatabaseWorkerPool::MakeExtraFile() { - WPFatal(_connectionInfo.get(), "Connection info was not set!"); + namespace fs = std::filesystem; - LOG_INFO("sql.driver", "Opening DatabasePool '{}'. Asynchronous connections: {}, synchronous connections: {}.", - GetDatabaseName(), _async_threads, _synch_threads); + fs::path extraFile(sConfigMgr->GetConfigPath()); + extraFile /= "DB"; - uint32 error = OpenConnections(IDX_ASYNC, _async_threads); + // Make dir if need + ASSERT(Acore::File::CreateDirIfNeed(extraFile.generic_string())); + extraFile /= Acore::StringFormatFmt("{}Config.cnf", GetPoolName()); + _pathToExtraFile = extraFile.generic_string(); - if (error) - return error; + try + { + if (fs::exists(extraFile)) + return; + } + catch (const std::error_code& error) + { + LOG_FATAL("db.pool", "> Error at check '{}'. {}", extraFile.generic_string(), error.message()); + ABORT(); + } - error = OpenConnections(IDX_SYNCH, _synch_threads); + std::ofstream outfile(extraFile.generic_string()); + if (!outfile.is_open()) + { + LOG_FATAL("db.pool", "Failed to create extra file '{}'", extraFile.generic_string()); + ABORT(); + } - if (!error) + outfile << "[client]\npassword = \"" << _connectionInfo->Password << '"' << std::endl; + outfile.close(); +} + +uint32 DatabaseWorkerPool::Open() +{ + ASSERT(_connectionInfo, "Connection info was not set!"); + + LOG_INFO("db.pool", "Opening DatabasePool '{}'", GetDatabaseName()); + + // Async connection { - LOG_INFO("sql.driver", "DatabasePool '{}' opened successfully. {} total connections running.", - GetDatabaseName(), (_connections[IDX_SYNCH].size() + _connections[IDX_ASYNC].size())); + auto [error, connection] = OpenConnection(IDX_ASYNC); + if (error) + return error; } - LOG_INFO("sql.driver", " "); + // Sync connection + auto [error, connection] = OpenConnection(IDX_SYNCH); + if (error) + return error; + LOG_INFO("db.pool", "DatabasePool '{}' opened successfully", GetDatabaseName()); + LOG_INFO("db.pool", "DB server ver: {}", connection->GetServerInfo()); + LOG_INFO("db.pool", " "); + + AddTasks(); return error; } -template -void DatabaseWorkerPool::Close() +void DatabaseWorkerPool::Close() { - LOG_INFO("sql.driver", "Closing down DatabasePool '{}'.", GetDatabaseName()); + if (_connections[IDX_ASYNC].empty() && _connections[IDX_SYNCH].empty()) + return; - //! Closes the actualy MySQL connection. - _connections[IDX_ASYNC].clear(); + // Stop all tasks + _scheduler->CancelAll(); - LOG_INFO("sql.driver", "Asynchronous connections on DatabasePool '{}' terminated. Proceeding with synchronous connections.", - GetDatabaseName()); + LOG_INFO("db.pool", "Closing down DatabasePool '{}' ...", GetDatabaseName()); + + //! Closes the actually DB connection. + _connections[IDX_ASYNC].clear(); //! Shut down the synchronous connections //! There's no need for locking the connection, because DatabaseWorkerPool<>::Close @@ -137,127 +181,263 @@ void DatabaseWorkerPool::Close() //! meaning there can be no concurrent access at this point. _connections[IDX_SYNCH].clear(); - LOG_INFO("sql.driver", "All connections on DatabasePool '{}' closed.", GetDatabaseName()); + LOG_INFO("db.pool", "All connections on DatabasePool '{}' closed.", GetDatabaseName()); +} + +QueryResult DatabaseWorkerPool::Query(std::string_view sql) +{ + auto connection = GetFreeConnection(); + if (!connection) + return { nullptr }; + + auto result = connection->Query(sql); + connection->Unlock(); + + if (!result || !result->GetRowCount() || !result->NextRow()) + return { nullptr }; + + return { result }; +} + +std::pair DatabaseWorkerPool::OpenConnection(InternalIndex type, bool isDynamic /*= false*/) +{ + auto connection = std::make_unique(*_connectionInfo, type == IDX_ASYNC ? _queue.get() : nullptr, isDynamic); + if (uint32 error = connection->Open()) + { + // Failed to open a connection or invalid version + return { error, nullptr }; + } + else if (connection->GetServerVersion() < MIN_DB_SERVER_VERSION) + { + LOG_ERROR("db.pool", "AzerothCore does not support MySQL versions below 5.7 or MariaDB versions below 10.3"); + return { 1, nullptr }; + } + + auto& itrConnection = _connections[type].emplace_back(std::move(connection)); + + // Everything is fine + return { 0, itrConnection.get() }; +} + +MySQLConnection* DatabaseWorkerPool::GetFreeConnection() +{ +#ifdef ACORE_DEBUG + if (_warnSyncQueries) + { + std::ostringstream ss; + ss << boost::stacktrace::stacktrace(); + LOG_WARN("db.pool", "Sync query at:\n{}", ss.str()); + } +#endif + + std::lock_guard guardCleanup(_cleanupMutex); + + // Check default connections + for (auto& connection : _connections[IDX_SYNCH]) + if (connection->LockIfReady()) + return connection.get(); + + LOG_WARN("db.pool", "> Not found free sync connection. Connections count: {}", _connections[IDX_SYNCH].size()); + + // Try to make new connect if connections count < MAX_SYNC_CONNECTIONS + OpenDynamicSyncConnect(); + + std::lock_guard guardOpenConnect(_openSyncConnectMutex); + + MySQLConnection* freeConnection{ nullptr }; + + uint8 i{}; + auto const num_cons{ _connections[IDX_SYNCH].size()}; + + //! Block forever until a connection is free + for (;;) + { + freeConnection = _connections[IDX_SYNCH][++i % num_cons].get(); + + //! Must be matched with t->Unlock() or you will get deadlocks + if (freeConnection->LockIfReady()) + break; + } + + return freeConnection; +} + +std::string_view DatabaseWorkerPool::GetDatabaseName() const +{ + return _connectionInfo->Database; +} + +void DatabaseWorkerPool::Execute(std::string_view sql) +{ + if (sql.empty()) + return; + + Enqueue(new BasicStatementTask(sql)); +} + +void DatabaseWorkerPool::Execute(PreparedStatement stmt) +{ + if (!stmt) + return; + + auto [isAllSet, notSetIndex] = stmt->IsAllParamsSet(); + if (!isAllSet) + { + LOG_ERROR("db.pool", "{} DBPool: Trying to execute incorrect stmt. Index: {}. Incorrect param index: {}", GetPoolName(), stmt->GetIndex(), notSetIndex); + return; + } + + Enqueue(new PreparedStatementTask(std::move(stmt))); +} + +void DatabaseWorkerPool::CleanupConnections() +{ + std::lock_guard guard(_cleanupMutex); + + _connections[IDX_SYNCH].erase(std::remove_if(_connections[IDX_SYNCH].begin(), _connections[IDX_SYNCH].end(), [](std::unique_ptr& connection) + { + return connection->CanRemoveConnection(); + }), _connections[IDX_SYNCH].end()); + + _connections[IDX_ASYNC].erase(std::remove_if(_connections[IDX_ASYNC].begin(), _connections[IDX_ASYNC].end(), [](std::unique_ptr& connection) + { + return connection->CanRemoveConnection(); + }), _connections[IDX_ASYNC].end()); } -template -bool DatabaseWorkerPool::PrepareStatements() +bool DatabaseWorkerPool::PrepareStatements() { + // Init all prepare statements + DoPrepareStatements(); + for (auto const& connections : _connections) { for (auto const& connection : connections) { - connection->LockIfReady(); - if (!connection->PrepareStatements()) - { - connection->Unlock(); - Close(); - return false; - } - else - connection->Unlock(); + connection->GetPreparedStatementList()->resize(GetStatementSize()); - size_t const preparedSize = connection->m_stmts.size(); - if (_preparedStatementSize.size() < preparedSize) - _preparedStatementSize.resize(preparedSize); + for (auto const& [index, stmt] : _stringPreparedStatement) + connection->PrepareStatement(index, stmt.Query, stmt.ConnectionType); + } + } - for (size_t i = 0; i < preparedSize; ++i) - { - // already set by another connection - // (each connection only has prepared statements of it's own type sync/async) - if (_preparedStatementSize[i] > 0) - continue; + auto IsValidPrepareStatements = [this](MySQLConnection* connection) + { + if (!connection->LockIfReady()) + return false; - if (MySQLPreparedStatement* stmt = connection->m_stmts[i].get()) - { - uint32 const paramCount = stmt->GetParameterCount(); + if (!connection->PrepareStatements()) + { + connection->Unlock(); + Close(); + return false; + } + else + connection->Unlock(); + + auto list = connection->GetPreparedStatementList(); + auto const preparedSize = list->size(); - // WH only supports uint8 indices. - ASSERT(paramCount < std::numeric_limits::max()); + if (_preparedStatementSize.size() < preparedSize) + _preparedStatementSize.resize(preparedSize); + + for (uint32 i = 0; i < preparedSize; ++i) + { + // already set by another connection + // (each connection only has prepared statements of its own type sync/async) + if (_preparedStatementSize[i] > 0) + continue; - _preparedStatementSize[i] = static_cast(paramCount); - } + if (auto stmt = (*list)[i].get()) + { + uint32 const paramCount = stmt->GetParameterCount(); + + // WH only supports uint8 indices. + ASSERT(paramCount < std::numeric_limits::max()); + _preparedStatementSize[i] = static_cast(paramCount); } } - } + + return true; + }; + + for (auto const& connections : _connections) + for (auto const& connection : connections) + if (!IsValidPrepareStatements(connection.get())) + return false; return true; } -template -QueryResult DatabaseWorkerPool::Query(std::string_view sql) +PreparedStatement DatabaseWorkerPool::GetPreparedStatement(uint32 index) { - auto connection = GetFreeConnection(); - - ResultSet* result = connection->Query(sql); - connection->Unlock(); + return std::make_shared(index, _preparedStatementSize[index]); +} - if (!result || !result->GetRowCount() || !result->NextRow()) +void DatabaseWorkerPool::PrepareStatement(uint32 index, std::string_view sql, ConnectionFlags flags) +{ + auto const& itr = _stringPreparedStatement.find(index); + if (itr != _stringPreparedStatement.end()) { - delete result; - return QueryResult(nullptr); + LOG_ERROR("db.pool", "{} DBPool: Trying add exist statement with index ()! Skip", GetPoolName(), index); + return; } - return QueryResult(result); + _stringPreparedStatement.emplace(index, StringPreparedStatement{ index, sql, flags }); } -template -PreparedQueryResult DatabaseWorkerPool::Query(PreparedStatement* stmt) +PreparedQueryResult DatabaseWorkerPool::Query(PreparedStatement stmt) { + auto [isAllSet, notSetIndex] = stmt->IsAllParamsSet(); + if (!isAllSet) + { + LOG_ERROR("db.pool", "{} DBPool: Trying to query incorrect stmt. Index: {}. Incorrect param index: {}", GetPoolName(), stmt->GetIndex(), notSetIndex); + return { nullptr }; + } + auto connection = GetFreeConnection(); - PreparedResultSet* ret = connection->Query(stmt); - connection->Unlock(); + if (!connection) + return { nullptr }; - //! Delete proxy-class. Not needed anymore - delete stmt; + auto result = connection->Query(std::move(stmt)); + connection->Unlock(); - if (!ret || !ret->GetRowCount()) - { - delete ret; - return PreparedQueryResult(nullptr); - } + if (!result || !result->GetRowCount()) + return { nullptr }; - return PreparedQueryResult(ret); + return { result }; } -template -QueryCallback DatabaseWorkerPool::AsyncQuery(std::string_view sql) +void DatabaseWorkerPool::InitPrepareStatement(MySQLConnection* connection) { - BasicStatementTask* task = new BasicStatementTask(sql, true); - // Store future result before enqueueing - task might get already processed and deleted before returning from this method - QueryResultFuture result = task->GetFuture(); - Enqueue(task); - return QueryCallback(std::move(result)); + connection->GetPreparedStatementList()->resize(GetStatementSize()); + + for (auto const& [index, stmt] : _stringPreparedStatement) + connection->PrepareStatement(index, stmt.Query, stmt.ConnectionType); } -template -QueryCallback DatabaseWorkerPool::AsyncQuery(PreparedStatement* stmt) +QueryCallback DatabaseWorkerPool::AsyncQuery(std::string_view sql) { - PreparedStatementTask* task = new PreparedStatementTask(stmt, true); - // Store future result before enqueueing - task might get already processed and deleted before returning from this method - PreparedQueryResultFuture result = task->GetFuture(); + auto task = new BasicStatementTask(sql, true); + auto result = task->GetFuture(); Enqueue(task); return QueryCallback(std::move(result)); } -template -SQLQueryHolderCallback DatabaseWorkerPool::DelayQueryHolder(std::shared_ptr> holder) +QueryCallback DatabaseWorkerPool::AsyncQuery(PreparedStatement stmt) { - SQLQueryHolderTask* task = new SQLQueryHolderTask(holder); - // Store future result before enqueueing - task might get already processed and deleted before returning from this method - QueryResultHolderFuture result = task->GetFuture(); + auto task = new PreparedStatementTask(std::move(stmt), true); + auto result = task->GetFuture(); Enqueue(task); - return { std::move(holder), std::move(result) }; + return QueryCallback(std::move(result)); } -template -SQLTransaction DatabaseWorkerPool::BeginTransaction() +SQLTransaction DatabaseWorkerPool::BeginTransaction() { - return std::make_shared>(); + return std::make_shared(); } -template -void DatabaseWorkerPool::CommitTransaction(SQLTransaction transaction) +void DatabaseWorkerPool::CommitTransaction(SQLTransaction transaction) { #ifdef ACORE_DEBUG //! Only analyze transaction weaknesses in Debug mode. @@ -266,21 +446,20 @@ void DatabaseWorkerPool::CommitTransaction(SQLTransaction transaction) switch (transaction->GetSize()) { case 0: - LOG_DEBUG("sql.driver", "Transaction contains 0 queries. Not executing."); + LOG_DEBUG("db.pool", "Transaction contains 0 queries. Not executing."); return; case 1: - LOG_DEBUG("sql.driver", "Warning: Transaction only holds 1 query, consider removing Transaction context in code."); + LOG_DEBUG("db.pool", "Warning: Transaction only holds 1 query, consider removing Transaction context in code."); break; default: break; } #endif // ACORE_DEBUG - Enqueue(new TransactionTask(transaction)); + Enqueue(new TransactionTask(std::move(transaction))); } -template -TransactionCallback DatabaseWorkerPool::AsyncCommitTransaction(SQLTransaction transaction) +TransactionCallback DatabaseWorkerPool::AsyncCommitTransaction(SQLTransaction transaction) { #ifdef ACORE_DEBUG //! Only analyze transaction weaknesses in Debug mode. @@ -289,31 +468,35 @@ TransactionCallback DatabaseWorkerPool::AsyncCommitTransaction(SQLTransaction switch (transaction->GetSize()) { case 0: - LOG_DEBUG("sql.driver", "Transaction contains 0 queries. Not executing."); + LOG_DEBUG("db.pool", "Transaction contains 0 queries. Not executing."); break; case 1: - LOG_DEBUG("sql.driver", "Warning: Transaction only holds 1 query, consider removing Transaction context in code."); + LOG_DEBUG("db.pool", "Warning: Transaction only holds 1 query, consider removing Transaction context in code."); break; default: break; } #endif // ACORE_DEBUG - TransactionWithResultTask* task = new TransactionWithResultTask(transaction); + auto task = new TransactionWithResultTask(std::move(transaction)); TransactionFuture result = task->GetFuture(); Enqueue(task); - return TransactionCallback(std::move(result)); + return TransactionCallback{ std::move(result) }; } -template -void DatabaseWorkerPool::DirectCommitTransaction(SQLTransaction& transaction) +void DatabaseWorkerPool::Enqueue(AsyncOperation* operation) { - T* connection = GetFreeConnection(); - int errorCode = connection->ExecuteTransaction(transaction); + _queue->Push(operation); +} +void DatabaseWorkerPool::DirectCommitTransaction(SQLTransaction transaction) +{ + auto connection = GetFreeConnection(); + + auto errorCode = connection->ExecuteTransaction(transaction); if (!errorCode) { - connection->Unlock(); // OK, operation succesful + connection->Unlock(); // OK, operation succesful return; } @@ -333,18 +516,43 @@ void DatabaseWorkerPool::DirectCommitTransaction(SQLTransaction& transacti //! Clean up now. transaction->Cleanup(); + connection->Unlock(); +} + +void DatabaseWorkerPool::ExecuteOrAppend(SQLTransaction trans, std::string_view sql) +{ + if (!trans) + Execute(sql); + else + trans->Append(sql); +} + +void DatabaseWorkerPool::ExecuteOrAppend(SQLTransaction trans, PreparedStatement stmt) +{ + if (!trans) + Execute(std::move(stmt)); + else + trans->Append(std::move(stmt)); +} + +void DatabaseWorkerPool::DirectExecute(std::string_view sql) +{ + if (sql.empty()) + return; + auto connection = GetFreeConnection(); + connection->Execute(sql); connection->Unlock(); } -template -PreparedStatement* DatabaseWorkerPool::GetPreparedStatement(PreparedStatementIndex index) +void DatabaseWorkerPool::DirectExecute(PreparedStatement stmt) { - return new PreparedStatement(index, _preparedStatementSize[index]); + auto connection = GetFreeConnection(); + connection->Execute(std::move(stmt)); + connection->Unlock(); } -template -void DatabaseWorkerPool::EscapeString(std::string& str) +void DatabaseWorkerPool::EscapeString(std::string& str) { if (str.empty()) return; @@ -355,71 +563,28 @@ void DatabaseWorkerPool::EscapeString(std::string& str) delete[] buf; } -template -void DatabaseWorkerPool::KeepAlive() +void DatabaseWorkerPool::KeepAlive() { - //! Ping synchronous connections - for (auto& connection : _connections[IDX_SYNCH]) + std::lock_guard guard(_cleanupMutex); + + //! Ping synchronous connection + auto& connection = _connections[IDX_SYNCH].front(); + if (connection->LockIfReady()) { - if (connection->LockIfReady()) - { - connection->Ping(); - connection->Unlock(); - } + connection->Ping(); + connection->Unlock(); } - //! Assuming all worker threads are free, every worker thread will receive 1 ping operation request - //! If one or more worker threads are busy, the ping operations will not be split evenly, but this doesn't matter - //! as the sole purpose is to prevent connections from idling. - auto const count = _connections[IDX_ASYNC].size(); - - for (uint8 i = 0; i < count; ++i) - Enqueue(new PingOperation); + //! Ping asynchronous connection + Enqueue(new PingOperation); } -template -uint32 DatabaseWorkerPool::OpenConnections(InternalIndex type, uint8 numConnections) +std::size_t DatabaseWorkerPool::GetQueueSize() const { - for (uint8 i = 0; i < numConnections; ++i) - { - // Create the connection - auto connection = [&] - { - switch (type) - { - case IDX_ASYNC: - return std::make_unique(_queue.get(), *_connectionInfo); - case IDX_SYNCH: - return std::make_unique(*_connectionInfo); - default: - ABORT(); - } - }(); - - if (uint32 error = connection->Open()) - { - // Failed to open a connection or invalid version, abort and cleanup - _connections[type].clear(); - return error; - } - else if (connection->GetServerVersion() < MIN_MYSQL_SERVER_VERSION) - { - LOG_ERROR("sql.driver", "AzerothCore does not support MySQL versions below 5.7 or MariaDB versions below 10.5.\n\nFound server version: {}. Server compiled with: {}.", - connection->GetServerVersion(), MYSQL_VERSION_ID); - return 1; - } - else - { - _connections[type].push_back(std::move(connection)); - } - } - - // Everything is fine - return 0; + return _queue->Size(); } -template -unsigned long DatabaseWorkerPool::EscapeString(char* to, char const* from, unsigned long length) +unsigned long DatabaseWorkerPool::EscapeString(char* to, char const* from, unsigned long length) { if (!to || !from || !length) return 0; @@ -427,109 +592,102 @@ unsigned long DatabaseWorkerPool::EscapeString(char* to, char const* from, un return _connections[IDX_SYNCH].front()->EscapeString(to, from, length); } -template -void DatabaseWorkerPool::Enqueue(SQLOperation* op) +SQLQueryHolderCallback DatabaseWorkerPool::DelayQueryHolder(SQLQueryHolder holder) { - _queue->Push(op); + auto task = new SQLQueryHolderTask(holder); + QueryResultHolderFuture result = task->GetFuture(); + Enqueue(task); + return { std::move(holder), std::move(result) }; } -template -size_t DatabaseWorkerPool::QueueSize() const +void DatabaseWorkerPool::Update(Milliseconds diff) { - return _queue->Size(); + if (diff > 0ms) + _scheduler->Update(diff); + else + _scheduler->Update(); } -template -T* DatabaseWorkerPool::GetFreeConnection() +void DatabaseWorkerPool::AddTasks() { -#ifdef ACORE_DEBUG - if (_warnSyncQueries) - { - std::ostringstream ss; - ss << boost::stacktrace::stacktrace(); - LOG_WARN("sql.performances", "Sync query at:\n{}", ss.str()); - } -#endif + _maxAsyncQueueSize = sConfigMgr->GetOption("MaxQueueSize", 10); + ASSERT(_maxAsyncQueueSize >= 10, "Queue size can only be greater than or equal to 10"); - uint8 i = 0; - auto const num_cons = _connections[IDX_SYNCH].size(); - T* connection = nullptr; + // DB ping + _scheduler->Schedule(Minutes{ sConfigMgr->GetOption("MaxPingTime", 30) }, [this](TaskContext context) + { + LOG_DEBUG("db.connection", "Ping DB to keep connection alive. Pool name: {}", _poolName); + KeepAlive(); + context.Repeat(); + }); - //! Block forever until a connection is free - for (;;) + // Cleanup dynamic connections + _scheduler->Schedule(10s, [this](TaskContext context) { - connection = _connections[IDX_SYNCH][++i % num_cons].get(); - //! Must be matched with t->Unlock() or you will get deadlocks - if (connection->LockIfReady()) - break; - } + CleanupConnections(); + context.Repeat(1s); + }); - return connection; + // Check queue and add dymanic async connects if need + _scheduler->Schedule(1s, [this](TaskContext context) + { + _asyncQueueCheckQueue->Push(new CheckAsyncQueueTask(this)); + context.Repeat(5s); + }); } -template -std::string_view DatabaseWorkerPool::GetDatabaseName() const +void DatabaseWorkerPool::OpenDynamicAsyncConnect() { - return std::string_view{ _connectionInfo->database }; -} + std::lock_guard guard(_openAsyncConnectMutex); -template -void DatabaseWorkerPool::Execute(std::string_view sql) -{ - if (sql.empty()) + if (_connections[IDX_ASYNC].size() >= MAX_ASYNC_CONNECTIONS) return; - BasicStatementTask* task = new BasicStatementTask(sql); - Enqueue(task); -} + LOG_DEBUG("db.pool", "Add new dynamic async connection. Pool name: {}", GetPoolName()); -template -void DatabaseWorkerPool::Execute(PreparedStatement* stmt) -{ - PreparedStatementTask* task = new PreparedStatementTask(stmt); - Enqueue(task); + auto [error, connection] = OpenConnection(IDX_ASYNC, true); + if (error) + return; + + InitPrepareStatement(connection); + ASSERT(connection->PrepareStatements(), "Can't register prepare statements for dynamic async connection"); } -template -void DatabaseWorkerPool::DirectExecute(std::string_view sql) +void DatabaseWorkerPool::OpenDynamicSyncConnect() { - if (sql.empty()) + std::lock_guard guard(_openSyncConnectMutex); + + if (_connections[IDX_SYNCH].size() >= MAX_SYNC_CONNECTIONS) return; - T* connection = GetFreeConnection(); - connection->Execute(sql); - connection->Unlock(); + LOG_DEBUG("db.pool", "Add new dynamic sync connection. Pool name: {}", GetPoolName()); + + auto [error, connection] = OpenConnection(IDX_SYNCH, true); + if (!error) + { + InitPrepareStatement(connection); + ASSERT(connection->PrepareStatements()); + } } -template -void DatabaseWorkerPool::DirectExecute(PreparedStatement* stmt) +void DatabaseWorkerPool::GetPoolInfo(std::function const& info) { - T* connection = GetFreeConnection(); - connection->Execute(stmt); - connection->Unlock(); + std::lock_guard guard(_cleanupMutex); - //! Delete proxy-class. Not needed anymore - delete stmt; + info(Acore::StringFormatFmt("Pool name: {}. Connections count (sync/async): {}/{}", GetPoolName(), _connections[IDX_SYNCH].size(), _connections[IDX_ASYNC].size())); + info(Acore::StringFormatFmt("Queue size: {}. Max size: {}", GetQueueSize(), _maxAsyncQueueSize)); } -template -void DatabaseWorkerPool::ExecuteOrAppend(SQLTransaction& trans, std::string_view sql) +void DatabaseWorkerPool::CheckAsyncQueue() { - if (!trans) - Execute(sql); - else - trans->Append(sql); -} + auto queueSize{ _queue->Size() }; + if (queueSize < _maxAsyncQueueSize) + return; -template -void DatabaseWorkerPool::ExecuteOrAppend(SQLTransaction& trans, PreparedStatement* stmt) -{ - if (!trans) - Execute(stmt); - else - trans->Append(stmt); -} + std::lock_guard guard(_cleanupMutex); + + LOG_WARN("db.pool", "{} DBPool: Queue overload. Size: {}. Max size: {}. Connections size: {}", _poolName, queueSize, _maxAsyncQueueSize, _connections[IDX_ASYNC].size()); -template class AC_DATABASE_API DatabaseWorkerPool; -template class AC_DATABASE_API DatabaseWorkerPool; -template class AC_DATABASE_API DatabaseWorkerPool; + for (std::size_t i{}; i < queueSize; i += _maxAsyncQueueSize) + OpenDynamicAsyncConnect(); +} diff --git a/src/server/database/Database/DatabaseWorkerPool.h b/src/server/database/Database/DatabaseWorkerPool.h index c7bc7798a45d82..b935ed9287ac3a 100644 --- a/src/server/database/Database/DatabaseWorkerPool.h +++ b/src/server/database/Database/DatabaseWorkerPool.h @@ -19,19 +19,34 @@ #define _DATABASEWORKERPOOL_H #include "DatabaseEnvFwd.h" -#include "Define.h" +#include "Duration.h" #include "StringFormat.h" #include +#include +#include +#include +#include #include template class ProducerConsumerQueue; -class SQLOperation; -struct MySQLConnectionInfo; +class AsyncDBQueueChecker; +class AsyncOperation; +class CheckAsyncQueueTask; +class TaskScheduler; -template -class DatabaseWorkerPool +struct StringPreparedStatement +{ + StringPreparedStatement(uint32 index, std::string_view sql, ConnectionFlags flags) : + Index(index), Query(sql), ConnectionType(flags) { } + + uint32 Index{}; + std::string Query; + ConnectionFlags ConnectionType{ ConnectionFlags::Sync }; +}; + +class AC_DATABASE_API DatabaseWorkerPool { private: enum InternalIndex @@ -42,22 +57,21 @@ class DatabaseWorkerPool }; public: - /* Activity state */ - DatabaseWorkerPool(); + explicit DatabaseWorkerPool(DatabaseType type); ~DatabaseWorkerPool(); - void SetConnectionInfo(std::string_view infoString, uint8 const asyncThreads, uint8 const synchThreads); + void SetConnectionInfo(std::string_view infoString); uint32 Open(); void Close(); //! Prepares all prepared statements bool PrepareStatements(); + virtual void DoPrepareStatements() = 0; - [[nodiscard]] inline MySQLConnectionInfo const* GetConnectionInfo() const - { - return _connectionInfo.get(); - } + [[nodiscard]] inline MySQLConnectionInfo const* GetConnectionInfo() const { return _connectionInfo.get(); } + + void Enqueue(AsyncOperation* operation); /** Delayed one-way statement methods. @@ -78,9 +92,7 @@ class DatabaseWorkerPool Execute(Acore::StringFormatFmt(sql, std::forward(args)...)); } - //! Enqueues a one-way SQL operation in prepared statement format that will be executed asynchronously. - //! Statement must be prepared with CONNECTION_ASYNC flag. - void Execute(PreparedStatement* stmt); + void Execute(PreparedStatement stmt); /** Direct synchronous one-way statement methods. @@ -103,7 +115,7 @@ class DatabaseWorkerPool //! Directly executes a one-way SQL operation in prepared statement format, that will block the calling thread until finished. //! Statement must be prepared with the CONNECTION_SYNCH flag. - void DirectExecute(PreparedStatement* stmt); + void DirectExecute(PreparedStatement stmt); /** Synchronous query (with resultset) methods. @@ -119,7 +131,7 @@ class DatabaseWorkerPool QueryResult Query(std::string_view sql, Args&&... args) { if (sql.empty()) - return QueryResult(nullptr); + return { nullptr }; return Query(Acore::StringFormatFmt(sql, std::forward(args)...)); } @@ -127,7 +139,7 @@ class DatabaseWorkerPool //! Directly executes an SQL query in prepared format that will block the calling thread until finished. //! Returns reference counted auto pointer, no need for manual memory management in upper level code. //! Statement must be prepared with CONNECTION_SYNCH flag. - PreparedQueryResult Query(PreparedStatement* stmt); + PreparedQueryResult Query(PreparedStatement stmt); /** Asynchronous query (with resultset) methods. @@ -140,51 +152,54 @@ class DatabaseWorkerPool //! Enqueues a query in prepared format that will set the value of the PreparedQueryResultFuture return object as soon as the query is executed. //! The return value is then processed in ProcessQueryCallback methods. //! Statement must be prepared with CONNECTION_ASYNC flag. - QueryCallback AsyncQuery(PreparedStatement* stmt); + QueryCallback AsyncQuery(PreparedStatement stmt); //! Enqueues a vector of SQL operations (can be both adhoc and prepared) that will set the value of the QueryResultHolderFuture //! return object as soon as the query is executed. //! The return value is then processed in ProcessQueryCallback methods. //! Any prepared statements added to this holder need to be prepared with the CONNECTION_ASYNC flag. - SQLQueryHolderCallback DelayQueryHolder(std::shared_ptr> holder); + SQLQueryHolderCallback DelayQueryHolder(SQLQueryHolder holder); /** Transaction context methods. */ //! Begins an automanaged transaction pointer that will automatically rollback if not commited. (Autocommit=0) - SQLTransaction BeginTransaction(); + SQLTransaction BeginTransaction(); //! Enqueues a collection of one-way SQL operations (can be both adhoc and prepared). The order in which these operations //! were appended to the transaction will be respected during execution. - void CommitTransaction(SQLTransaction transaction); + void CommitTransaction(SQLTransaction transaction); //! Enqueues a collection of one-way SQL operations (can be both adhoc and prepared). The order in which these operations //! were appended to the transaction will be respected during execution. - TransactionCallback AsyncCommitTransaction(SQLTransaction transaction); + TransactionCallback AsyncCommitTransaction(SQLTransaction transaction); //! Directly executes a collection of one-way SQL operations (can be both adhoc and prepared). The order in which these operations //! were appended to the transaction will be respected during execution. - void DirectCommitTransaction(SQLTransaction& transaction); + void DirectCommitTransaction(SQLTransaction transaction); //! Method used to execute ad-hoc statements in a diverse context. //! Will be wrapped in a transaction if valid object is present, otherwise executed standalone. - void ExecuteOrAppend(SQLTransaction& trans, std::string_view sql); + void ExecuteOrAppend(SQLTransaction trans, std::string_view sql); //! Method used to execute prepared statements in a diverse context. //! Will be wrapped in a transaction if valid object is present, otherwise executed standalone. - void ExecuteOrAppend(SQLTransaction& trans, PreparedStatement* stmt); + void ExecuteOrAppend(SQLTransaction trans, PreparedStatement stmt); /** Other */ - typedef typename T::Statements PreparedStatementIndex; - - //! Automanaged (internally) pointer to a prepared statement object for usage in upper level code. - //! Pointer is deleted in this->DirectExecute(PreparedStatement*), this->Query(PreparedStatement*) or PreparedStatementTask::~PreparedStatementTask. + //! Auto managed (internally) pointer to a prepared statement object for usage in upper level code. + //! Pointer is deleted in this->DirectExecute(PreparedStatementBase*), this->Query(PreparedStatementBase*) or PreparedStatementTask::~PreparedStatementTask. //! This object is not tied to the prepared statement on the MySQL context yet until execution. - PreparedStatement* GetPreparedStatement(PreparedStatementIndex index); + PreparedStatement GetPreparedStatement(uint32 index); + + void PrepareStatement(uint32 index, std::string_view sql, ConnectionFlags flags); + + // Close dynamic connections if need + void CleanupConnections(); //! Apply escape string'ing for current collation. (utf8) void EscapeString(std::string& str); @@ -199,30 +214,70 @@ class DatabaseWorkerPool #endif } - [[nodiscard]] size_t QueueSize() const; + inline std::string_view GetPoolName() const { return _poolName; } + inline void SetPoolName(std::string_view name) { _poolName = name; } + + inline DatabaseType GetType() const { return _poolType; } + inline void SetType(DatabaseType type) { _poolType = type; } + + void Update(Milliseconds diff); + [[nodiscard]] std::size_t GetQueueSize() const; + + void OpenDynamicAsyncConnect(); + void OpenDynamicSyncConnect(); + + void GetPoolInfo(std::function const& info); + + inline std::string_view GetPathToExtraFile() { return _pathToExtraFile; } + + void CheckCleanup(); + void CheckAsyncQueue(); + +protected: + inline void SetStatementSize(std::size_t statementSize) { _statementSize = statementSize; } + inline std::size_t GetStatementSize() const { return _statementSize; } + + std::size_t _statementSize{}; private: - uint32 OpenConnections(InternalIndex type, uint8 numConnections); + std::pair OpenConnection(InternalIndex type, bool isDynamic = false); + void InitPrepareStatement(MySQLConnection* connection); unsigned long EscapeString(char* to, char const* from, unsigned long length); - - void Enqueue(SQLOperation* op); + void AddTasks(); + void MakeExtraFile(); //! Gets a free connection in the synchronous connection pool. //! Caller MUST call t->Unlock() after touching the MySQL context to prevent deadlocks. - T* GetFreeConnection(); + MySQLConnection* GetFreeConnection(); + // Get using db name from connection info [[nodiscard]] std::string_view GetDatabaseName() const; - //! Queue shared by async worker threads. - std::unique_ptr> _queue; - std::array>, IDX_SIZE> _connections; + std::unordered_map _stringPreparedStatement; + std::array>, IDX_SIZE> _connections; std::unique_ptr _connectionInfo; std::vector _preparedStatementSize; - uint8 _async_threads, _synch_threads; + std::mutex _openSyncConnectMutex; + std::mutex _openAsyncConnectMutex; + std::mutex _cleanupMutex; + std::string _poolName; + std::string _pathToExtraFile; + DatabaseType _poolType{ DatabaseType::None }; + std::unique_ptr _scheduler; + + // Async queue + std::unique_ptr> _queue; + std::unique_ptr> _asyncQueueCheckQueue; + std::unique_ptr _asyncQueueChecker; + std::size_t _maxAsyncQueueSize{ 10 }; + #ifdef ACORE_DEBUG static inline thread_local bool _warnSyncQueries = false; #endif + + DatabaseWorkerPool(DatabaseWorkerPool const& right) = delete; + DatabaseWorkerPool& operator=(DatabaseWorkerPool const& right) = delete; }; #endif diff --git a/src/server/database/Database/Field.cpp b/src/server/database/Database/Field.cpp index 35f84c2a0a3ced..fd4f87bac3dfca 100644 --- a/src/server/database/Database/Field.cpp +++ b/src/server/database/Database/Field.cpp @@ -18,18 +18,9 @@ #include "Field.h" #include "Errors.h" #include "Log.h" -#include "MySQLHacks.h" #include "StringConvert.h" #include "Types.h" -Field::Field() -{ - data.value = nullptr; - data.length = 0; - data.raw = false; - meta = nullptr; -} - namespace { template @@ -57,7 +48,7 @@ namespace return true; } - // In16 + // Int16 if constexpr (std::is_same_v || std::is_same_v) { if (type == DatabaseFieldTypes::Int16) @@ -85,7 +76,7 @@ namespace return true; } - // dobule + // double if constexpr (std::is_same_v) { if (type == DatabaseFieldTypes::Double || type == DatabaseFieldTypes::Decimal) @@ -102,7 +93,7 @@ namespace return false; } - inline Optional GetCleanAliasName(std::string_view alias) + inline std::optional GetCleanAliasName(std::string_view alias) { if (alias.empty()) return {}; @@ -144,6 +135,14 @@ namespace } } +Field::Field() +{ + data.value = nullptr; + data.length = 0; + data.raw = false; + meta = nullptr; +} + void Field::GetBinarySizeChecked(uint8* buf, size_t length) const { ASSERT(data.value && (data.length == length), "Expected {}-byte binary blob, got {}data ({} bytes) instead", length, data.value ? "" : "no ", data.length); @@ -183,7 +182,7 @@ bool Field::IsNumeric() const void Field::LogWrongType(std::string_view getter, std::string_view typeName) const { - LOG_WARN("sql.sql", "Warning: {}<{}> on {} field {}.{} ({}.{}) at index {}.", + LOG_WARN("db.query", "Warning: {}<{}> on {} field {}.{} ({}.{}) at index {}.", getter, typeName, meta->TypeName, meta->TableAlias, meta->Alias, meta->TableName, meta->Name, meta->Index); } @@ -208,13 +207,22 @@ T Field::GetData() const } #endif - Optional result = {}; + std::optional result; if (data.raw) result = *reinterpret_cast(data.value); else result = Acore::StringTo(data.value); + if (!result) + { + if constexpr (std::is_unsigned_v && !std::is_same_v) + { + if (auto newResult = Acore::StringTo>(data.value)) + result = static_cast(*newResult); + } + } + // Correct double fields... this undefined behavior :/ if constexpr (std::is_same_v) { @@ -224,50 +232,35 @@ T Field::GetData() const result = Acore::StringTo(data.value); } - // Check -1 for *_dbc db tables - if constexpr (std::is_same_v) - { - std::string_view tableName{ meta->TableName }; - - if (!tableName.empty() && tableName.size() > 4) - { - auto signedResult = Acore::StringTo(data.value); - - if (signedResult && !result && tableName.substr(tableName.length() - 4) == "_dbc") - { - LOG_DEBUG("sql.sql", "> Found incorrect value '{}' for type '{}' in _dbc table.", data.value, typeid(T).name()); - LOG_DEBUG("sql.sql", "> Table name '{}'. Field name '{}'. Try return int32 value", meta->TableName, meta->Name); - return GetData(); - } - } - } - if (auto alias = GetCleanAliasName(meta->Alias)) { if ((StringEqualI(*alias, "min") || StringEqualI(*alias, "max")) && !IsCorrectAlias(meta->Type, *alias)) { - LogWrongType(__FUNCTION__, typeid(T).name()); + LogWrongType(__FUNCTION__, GetTypeName()); + //ABORT(); } if ((StringEqualI(*alias, "sum") || StringEqualI(*alias, "avg")) && !IsCorrectAlias(meta->Type, *alias)) { - LogWrongType(__FUNCTION__, typeid(T).name()); - LOG_WARN("sql.sql", "> Please use GetData()"); + LogWrongType(__FUNCTION__, GetTypeName()); + LOG_WARN("db.query", "> Please use GetData()"); return GetData(); + //ABORT(); } if (StringEqualI(*alias, "count") && !IsCorrectAlias(meta->Type, *alias)) { - LogWrongType(__FUNCTION__, typeid(T).name()); - LOG_WARN("sql.sql", "> Please use GetData()"); + LogWrongType(__FUNCTION__, GetTypeName()); + LOG_WARN("db.query", "> Please use GetData()"); return GetData(); + //ABORT(); } } if (!result) { - LOG_FATAL("sql.sql", "> Incorrect value '{}' for type '{}'. Value is raw ? '{}'", data.value, typeid(T).name(), data.raw); - LOG_FATAL("sql.sql", "> Table name '{}'. Field name '{}'", meta->TableName, meta->Name); + LOG_FATAL("db.query", "> Incorrect value '{}' for type '{}'. Value is raw ? '{}'", data.value, GetTypeName(), data.raw); + LOG_FATAL("db.query", "> Table name '{}'. Field name '{}'", meta->TableName, meta->Name); //ABORT(); return GetDefaultValue(); } @@ -275,17 +268,17 @@ T Field::GetData() const return *result; } -template bool Field::GetData() const; -template uint8 Field::GetData() const; -template uint16 Field::GetData() const; -template uint32 Field::GetData() const; -template uint64 Field::GetData() const; -template int8 Field::GetData() const; -template int16 Field::GetData() const; -template int32 Field::GetData() const; -template int64 Field::GetData() const; -template float Field::GetData() const; -template double Field::GetData() const; +template AC_DATABASE_API bool Field::GetData() const; +template AC_DATABASE_API uint8 Field::GetData() const; +template AC_DATABASE_API uint16 Field::GetData() const; +template AC_DATABASE_API uint32 Field::GetData() const; +template AC_DATABASE_API uint64 Field::GetData() const; +template AC_DATABASE_API int8 Field::GetData() const; +template AC_DATABASE_API int16 Field::GetData() const; +template AC_DATABASE_API int32 Field::GetData() const; +template AC_DATABASE_API int64 Field::GetData() const; +template AC_DATABASE_API float Field::GetData() const; +template AC_DATABASE_API double Field::GetData() const; std::string Field::GetDataString() const { diff --git a/src/server/database/Database/Field.h b/src/server/database/Database/Field.h index 8496560c3c6ffa..2f1a2ebb72e441 100644 --- a/src/server/database/Database/Field.h +++ b/src/server/database/Database/Field.h @@ -19,25 +19,11 @@ #define _FIELD_H #include "DatabaseEnvFwd.h" -#include "Define.h" #include "Duration.h" #include #include #include -namespace Acore::Types -{ - template - using is_chrono_v = std::enable_if_t - || std::is_same_v - || std::is_same_v - || std::is_same_v - || std::is_same_v - || std::is_same_v - || std::is_same_v - || std::is_same_v, T>; -} - using Binary = std::vector; enum class DatabaseFieldTypes : uint8 @@ -56,13 +42,13 @@ enum class DatabaseFieldTypes : uint8 struct QueryResultFieldMetadata { - std::string TableName{}; - std::string TableAlias{}; - std::string Name{}; - std::string Alias{}; - std::string TypeName{}; - uint32 Index = 0; - DatabaseFieldTypes Type = DatabaseFieldTypes::Null; + std::string TableName; + std::string TableAlias; + std::string Name; + std::string Alias; + std::string TypeName; + uint32 Index{ 0 }; + DatabaseFieldTypes Type{ DatabaseFieldTypes::Null }; }; /** @@ -97,18 +83,13 @@ struct QueryResultFieldMetadata */ class AC_DATABASE_API Field { -friend class ResultSet; -friend class PreparedResultSet; + friend class ResultSet; + friend class PreparedResultSet; public: Field(); ~Field() = default; - [[nodiscard]] inline bool IsNull() const - { - return data.value == nullptr; - } - template inline std::enable_if_t, T> Get() const { @@ -136,43 +117,50 @@ friend class PreparedResultSet; template inline std::enable_if_t, std::array> Get() const { - std::array buf = {}; + std::array buf{}; GetBinarySizeChecked(buf.data(), S); return buf; } template - inline Acore::Types::is_chrono_v Get(bool convertToUin32 = true) const + inline std::enable_if_t, T> Get(bool convertToUin32 = true) const { return convertToUin32 ? T(GetData()) : T(GetData()); } + [[nodiscard]] inline bool IsNull() const + { + return data.value == nullptr; + } + DatabaseFieldTypes GetType() { return meta->Type; } protected: struct { - char const* value; // Actual data in memory - uint32 length; // Length - bool raw; // Raw bytes? (Prepared statement or ad hoc) + char const* value; // Actual data in memory + uint32 length; // Length + bool raw; // Raw bytes? (Prepared statement or ad hoc) } data; void SetByteValue(char const* newValue, uint32 length); void SetStructuredValue(char const* newValue, uint32 length); + [[nodiscard]] bool IsType(DatabaseFieldTypes type) const; [[nodiscard]] bool IsNumeric() const; private: template - T GetData() const; + [[nodiscard]] T GetData() const; - std::string GetDataString() const; - std::string_view GetDataStringView() const; - Binary GetDataBinary() const; + [[nodiscard]] std::string GetDataString() const; + [[nodiscard]] std::string_view GetDataStringView() const; + [[nodiscard]] Binary GetDataBinary() const; QueryResultFieldMetadata const* meta; void LogWrongType(std::string_view getter, std::string_view typeName) const; void SetMetadata(QueryResultFieldMetadata const* fieldMeta); + void GetBinarySizeChecked(uint8* buf, size_t size) const; }; diff --git a/src/server/database/Database/Implementation/CharacterDatabase.cpp b/src/server/database/Database/Implementation/CharacterDatabase.cpp index 9565cf310ead46..68db6f2ccf39d4 100644 --- a/src/server/database/Database/Implementation/CharacterDatabase.cpp +++ b/src/server/database/Database/Implementation/CharacterDatabase.cpp @@ -16,54 +16,54 @@ */ #include "CharacterDatabase.h" -#include "MySQLPreparedStatement.h" -void CharacterDatabaseConnection::DoPrepareStatements() +CharacterDatabasePool CharacterDatabase; + +void CharacterDatabasePool::DoPrepareStatements() { - if (!m_reconnecting) - m_stmts.resize(MAX_CHARACTERDATABASE_STATEMENTS); - - PrepareStatement(CHAR_DEL_QUEST_POOL_SAVE, "DELETE FROM pool_quest_save WHERE pool_id = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_QUEST_POOL_SAVE, "INSERT INTO pool_quest_save (pool_id, quest_id) VALUES (?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_NONEXISTENT_GUILD_BANK_ITEM, "DELETE FROM guild_bank_item WHERE guildid = ? AND TabId = ? AND SlotId = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_EXPIRED_BANS, "UPDATE character_banned SET active = 0 WHERE unbandate <= UNIX_TIMESTAMP() AND unbandate <> bandate", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_DATA_BY_NAME, "SELECT guid, account, name, gender, race, class, level FROM characters WHERE deleteDate IS NULL AND name = ?", CONNECTION_BOTH); - PrepareStatement(CHAR_SEL_DATA_BY_GUID, "SELECT guid, account, name, gender, race, class, level FROM characters WHERE deleteDate IS NULL AND guid = ?", CONNECTION_BOTH); - PrepareStatement(CHAR_SEL_CHECK_NAME, "SELECT 1 FROM characters WHERE name = ?", CONNECTION_BOTH); - PrepareStatement(CHAR_SEL_CHECK_GUID, "SELECT 1 FROM characters WHERE guid = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_SUM_CHARS, "SELECT COUNT(guid) FROM characters WHERE account = ?", CONNECTION_BOTH); - PrepareStatement(CHAR_SEL_CHAR_CREATE_INFO, "SELECT level, race, class FROM characters WHERE account = ? LIMIT 0, ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_CHARACTER_BAN, "INSERT INTO character_banned VALUES (?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, ?, ?, 1)", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHARACTER_BAN, "UPDATE character_banned SET active = 0 WHERE guid = ? AND active != 0", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHARACTER_BAN, "DELETE cb FROM character_banned cb INNER JOIN characters c ON c.guid = cb.guid WHERE c.account = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_BANINFO, "SELECT FROM_UNIXTIME(bandate, '%Y-%m-%d %H:%i:%s'), unbandate-bandate, active, unbandate, banreason, bannedby FROM character_banned WHERE guid = ? ORDER BY bandate ASC", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_GUID_BY_NAME_FILTER, "SELECT guid, name FROM characters WHERE name LIKE CONCAT('%%', ?, '%%')", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_BANINFO_LIST, "SELECT bandate, unbandate, bannedby, banreason FROM character_banned WHERE guid = ? ORDER BY unbandate", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_BANNED_NAME, "SELECT characters.name FROM characters, character_banned WHERE character_banned.guid = ? AND character_banned.guid = characters.guid", CONNECTION_SYNCH); + SetStatementSize(MAX_CHARACTER_DATABASE_STATEMENTS); + + PrepareStatement(CHAR_DEL_QUEST_POOL_SAVE, "DELETE FROM pool_quest_save WHERE pool_id = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_QUEST_POOL_SAVE, "INSERT INTO pool_quest_save (pool_id, quest_id) VALUES (?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_NONEXISTENT_GUILD_BANK_ITEM, "DELETE FROM guild_bank_item WHERE guildid = ? AND TabId = ? AND SlotId = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_EXPIRED_BANS, "UPDATE character_banned SET active = 0 WHERE unbandate <= UNIX_TIMESTAMP() AND unbandate <> bandate", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_DATA_BY_NAME, "SELECT guid, account, name, gender, race, class, level FROM characters WHERE deleteDate IS NULL AND name = ?", ConnectionFlags::Both); + PrepareStatement(CHAR_SEL_DATA_BY_GUID, "SELECT guid, account, name, gender, race, class, level FROM characters WHERE deleteDate IS NULL AND guid = ?", ConnectionFlags::Both); + PrepareStatement(CHAR_SEL_CHECK_NAME, "SELECT 1 FROM characters WHERE name = ?", ConnectionFlags::Both); + PrepareStatement(CHAR_SEL_CHECK_GUID, "SELECT 1 FROM characters WHERE guid = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_SUM_CHARS, "SELECT COUNT(guid) FROM characters WHERE account = ?", ConnectionFlags::Both); + PrepareStatement(CHAR_SEL_CHAR_CREATE_INFO, "SELECT level, race, class FROM characters WHERE account = ? LIMIT 0, ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_CHARACTER_BAN, "INSERT INTO character_banned VALUES (?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, ?, ?, 1)", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHARACTER_BAN, "UPDATE character_banned SET active = 0 WHERE guid = ? AND active != 0", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHARACTER_BAN, "DELETE cb FROM character_banned cb INNER JOIN characters c ON c.guid = cb.guid WHERE c.account = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_BANINFO, "SELECT FROM_UNIXTIME(bandate, '%Y-%m-%d %H:%i:%s'), unbandate-bandate, active, unbandate, banreason, bannedby FROM character_banned WHERE guid = ? ORDER BY bandate ASC", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_GUID_BY_NAME_FILTER, "SELECT guid, name FROM characters WHERE name LIKE CONCAT('%%', ?, '%%')", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_BANINFO_LIST, "SELECT bandate, unbandate, bannedby, banreason FROM character_banned WHERE guid = ? ORDER BY unbandate", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_BANNED_NAME, "SELECT characters.name FROM characters, character_banned WHERE character_banned.guid = ? AND character_banned.guid = characters.guid", ConnectionFlags::Sync); PrepareStatement(CHAR_SEL_ENUM, "SELECT c.guid, c.name, c.race, c.class, c.gender, c.skin, c.face, c.hairStyle, c.hairColor, c.facialStyle, c.level, c.zone, c.map, c.position_x, c.position_y, c.position_z, " "gm.guildid, c.playerFlags, c.at_login, cp.entry, cp.modelid, cp.level, c.equipmentCache, cb.guid, c.extra_flags " "FROM characters AS c LEFT JOIN character_pet AS cp ON c.guid = cp.owner AND cp.slot = ? LEFT JOIN guild_member AS gm ON c.guid = gm.guid " - "LEFT JOIN character_banned AS cb ON c.guid = cb.guid AND cb.active = 1 WHERE c.account = ? AND c.deleteInfos_Name IS NULL ORDER BY COALESCE(c.order, c.guid)", CONNECTION_ASYNC); + "LEFT JOIN character_banned AS cb ON c.guid = cb.guid AND cb.active = 1 WHERE c.account = ? AND c.deleteInfos_Name IS NULL ORDER BY COALESCE(c.order, c.guid)", ConnectionFlags::Async); PrepareStatement(CHAR_SEL_ENUM_DECLINED_NAME, "SELECT c.guid, c.name, c.race, c.class, c.gender, c.skin, c.face, c.hairStyle, c.hairColor, c.facialStyle, c.level, c.zone, c.map, " "c.position_x, c.position_y, c.position_z, gm.guildid, c.playerFlags, c.at_login, cp.entry, cp.modelid, cp.level, c.equipmentCache, " "cb.guid, c.extra_flags, cd.genitive FROM characters AS c LEFT JOIN character_pet AS cp ON c.guid = cp.owner AND cp.slot = ? " "LEFT JOIN character_declinedname AS cd ON c.guid = cd.guid LEFT JOIN guild_member AS gm ON c.guid = gm.guid " - "LEFT JOIN character_banned AS cb ON c.guid = cb.guid AND cb.active = 1 WHERE c.account = ? AND c.deleteInfos_Name IS NULL ORDER BY COALESCE(c.order, c.guid)", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_FREE_NAME, "SELECT guid, name, at_login FROM characters WHERE guid = ? AND account = ? AND NOT EXISTS (SELECT NULL FROM characters WHERE name = ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHAR_ZONE, "SELECT zone FROM characters WHERE guid = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHARACTER_NAME_DATA, "SELECT race, class, gender, level FROM characters WHERE guid = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHAR_POSITION_XYZ, "SELECT map, position_x, position_y, position_z FROM characters WHERE guid = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHAR_POSITION, "SELECT position_x, position_y, position_z, orientation, map, taxi_path FROM characters WHERE guid = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_DEL_QUEST_STATUS_DAILY, "DELETE FROM character_queststatus_daily", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_QUEST_STATUS_WEEKLY, "DELETE FROM character_queststatus_weekly", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_QUEST_STATUS_MONTHLY, "DELETE FROM character_queststatus_monthly", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_QUEST_STATUS_SEASONAL, "DELETE FROM character_queststatus_seasonal WHERE event = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_QUEST_STATUS_DAILY_CHAR, "DELETE FROM character_queststatus_daily WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_QUEST_STATUS_WEEKLY_CHAR, "DELETE FROM character_queststatus_weekly WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_QUEST_STATUS_MONTHLY_CHAR, "DELETE FROM character_queststatus_monthly WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_QUEST_STATUS_SEASONAL_CHAR, "DELETE FROM character_queststatus_seasonal WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_BATTLEGROUND_RANDOM, "DELETE FROM character_battleground_random", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_BATTLEGROUND_RANDOM, "INSERT INTO character_battleground_random (guid) VALUES (?)", CONNECTION_ASYNC); + "LEFT JOIN character_banned AS cb ON c.guid = cb.guid AND cb.active = 1 WHERE c.account = ? AND c.deleteInfos_Name IS NULL ORDER BY COALESCE(c.order, c.guid)", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_FREE_NAME, "SELECT guid, name, at_login FROM characters WHERE guid = ? AND account = ? AND NOT EXISTS (SELECT NULL FROM characters WHERE name = ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHAR_ZONE, "SELECT zone FROM characters WHERE guid = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_CHARACTER_NAME_DATA, "SELECT race, class, gender, level FROM characters WHERE guid = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_CHAR_POSITION_XYZ, "SELECT map, position_x, position_y, position_z FROM characters WHERE guid = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_CHAR_POSITION, "SELECT position_x, position_y, position_z, orientation, map, taxi_path FROM characters WHERE guid = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_DEL_QUEST_STATUS_DAILY, "DELETE FROM character_queststatus_daily", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_QUEST_STATUS_WEEKLY, "DELETE FROM character_queststatus_weekly", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_QUEST_STATUS_MONTHLY, "DELETE FROM character_queststatus_monthly", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_QUEST_STATUS_SEASONAL, "DELETE FROM character_queststatus_seasonal WHERE event = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_QUEST_STATUS_DAILY_CHAR, "DELETE FROM character_queststatus_daily WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_QUEST_STATUS_WEEKLY_CHAR, "DELETE FROM character_queststatus_weekly WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_QUEST_STATUS_MONTHLY_CHAR, "DELETE FROM character_queststatus_monthly WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_QUEST_STATUS_SEASONAL_CHAR, "DELETE FROM character_queststatus_seasonal WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_BATTLEGROUND_RANDOM, "DELETE FROM character_battleground_random", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_BATTLEGROUND_RANDOM, "INSERT INTO character_battleground_random (guid) VALUES (?)", ConnectionFlags::Async); // Start LoginQueryHolder content PrepareStatement(CHAR_SEL_CHARACTER, "SELECT guid, account, name, race, class, gender, level, xp, money, skin, face, hairStyle, hairColor, facialStyle, bankSlots, restState, playerFlags, " @@ -71,263 +71,263 @@ void CharacterDatabaseConnection::DoPrepareStatements() "resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, instance_mode_mask, " "arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk, " "health, power1, power2, power3, power4, power5, power6, power7, instance_id, talentGroupsCount, activeTalentGroup, exploredZones, equipmentCache, ammoId, " - "knownTitles, actionBars, grantableLevels, innTriggerId, extraBonusTalentCount FROM characters WHERE guid = ?", CONNECTION_ASYNC); + "knownTitles, actionBars, grantableLevels, innTriggerId, extraBonusTalentCount FROM characters WHERE guid = ?", ConnectionFlags::Async); PrepareStatement(CHAR_SEL_CHARACTER_AURAS, "SELECT casterGuid, itemGuid, spell, effectMask, recalculateMask, stackCount, amount0, amount1, amount2, " - "base_amount0, base_amount1, base_amount2, maxDuration, remainTime, remainCharges FROM character_aura WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_SPELL, "SELECT spell, specMask FROM character_spell WHERE guid = ?", CONNECTION_ASYNC); + "base_amount0, base_amount1, base_amount2, maxDuration, remainTime, remainCharges FROM character_aura WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_SPELL, "SELECT spell, specMask FROM character_spell WHERE guid = ?", ConnectionFlags::Async); PrepareStatement(CHAR_SEL_CHARACTER_QUESTSTATUS, "SELECT quest, status, explored, timer, mobcount1, mobcount2, mobcount3, mobcount4, " - "itemcount1, itemcount2, itemcount3, itemcount4, itemcount5, itemcount6, playercount FROM character_queststatus WHERE guid = ? AND status <> 0", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_DAILYQUESTSTATUS, "SELECT quest, time FROM character_queststatus_daily WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_WEEKLYQUESTSTATUS, "SELECT quest FROM character_queststatus_weekly WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_MONTHLYQUESTSTATUS, "SELECT quest FROM character_queststatus_monthly WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_SEASONALQUESTSTATUS, "SELECT quest, event FROM character_queststatus_seasonal WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_CHARACTER_DAILYQUESTSTATUS, "INSERT INTO character_queststatus_daily (guid, quest, time) VALUES (?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_CHARACTER_WEEKLYQUESTSTATUS, "INSERT INTO character_queststatus_weekly (guid, quest) VALUES (?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_CHARACTER_MONTHLYQUESTSTATUS, "INSERT INTO character_queststatus_monthly (guid, quest) VALUES (?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_CHARACTER_SEASONALQUESTSTATUS, "INSERT IGNORE INTO character_queststatus_seasonal (guid, quest, event) VALUES (?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_REPUTATION, "SELECT faction, standing, flags FROM character_reputation WHERE guid = ?", CONNECTION_ASYNC); + "itemcount1, itemcount2, itemcount3, itemcount4, itemcount5, itemcount6, playercount FROM character_queststatus WHERE guid = ? AND status <> 0", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_DAILYQUESTSTATUS, "SELECT quest, time FROM character_queststatus_daily WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_WEEKLYQUESTSTATUS, "SELECT quest FROM character_queststatus_weekly WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_MONTHLYQUESTSTATUS, "SELECT quest FROM character_queststatus_monthly WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_SEASONALQUESTSTATUS, "SELECT quest, event FROM character_queststatus_seasonal WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_CHARACTER_DAILYQUESTSTATUS, "INSERT INTO character_queststatus_daily (guid, quest, time) VALUES (?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_CHARACTER_WEEKLYQUESTSTATUS, "INSERT INTO character_queststatus_weekly (guid, quest) VALUES (?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_CHARACTER_MONTHLYQUESTSTATUS, "INSERT INTO character_queststatus_monthly (guid, quest) VALUES (?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_CHARACTER_SEASONALQUESTSTATUS, "INSERT IGNORE INTO character_queststatus_seasonal (guid, quest, event) VALUES (?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_REPUTATION, "SELECT faction, standing, flags FROM character_reputation WHERE guid = ?", ConnectionFlags::Async); PrepareStatement(CHAR_SEL_CHARACTER_INVENTORY, "SELECT creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, playedTime, text, bag, slot, " - "item, itemEntry FROM character_inventory ci JOIN item_instance ii ON ci.item = ii.guid WHERE ci.guid = ? ORDER BY bag, slot", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_ACTIONS, "SELECT a.button, a.action, a.type FROM character_action as a, characters as c WHERE a.guid = c.guid AND a.spec = c.activeTalentGroup AND a.guid = ? ORDER BY button", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_MAILCOUNT_UNREAD, "SELECT COUNT(id) FROM mail WHERE receiver = ? AND (checked & 1) = 0 AND deliver_time <= ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_MAILCOUNT_UNREAD_SYNCH, "SELECT COUNT(id) FROM mail WHERE receiver = ? AND (checked & 1) = 0 AND deliver_time <= ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_MAIL_SERVER_CHARACTER, "SELECT mailId from mail_server_character WHERE guid = ? and mailId = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_REP_MAIL_SERVER_CHARACTER, "REPLACE INTO mail_server_character (guid, mailId) values (?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_SOCIALLIST, "SELECT friend, flags, note FROM character_social JOIN characters ON characters.guid = character_social.friend WHERE character_social.guid = ? AND deleteinfos_name IS NULL LIMIT 255", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_HOMEBIND, "SELECT mapId, zoneId, posX, posY, posZ, posO FROM character_homebind WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_SPELLCOOLDOWNS, "SELECT spell, category, item, time, needSend FROM character_spell_cooldown WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_DECLINEDNAMES, "SELECT genitive, dative, accusative, instrumental, prepositional FROM character_declinedname WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_ACHIEVEMENTS, "SELECT achievement, date FROM character_achievement WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_CRITERIAPROGRESS, "SELECT criteria, counter, date FROM character_achievement_progress WHERE guid = ?", CONNECTION_ASYNC); + "item, itemEntry FROM character_inventory ci JOIN item_instance ii ON ci.item = ii.guid WHERE ci.guid = ? ORDER BY bag, slot", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_ACTIONS, "SELECT a.button, a.action, a.type FROM character_action as a, characters as c WHERE a.guid = c.guid AND a.spec = c.activeTalentGroup AND a.guid = ? ORDER BY button", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_MAILCOUNT_UNREAD, "SELECT COUNT(id) FROM mail WHERE receiver = ? AND (checked & 1) = 0 AND deliver_time <= ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_MAILCOUNT_UNREAD_SYNCH, "SELECT COUNT(id) FROM mail WHERE receiver = ? AND (checked & 1) = 0 AND deliver_time <= ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_MAIL_SERVER_CHARACTER, "SELECT mailId from mail_server_character WHERE guid = ? and mailId = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_REP_MAIL_SERVER_CHARACTER, "REPLACE INTO mail_server_character (guid, mailId) values (?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_SOCIALLIST, "SELECT friend, flags, note FROM character_social JOIN characters ON characters.guid = character_social.friend WHERE character_social.guid = ? AND deleteinfos_name IS NULL LIMIT 255", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_HOMEBIND, "SELECT mapId, zoneId, posX, posY, posZ, posO FROM character_homebind WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_SPELLCOOLDOWNS, "SELECT spell, category, item, time, needSend FROM character_spell_cooldown WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_DECLINEDNAMES, "SELECT genitive, dative, accusative, instrumental, prepositional FROM character_declinedname WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_ACHIEVEMENTS, "SELECT achievement, date FROM character_achievement WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_CRITERIAPROGRESS, "SELECT criteria, counter, date FROM character_achievement_progress WHERE guid = ?", ConnectionFlags::Async); PrepareStatement(CHAR_SEL_CHARACTER_EQUIPMENTSETS, "SELECT setguid, setindex, name, iconname, ignore_mask, item0, item1, item2, item3, item4, item5, item6, item7, item8, " - "item9, item10, item11, item12, item13, item14, item15, item16, item17, item18 FROM character_equipmentsets WHERE guid = ? ORDER BY setindex", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_ENTRY_POINT, "SELECT joinX, joinY, joinZ, joinO, joinMapId, taxiPath0, taxiPath1, mountSpell FROM character_entry_point WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_GLYPHS, "SELECT talentGroup, glyph1, glyph2, glyph3, glyph4, glyph5, glyph6 FROM character_glyphs WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_TALENTS, "SELECT spell, specMask FROM character_talent WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_SKILLS, "SELECT skill, value, max FROM character_skills WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_RANDOMBG, "SELECT guid FROM character_battleground_random WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_BANNED, "SELECT guid FROM character_banned WHERE guid = ? AND active = 1", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_QUESTSTATUSREW, "SELECT quest FROM character_queststatus_rewarded WHERE guid = ? AND active = 1", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_ACCOUNT_INSTANCELOCKTIMES, "SELECT instanceId, releaseTime FROM account_instance_times WHERE accountId = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_BREW_OF_THE_MONTH, "SELECT lastEventId FROM character_brew_of_the_month WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_REP_BREW_OF_THE_MONTH, "REPLACE INTO character_brew_of_the_month (guid, lastEventId) VALUES (?, ?)", CONNECTION_ASYNC); + "item9, item10, item11, item12, item13, item14, item15, item16, item17, item18 FROM character_equipmentsets WHERE guid = ? ORDER BY setindex", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_ENTRY_POINT, "SELECT joinX, joinY, joinZ, joinO, joinMapId, taxiPath0, taxiPath1, mountSpell FROM character_entry_point WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_GLYPHS, "SELECT talentGroup, glyph1, glyph2, glyph3, glyph4, glyph5, glyph6 FROM character_glyphs WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_TALENTS, "SELECT spell, specMask FROM character_talent WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_SKILLS, "SELECT skill, value, max FROM character_skills WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_RANDOMBG, "SELECT guid FROM character_battleground_random WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_BANNED, "SELECT guid FROM character_banned WHERE guid = ? AND active = 1", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_QUESTSTATUSREW, "SELECT quest FROM character_queststatus_rewarded WHERE guid = ? AND active = 1", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_ACCOUNT_INSTANCELOCKTIMES, "SELECT instanceId, releaseTime FROM account_instance_times WHERE accountId = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_BREW_OF_THE_MONTH, "SELECT lastEventId FROM character_brew_of_the_month WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_REP_BREW_OF_THE_MONTH, "REPLACE INTO character_brew_of_the_month (guid, lastEventId) VALUES (?, ?)", ConnectionFlags::Async); // End LoginQueryHolder content - PrepareStatement(CHAR_SEL_CHARACTER_ACTIONS_SPEC, "SELECT button, action, type FROM character_action WHERE guid = ? AND spec = ? ORDER BY button", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_MAILITEMS, "SELECT creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, playedTime, text, item_guid, itemEntry, ii.owner_guid, m.id FROM mail_items mi INNER JOIN mail m ON mi.mail_id = m.id LEFT JOIN item_instance ii ON mi.item_guid = ii.guid WHERE m.receiver = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_AUCTION_ITEMS, "SELECT creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, playedTime, text, itemguid, itemEntry FROM auctionhouse ah JOIN item_instance ii ON ah.itemguid = ii.guid", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_AUCTIONS, "SELECT id, houseid, itemguid, itemEntry, count, itemowner, buyoutprice, time, buyguid, lastbid, startbid, deposit FROM auctionhouse ah INNER JOIN item_instance ii ON ii.guid = ah.itemguid", CONNECTION_SYNCH); - PrepareStatement(CHAR_INS_AUCTION, "INSERT INTO auctionhouse (id, houseid, itemguid, itemowner, buyoutprice, time, buyguid, lastbid, startbid, deposit) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_AUCTION, "DELETE FROM auctionhouse WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_AUCTION_BID, "UPDATE auctionhouse SET buyguid = ?, lastbid = ? WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_MAIL, "INSERT INTO mail(id, messageType, stationery, mailTemplateId, sender, receiver, subject, body, has_items, expire_time, deliver_time, money, cod, checked) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_MAIL_BY_ID, "DELETE FROM mail WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_MAIL_ITEM, "INSERT INTO mail_items(mail_id, item_guid, receiver) VALUES (?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_MAIL_ITEM, "DELETE FROM mail_items WHERE item_guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_INVALID_MAIL_ITEM, "DELETE FROM mail_items WHERE item_guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_EXPIRED_MAIL, "SELECT id, messageType, sender, receiver, has_items, expire_time, stationery, checked, mailTemplateId FROM mail WHERE expire_time < ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_EXPIRED_MAIL_ITEMS, "SELECT item_guid, itemEntry, mail_id FROM mail_items mi INNER JOIN item_instance ii ON ii.guid = mi.item_guid LEFT JOIN mail mm ON mi.mail_id = mm.id WHERE mm.id IS NOT NULL AND mm.expire_time < ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_UPD_MAIL_RETURNED, "UPDATE mail SET sender = ?, receiver = ?, expire_time = ?, deliver_time = ?, cod = 0, checked = ? WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_MAIL_ITEM_RECEIVER, "UPDATE mail_items SET receiver = ? WHERE item_guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_ITEM_OWNER, "UPDATE item_instance SET owner_guid = ? WHERE guid = ?", CONNECTION_ASYNC); - - PrepareStatement(CHAR_SEL_ITEM_REFUNDS, "SELECT player_guid, paidMoney, paidExtendedCost FROM item_refund_instance WHERE item_guid = ? AND player_guid = ? LIMIT 1", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_ITEM_BOP_TRADE, "SELECT allowedPlayers FROM item_soulbound_trade_data WHERE itemGuid = ? LIMIT 1", CONNECTION_SYNCH); - PrepareStatement(CHAR_DEL_ITEM_BOP_TRADE, "DELETE FROM item_soulbound_trade_data WHERE itemGuid = ? LIMIT 1", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_ITEM_BOP_TRADE, "INSERT INTO item_soulbound_trade_data VALUES (?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_REP_INVENTORY_ITEM, "REPLACE INTO character_inventory (guid, bag, slot, item) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_REP_ITEM_INSTANCE, "REPLACE INTO item_instance (itemEntry, owner_guid, creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, playedTime, text, guid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_ITEM_INSTANCE, "UPDATE item_instance SET itemEntry = ?, owner_guid = ?, creatorGuid = ?, giftCreatorGuid = ?, count = ?, duration = ?, charges = ?, flags = ?, enchantments = ?, randomPropertyId = ?, durability = ?, playedTime = ?, text = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_ITEM_INSTANCE_ON_LOAD, "UPDATE item_instance SET duration = ?, flags = ?, durability = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_ITEM_INSTANCE, "DELETE FROM item_instance WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_ITEM_INSTANCE_BY_OWNER, "DELETE FROM item_instance WHERE owner_guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_GIFT_OWNER, "UPDATE character_gifts SET guid = ? WHERE item_guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_GIFT, "DELETE FROM character_gifts WHERE item_guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_GIFT_BY_ITEM, "SELECT entry, flags FROM character_gifts WHERE item_guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_ACCOUNT_BY_NAME, "SELECT account FROM characters WHERE name = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_DEL_ACCOUNT_INSTANCE_LOCK_TIMES, "DELETE FROM account_instance_times WHERE accountId = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_ACCOUNT_INSTANCE_LOCK_TIMES, "INSERT INTO account_instance_times (accountId, instanceId, releaseTime) VALUES (?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_MATCH_MAKER_RATING, "SELECT matchMakerRating, maxMMR FROM character_arena_stats WHERE guid = ? AND slot = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHARACTER_COUNT, "SELECT account, COUNT(guid) FROM characters WHERE account = ? GROUP BY account", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_NAME_BY_GUID, "UPDATE characters SET name = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_DECLINED_NAME, "DELETE FROM character_declinedname WHERE guid = ?", CONNECTION_ASYNC); + PrepareStatement(CHAR_SEL_CHARACTER_ACTIONS_SPEC, "SELECT button, action, type FROM character_action WHERE guid = ? AND spec = ? ORDER BY button", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_MAILITEMS, "SELECT creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, playedTime, text, item_guid, itemEntry, ii.owner_guid, m.id FROM mail_items mi INNER JOIN mail m ON mi.mail_id = m.id LEFT JOIN item_instance ii ON mi.item_guid = ii.guid WHERE m.receiver = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_AUCTION_ITEMS, "SELECT creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, playedTime, text, itemguid, itemEntry FROM auctionhouse ah JOIN item_instance ii ON ah.itemguid = ii.guid", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_AUCTIONS, "SELECT id, houseid, itemguid, itemEntry, count, itemowner, buyoutprice, time, buyguid, lastbid, startbid, deposit FROM auctionhouse ah INNER JOIN item_instance ii ON ii.guid = ah.itemguid", ConnectionFlags::Sync); + PrepareStatement(CHAR_INS_AUCTION, "INSERT INTO auctionhouse (id, houseid, itemguid, itemowner, buyoutprice, time, buyguid, lastbid, startbid, deposit) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_AUCTION, "DELETE FROM auctionhouse WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_AUCTION_BID, "UPDATE auctionhouse SET buyguid = ?, lastbid = ? WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_MAIL, "INSERT INTO mail(id, messageType, stationery, mailTemplateId, sender, receiver, subject, body, has_items, expire_time, deliver_time, money, cod, checked) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_MAIL_BY_ID, "DELETE FROM mail WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_MAIL_ITEM, "INSERT INTO mail_items(mail_id, item_guid, receiver) VALUES (?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_MAIL_ITEM, "DELETE FROM mail_items WHERE item_guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_INVALID_MAIL_ITEM, "DELETE FROM mail_items WHERE item_guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_EXPIRED_MAIL, "SELECT id, messageType, sender, receiver, has_items, expire_time, stationery, checked, mailTemplateId FROM mail WHERE expire_time < ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_EXPIRED_MAIL_ITEMS, "SELECT item_guid, itemEntry, mail_id FROM mail_items mi INNER JOIN item_instance ii ON ii.guid = mi.item_guid LEFT JOIN mail mm ON mi.mail_id = mm.id WHERE mm.id IS NOT NULL AND mm.expire_time < ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_UPD_MAIL_RETURNED, "UPDATE mail SET sender = ?, receiver = ?, expire_time = ?, deliver_time = ?, cod = 0, checked = ? WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_MAIL_ITEM_RECEIVER, "UPDATE mail_items SET receiver = ? WHERE item_guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_ITEM_OWNER, "UPDATE item_instance SET owner_guid = ? WHERE guid = ?", ConnectionFlags::Async); + + PrepareStatement(CHAR_SEL_ITEM_REFUNDS, "SELECT player_guid, paidMoney, paidExtendedCost FROM item_refund_instance WHERE item_guid = ? AND player_guid = ? LIMIT 1", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_ITEM_BOP_TRADE, "SELECT allowedPlayers FROM item_soulbound_trade_data WHERE itemGuid = ? LIMIT 1", ConnectionFlags::Sync); + PrepareStatement(CHAR_DEL_ITEM_BOP_TRADE, "DELETE FROM item_soulbound_trade_data WHERE itemGuid = ? LIMIT 1", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_ITEM_BOP_TRADE, "INSERT INTO item_soulbound_trade_data VALUES (?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_REP_INVENTORY_ITEM, "REPLACE INTO character_inventory (guid, bag, slot, item) VALUES (?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_REP_ITEM_INSTANCE, "REPLACE INTO item_instance (itemEntry, owner_guid, creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, playedTime, text, guid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_ITEM_INSTANCE, "UPDATE item_instance SET itemEntry = ?, owner_guid = ?, creatorGuid = ?, giftCreatorGuid = ?, count = ?, duration = ?, charges = ?, flags = ?, enchantments = ?, randomPropertyId = ?, durability = ?, playedTime = ?, text = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_ITEM_INSTANCE_ON_LOAD, "UPDATE item_instance SET duration = ?, flags = ?, durability = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_ITEM_INSTANCE, "DELETE FROM item_instance WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_ITEM_INSTANCE_BY_OWNER, "DELETE FROM item_instance WHERE owner_guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_GIFT_OWNER, "UPDATE character_gifts SET guid = ? WHERE item_guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_GIFT, "DELETE FROM character_gifts WHERE item_guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_GIFT_BY_ITEM, "SELECT entry, flags FROM character_gifts WHERE item_guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_ACCOUNT_BY_NAME, "SELECT account FROM characters WHERE name = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_DEL_ACCOUNT_INSTANCE_LOCK_TIMES, "DELETE FROM account_instance_times WHERE accountId = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_ACCOUNT_INSTANCE_LOCK_TIMES, "INSERT INTO account_instance_times (accountId, instanceId, releaseTime) VALUES (?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_MATCH_MAKER_RATING, "SELECT matchMakerRating, maxMMR FROM character_arena_stats WHERE guid = ? AND slot = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_CHARACTER_COUNT, "SELECT account, COUNT(guid) FROM characters WHERE account = ? GROUP BY account", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_NAME_BY_GUID, "UPDATE characters SET name = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_DECLINED_NAME, "DELETE FROM character_declinedname WHERE guid = ?", ConnectionFlags::Async); // Guild handling // 0: uint32, 1: string, 2: uint32, 3: string, 4: string, 5: uint64, 6-10: uint32, 11: uint64 - PrepareStatement(CHAR_INS_GUILD, "INSERT INTO guild (guildid, name, leaderguid, info, motd, createdate, EmblemStyle, EmblemColor, BorderStyle, BorderColor, BackgroundColor, BankMoney) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_GUILD, "DELETE FROM guild WHERE guildid = ?", CONNECTION_ASYNC); // 0: uint32 + PrepareStatement(CHAR_INS_GUILD, "INSERT INTO guild (guildid, name, leaderguid, info, motd, createdate, EmblemStyle, EmblemColor, BorderStyle, BorderColor, BackgroundColor, BankMoney) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_GUILD, "DELETE FROM guild WHERE guildid = ?", ConnectionFlags::Async); // 0: uint32 // 0: string, 1: uint32 - PrepareStatement(CHAR_UPD_GUILD_NAME, "UPDATE guild SET name = ? WHERE guildid = ?", CONNECTION_ASYNC); + PrepareStatement(CHAR_UPD_GUILD_NAME, "UPDATE guild SET name = ? WHERE guildid = ?", ConnectionFlags::Async); // 0: uint32, 1: uint32, 2: uint8, 4: string, 5: string - PrepareStatement(CHAR_INS_GUILD_MEMBER, "INSERT INTO guild_member (guildid, guid, `rank`, pnote, offnote) VALUES (?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_GUILD_MEMBER, "DELETE FROM guild_member WHERE guid = ?", CONNECTION_ASYNC); // 0: uint32 - PrepareStatement(CHAR_DEL_GUILD_MEMBERS, "DELETE FROM guild_member WHERE guildid = ?", CONNECTION_ASYNC); // 0: uint32 + PrepareStatement(CHAR_INS_GUILD_MEMBER, "INSERT INTO guild_member (guildid, guid, `rank`, pnote, offnote) VALUES (?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_GUILD_MEMBER, "DELETE FROM guild_member WHERE guid = ?", ConnectionFlags::Async); // 0: uint32 + PrepareStatement(CHAR_DEL_GUILD_MEMBERS, "DELETE FROM guild_member WHERE guildid = ?", ConnectionFlags::Async); // 0: uint32 PrepareStatement(CHAR_SEL_GUILD_MEMBER_EXTENDED, "SELECT g.guildid, g.name, gr.rname, gm.pnote, gm.offnote " "FROM guild g JOIN guild_member gm ON g.guildid = gm.guildid " - "JOIN guild_rank gr ON g.guildid = gr.guildid AND gm.`rank` = gr.rid WHERE gm.guid = ?", CONNECTION_BOTH); + "JOIN guild_rank gr ON g.guildid = gr.guildid AND gm.`rank` = gr.rid WHERE gm.guid = ?", ConnectionFlags::Both); // 0: uint32, 1: uint8, 3: string, 4: uint32, 5: uint32 - PrepareStatement(CHAR_INS_GUILD_RANK, "INSERT INTO guild_rank (guildid, rid, rname, rights, BankMoneyPerDay) VALUES (?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_GUILD_RANKS, "DELETE FROM guild_rank WHERE guildid = ?", CONNECTION_ASYNC); // 0: uint32 - PrepareStatement(CHAR_DEL_GUILD_LOWEST_RANK, "DELETE FROM guild_rank WHERE guildid = ? AND rid >= ?", CONNECTION_ASYNC); // 0: uint32, 1: uint8 - PrepareStatement(CHAR_INS_GUILD_BANK_TAB, "INSERT INTO guild_bank_tab (guildid, TabId) VALUES (?, ?)", CONNECTION_ASYNC); // 0: uint32, 1: uint8 - PrepareStatement(CHAR_DEL_GUILD_BANK_TAB, "DELETE FROM guild_bank_tab WHERE guildid = ? AND TabId = ?", CONNECTION_ASYNC); // 0: uint32, 1: uint8 - PrepareStatement(CHAR_DEL_GUILD_BANK_TABS, "DELETE FROM guild_bank_tab WHERE guildid = ?", CONNECTION_ASYNC); // 0: uint32 + PrepareStatement(CHAR_INS_GUILD_RANK, "INSERT INTO guild_rank (guildid, rid, rname, rights, BankMoneyPerDay) VALUES (?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_GUILD_RANKS, "DELETE FROM guild_rank WHERE guildid = ?", ConnectionFlags::Async); // 0: uint32 + PrepareStatement(CHAR_DEL_GUILD_LOWEST_RANK, "DELETE FROM guild_rank WHERE guildid = ? AND rid >= ?", ConnectionFlags::Async); // 0: uint32, 1: uint8 + PrepareStatement(CHAR_INS_GUILD_BANK_TAB, "INSERT INTO guild_bank_tab (guildid, TabId) VALUES (?, ?)", ConnectionFlags::Async); // 0: uint32, 1: uint8 + PrepareStatement(CHAR_DEL_GUILD_BANK_TAB, "DELETE FROM guild_bank_tab WHERE guildid = ? AND TabId = ?", ConnectionFlags::Async); // 0: uint32, 1: uint8 + PrepareStatement(CHAR_DEL_GUILD_BANK_TABS, "DELETE FROM guild_bank_tab WHERE guildid = ?", ConnectionFlags::Async); // 0: uint32 // 0: uint32, 1: uint8, 2: uint8, 3: uint32, 4: uint32 - PrepareStatement(CHAR_INS_GUILD_BANK_ITEM, "INSERT INTO guild_bank_item (guildid, TabId, SlotId, item_guid) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_GUILD_BANK_ITEM, "DELETE FROM guild_bank_item WHERE guildid = ? AND TabId = ? AND SlotId = ?", CONNECTION_ASYNC); // 0: uint32, 1: uint8, 2: uint8 - PrepareStatement(CHAR_DEL_GUILD_BANK_ITEMS, "DELETE FROM guild_bank_item WHERE guildid = ?", CONNECTION_ASYNC); // 0: uint32 + PrepareStatement(CHAR_INS_GUILD_BANK_ITEM, "INSERT INTO guild_bank_item (guildid, TabId, SlotId, item_guid) VALUES (?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_GUILD_BANK_ITEM, "DELETE FROM guild_bank_item WHERE guildid = ? AND TabId = ? AND SlotId = ?", ConnectionFlags::Async); // 0: uint32, 1: uint8, 2: uint8 + PrepareStatement(CHAR_DEL_GUILD_BANK_ITEMS, "DELETE FROM guild_bank_item WHERE guildid = ?", ConnectionFlags::Async); // 0: uint32 // 0: uint32, 1: uint8, 2: uint8, 3: uint8, 4: uint32 PrepareStatement(CHAR_INS_GUILD_BANK_RIGHT, "INSERT INTO guild_bank_right (guildid, TabId, rid, gbright, SlotPerDay) VALUES (?, ?, ?, ?, ?) " - "ON DUPLICATE KEY UPDATE gbright = VALUES(gbright), SlotPerDay = VALUES(SlotPerDay)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_GUILD_BANK_RIGHTS, "DELETE FROM guild_bank_right WHERE guildid = ?", CONNECTION_ASYNC); // 0: uint32 - PrepareStatement(CHAR_DEL_GUILD_BANK_RIGHTS_FOR_RANK, "DELETE FROM guild_bank_right WHERE guildid = ? AND rid = ?", CONNECTION_ASYNC); // 0: uint32, 1: uint8 + "ON DUPLICATE KEY UPDATE gbright = VALUES(gbright), SlotPerDay = VALUES(SlotPerDay)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_GUILD_BANK_RIGHTS, "DELETE FROM guild_bank_right WHERE guildid = ?", ConnectionFlags::Async); // 0: uint32 + PrepareStatement(CHAR_DEL_GUILD_BANK_RIGHTS_FOR_RANK, "DELETE FROM guild_bank_right WHERE guildid = ? AND rid = ?", ConnectionFlags::Async); // 0: uint32, 1: uint8 // 0-1: uint32, 2-3: uint8, 4-5: uint32, 6: uint16, 7: uint8, 8: uint64 - PrepareStatement(CHAR_INS_GUILD_BANK_EVENTLOG, "INSERT INTO guild_bank_eventlog (guildid, LogGuid, TabId, EventType, PlayerGuid, ItemOrMoney, ItemStackCount, DestTabId, TimeStamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_GUILD_BANK_EVENTLOG, "DELETE FROM guild_bank_eventlog WHERE guildid = ? AND LogGuid = ? AND TabId = ?", CONNECTION_ASYNC); // 0: uint32, 1: uint32, 2: uint8 - PrepareStatement(CHAR_DEL_GUILD_BANK_EVENTLOGS, "DELETE FROM guild_bank_eventlog WHERE guildid = ?", CONNECTION_ASYNC); // 0: uint32 + PrepareStatement(CHAR_INS_GUILD_BANK_EVENTLOG, "INSERT INTO guild_bank_eventlog (guildid, LogGuid, TabId, EventType, PlayerGuid, ItemOrMoney, ItemStackCount, DestTabId, TimeStamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_GUILD_BANK_EVENTLOG, "DELETE FROM guild_bank_eventlog WHERE guildid = ? AND LogGuid = ? AND TabId = ?", ConnectionFlags::Async); // 0: uint32, 1: uint32, 2: uint8 + PrepareStatement(CHAR_DEL_GUILD_BANK_EVENTLOGS, "DELETE FROM guild_bank_eventlog WHERE guildid = ?", ConnectionFlags::Async); // 0: uint32 // 0-1: uint32, 2: uint8, 3-4: uint32, 5: uint8, 6: uint64 - PrepareStatement(CHAR_INS_GUILD_EVENTLOG, "INSERT INTO guild_eventlog (guildid, LogGuid, EventType, PlayerGuid1, PlayerGuid2, NewRank, TimeStamp) VALUES (?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_GUILD_EVENTLOG, "DELETE FROM guild_eventlog WHERE guildid = ? AND LogGuid = ?", CONNECTION_ASYNC); // 0: uint32, 1: uint32 - PrepareStatement(CHAR_DEL_GUILD_EVENTLOGS, "DELETE FROM guild_eventlog WHERE guildid = ?", CONNECTION_ASYNC); // 0: uint32 - PrepareStatement(CHAR_UPD_GUILD_MEMBER_PNOTE, "UPDATE guild_member SET pnote = ? WHERE guid = ?", CONNECTION_ASYNC); // 0: string, 1: uint32 - PrepareStatement(CHAR_UPD_GUILD_MEMBER_OFFNOTE, "UPDATE guild_member SET offnote = ? WHERE guid = ?", CONNECTION_ASYNC); // 0: string, 1: uint32 - PrepareStatement(CHAR_UPD_GUILD_MEMBER_RANK, "UPDATE guild_member SET `rank` = ? WHERE guid = ?", CONNECTION_ASYNC); // 0: uint8, 1: uint32 - PrepareStatement(CHAR_UPD_GUILD_MOTD, "UPDATE guild SET motd = ? WHERE guildid = ?", CONNECTION_ASYNC); // 0: string, 1: uint32 - PrepareStatement(CHAR_UPD_GUILD_INFO, "UPDATE guild SET info = ? WHERE guildid = ?", CONNECTION_ASYNC); // 0: string, 1: uint32 - PrepareStatement(CHAR_UPD_GUILD_LEADER, "UPDATE guild SET leaderguid = ? WHERE guildid = ?", CONNECTION_ASYNC); // 0: uint32, 1: uint32 - PrepareStatement(CHAR_UPD_GUILD_RANK_NAME, "UPDATE guild_rank SET rname = ? WHERE rid = ? AND guildid = ?", CONNECTION_ASYNC); // 0: string, 1: uint8, 2: uint32 - PrepareStatement(CHAR_UPD_GUILD_RANK_RIGHTS, "UPDATE guild_rank SET rights = ? WHERE rid = ? AND guildid = ?", CONNECTION_ASYNC); // 0: uint32, 1: uint8, 2: uint32 + PrepareStatement(CHAR_INS_GUILD_EVENTLOG, "INSERT INTO guild_eventlog (guildid, LogGuid, EventType, PlayerGuid1, PlayerGuid2, NewRank, TimeStamp) VALUES (?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_GUILD_EVENTLOG, "DELETE FROM guild_eventlog WHERE guildid = ? AND LogGuid = ?", ConnectionFlags::Async); // 0: uint32, 1: uint32 + PrepareStatement(CHAR_DEL_GUILD_EVENTLOGS, "DELETE FROM guild_eventlog WHERE guildid = ?", ConnectionFlags::Async); // 0: uint32 + PrepareStatement(CHAR_UPD_GUILD_MEMBER_PNOTE, "UPDATE guild_member SET pnote = ? WHERE guid = ?", ConnectionFlags::Async); // 0: string, 1: uint32 + PrepareStatement(CHAR_UPD_GUILD_MEMBER_OFFNOTE, "UPDATE guild_member SET offnote = ? WHERE guid = ?", ConnectionFlags::Async); // 0: string, 1: uint32 + PrepareStatement(CHAR_UPD_GUILD_MEMBER_RANK, "UPDATE guild_member SET `rank` = ? WHERE guid = ?", ConnectionFlags::Async); // 0: uint8, 1: uint32 + PrepareStatement(CHAR_UPD_GUILD_MOTD, "UPDATE guild SET motd = ? WHERE guildid = ?", ConnectionFlags::Async); // 0: string, 1: uint32 + PrepareStatement(CHAR_UPD_GUILD_INFO, "UPDATE guild SET info = ? WHERE guildid = ?", ConnectionFlags::Async); // 0: string, 1: uint32 + PrepareStatement(CHAR_UPD_GUILD_LEADER, "UPDATE guild SET leaderguid = ? WHERE guildid = ?", ConnectionFlags::Async); // 0: uint32, 1: uint32 + PrepareStatement(CHAR_UPD_GUILD_RANK_NAME, "UPDATE guild_rank SET rname = ? WHERE rid = ? AND guildid = ?", ConnectionFlags::Async); // 0: string, 1: uint8, 2: uint32 + PrepareStatement(CHAR_UPD_GUILD_RANK_RIGHTS, "UPDATE guild_rank SET rights = ? WHERE rid = ? AND guildid = ?", ConnectionFlags::Async); // 0: uint32, 1: uint8, 2: uint32 // 0-5: uint32 - PrepareStatement(CHAR_UPD_GUILD_EMBLEM_INFO, "UPDATE guild SET EmblemStyle = ?, EmblemColor = ?, BorderStyle = ?, BorderColor = ?, BackgroundColor = ? WHERE guildid = ?", CONNECTION_ASYNC); + PrepareStatement(CHAR_UPD_GUILD_EMBLEM_INFO, "UPDATE guild SET EmblemStyle = ?, EmblemColor = ?, BorderStyle = ?, BorderColor = ?, BackgroundColor = ? WHERE guildid = ?", ConnectionFlags::Async); // 0: string, 1: string, 2: uint32, 3: uint8 - PrepareStatement(CHAR_UPD_GUILD_BANK_TAB_INFO, "UPDATE guild_bank_tab SET TabName = ?, TabIcon = ? WHERE guildid = ? AND TabId = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_GUILD_BANK_MONEY, "UPDATE guild SET BankMoney = ? WHERE guildid = ?", CONNECTION_ASYNC); // 0: uint64, 1: uint32 + PrepareStatement(CHAR_UPD_GUILD_BANK_TAB_INFO, "UPDATE guild_bank_tab SET TabName = ?, TabIcon = ? WHERE guildid = ? AND TabId = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_GUILD_BANK_MONEY, "UPDATE guild SET BankMoney = ? WHERE guildid = ?", ConnectionFlags::Async); // 0: uint64, 1: uint32 // 0: uint8, 1: uint32, 2: uint8, 3: uint32 - PrepareStatement(CHAR_UPD_GUILD_BANK_EVENTLOG_TAB, "UPDATE guild_bank_eventlog SET TabId = ? WHERE guildid = ? AND TabId = ? AND LogGuid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_GUILD_RANK_BANK_MONEY, "UPDATE guild_rank SET BankMoneyPerDay = ? WHERE rid = ? AND guildid = ?", CONNECTION_ASYNC); // 0: uint32, 1: uint8, 2: uint32 - PrepareStatement(CHAR_UPD_GUILD_BANK_TAB_TEXT, "UPDATE guild_bank_tab SET TabText = ? WHERE guildid = ? AND TabId = ?", CONNECTION_ASYNC); // 0: string, 1: uint32, 2: uint8 + PrepareStatement(CHAR_UPD_GUILD_BANK_EVENTLOG_TAB, "UPDATE guild_bank_eventlog SET TabId = ? WHERE guildid = ? AND TabId = ? AND LogGuid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_GUILD_RANK_BANK_MONEY, "UPDATE guild_rank SET BankMoneyPerDay = ? WHERE rid = ? AND guildid = ?", ConnectionFlags::Async); // 0: uint32, 1: uint8, 2: uint32 + PrepareStatement(CHAR_UPD_GUILD_BANK_TAB_TEXT, "UPDATE guild_bank_tab SET TabText = ? WHERE guildid = ? AND TabId = ?", ConnectionFlags::Async); // 0: string, 1: uint32, 2: uint8 PrepareStatement(CHAR_INS_GUILD_MEMBER_WITHDRAW, "INSERT INTO guild_member_withdraw (guid, tab0, tab1, tab2, tab3, tab4, tab5, money) VALUES (?, ?, ?, ?, ?, ?, ?, ?) " - "ON DUPLICATE KEY UPDATE tab0 = VALUES (tab0), tab1 = VALUES (tab1), tab2 = VALUES (tab2), tab3 = VALUES (tab3), tab4 = VALUES (tab4), tab5 = VALUES (tab5)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_GUILD_MEMBER_WITHDRAW, "TRUNCATE guild_member_withdraw", CONNECTION_ASYNC); + "ON DUPLICATE KEY UPDATE tab0 = VALUES (tab0), tab1 = VALUES (tab1), tab2 = VALUES (tab2), tab3 = VALUES (tab3), tab4 = VALUES (tab4), tab5 = VALUES (tab5)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_GUILD_MEMBER_WITHDRAW, "TRUNCATE guild_member_withdraw", ConnectionFlags::Async); // 0: uint32, 1: uint32, 2: uint32 - PrepareStatement(CHAR_SEL_CHAR_DATA_FOR_GUILD, "SELECT name, level, class, gender, zone, account FROM characters WHERE guid = ?", CONNECTION_SYNCH); + PrepareStatement(CHAR_SEL_CHAR_DATA_FOR_GUILD, "SELECT name, level, class, gender, zone, account FROM characters WHERE guid = ?", ConnectionFlags::Sync); // Chat channel handling - PrepareStatement(CHAR_INS_CHANNEL, "INSERT INTO channels(channelId, name, team, announce, lastUsed) VALUES (?, ?, ?, ?, UNIX_TIMESTAMP())", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHANNEL, "UPDATE channels SET announce = ?, password = ?, lastUsed = UNIX_TIMESTAMP() WHERE channelId = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHANNEL, "DELETE FROM channels WHERE name = ? AND team = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHANNEL_USAGE, "UPDATE channels SET lastUsed = UNIX_TIMESTAMP() WHERE channelId = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_OLD_CHANNELS, "DELETE FROM channels WHERE lastUsed + ? < UNIX_TIMESTAMP()", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_OLD_CHANNELS_BANS, "DELETE cb.* FROM channels_bans cb LEFT JOIN channels cn ON cb.channelId=cn.channelId WHERE cn.channelId IS NULL OR cb.banTime <= UNIX_TIMESTAMP()", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_CHANNEL_BAN, "REPLACE INTO channels_bans VALUES (?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHANNEL_BAN, "DELETE FROM channels_bans WHERE channelId = ? AND playerGUID = ?", CONNECTION_ASYNC); + PrepareStatement(CHAR_INS_CHANNEL, "INSERT INTO channels(channelId, name, team, announce, lastUsed) VALUES (?, ?, ?, ?, UNIX_TIMESTAMP())", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHANNEL, "UPDATE channels SET announce = ?, password = ?, lastUsed = UNIX_TIMESTAMP() WHERE channelId = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHANNEL, "DELETE FROM channels WHERE name = ? AND team = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHANNEL_USAGE, "UPDATE channels SET lastUsed = UNIX_TIMESTAMP() WHERE channelId = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_OLD_CHANNELS, "DELETE FROM channels WHERE lastUsed + ? < UNIX_TIMESTAMP()", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_OLD_CHANNELS_BANS, "DELETE cb.* FROM channels_bans cb LEFT JOIN channels cn ON cb.channelId=cn.channelId WHERE cn.channelId IS NULL OR cb.banTime <= UNIX_TIMESTAMP()", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_CHANNEL_BAN, "REPLACE INTO channels_bans VALUES (?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHANNEL_BAN, "DELETE FROM channels_bans WHERE channelId = ? AND playerGUID = ?", ConnectionFlags::Async); // Equipmentsets PrepareStatement(CHAR_UPD_EQUIP_SET, "UPDATE character_equipmentsets SET name=?, iconname=?, ignore_mask=?, item0=?, item1=?, item2=?, item3=?, " "item4=?, item5=?, item6=?, item7=?, item8=?, item9=?, item10=?, item11=?, item12=?, item13=?, item14=?, item15=?, item16=?, " - "item17=?, item18=? WHERE guid=? AND setguid=? AND setindex=?", CONNECTION_ASYNC); + "item17=?, item18=? WHERE guid=? AND setguid=? AND setindex=?", ConnectionFlags::Async); PrepareStatement(CHAR_INS_EQUIP_SET, "INSERT INTO character_equipmentsets (guid, setguid, setindex, name, iconname, ignore_mask, item0, item1, item2, item3, " "item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_EQUIP_SET, "DELETE FROM character_equipmentsets WHERE setguid=?", CONNECTION_ASYNC); + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_EQUIP_SET, "DELETE FROM character_equipmentsets WHERE setguid=?", ConnectionFlags::Async); // Auras PrepareStatement(CHAR_INS_AURA, "INSERT INTO character_aura (guid, casterGuid, itemGuid, spell, effectMask, recalculateMask, stackcount, amount0, amount1, amount2, base_amount0, base_amount1, base_amount2, maxDuration, remainTime, remainCharges) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); // Account data - PrepareStatement(CHAR_SEL_ACCOUNT_DATA, "SELECT type, time, data FROM account_data WHERE accountId = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_REP_ACCOUNT_DATA, "REPLACE INTO account_data (accountId, type, time, data) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_ACCOUNT_DATA, "DELETE FROM account_data WHERE accountId = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_PLAYER_ACCOUNT_DATA, "SELECT type, time, data FROM character_account_data WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_REP_PLAYER_ACCOUNT_DATA, "REPLACE INTO character_account_data(guid, type, time, data) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_PLAYER_ACCOUNT_DATA, "DELETE FROM character_account_data WHERE guid = ?", CONNECTION_ASYNC); + PrepareStatement(CHAR_SEL_ACCOUNT_DATA, "SELECT type, time, data FROM account_data WHERE accountId = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_REP_ACCOUNT_DATA, "REPLACE INTO account_data (accountId, type, time, data) VALUES (?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_ACCOUNT_DATA, "DELETE FROM account_data WHERE accountId = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_PLAYER_ACCOUNT_DATA, "SELECT type, time, data FROM character_account_data WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_REP_PLAYER_ACCOUNT_DATA, "REPLACE INTO character_account_data(guid, type, time, data) VALUES (?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_PLAYER_ACCOUNT_DATA, "DELETE FROM character_account_data WHERE guid = ?", ConnectionFlags::Async); // Tutorials - PrepareStatement(CHAR_SEL_TUTORIALS, "SELECT tut0, tut1, tut2, tut3, tut4, tut5, tut6, tut7 FROM account_tutorial WHERE accountId = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_HAS_TUTORIALS, "SELECT 1 FROM account_tutorial WHERE accountId = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_INS_TUTORIALS, "INSERT INTO account_tutorial(tut0, tut1, tut2, tut3, tut4, tut5, tut6, tut7, accountId) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_TUTORIALS, "UPDATE account_tutorial SET tut0 = ?, tut1 = ?, tut2 = ?, tut3 = ?, tut4 = ?, tut5 = ?, tut6 = ?, tut7 = ? WHERE accountId = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_TUTORIALS, "DELETE FROM account_tutorial WHERE accountId = ?", CONNECTION_ASYNC); + PrepareStatement(CHAR_SEL_TUTORIALS, "SELECT tut0, tut1, tut2, tut3, tut4, tut5, tut6, tut7 FROM account_tutorial WHERE accountId = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_HAS_TUTORIALS, "SELECT 1 FROM account_tutorial WHERE accountId = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_INS_TUTORIALS, "INSERT INTO account_tutorial(tut0, tut1, tut2, tut3, tut4, tut5, tut6, tut7, accountId) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_TUTORIALS, "UPDATE account_tutorial SET tut0 = ?, tut1 = ?, tut2 = ?, tut3 = ?, tut4 = ?, tut5 = ?, tut6 = ?, tut7 = ? WHERE accountId = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_TUTORIALS, "DELETE FROM account_tutorial WHERE accountId = ?", ConnectionFlags::Async); // Instance saves - PrepareStatement(CHAR_INS_INSTANCE_SAVE, "INSERT INTO instance (id, map, resettime, difficulty, completedEncounters, data) VALUES (?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_INSTANCE_SAVE_DATA, "UPDATE instance SET data=? WHERE id=?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_INSTANCE_SAVE_ENCOUNTERMASK, "UPDATE instance SET completedEncounters=? WHERE id=?", CONNECTION_ASYNC); + PrepareStatement(CHAR_INS_INSTANCE_SAVE, "INSERT INTO instance (id, map, resettime, difficulty, completedEncounters, data) VALUES (?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_INSTANCE_SAVE_DATA, "UPDATE instance SET data=? WHERE id=?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_INSTANCE_SAVE_ENCOUNTERMASK, "UPDATE instance SET completedEncounters=? WHERE id=?", ConnectionFlags::Async); // Game event saves - PrepareStatement(CHAR_DEL_GAME_EVENT_SAVE, "DELETE FROM game_event_save WHERE eventEntry = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_GAME_EVENT_SAVE, "INSERT INTO game_event_save (eventEntry, state, next_start) VALUES (?, ?, ?)", CONNECTION_ASYNC); + PrepareStatement(CHAR_DEL_GAME_EVENT_SAVE, "DELETE FROM game_event_save WHERE eventEntry = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_GAME_EVENT_SAVE, "INSERT INTO game_event_save (eventEntry, state, next_start) VALUES (?, ?, ?)", ConnectionFlags::Async); // Game event condition saves - PrepareStatement(CHAR_DEL_ALL_GAME_EVENT_CONDITION_SAVE, "DELETE FROM game_event_condition_save WHERE eventEntry = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_GAME_EVENT_CONDITION_SAVE, "DELETE FROM game_event_condition_save WHERE eventEntry = ? AND condition_id = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_GAME_EVENT_CONDITION_SAVE, "INSERT INTO game_event_condition_save (eventEntry, condition_id, done) VALUES (?, ?, ?)", CONNECTION_ASYNC); + PrepareStatement(CHAR_DEL_ALL_GAME_EVENT_CONDITION_SAVE, "DELETE FROM game_event_condition_save WHERE eventEntry = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_GAME_EVENT_CONDITION_SAVE, "DELETE FROM game_event_condition_save WHERE eventEntry = ? AND condition_id = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_GAME_EVENT_CONDITION_SAVE, "INSERT INTO game_event_condition_save (eventEntry, condition_id, done) VALUES (?, ?, ?)", ConnectionFlags::Async); // Petitions - PrepareStatement(CHAR_DEL_ALL_PETITION_SIGNATURES, "DELETE FROM petition_sign WHERE playerguid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_PETITION_SIGNATURE, "DELETE FROM petition_sign WHERE playerguid = ? AND type = ?", CONNECTION_ASYNC); + PrepareStatement(CHAR_DEL_ALL_PETITION_SIGNATURES, "DELETE FROM petition_sign WHERE playerguid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_PETITION_SIGNATURE, "DELETE FROM petition_sign WHERE playerguid = ? AND type = ?", ConnectionFlags::Async); // Arena teams - PrepareStatement(CHAR_INS_ARENA_TEAM, "INSERT INTO arena_team (arenaTeamId, name, captainGuid, type, rating, backgroundColor, emblemStyle, emblemColor, borderStyle, borderColor) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_ARENA_TEAM_MEMBER, "INSERT INTO arena_team_member (arenaTeamId, guid) VALUES (?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_ARENA_TEAM, "DELETE FROM arena_team WHERE arenaTeamId = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_ARENA_TEAM_MEMBERS, "DELETE FROM arena_team_member WHERE arenaTeamId = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_ARENA_TEAM_CAPTAIN, "UPDATE arena_team SET captainGuid = ? WHERE arenaTeamId = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_ARENA_TEAM_MEMBER, "DELETE FROM arena_team_member WHERE arenaTeamId = ? AND guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_ARENA_TEAM_STATS, "UPDATE arena_team SET rating = ?, weekGames = ?, weekWins = ?, seasonGames = ?, seasonWins = ?, `rank` = ? WHERE arenaTeamId = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_ARENA_TEAM_MEMBER, "UPDATE arena_team_member SET personalRating = ?, weekGames = ?, weekWins = ?, seasonGames = ?, seasonWins = ? WHERE arenaTeamId = ? AND guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_REP_CHARACTER_ARENA_STATS, "REPLACE INTO character_arena_stats (guid, slot, matchMakerRating, maxMMR) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_PLAYER_ARENA_TEAMS, "SELECT arena_team_member.arenaTeamId FROM arena_team_member JOIN arena_team ON arena_team_member.arenaTeamId = arena_team.arenaTeamId WHERE guid = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_UPD_ARENA_TEAM_NAME, "UPDATE arena_team SET name = ? WHERE arenaTeamId = ?", CONNECTION_ASYNC); + PrepareStatement(CHAR_INS_ARENA_TEAM, "INSERT INTO arena_team (arenaTeamId, name, captainGuid, type, rating, backgroundColor, emblemStyle, emblemColor, borderStyle, borderColor) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_ARENA_TEAM_MEMBER, "INSERT INTO arena_team_member (arenaTeamId, guid) VALUES (?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_ARENA_TEAM, "DELETE FROM arena_team WHERE arenaTeamId = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_ARENA_TEAM_MEMBERS, "DELETE FROM arena_team_member WHERE arenaTeamId = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_ARENA_TEAM_CAPTAIN, "UPDATE arena_team SET captainGuid = ? WHERE arenaTeamId = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_ARENA_TEAM_MEMBER, "DELETE FROM arena_team_member WHERE arenaTeamId = ? AND guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_ARENA_TEAM_STATS, "UPDATE arena_team SET rating = ?, weekGames = ?, weekWins = ?, seasonGames = ?, seasonWins = ?, `rank` = ? WHERE arenaTeamId = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_ARENA_TEAM_MEMBER, "UPDATE arena_team_member SET personalRating = ?, weekGames = ?, weekWins = ?, seasonGames = ?, seasonWins = ? WHERE arenaTeamId = ? AND guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_REP_CHARACTER_ARENA_STATS, "REPLACE INTO character_arena_stats (guid, slot, matchMakerRating, maxMMR) VALUES (?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_PLAYER_ARENA_TEAMS, "SELECT arena_team_member.arenaTeamId FROM arena_team_member JOIN arena_team ON arena_team_member.arenaTeamId = arena_team.arenaTeamId WHERE guid = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_UPD_ARENA_TEAM_NAME, "UPDATE arena_team SET name = ? WHERE arenaTeamId = ?", ConnectionFlags::Async); // Character battleground data - PrepareStatement(CHAR_INS_PLAYER_ENTRY_POINT, "INSERT INTO character_entry_point (guid, joinX, joinY, joinZ, joinO, joinMapId, taxiPath0, taxiPath1, mountSpell) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_PLAYER_ENTRY_POINT, "DELETE FROM character_entry_point WHERE guid = ?", CONNECTION_ASYNC); + PrepareStatement(CHAR_INS_PLAYER_ENTRY_POINT, "INSERT INTO character_entry_point (guid, joinX, joinY, joinZ, joinO, joinMapId, taxiPath0, taxiPath1, mountSpell) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_PLAYER_ENTRY_POINT, "DELETE FROM character_entry_point WHERE guid = ?", ConnectionFlags::Async); // Character homebind - PrepareStatement(CHAR_INS_PLAYER_HOMEBIND, "INSERT INTO character_homebind (guid, mapId, zoneId, posX, posY, posZ, posO) VALUES (?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_PLAYER_HOMEBIND, "UPDATE character_homebind SET mapId = ?, zoneId = ?, posX = ?, posY = ?, posZ = ?, posO = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_PLAYER_HOMEBIND, "DELETE FROM character_homebind WHERE guid = ?", CONNECTION_ASYNC); + PrepareStatement(CHAR_INS_PLAYER_HOMEBIND, "INSERT INTO character_homebind (guid, mapId, zoneId, posX, posY, posZ, posO) VALUES (?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_PLAYER_HOMEBIND, "UPDATE character_homebind SET mapId = ?, zoneId = ?, posX = ?, posY = ?, posZ = ?, posO = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_PLAYER_HOMEBIND, "DELETE FROM character_homebind WHERE guid = ?", ConnectionFlags::Async); // Corpse - PrepareStatement(CHAR_SEL_CORPSES, "SELECT posX, posY, posZ, orientation, mapId, displayId, itemCache, bytes1, bytes2, guildId, flags, dynFlags, time, corpseType, instanceId, phaseMask, guid FROM corpse WHERE mapId = ? AND instanceId = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_INS_CORPSE, "INSERT INTO corpse (guid, posX, posY, posZ, orientation, mapId, displayId, itemCache, bytes1, bytes2, guildId, flags, dynFlags, time, corpseType, instanceId, phaseMask) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CORPSE, "DELETE FROM corpse WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CORPSES_FROM_MAP, "DELETE FROM corpse WHERE mapId = ? AND instanceId = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CORPSE_LOCATION, "SELECT mapId, posX, posY, posZ, orientation FROM corpse WHERE guid = ?", CONNECTION_ASYNC); + PrepareStatement(CHAR_SEL_CORPSES, "SELECT posX, posY, posZ, orientation, mapId, displayId, itemCache, bytes1, bytes2, guildId, flags, dynFlags, time, corpseType, instanceId, phaseMask, guid FROM corpse WHERE mapId = ? AND instanceId = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_INS_CORPSE, "INSERT INTO corpse (guid, posX, posY, posZ, orientation, mapId, displayId, itemCache, bytes1, bytes2, guildId, flags, dynFlags, time, corpseType, instanceId, phaseMask) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CORPSE, "DELETE FROM corpse WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CORPSES_FROM_MAP, "DELETE FROM corpse WHERE mapId = ? AND instanceId = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CORPSE_LOCATION, "SELECT mapId, posX, posY, posZ, orientation FROM corpse WHERE guid = ?", ConnectionFlags::Async); // Creature respawn - PrepareStatement(CHAR_SEL_CREATURE_RESPAWNS, "SELECT guid, respawnTime FROM creature_respawn WHERE mapId = ? AND instanceId = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_REP_CREATURE_RESPAWN, "REPLACE INTO creature_respawn (guid, respawnTime, mapId, instanceId) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CREATURE_RESPAWN, "DELETE FROM creature_respawn WHERE guid = ? AND mapId = ? AND instanceId = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CREATURE_RESPAWN_BY_INSTANCE, "DELETE FROM creature_respawn WHERE mapId = ? AND instanceId = ?", CONNECTION_ASYNC); + PrepareStatement(CHAR_SEL_CREATURE_RESPAWNS, "SELECT guid, respawnTime FROM creature_respawn WHERE mapId = ? AND instanceId = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_REP_CREATURE_RESPAWN, "REPLACE INTO creature_respawn (guid, respawnTime, mapId, instanceId) VALUES (?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CREATURE_RESPAWN, "DELETE FROM creature_respawn WHERE guid = ? AND mapId = ? AND instanceId = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CREATURE_RESPAWN_BY_INSTANCE, "DELETE FROM creature_respawn WHERE mapId = ? AND instanceId = ?", ConnectionFlags::Async); // Gameobject respawn - PrepareStatement(CHAR_SEL_GO_RESPAWNS, "SELECT guid, respawnTime FROM gameobject_respawn WHERE mapId = ? AND instanceId = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_REP_GO_RESPAWN, "REPLACE INTO gameobject_respawn (guid, respawnTime, mapId, instanceId) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_GO_RESPAWN, "DELETE FROM gameobject_respawn WHERE guid = ? AND mapId = ? AND instanceId = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_GO_RESPAWN_BY_INSTANCE, "DELETE FROM gameobject_respawn WHERE mapId = ? AND instanceId = ?", CONNECTION_ASYNC); + PrepareStatement(CHAR_SEL_GO_RESPAWNS, "SELECT guid, respawnTime FROM gameobject_respawn WHERE mapId = ? AND instanceId = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_REP_GO_RESPAWN, "REPLACE INTO gameobject_respawn (guid, respawnTime, mapId, instanceId) VALUES (?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_GO_RESPAWN, "DELETE FROM gameobject_respawn WHERE guid = ? AND mapId = ? AND instanceId = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_GO_RESPAWN_BY_INSTANCE, "DELETE FROM gameobject_respawn WHERE mapId = ? AND instanceId = ?", ConnectionFlags::Async); // GM Tickets - PrepareStatement(CHAR_SEL_GM_TICKETS, "SELECT id, type, playerGuid, name, description, createTime, mapId, posX, posY, posZ, lastModifiedTime, closedBy, assignedTo, comment, response, completed, escalated, viewed, needMoreHelp, resolvedBy FROM gm_ticket", CONNECTION_SYNCH); - PrepareStatement(CHAR_REP_GM_TICKET, "REPLACE INTO gm_ticket (id, type, playerGuid, name, description, createTime, mapId, posX, posY, posZ, lastModifiedTime, closedBy, assignedTo, comment, response, completed, escalated, viewed, needMoreHelp, resolvedBy) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_GM_TICKET, "DELETE FROM gm_ticket WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_PLAYER_GM_TICKETS, "DELETE FROM gm_ticket WHERE playerGuid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_PLAYER_GM_TICKETS_ON_CHAR_DELETION, "UPDATE gm_ticket SET type = 2 WHERE playerGuid = ?", CONNECTION_ASYNC); + PrepareStatement(CHAR_SEL_GM_TICKETS, "SELECT id, type, playerGuid, name, description, createTime, mapId, posX, posY, posZ, lastModifiedTime, closedBy, assignedTo, comment, response, completed, escalated, viewed, needMoreHelp, resolvedBy FROM gm_ticket", ConnectionFlags::Sync); + PrepareStatement(CHAR_REP_GM_TICKET, "REPLACE INTO gm_ticket (id, type, playerGuid, name, description, createTime, mapId, posX, posY, posZ, lastModifiedTime, closedBy, assignedTo, comment, response, completed, escalated, viewed, needMoreHelp, resolvedBy) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_GM_TICKET, "DELETE FROM gm_ticket WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_PLAYER_GM_TICKETS, "DELETE FROM gm_ticket WHERE playerGuid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_PLAYER_GM_TICKETS_ON_CHAR_DELETION, "UPDATE gm_ticket SET type = 2 WHERE playerGuid = ?", ConnectionFlags::Async); // GM Survey/subsurvey/lag report - PrepareStatement(CHAR_INS_GM_SURVEY, "INSERT INTO gm_survey (guid, surveyId, mainSurvey, comment, createTime) VALUES (?, ?, ?, ?, UNIX_TIMESTAMP(NOW()))", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_GM_SUBSURVEY, "INSERT INTO gm_subsurvey (surveyId, questionId, answer, answerComment) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_LAG_REPORT, "INSERT INTO lag_reports (guid, lagType, mapId, posX, posY, posZ, latency, createTime) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); + PrepareStatement(CHAR_INS_GM_SURVEY, "INSERT INTO gm_survey (guid, surveyId, mainSurvey, comment, createTime) VALUES (?, ?, ?, ?, UNIX_TIMESTAMP(NOW()))", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_GM_SUBSURVEY, "INSERT INTO gm_subsurvey (surveyId, questionId, answer, answerComment) VALUES (?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_LAG_REPORT, "INSERT INTO lag_reports (guid, lagType, mapId, posX, posY, posZ, latency, createTime) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); // LFG Data - PrepareStatement(CHAR_REP_LFG_DATA, "REPLACE INTO lfg_data (guid, dungeon, state) VALUES (?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_LFG_DATA, "DELETE FROM lfg_data WHERE guid = ?", CONNECTION_ASYNC); + PrepareStatement(CHAR_REP_LFG_DATA, "REPLACE INTO lfg_data (guid, dungeon, state) VALUES (?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_LFG_DATA, "DELETE FROM lfg_data WHERE guid = ?", ConnectionFlags::Async); // Player saving PrepareStatement(CHAR_INS_CHARACTER, "INSERT INTO characters (guid, account, name, race, class, gender, level, xp, money, skin, face, hairStyle, hairColor, facialStyle, bankSlots, restState, playerFlags, " @@ -339,286 +339,274 @@ void CharacterDatabaseConnection::DoPrepareStatements() "todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk, health, power1, power2, power3, " "power4, power5, power6, power7, latency, talentGroupsCount, activeTalentGroup, exploredZones, equipmentCache, " "ammoId, knownTitles, actionBars, grantableLevels, innTriggerId, extraBonusTalentCount) VALUES " - "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?)", CONNECTION_ASYNC); + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ?)", ConnectionFlags::Async); PrepareStatement(CHAR_UPD_CHARACTER, "UPDATE characters SET name=?,race=?,class=?,gender=?,level=?,xp=?,money=?,skin=?,face=?,hairStyle=?,hairColor=?,facialStyle=?,bankSlots=?,restState=?,playerFlags=?," "map=?,instance_id=?,instance_mode_mask=?,position_x=?,position_y=?,position_z=?,orientation=?,trans_x=?,trans_y=?,trans_z=?,trans_o=?,transguid=?,taximask=?,cinematic=?,totaltime=?,leveltime=?,rest_bonus=?," "logout_time=?,is_logout_resting=?,resettalents_cost=?,resettalents_time=?,extra_flags=?,stable_slots=?,at_login=?,zone=?,death_expire_time=?,taxi_path=?," "arenaPoints=?,totalHonorPoints=?,todayHonorPoints=?,yesterdayHonorPoints=?,totalKills=?,todayKills=?,yesterdayKills=?,chosenTitle=?,knownCurrencies=?," "watchedFaction=?,drunk=?,health=?,power1=?,power2=?,power3=?,power4=?,power5=?,power6=?,power7=?,latency=?,talentGroupsCount=?,activeTalentGroup=?,exploredZones=?," - "equipmentCache=?,ammoId=?,knownTitles=?,actionBars=?,grantableLevels=?,innTriggerId=?,extraBonusTalentCount=?,online=? WHERE guid=?", CONNECTION_ASYNC); - - PrepareStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG, "UPDATE characters SET at_login = at_login | ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_REM_AT_LOGIN_FLAG, "UPDATE characters set at_login = at_login & ~ ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_ALL_AT_LOGIN_FLAGS, "UPDATE characters SET at_login = at_login | ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_BUG_REPORT, "INSERT INTO bugreport (type, content) VALUES(?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_PETITION_NAME, "UPDATE petition SET name = ? WHERE petitionguid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_PETITION_SIGNATURE, "INSERT INTO petition_sign (ownerguid, petitionguid, playerguid, player_account) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_ACCOUNT_ONLINE, "UPDATE characters SET online = 0 WHERE account = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_GROUP, "INSERT INTO `groups` (guid, leaderGuid, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, groupType, difficulty, raidDifficulty, masterLooterGuid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_REP_GROUP_MEMBER, "REPLACE INTO group_member (guid, memberGuid, memberFlags, subgroup, roles) VALUES(?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_GROUP_MEMBER, "DELETE FROM group_member WHERE memberGuid = ? AND guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_GROUP_LEADER, "UPDATE `groups` SET leaderGuid = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_GROUP_TYPE, "UPDATE `groups` SET groupType = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_GROUP_MEMBER_SUBGROUP, "UPDATE group_member SET subgroup = ? WHERE memberGuid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_GROUP_MEMBER_FLAG, "UPDATE group_member SET memberFlags = ? WHERE memberGuid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_GROUP_DIFFICULTY, "UPDATE `groups` SET difficulty = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_GROUP_RAID_DIFFICULTY, "UPDATE `groups` SET raidDifficulty = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_ALL_GM_TICKETS, "TRUNCATE TABLE gm_ticket", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_INVALID_SPELL_TALENTS, "DELETE FROM character_talent WHERE spell = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_INVALID_SPELL_SPELLS, "DELETE FROM character_spell WHERE spell = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_DELETE_INFO, "UPDATE characters SET deleteInfos_Name = name, deleteInfos_Account = account, deleteDate = UNIX_TIMESTAMP(), name = '', account = 0 WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UDP_RESTORE_DELETE_INFO, "UPDATE characters SET name = ?, account = ?, deleteDate = NULL, deleteInfos_Name = NULL, deleteInfos_Account = NULL WHERE deleteDate IS NOT NULL AND guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_ZONE, "UPDATE characters SET zone = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_LEVEL, "UPDATE characters SET level = ?, xp = 0 WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_XP_ACCUMULATIVE, "UPDATE characters SET xp = xp + ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_INVALID_ACHIEV_PROGRESS_CRITERIA, "DELETE FROM character_achievement_progress WHERE criteria = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_INVALID_ACHIEVMENT, "DELETE FROM character_achievement WHERE achievement = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_ADDON, "INSERT INTO addons (name, crc) VALUES (?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_INVALID_PET_SPELL, "DELETE FROM pet_spell WHERE spell = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_GLOBAL_INSTANCE_RESETTIME, "UPDATE instance_reset SET resettime = ? WHERE mapid = ? AND difficulty = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHAR_ONLINE, "UPDATE characters SET online = 1 WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHAR_NAME_AT_LOGIN, "UPDATE characters set name = ?, at_login = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_WORLDSTATE, "UPDATE worldstates SET value = ? WHERE entry = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_WORLDSTATE, "INSERT INTO worldstates (entry, value) VALUES (?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE, "DELETE FROM character_instance WHERE instance = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_NOT_EXTENDED, "DELETE FROM character_instance WHERE instance = ? AND extended = 0", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHAR_INSTANCE_SET_NOT_EXTENDED, "UPDATE character_instance SET extended = 0 WHERE instance = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID, "DELETE FROM character_instance WHERE guid = ? AND instance = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHAR_INSTANCE, "UPDATE character_instance SET instance = ?, permanent = ?, extended = 0 WHERE guid = ? AND instance = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHAR_INSTANCE_EXTENDED, "UPDATE character_instance SET extended = ? WHERE guid = ? AND instance = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_CHAR_INSTANCE, "INSERT INTO character_instance (guid, instance, permanent, extended) VALUES (?, ?, ?, 0)", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_ARENA_LOG_FIGHT, "INSERT INTO log_arena_fights VALUES (?, NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_ARENA_LOG_MEMBERSTATS, "INSERT INTO log_arena_memberstats VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_GENDER_AND_APPEARANCE, "UPDATE characters SET gender = ?, skin = ?, face = ?, hairStyle = ?, hairColor = ?, facialStyle = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHARACTER_SKILL, "DELETE FROM character_skills WHERE guid = ? AND skill = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_ADD_CHARACTER_SOCIAL_FLAGS, "UPDATE character_social SET flags = flags | ? WHERE guid = ? AND friend = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_REM_CHARACTER_SOCIAL_FLAGS, "UPDATE character_social SET flags = flags & ~ ? WHERE guid = ? AND friend = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_CHARACTER_SOCIAL, "REPLACE INTO character_social (guid, friend, flags) VALUES (?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHARACTER_SOCIAL, "DELETE FROM character_social WHERE guid = ? AND friend = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHARACTER_SOCIAL_NOTE, "UPDATE character_social SET note = ? WHERE guid = ? AND friend = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHARACTER_POSITION, "UPDATE characters SET position_x = ?, position_y = ?, position_z = ?, orientation = ?, map = ?, zone = ?, trans_x = 0, trans_y = 0, trans_z = 0, transguid = 0, taxi_path = '', cinematic = 1 WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_AURA_FROZEN, "SELECT characters.name FROM characters LEFT JOIN character_aura ON (characters.guid = character_aura.guid) WHERE character_aura.spell = 9454", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHARACTER_ONLINE, "SELECT name, account, map, zone FROM characters WHERE online > 0", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHAR_DEL_INFO_BY_GUID, "SELECT guid, deleteInfos_Name, deleteInfos_Account, deleteDate FROM characters WHERE deleteDate IS NOT NULL AND guid = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHAR_DEL_INFO_BY_NAME, "SELECT guid, deleteInfos_Name, deleteInfos_Account, deleteDate FROM characters WHERE deleteDate IS NOT NULL AND deleteInfos_Name LIKE CONCAT('%%', ?, '%%')", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHAR_DEL_INFO, "SELECT guid, deleteInfos_Name, deleteInfos_Account, deleteDate FROM characters WHERE deleteDate IS NOT NULL", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHARS_BY_ACCOUNT_ID, "SELECT guid FROM characters WHERE account = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHAR_PINFO, "SELECT totaltime, level, money, account, race, class, map, zone, gender, health, playerFlags FROM characters WHERE guid = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_PINFO_BANS, "SELECT unbandate, bandate = unbandate, bannedby, banreason FROM character_banned WHERE guid = ? AND active ORDER BY bandate ASC LIMIT 1", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_PINFO_MAILS, "SELECT SUM(CASE WHEN (checked & 1) THEN 1 ELSE 0 END) AS 'readmail', COUNT(*) AS 'totalmail' FROM mail WHERE `receiver` = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_PINFO_XP, "SELECT a.xp, b.guid FROM characters a LEFT JOIN guild_member b ON a.guid = b.guid WHERE a.guid = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHAR_HOMEBIND, "SELECT mapId, zoneId, posX, posY, posZ, posO FROM character_homebind WHERE guid = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHAR_GUID_NAME_BY_ACC, "SELECT guid, name FROM characters WHERE account = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_POOL_QUEST_SAVE, "SELECT quest_id FROM pool_quest_save WHERE pool_id = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHARACTER_AT_LOGIN, "SELECT at_login FROM characters WHERE guid = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHAR_CLASS_LVL_AT_LOGIN, "SELECT class, level, at_login, knownTitles FROM characters WHERE guid = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHAR_CUSTOMIZE_INFO, "SELECT name, race, class, gender, at_login FROM characters WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHAR_RACE_OR_FACTION_CHANGE_INFOS, "SELECT at_login, knownTitles, money FROM characters WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHAR_AT_LOGIN_TITLES_MONEY, "SELECT at_login, knownTitles, money FROM characters WHERE guid = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHAR_COD_ITEM_MAIL, "SELECT id, messageType, mailTemplateId, sender, subject, body, money, has_items FROM mail WHERE receiver = ? AND has_items <> 0 AND cod <> 0", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHAR_SOCIAL, "SELECT DISTINCT guid FROM character_social WHERE friend = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHAR_OLD_CHARS, "SELECT guid, deleteInfos_Account FROM characters WHERE deleteDate IS NOT NULL AND deleteDate < ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_ARENA_TEAM_ID_BY_PLAYER_GUID, "SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid = ? AND type = ? LIMIT 1", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_MAIL, "SELECT id, messageType, sender, receiver, subject, body, expire_time, deliver_time, money, cod, checked, stationery, mailTemplateId FROM mail WHERE receiver = ? AND deliver_time <= ? ORDER BY id DESC", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_NEXT_MAIL_DELIVERYTIME, "SELECT MIN(deliver_time) FROM mail WHERE receiver = ? AND deliver_time > ? AND (checked & 1) = 0 LIMIT 1", CONNECTION_SYNCH); - PrepareStatement(CHAR_DEL_CHAR_AURA_FROZEN, "DELETE FROM character_aura WHERE spell = 9454 AND guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHAR_INVENTORY_COUNT_ITEM, "SELECT COUNT(itemEntry) FROM character_inventory ci INNER JOIN item_instance ii ON ii.guid = ci.item WHERE itemEntry = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_MAIL_COUNT_ITEM, "SELECT COUNT(itemEntry) FROM mail_items mi INNER JOIN item_instance ii ON ii.guid = mi.item_guid WHERE itemEntry = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_AUCTIONHOUSE_COUNT_ITEM, "SELECT COUNT(itemEntry) FROM auctionhouse ah INNER JOIN item_instance ii ON ii.guid = ah.itemguid WHERE itemEntry = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_GUILD_BANK_COUNT_ITEM, "SELECT COUNT(itemEntry) FROM guild_bank_item gbi INNER JOIN item_instance ii ON ii.guid = gbi.item_guid WHERE itemEntry = ?", CONNECTION_SYNCH); + "equipmentCache=?,ammoId=?,knownTitles=?,actionBars=?,grantableLevels=?,innTriggerId=?,extraBonusTalentCount=?,online=? WHERE guid=?", ConnectionFlags::Async); + + PrepareStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG, "UPDATE characters SET at_login = at_login | ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_REM_AT_LOGIN_FLAG, "UPDATE characters set at_login = at_login & ~ ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_ALL_AT_LOGIN_FLAGS, "UPDATE characters SET at_login = at_login | ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_BUG_REPORT, "INSERT INTO bugreport (type, content) VALUES(?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_PETITION_NAME, "UPDATE petition SET name = ? WHERE petitionguid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_PETITION_SIGNATURE, "INSERT INTO petition_sign (ownerguid, petitionguid, playerguid, player_account) VALUES (?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_ACCOUNT_ONLINE, "UPDATE characters SET online = 0 WHERE account = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_GROUP, "INSERT INTO `groups` (guid, leaderGuid, lootMethod, looterGuid, lootThreshold, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, groupType, difficulty, raidDifficulty, masterLooterGuid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_REP_GROUP_MEMBER, "REPLACE INTO group_member (guid, memberGuid, memberFlags, subgroup, roles) VALUES(?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_GROUP_MEMBER, "DELETE FROM group_member WHERE memberGuid = ? AND guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_GROUP_LEADER, "UPDATE `groups` SET leaderGuid = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_GROUP_TYPE, "UPDATE `groups` SET groupType = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_GROUP_MEMBER_SUBGROUP, "UPDATE group_member SET subgroup = ? WHERE memberGuid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_GROUP_MEMBER_FLAG, "UPDATE group_member SET memberFlags = ? WHERE memberGuid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_GROUP_DIFFICULTY, "UPDATE `groups` SET difficulty = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_GROUP_RAID_DIFFICULTY, "UPDATE `groups` SET raidDifficulty = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_ALL_GM_TICKETS, "TRUNCATE TABLE gm_ticket", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_INVALID_SPELL_TALENTS, "DELETE FROM character_talent WHERE spell = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_INVALID_SPELL_SPELLS, "DELETE FROM character_spell WHERE spell = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_DELETE_INFO, "UPDATE characters SET deleteInfos_Name = name, deleteInfos_Account = account, deleteDate = UNIX_TIMESTAMP(), name = '', account = 0 WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UDP_RESTORE_DELETE_INFO, "UPDATE characters SET name = ?, account = ?, deleteDate = NULL, deleteInfos_Name = NULL, deleteInfos_Account = NULL WHERE deleteDate IS NOT NULL AND guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_ZONE, "UPDATE characters SET zone = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_LEVEL, "UPDATE characters SET level = ?, xp = 0 WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_XP_ACCUMULATIVE, "UPDATE characters SET xp = xp + ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_INVALID_ACHIEV_PROGRESS_CRITERIA, "DELETE FROM character_achievement_progress WHERE criteria = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_INVALID_ACHIEVMENT, "DELETE FROM character_achievement WHERE achievement = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_ADDON, "INSERT INTO addons (name, crc) VALUES (?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_INVALID_PET_SPELL, "DELETE FROM pet_spell WHERE spell = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_GLOBAL_INSTANCE_RESETTIME, "UPDATE instance_reset SET resettime = ? WHERE mapid = ? AND difficulty = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHAR_ONLINE, "UPDATE characters SET online = 1 WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHAR_NAME_AT_LOGIN, "UPDATE characters set name = ?, at_login = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_WORLDSTATE, "UPDATE worldstates SET value = ? WHERE entry = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_WORLDSTATE, "INSERT INTO worldstates (entry, value) VALUES (?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE, "DELETE FROM character_instance WHERE instance = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_NOT_EXTENDED, "DELETE FROM character_instance WHERE instance = ? AND extended = 0", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHAR_INSTANCE_SET_NOT_EXTENDED, "UPDATE character_instance SET extended = 0 WHERE instance = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID, "DELETE FROM character_instance WHERE guid = ? AND instance = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHAR_INSTANCE, "UPDATE character_instance SET instance = ?, permanent = ?, extended = 0 WHERE guid = ? AND instance = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHAR_INSTANCE_EXTENDED, "UPDATE character_instance SET extended = ? WHERE guid = ? AND instance = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_CHAR_INSTANCE, "INSERT INTO character_instance (guid, instance, permanent, extended) VALUES (?, ?, ?, 0)", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_ARENA_LOG_FIGHT, "INSERT INTO log_arena_fights VALUES (?, NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_ARENA_LOG_MEMBERSTATS, "INSERT INTO log_arena_memberstats VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_GENDER_AND_APPEARANCE, "UPDATE characters SET gender = ?, skin = ?, face = ?, hairStyle = ?, hairColor = ?, facialStyle = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHARACTER_SKILL, "DELETE FROM character_skills WHERE guid = ? AND skill = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_ADD_CHARACTER_SOCIAL_FLAGS, "UPDATE character_social SET flags = flags | ? WHERE guid = ? AND friend = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_REM_CHARACTER_SOCIAL_FLAGS, "UPDATE character_social SET flags = flags & ~ ? WHERE guid = ? AND friend = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_CHARACTER_SOCIAL, "REPLACE INTO character_social (guid, friend, flags) VALUES (?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHARACTER_SOCIAL, "DELETE FROM character_social WHERE guid = ? AND friend = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHARACTER_SOCIAL_NOTE, "UPDATE character_social SET note = ? WHERE guid = ? AND friend = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHARACTER_POSITION, "UPDATE characters SET position_x = ?, position_y = ?, position_z = ?, orientation = ?, map = ?, zone = ?, trans_x = 0, trans_y = 0, trans_z = 0, transguid = 0, taxi_path = '', cinematic = 1 WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_AURA_FROZEN, "SELECT characters.name FROM characters LEFT JOIN character_aura ON (characters.guid = character_aura.guid) WHERE character_aura.spell = 9454", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHARACTER_ONLINE, "SELECT name, account, map, zone FROM characters WHERE online > 0", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_CHAR_DEL_INFO_BY_GUID, "SELECT guid, deleteInfos_Name, deleteInfos_Account, deleteDate FROM characters WHERE deleteDate IS NOT NULL AND guid = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_CHAR_DEL_INFO_BY_NAME, "SELECT guid, deleteInfos_Name, deleteInfos_Account, deleteDate FROM characters WHERE deleteDate IS NOT NULL AND deleteInfos_Name LIKE CONCAT('%%', ?, '%%')", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_CHAR_DEL_INFO, "SELECT guid, deleteInfos_Name, deleteInfos_Account, deleteDate FROM characters WHERE deleteDate IS NOT NULL", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_CHARS_BY_ACCOUNT_ID, "SELECT guid FROM characters WHERE account = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_CHAR_PINFO, "SELECT totaltime, level, money, account, race, class, map, zone, gender, health, playerFlags FROM characters WHERE guid = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_PINFO_BANS, "SELECT unbandate, bandate = unbandate, bannedby, banreason FROM character_banned WHERE guid = ? AND active ORDER BY bandate ASC LIMIT 1", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_PINFO_MAILS, "SELECT SUM(CASE WHEN (checked & 1) THEN 1 ELSE 0 END) AS 'readmail', COUNT(*) AS 'totalmail' FROM mail WHERE `receiver` = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_PINFO_XP, "SELECT a.xp, b.guid FROM characters a LEFT JOIN guild_member b ON a.guid = b.guid WHERE a.guid = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_CHAR_HOMEBIND, "SELECT mapId, zoneId, posX, posY, posZ, posO FROM character_homebind WHERE guid = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_CHAR_GUID_NAME_BY_ACC, "SELECT guid, name FROM characters WHERE account = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_POOL_QUEST_SAVE, "SELECT quest_id FROM pool_quest_save WHERE pool_id = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_CHARACTER_AT_LOGIN, "SELECT at_login FROM characters WHERE guid = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_CHAR_CLASS_LVL_AT_LOGIN, "SELECT class, level, at_login, knownTitles FROM characters WHERE guid = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_CHAR_CUSTOMIZE_INFO, "SELECT name, race, class, gender, at_login FROM characters WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHAR_RACE_OR_FACTION_CHANGE_INFOS, "SELECT at_login, knownTitles, money FROM characters WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHAR_AT_LOGIN_TITLES_MONEY, "SELECT at_login, knownTitles, money FROM characters WHERE guid = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_CHAR_COD_ITEM_MAIL, "SELECT id, messageType, mailTemplateId, sender, subject, body, money, has_items FROM mail WHERE receiver = ? AND has_items <> 0 AND cod <> 0", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_CHAR_SOCIAL, "SELECT DISTINCT guid FROM character_social WHERE friend = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_CHAR_OLD_CHARS, "SELECT guid, deleteInfos_Account FROM characters WHERE deleteDate IS NOT NULL AND deleteDate < ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_ARENA_TEAM_ID_BY_PLAYER_GUID, "SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid = ? AND type = ? LIMIT 1", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_MAIL, "SELECT id, messageType, sender, receiver, subject, body, expire_time, deliver_time, money, cod, checked, stationery, mailTemplateId FROM mail WHERE receiver = ? AND deliver_time <= ? ORDER BY id DESC", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_NEXT_MAIL_DELIVERYTIME, "SELECT MIN(deliver_time) FROM mail WHERE receiver = ? AND deliver_time > ? AND (checked & 1) = 0 LIMIT 1", ConnectionFlags::Sync); + PrepareStatement(CHAR_DEL_CHAR_AURA_FROZEN, "DELETE FROM character_aura WHERE spell = 9454 AND guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHAR_INVENTORY_COUNT_ITEM, "SELECT COUNT(itemEntry) FROM character_inventory ci INNER JOIN item_instance ii ON ii.guid = ci.item WHERE itemEntry = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_MAIL_COUNT_ITEM, "SELECT COUNT(itemEntry) FROM mail_items mi INNER JOIN item_instance ii ON ii.guid = mi.item_guid WHERE itemEntry = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_AUCTIONHOUSE_COUNT_ITEM, "SELECT COUNT(itemEntry) FROM auctionhouse ah INNER JOIN item_instance ii ON ii.guid = ah.itemguid WHERE itemEntry = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_GUILD_BANK_COUNT_ITEM, "SELECT COUNT(itemEntry) FROM guild_bank_item gbi INNER JOIN item_instance ii ON ii.guid = gbi.item_guid WHERE itemEntry = ?", ConnectionFlags::Sync); PrepareStatement(CHAR_SEL_CHAR_INVENTORY_ITEM_BY_ENTRY, "SELECT ci.item, cb.slot AS bag, ci.slot, ci.guid, c.account, c.name FROM characters c " "INNER JOIN character_inventory ci ON ci.guid = c.guid " "INNER JOIN item_instance ii ON ii.guid = ci.item " - "LEFT JOIN character_inventory cb ON cb.item = ci.bag WHERE ii.itemEntry = ? LIMIT ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_CHAR_INVENTORY_ITEM_BY_ENTRY_AND_OWNER, "SELECT ci.item FROM character_inventory ci INNER JOIN item_instance ii ON ii.guid = ci.item WHERE ii.itemEntry = ? AND ii.owner_guid = ?", CONNECTION_SYNCH); + "LEFT JOIN character_inventory cb ON cb.item = ci.bag WHERE ii.itemEntry = ? LIMIT ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_CHAR_INVENTORY_ITEM_BY_ENTRY_AND_OWNER, "SELECT ci.item FROM character_inventory ci INNER JOIN item_instance ii ON ii.guid = ci.item WHERE ii.itemEntry = ? AND ii.owner_guid = ?", ConnectionFlags::Sync); PrepareStatement(CHAR_SEL_MAIL_ITEMS_BY_ENTRY, "SELECT mi.item_guid, m.sender, m.receiver, cs.account, cs.name, cr.account, cr.name " "FROM mail m INNER JOIN mail_items mi ON mi.mail_id = m.id INNER JOIN item_instance ii ON ii.guid = mi.item_guid " - "INNER JOIN characters cs ON cs.guid = m.sender INNER JOIN characters cr ON cr.guid = m.receiver WHERE ii.itemEntry = ? LIMIT ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_AUCTIONHOUSE_ITEM_BY_ENTRY, "SELECT ah.itemguid, ah.itemowner, c.account, c.name FROM auctionhouse ah INNER JOIN characters c ON c.guid = ah.itemowner INNER JOIN item_instance ii ON ii.guid = ah.itemguid WHERE ii.itemEntry = ? LIMIT ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_GUILD_BANK_ITEM_BY_ENTRY, "SELECT gi.item_guid, gi.guildid, g.name FROM guild_bank_item gi INNER JOIN guild g ON g.guildid = gi.guildid INNER JOIN item_instance ii ON ii.guid = gi.item_guid WHERE ii.itemEntry = ? LIMIT ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_DEL_CHAR_ACHIEVEMENT, "DELETE FROM character_achievement WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_ACHIEVEMENT_PROGRESS, "DELETE FROM character_achievement_progress WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_CHAR_ACHIEVEMENT, "INSERT INTO character_achievement (guid, achievement, date) VALUES (?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_ACHIEVEMENT_PROGRESS_BY_CRITERIA, "DELETE FROM character_achievement_progress WHERE guid = ? AND criteria = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_CHAR_ACHIEVEMENT_PROGRESS, "INSERT INTO character_achievement_progress (guid, criteria, counter, date) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_REPUTATION_BY_FACTION, "DELETE FROM character_reputation WHERE guid = ? AND faction = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_CHAR_REPUTATION_BY_FACTION, "INSERT INTO character_reputation (guid, faction, standing, flags) VALUES (?, ?, ? , ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHAR_ARENA_POINTS, "UPDATE characters SET arenaPoints = (arenaPoints + ?) WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_ITEM_REFUND_INSTANCE, "DELETE FROM item_refund_instance WHERE item_guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_ITEM_REFUND_INSTANCE, "INSERT INTO item_refund_instance (item_guid, player_guid, paidMoney, paidExtendedCost) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_GROUP, "DELETE FROM `groups` WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_GROUP_MEMBER_ALL, "DELETE FROM group_member WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_CHAR_GIFT, "INSERT INTO character_gifts (guid, item_guid, entry, flags) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_INSTANCE_BY_INSTANCE, "DELETE FROM instance WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_MAIL_ITEM_BY_ID, "DELETE FROM mail_items WHERE mail_id = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_PETITION, "INSERT INTO petition (ownerguid, petitionguid, name, type) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_PETITION_BY_GUID, "DELETE FROM petition WHERE petitionguid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_PETITION_SIGNATURE_BY_GUID, "DELETE FROM petition_sign WHERE petitionguid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_DECLINED_NAME, "DELETE FROM character_declinedname WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_CHAR_DECLINED_NAME, "INSERT INTO character_declinedname (guid, genitive, dative, accusative, instrumental, prepositional) VALUES (?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHAR_RACE, "UPDATE characters SET race = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_SKILL_LANGUAGES, "DELETE FROM character_skills WHERE skill IN (98, 113, 759, 111, 313, 109, 115, 315, 673, 137) AND guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_CHAR_SKILL_LANGUAGE, "INSERT INTO `character_skills` (guid, skill, value, max) VALUES (?, ?, 300, 300)", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHAR_TAXI_PATH, "UPDATE characters SET taxi_path = '' WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHAR_TAXIMASK, "UPDATE characters SET taximask = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_QUESTSTATUS, "DELETE FROM character_queststatus WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_SOCIAL_BY_GUID, "DELETE FROM character_social WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_SOCIAL_BY_FRIEND, "DELETE FROM character_social WHERE friend = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_ACHIEVEMENT_BY_ACHIEVEMENT, "DELETE FROM character_achievement WHERE achievement = ? AND guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHAR_ACHIEVEMENT, "UPDATE character_achievement SET achievement = ? WHERE achievement = ? AND guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHAR_INVENTORY_FACTION_CHANGE, "UPDATE item_instance ii, character_inventory ci SET ii.itemEntry = ? WHERE ii.itemEntry = ? AND ci.guid = ? AND ci.item = ii.guid", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_SPELL_BY_SPELL, "DELETE FROM character_spell WHERE guid = ? AND spell = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHAR_SPELL_FACTION_CHANGE, "UPDATE character_spell SET spell = ? WHERE spell = ? AND guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHAR_REP_BY_FACTION, "SELECT standing FROM character_reputation WHERE faction = ? AND guid = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_DEL_CHAR_REP_BY_FACTION, "DELETE FROM character_reputation WHERE faction = ? AND guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHAR_REP_FACTION_CHANGE, "UPDATE character_reputation SET faction = ?, standing = ? WHERE faction = ? AND guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHAR_TITLES_FACTION_CHANGE, "UPDATE characters SET knownTitles = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_RES_CHAR_TITLES_FACTION_CHANGE, "UPDATE characters SET chosenTitle = 0 WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_SPELL_COOLDOWN, "DELETE FROM character_spell_cooldown WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHARACTER, "DELETE FROM characters WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_ACTION, "DELETE FROM character_action WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_AURA, "DELETE FROM character_aura WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_GIFT, "DELETE FROM character_gifts WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_INSTANCE, "DELETE FROM character_instance WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_INVENTORY, "DELETE FROM character_inventory WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_QUESTSTATUS_REWARDED, "DELETE FROM character_queststatus_rewarded WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_REPUTATION, "DELETE FROM character_reputation WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_SPELL, "DELETE FROM character_spell WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_MAIL, "DELETE FROM mail WHERE receiver = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_MAIL_ITEMS, "DELETE FROM mail_items WHERE receiver = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_ACHIEVEMENTS, "DELETE FROM character_achievement WHERE guid = ? AND achievement NOT BETWEEN '456' AND '467' AND achievement NOT BETWEEN '1400' AND '1427' AND achievement NOT IN(1463, 3117, 3259)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_EQUIPMENTSETS, "DELETE FROM character_equipmentsets WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_GUILD_EVENTLOG_BY_PLAYER, "DELETE FROM guild_eventlog WHERE PlayerGuid1 = ? OR PlayerGuid2 = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_GUILD_BANK_EVENTLOG_BY_PLAYER, "DELETE FROM guild_bank_eventlog WHERE PlayerGuid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_GLYPHS, "DELETE FROM character_glyphs WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_TALENT, "DELETE FROM character_talent WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_SKILLS, "DELETE FROM character_skills WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UDP_CHAR_HONOR_POINTS, "UPDATE characters SET totalHonorPoints = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UDP_CHAR_HONOR_POINTS_ACCUMULATIVE, "UPDATE characters SET totalHonorPoints = totalHonorPoints + ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UDP_CHAR_ARENA_POINTS, "UPDATE characters SET arenaPoints = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UDP_CHAR_ARENA_POINTS_ACCUMULATIVE, "UPDATE characters SET arenaPoints = arenaPoints + ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UDP_CHAR_MONEY, "UPDATE characters SET money = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UDP_CHAR_MONEY_ACCUMULATIVE, "UPDATE characters SET money = money + ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHAR_REMOVE_GHOST, "UPDATE characters SET playerFlags = (playerFlags & (~16)) WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_CHAR_ACTION, "INSERT INTO character_action (guid, spec, button, action, type) VALUES (?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHAR_ACTION, "UPDATE character_action SET action = ?, type = ? WHERE guid = ? AND button = ? AND spec = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_ACTION_BY_BUTTON_SPEC, "DELETE FROM character_action WHERE guid = ? AND button = ? AND spec = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_INVENTORY_BY_ITEM, "DELETE FROM character_inventory WHERE item = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_INVENTORY_BY_BAG_SLOT, "DELETE FROM character_inventory WHERE bag = ? AND slot = ? AND guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_MAIL, "UPDATE mail SET has_items = ?, expire_time = ?, deliver_time = ?, money = ?, cod = ?, checked = ? WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_REP_CHAR_QUESTSTATUS, "REPLACE INTO character_queststatus (guid, quest, status, explored, timer, mobcount1, mobcount2, mobcount3, mobcount4, itemcount1, itemcount2, itemcount3, itemcount4, itemcount5, itemcount6, playercount) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_QUESTSTATUS_BY_QUEST, "DELETE FROM character_queststatus WHERE guid = ? AND quest = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_CHAR_QUESTSTATUS_REWARDED, "INSERT IGNORE INTO character_queststatus_rewarded (guid, quest, active) VALUES (?, ?, 1)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_QUESTSTATUS_REWARDED_BY_QUEST, "DELETE FROM character_queststatus_rewarded WHERE guid = ? AND quest = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHAR_QUESTSTATUS_REWARDED_FACTION_CHANGE, "UPDATE character_queststatus_rewarded SET quest = ? WHERE quest = ? AND guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHAR_QUESTSTATUS_REWARDED_ACTIVE, "UPDATE character_queststatus_rewarded SET active = 1 WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHAR_QUESTSTATUS_REWARDED_ACTIVE_BY_QUEST, "UPDATE character_queststatus_rewarded SET active = 0 WHERE quest = ? AND guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_SKILL_BY_SKILL, "DELETE FROM character_skills WHERE guid = ? AND skill = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_CHAR_SKILLS, "INSERT INTO character_skills (guid, skill, value, max) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_UDP_CHAR_SKILLS, "UPDATE character_skills SET value = ?, max = ? WHERE guid = ? AND skill = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_CHAR_SPELL, "INSERT INTO character_spell (guid, spell, specMask) VALUES (?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_STATS, "DELETE FROM character_stats WHERE guid = ?", CONNECTION_ASYNC); + "INNER JOIN characters cs ON cs.guid = m.sender INNER JOIN characters cr ON cr.guid = m.receiver WHERE ii.itemEntry = ? LIMIT ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_AUCTIONHOUSE_ITEM_BY_ENTRY, "SELECT ah.itemguid, ah.itemowner, c.account, c.name FROM auctionhouse ah INNER JOIN characters c ON c.guid = ah.itemowner INNER JOIN item_instance ii ON ii.guid = ah.itemguid WHERE ii.itemEntry = ? LIMIT ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_GUILD_BANK_ITEM_BY_ENTRY, "SELECT gi.item_guid, gi.guildid, g.name FROM guild_bank_item gi INNER JOIN guild g ON g.guildid = gi.guildid INNER JOIN item_instance ii ON ii.guid = gi.item_guid WHERE ii.itemEntry = ? LIMIT ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_DEL_CHAR_ACHIEVEMENT, "DELETE FROM character_achievement WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_ACHIEVEMENT_PROGRESS, "DELETE FROM character_achievement_progress WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_CHAR_ACHIEVEMENT, "INSERT INTO character_achievement (guid, achievement, date) VALUES (?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_ACHIEVEMENT_PROGRESS_BY_CRITERIA, "DELETE FROM character_achievement_progress WHERE guid = ? AND criteria = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_CHAR_ACHIEVEMENT_PROGRESS, "INSERT INTO character_achievement_progress (guid, criteria, counter, date) VALUES (?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_REPUTATION_BY_FACTION, "DELETE FROM character_reputation WHERE guid = ? AND faction = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_CHAR_REPUTATION_BY_FACTION, "INSERT INTO character_reputation (guid, faction, standing, flags) VALUES (?, ?, ? , ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHAR_ARENA_POINTS, "UPDATE characters SET arenaPoints = (arenaPoints + ?) WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_ITEM_REFUND_INSTANCE, "DELETE FROM item_refund_instance WHERE item_guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_ITEM_REFUND_INSTANCE, "INSERT INTO item_refund_instance (item_guid, player_guid, paidMoney, paidExtendedCost) VALUES (?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_GROUP, "DELETE FROM `groups` WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_GROUP_MEMBER_ALL, "DELETE FROM group_member WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_CHAR_GIFT, "INSERT INTO character_gifts (guid, item_guid, entry, flags) VALUES (?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_INSTANCE_BY_INSTANCE, "DELETE FROM instance WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_MAIL_ITEM_BY_ID, "DELETE FROM mail_items WHERE mail_id = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_PETITION, "INSERT INTO petition (ownerguid, petitionguid, name, type) VALUES (?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_PETITION_BY_GUID, "DELETE FROM petition WHERE petitionguid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_PETITION_SIGNATURE_BY_GUID, "DELETE FROM petition_sign WHERE petitionguid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_DECLINED_NAME, "DELETE FROM character_declinedname WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_CHAR_DECLINED_NAME, "INSERT INTO character_declinedname (guid, genitive, dative, accusative, instrumental, prepositional) VALUES (?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHAR_RACE, "UPDATE characters SET race = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_SKILL_LANGUAGES, "DELETE FROM character_skills WHERE skill IN (98, 113, 759, 111, 313, 109, 115, 315, 673, 137) AND guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_CHAR_SKILL_LANGUAGE, "INSERT INTO `character_skills` (guid, skill, value, max) VALUES (?, ?, 300, 300)", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHAR_TAXI_PATH, "UPDATE characters SET taxi_path = '' WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHAR_TAXIMASK, "UPDATE characters SET taximask = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_QUESTSTATUS, "DELETE FROM character_queststatus WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_SOCIAL_BY_GUID, "DELETE FROM character_social WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_SOCIAL_BY_FRIEND, "DELETE FROM character_social WHERE friend = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_ACHIEVEMENT_BY_ACHIEVEMENT, "DELETE FROM character_achievement WHERE achievement = ? AND guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHAR_ACHIEVEMENT, "UPDATE character_achievement SET achievement = ? WHERE achievement = ? AND guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHAR_INVENTORY_FACTION_CHANGE, "UPDATE item_instance ii, character_inventory ci SET ii.itemEntry = ? WHERE ii.itemEntry = ? AND ci.guid = ? AND ci.item = ii.guid", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_SPELL_BY_SPELL, "DELETE FROM character_spell WHERE guid = ? AND spell = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHAR_SPELL_FACTION_CHANGE, "UPDATE character_spell SET spell = ? WHERE spell = ? AND guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHAR_REP_BY_FACTION, "SELECT standing FROM character_reputation WHERE faction = ? AND guid = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_DEL_CHAR_REP_BY_FACTION, "DELETE FROM character_reputation WHERE faction = ? AND guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHAR_REP_FACTION_CHANGE, "UPDATE character_reputation SET faction = ?, standing = ? WHERE faction = ? AND guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHAR_TITLES_FACTION_CHANGE, "UPDATE characters SET knownTitles = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_RES_CHAR_TITLES_FACTION_CHANGE, "UPDATE characters SET chosenTitle = 0 WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_SPELL_COOLDOWN, "DELETE FROM character_spell_cooldown WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHARACTER, "DELETE FROM characters WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_ACTION, "DELETE FROM character_action WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_AURA, "DELETE FROM character_aura WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_GIFT, "DELETE FROM character_gifts WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_INSTANCE, "DELETE FROM character_instance WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_INVENTORY, "DELETE FROM character_inventory WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_QUESTSTATUS_REWARDED, "DELETE FROM character_queststatus_rewarded WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_REPUTATION, "DELETE FROM character_reputation WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_SPELL, "DELETE FROM character_spell WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_MAIL, "DELETE FROM mail WHERE receiver = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_MAIL_ITEMS, "DELETE FROM mail_items WHERE receiver = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_ACHIEVEMENTS, "DELETE FROM character_achievement WHERE guid = ? AND achievement NOT BETWEEN '456' AND '467' AND achievement NOT BETWEEN '1400' AND '1427' AND achievement NOT IN(1463, 3117, 3259)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_EQUIPMENTSETS, "DELETE FROM character_equipmentsets WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_GUILD_EVENTLOG_BY_PLAYER, "DELETE FROM guild_eventlog WHERE PlayerGuid1 = ? OR PlayerGuid2 = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_GUILD_BANK_EVENTLOG_BY_PLAYER, "DELETE FROM guild_bank_eventlog WHERE PlayerGuid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_GLYPHS, "DELETE FROM character_glyphs WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_TALENT, "DELETE FROM character_talent WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_SKILLS, "DELETE FROM character_skills WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UDP_CHAR_HONOR_POINTS, "UPDATE characters SET totalHonorPoints = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UDP_CHAR_HONOR_POINTS_ACCUMULATIVE, "UPDATE characters SET totalHonorPoints = totalHonorPoints + ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UDP_CHAR_ARENA_POINTS, "UPDATE characters SET arenaPoints = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UDP_CHAR_ARENA_POINTS_ACCUMULATIVE, "UPDATE characters SET arenaPoints = arenaPoints + ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UDP_CHAR_MONEY, "UPDATE characters SET money = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UDP_CHAR_MONEY_ACCUMULATIVE, "UPDATE characters SET money = money + ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHAR_REMOVE_GHOST, "UPDATE characters SET playerFlags = (playerFlags & (~16)) WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_CHAR_ACTION, "INSERT INTO character_action (guid, spec, button, action, type) VALUES (?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHAR_ACTION, "UPDATE character_action SET action = ?, type = ? WHERE guid = ? AND button = ? AND spec = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_ACTION_BY_BUTTON_SPEC, "DELETE FROM character_action WHERE guid = ? AND button = ? AND spec = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_INVENTORY_BY_ITEM, "DELETE FROM character_inventory WHERE item = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_INVENTORY_BY_BAG_SLOT, "DELETE FROM character_inventory WHERE bag = ? AND slot = ? AND guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_MAIL, "UPDATE mail SET has_items = ?, expire_time = ?, deliver_time = ?, money = ?, cod = ?, checked = ? WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_REP_CHAR_QUESTSTATUS, "REPLACE INTO character_queststatus (guid, quest, status, explored, timer, mobcount1, mobcount2, mobcount3, mobcount4, itemcount1, itemcount2, itemcount3, itemcount4, itemcount5, itemcount6, playercount) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_QUESTSTATUS_BY_QUEST, "DELETE FROM character_queststatus WHERE guid = ? AND quest = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_CHAR_QUESTSTATUS_REWARDED, "INSERT IGNORE INTO character_queststatus_rewarded (guid, quest, active) VALUES (?, ?, 1)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_QUESTSTATUS_REWARDED_BY_QUEST, "DELETE FROM character_queststatus_rewarded WHERE guid = ? AND quest = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHAR_QUESTSTATUS_REWARDED_FACTION_CHANGE, "UPDATE character_queststatus_rewarded SET quest = ? WHERE quest = ? AND guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHAR_QUESTSTATUS_REWARDED_ACTIVE, "UPDATE character_queststatus_rewarded SET active = 1 WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHAR_QUESTSTATUS_REWARDED_ACTIVE_BY_QUEST, "UPDATE character_queststatus_rewarded SET active = 0 WHERE quest = ? AND guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_SKILL_BY_SKILL, "DELETE FROM character_skills WHERE guid = ? AND skill = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_CHAR_SKILLS, "INSERT INTO character_skills (guid, skill, value, max) VALUES (?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_UDP_CHAR_SKILLS, "UPDATE character_skills SET value = ?, max = ? WHERE guid = ? AND skill = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_CHAR_SPELL, "INSERT INTO character_spell (guid, spell, specMask) VALUES (?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_STATS, "DELETE FROM character_stats WHERE guid = ?", ConnectionFlags::Async); PrepareStatement(CHAR_INS_CHAR_STATS, "INSERT INTO character_stats (guid, maxhealth, maxpower1, maxpower2, maxpower3, maxpower4, maxpower5, maxpower6, maxpower7, strength, agility, stamina, intellect, spirit, " "armor, resHoly, resFire, resNature, resFrost, resShadow, resArcane, blockPct, dodgePct, parryPct, critPct, rangedCritPct, spellCritPct, attackPower, rangedAttackPower, " - "spellPower, resilience) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHAR_STATS, "SELECT maxhealth, strength, agility, stamina, intellect, spirit, armor, attackPower, spellPower, resilience FROM character_stats WHERE guid = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_DEL_PETITION_BY_OWNER, "DELETE FROM petition WHERE ownerguid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_PETITION_SIGNATURE_BY_OWNER, "DELETE FROM petition_sign WHERE ownerguid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_PETITION_BY_OWNER_AND_TYPE, "DELETE FROM petition WHERE ownerguid = ? AND type = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_PETITION_SIGNATURE_BY_OWNER_AND_TYPE, "DELETE FROM petition_sign WHERE ownerguid = ? AND type = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_CHAR_GLYPHS, "INSERT INTO character_glyphs VALUES(?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_TALENT_BY_SPELL, "DELETE FROM character_talent WHERE guid = ? AND spell = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_CHAR_TALENT, "INSERT INTO character_talent (guid, spell, specMask) VALUES (?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_ACTION_EXCEPT_SPEC, "DELETE FROM character_action WHERE spec<>? AND guid = ?", CONNECTION_ASYNC); + "spellPower, resilience) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHAR_STATS, "SELECT maxhealth, strength, agility, stamina, intellect, spirit, armor, attackPower, spellPower, resilience FROM character_stats WHERE guid = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_DEL_PETITION_BY_OWNER, "DELETE FROM petition WHERE ownerguid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_PETITION_SIGNATURE_BY_OWNER, "DELETE FROM petition_sign WHERE ownerguid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_PETITION_BY_OWNER_AND_TYPE, "DELETE FROM petition WHERE ownerguid = ? AND type = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_PETITION_SIGNATURE_BY_OWNER_AND_TYPE, "DELETE FROM petition_sign WHERE ownerguid = ? AND type = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_CHAR_GLYPHS, "INSERT INTO character_glyphs VALUES(?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_TALENT_BY_SPELL, "DELETE FROM character_talent WHERE guid = ? AND spell = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_CHAR_TALENT, "INSERT INTO character_talent (guid, spell, specMask) VALUES (?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_ACTION_EXCEPT_SPEC, "DELETE FROM character_action WHERE spec<>? AND guid = ?", ConnectionFlags::Async); // Items that hold loot or money - PrepareStatement(CHAR_SEL_ITEMCONTAINER_ITEMS, "SELECT containerGUID, itemid, count, item_index, randomPropertyId, randomSuffix, follow_loot_rules, freeforall, is_blocked, is_counted, is_underthreshold, needs_quest, conditionLootId FROM item_loot_storage", CONNECTION_SYNCH); - PrepareStatement(CHAR_DEL_ITEMCONTAINER_SINGLE_ITEM, "DELETE FROM item_loot_storage WHERE containerGUID = ? AND itemid = ? AND count = ? AND item_index = ? LIMIT 1", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_ITEMCONTAINER_SINGLE_ITEM, "INSERT INTO item_loot_storage (containerGUID, itemid, item_index, count, randomPropertyId, randomSuffix, follow_loot_rules, freeforall, is_blocked, is_counted, is_underthreshold, needs_quest, conditionLootId) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_ITEMCONTAINER_CONTAINER, "DELETE FROM item_loot_storage WHERE containerGUID = ?", CONNECTION_ASYNC); + PrepareStatement(CHAR_SEL_ITEMCONTAINER_ITEMS, "SELECT containerGUID, itemid, count, item_index, randomPropertyId, randomSuffix, follow_loot_rules, freeforall, is_blocked, is_counted, is_underthreshold, needs_quest, conditionLootId FROM item_loot_storage", ConnectionFlags::Sync); + PrepareStatement(CHAR_DEL_ITEMCONTAINER_SINGLE_ITEM, "DELETE FROM item_loot_storage WHERE containerGUID = ? AND itemid = ? AND count = ? AND item_index = ? LIMIT 1", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_ITEMCONTAINER_SINGLE_ITEM, "INSERT INTO item_loot_storage (containerGUID, itemid, item_index, count, randomPropertyId, randomSuffix, follow_loot_rules, freeforall, is_blocked, is_counted, is_underthreshold, needs_quest, conditionLootId) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_ITEMCONTAINER_CONTAINER, "DELETE FROM item_loot_storage WHERE containerGUID = ?", ConnectionFlags::Async); // Calendar - PrepareStatement(CHAR_REP_CALENDAR_EVENT, "REPLACE INTO calendar_events (id, creator, title, description, type, dungeon, eventtime, flags, time2) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CALENDAR_EVENT, "DELETE FROM calendar_events WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_REP_CALENDAR_INVITE, "REPLACE INTO calendar_invites (id, event, invitee, sender, status, statustime, `rank`, text) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CALENDAR_INVITE, "DELETE FROM calendar_invites WHERE id = ?", CONNECTION_ASYNC); + PrepareStatement(CHAR_REP_CALENDAR_EVENT, "REPLACE INTO calendar_events (id, creator, title, description, type, dungeon, eventtime, flags, time2) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CALENDAR_EVENT, "DELETE FROM calendar_events WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_REP_CALENDAR_INVITE, "REPLACE INTO calendar_invites (id, event, invitee, sender, status, statustime, `rank`, text) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CALENDAR_INVITE, "DELETE FROM calendar_invites WHERE id = ?", ConnectionFlags::Async); // Pet - PrepareStatement(CHAR_SEL_CHAR_PET_IDS, "SELECT id FROM character_pet WHERE owner = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_DEL_CHAR_PET_DECLINEDNAME_BY_OWNER, "DELETE FROM character_pet_declinedname WHERE owner = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_PET_DECLINEDNAME, "DELETE FROM character_pet_declinedname WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_ADD_CHAR_PET_DECLINEDNAME, "INSERT INTO character_pet_declinedname (id, owner, genitive, dative, accusative, instrumental, prepositional) VALUES (?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_PET_DECLINED_NAME, "SELECT genitive, dative, accusative, instrumental, prepositional FROM character_pet_declinedname WHERE owner = ? AND id = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_PET_AURA, "SELECT casterGuid, spell, effectMask, recalculateMask, stackCount, amount0, amount1, amount2, base_amount0, base_amount1, base_amount2, maxDuration, remainTime, remainCharges FROM pet_aura WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_PET_SPELL, "SELECT spell, active FROM pet_spell WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_PET_SPELL_COOLDOWN, "SELECT spell, category, time FROM pet_spell_cooldown WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_PET_AURAS, "DELETE FROM pet_aura WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_PET_SPELLS, "DELETE FROM pet_spell WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_PET_SPELL_COOLDOWNS, "DELETE FROM pet_spell_cooldown WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_PET_SPELL_COOLDOWN, "INSERT INTO pet_spell_cooldown (guid, spell, category, time) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_PET_SPELL_BY_SPELL, "DELETE FROM pet_spell WHERE guid = ? AND spell = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_PET_SPELL, "INSERT INTO pet_spell (guid, spell, active) VALUES (?, ?, ?)", CONNECTION_ASYNC); + PrepareStatement(CHAR_SEL_CHAR_PET_IDS, "SELECT id FROM character_pet WHERE owner = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_DEL_CHAR_PET_DECLINEDNAME_BY_OWNER, "DELETE FROM character_pet_declinedname WHERE owner = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_PET_DECLINEDNAME, "DELETE FROM character_pet_declinedname WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_ADD_CHAR_PET_DECLINEDNAME, "INSERT INTO character_pet_declinedname (id, owner, genitive, dative, accusative, instrumental, prepositional) VALUES (?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_PET_DECLINED_NAME, "SELECT genitive, dative, accusative, instrumental, prepositional FROM character_pet_declinedname WHERE owner = ? AND id = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_PET_AURA, "SELECT casterGuid, spell, effectMask, recalculateMask, stackCount, amount0, amount1, amount2, base_amount0, base_amount1, base_amount2, maxDuration, remainTime, remainCharges FROM pet_aura WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_PET_SPELL, "SELECT spell, active FROM pet_spell WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_PET_SPELL_COOLDOWN, "SELECT spell, category, time FROM pet_spell_cooldown WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_PET_AURAS, "DELETE FROM pet_aura WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_PET_SPELLS, "DELETE FROM pet_spell WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_PET_SPELL_COOLDOWNS, "DELETE FROM pet_spell_cooldown WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_PET_SPELL_COOLDOWN, "INSERT INTO pet_spell_cooldown (guid, spell, category, time) VALUES (?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_PET_SPELL_BY_SPELL, "DELETE FROM pet_spell WHERE guid = ? AND spell = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_PET_SPELL, "INSERT INTO pet_spell (guid, spell, active) VALUES (?, ?, ?)", ConnectionFlags::Async); PrepareStatement(CHAR_INS_PET_AURA, "INSERT INTO pet_aura (guid, casterGuid, spell, effectMask, recalculateMask, stackCount, amount0, amount1, amount2, " - "base_amount0, base_amount1, base_amount2, maxDuration, remainTime, remainCharges) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_CHAR_PETS, "SELECT id, entry, modelid, level, exp, Reactstate, slot, name, renamed, curhealth, curmana, curhappiness, abdata, savetime, CreatedBySpell, PetType FROM character_pet WHERE owner = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_PET_BY_OWNER, "DELETE FROM character_pet WHERE owner = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHAR_PET_NAME, "UPDATE character_pet SET name = ?, renamed = 1 WHERE owner = ? AND id = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_CHAR_PET_SLOT_BY_ID, "UPDATE character_pet SET slot = ? WHERE owner = ? AND id = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_PET_BY_ID, "DELETE FROM character_pet WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_PET_BY_SLOT, "DELETE FROM character_pet WHERE owner = ? AND (slot = ? OR slot > ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_REP_CHAR_PET, "REPLACE INTO character_pet (id, entry, owner, modelid, CreatedBySpell, PetType, level, exp, Reactstate, name, renamed, slot, curhealth, curmana, curhappiness, savetime, abdata) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); + "base_amount0, base_amount1, base_amount2, maxDuration, remainTime, remainCharges) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_CHAR_PETS, "SELECT id, entry, modelid, level, exp, Reactstate, slot, name, renamed, curhealth, curmana, curhappiness, abdata, savetime, CreatedBySpell, PetType FROM character_pet WHERE owner = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_PET_BY_OWNER, "DELETE FROM character_pet WHERE owner = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHAR_PET_NAME, "UPDATE character_pet SET name = ?, renamed = 1 WHERE owner = ? AND id = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_CHAR_PET_SLOT_BY_ID, "UPDATE character_pet SET slot = ? WHERE owner = ? AND id = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_PET_BY_ID, "DELETE FROM character_pet WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_PET_BY_SLOT, "DELETE FROM character_pet WHERE owner = ? AND (slot = ? OR slot > ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_REP_CHAR_PET, "REPLACE INTO character_pet (id, entry, owner, modelid, CreatedBySpell, PetType, level, exp, Reactstate, name, renamed, slot, curhealth, curmana, curhappiness, savetime, abdata) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); // PvPstats - PrepareStatement(CHAR_SEL_PVPSTATS_MAXID, "SELECT MAX(id) FROM pvpstats_battlegrounds", CONNECTION_SYNCH); - PrepareStatement(CHAR_INS_PVPSTATS_BATTLEGROUND, "INSERT INTO pvpstats_battlegrounds (id, winner_faction, bracket_id, type, date) VALUES (?, ?, ?, ?, NOW())", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_PVPSTATS_PLAYER, "INSERT INTO pvpstats_players (battleground_id, character_guid, winner, score_killing_blows, score_deaths, score_honorable_kills, score_bonus_honor, score_damage_done, score_healing_done, attr_1, attr_2, attr_3, attr_4, attr_5) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_PVPSTATS_FACTIONS_OVERALL, "SELECT winner_faction, COUNT(*) AS count FROM pvpstats_battlegrounds WHERE DATEDIFF(NOW(), date) < 7 GROUP BY winner_faction ORDER BY winner_faction ASC", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_PVPSTATS_BRACKET_MONTH, "SELECT character_guid, COUNT(character_guid) AS count, characters.name as character_name FROM pvpstats_players INNER JOIN pvpstats_battlegrounds ON pvpstats_players.battleground_id = pvpstats_battlegrounds.id AND bracket_id = ? AND MONTH(date) = MONTH(NOW()) AND YEAR(date) = YEAR(NOW()) INNER JOIN characters ON pvpstats_players.character_guid = characters.guid AND characters.deleteDate IS NULL WHERE pvpstats_players.winner = 1 GROUP BY character_guid ORDER BY count(character_guid) DESC LIMIT 0, ?", CONNECTION_SYNCH); + PrepareStatement(CHAR_SEL_PVPSTATS_MAXID, "SELECT MAX(id) FROM pvpstats_battlegrounds", ConnectionFlags::Sync); + PrepareStatement(CHAR_INS_PVPSTATS_BATTLEGROUND, "INSERT INTO pvpstats_battlegrounds (id, winner_faction, bracket_id, type, date) VALUES (?, ?, ?, ?, NOW())", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_PVPSTATS_PLAYER, "INSERT INTO pvpstats_players (battleground_id, character_guid, winner, score_killing_blows, score_deaths, score_honorable_kills, score_bonus_honor, score_damage_done, score_healing_done, attr_1, attr_2, attr_3, attr_4, attr_5) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_SEL_PVPSTATS_FACTIONS_OVERALL, "SELECT winner_faction, COUNT(*) AS count FROM pvpstats_battlegrounds WHERE DATEDIFF(NOW(), date) < 7 GROUP BY winner_faction ORDER BY winner_faction ASC", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_PVPSTATS_BRACKET_MONTH, "SELECT character_guid, COUNT(character_guid) AS count, characters.name as character_name FROM pvpstats_players INNER JOIN pvpstats_battlegrounds ON pvpstats_players.battleground_id = pvpstats_battlegrounds.id AND bracket_id = ? AND MONTH(date) = MONTH(NOW()) AND YEAR(date) = YEAR(NOW()) INNER JOIN characters ON pvpstats_players.character_guid = characters.guid AND characters.deleteDate IS NULL WHERE pvpstats_players.winner = 1 GROUP BY character_guid ORDER BY count(character_guid) DESC LIMIT 0, ?", ConnectionFlags::Sync); // Deserter tracker - PrepareStatement(CHAR_INS_DESERTER_TRACK, "INSERT INTO battleground_deserters (guid, type, datetime) VALUES (?, ?, NOW())", CONNECTION_ASYNC); + PrepareStatement(CHAR_INS_DESERTER_TRACK, "INSERT INTO battleground_deserters (guid, type, datetime) VALUES (?, ?, NOW())", ConnectionFlags::Async); // QuestTracker - PrepareStatement(CHAR_INS_QUEST_TRACK, "INSERT INTO quest_tracker (id, character_guid, quest_accept_time, core_hash, core_revision) VALUES (?, ?, NOW(), ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_QUEST_TRACK_GM_COMPLETE, "UPDATE quest_tracker SET completed_by_gm = 1 WHERE id = ? AND character_guid = ? ORDER BY quest_accept_time DESC LIMIT 1", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_QUEST_TRACK_COMPLETE_TIME, "UPDATE quest_tracker SET quest_complete_time = NOW() WHERE id = ? AND character_guid = ? ORDER BY quest_accept_time DESC LIMIT 1", CONNECTION_ASYNC); - PrepareStatement(CHAR_UPD_QUEST_TRACK_ABANDON_TIME, "UPDATE quest_tracker SET quest_abandon_time = NOW() WHERE id = ? AND character_guid = ? ORDER BY quest_accept_time DESC LIMIT 1", CONNECTION_ASYNC); + PrepareStatement(CHAR_INS_QUEST_TRACK, "INSERT INTO quest_tracker (id, character_guid, quest_accept_time, core_hash, core_revision) VALUES (?, ?, NOW(), ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_QUEST_TRACK_GM_COMPLETE, "UPDATE quest_tracker SET completed_by_gm = 1 WHERE id = ? AND character_guid = ? ORDER BY quest_accept_time DESC LIMIT 1", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_QUEST_TRACK_COMPLETE_TIME, "UPDATE quest_tracker SET quest_complete_time = NOW() WHERE id = ? AND character_guid = ? ORDER BY quest_accept_time DESC LIMIT 1", ConnectionFlags::Async); + PrepareStatement(CHAR_UPD_QUEST_TRACK_ABANDON_TIME, "UPDATE quest_tracker SET quest_abandon_time = NOW() WHERE id = ? AND character_guid = ? ORDER BY quest_accept_time DESC LIMIT 1", ConnectionFlags::Async); // Recovery Item - PrepareStatement(CHAR_INS_RECOVERY_ITEM, "INSERT INTO recovery_item (Guid, ItemEntry, Count) VALUES (?, ?, ?)", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_RECOVERY_ITEM, "SELECT id, itemEntry, Count, Guid FROM recovery_item WHERE id = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_RECOVERY_ITEM_LIST, "SELECT id, itemEntry, Count FROM recovery_item WHERE Guid = ? ORDER BY id DESC", CONNECTION_SYNCH); - PrepareStatement(CHAR_DEL_RECOVERY_ITEM, "DELETE FROM recovery_item WHERE Guid = ? AND ItemEntry = ? AND Count = ? ORDER BY Id DESC LIMIT 1", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_RECOVERY_ITEM_BY_RECOVERY_ID, "DELETE FROM recovery_item WHERE id = ?", CONNECTION_ASYNC); + PrepareStatement(CHAR_INS_RECOVERY_ITEM, "INSERT INTO recovery_item (Guid, ItemEntry, Count) VALUES (?, ?, ?)", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_RECOVERY_ITEM, "SELECT id, itemEntry, Count, Guid FROM recovery_item WHERE id = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_RECOVERY_ITEM_LIST, "SELECT id, itemEntry, Count FROM recovery_item WHERE Guid = ? ORDER BY id DESC", ConnectionFlags::Sync); + PrepareStatement(CHAR_DEL_RECOVERY_ITEM, "DELETE FROM recovery_item WHERE Guid = ? AND ItemEntry = ? AND Count = ? ORDER BY Id DESC LIMIT 1", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_RECOVERY_ITEM_BY_RECOVERY_ID, "DELETE FROM recovery_item WHERE id = ?", ConnectionFlags::Async); - PrepareStatement(CHAR_SEL_HONORPOINTS, "SELECT totalHonorPoints FROM characters WHERE guid = ?", CONNECTION_SYNCH); - PrepareStatement(CHAR_SEL_ARENAPOINTS, "SELECT arenaPoints FROM characters WHERE guid = ?", CONNECTION_SYNCH); + PrepareStatement(CHAR_SEL_HONORPOINTS, "SELECT totalHonorPoints FROM characters WHERE guid = ?", ConnectionFlags::Sync); + PrepareStatement(CHAR_SEL_ARENAPOINTS, "SELECT arenaPoints FROM characters WHERE guid = ?", ConnectionFlags::Sync); // Character names - PrepareStatement(CHAR_INS_RESERVED_PLAYER_NAME, "INSERT IGNORE INTO reserved_name (name) VALUES (?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_INS_PROFANITY_PLAYER_NAME, "INSERT IGNORE INTO profanity_name (name) VALUES (?)", CONNECTION_ASYNC); + PrepareStatement(CHAR_INS_RESERVED_PLAYER_NAME, "INSERT IGNORE INTO reserved_name (name) VALUES (?)", ConnectionFlags::Async); + PrepareStatement(CHAR_INS_PROFANITY_PLAYER_NAME, "INSERT IGNORE INTO profanity_name (name) VALUES (?)", ConnectionFlags::Async); // Character settings - PrepareStatement(CHAR_SEL_CHAR_SETTINGS, "SELECT source, data FROM character_settings WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_REP_CHAR_SETTINGS, "REPLACE INTO character_settings (guid, source, data) VALUES (?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_CHAR_SETTINGS, "DELETE FROM character_settings WHERE guid = ?", CONNECTION_ASYNC); + PrepareStatement(CHAR_SEL_CHAR_SETTINGS, "SELECT source, data FROM character_settings WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_REP_CHAR_SETTINGS, "REPLACE INTO character_settings (guid, source, data) VALUES (?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DEL_CHAR_SETTINGS, "DELETE FROM character_settings WHERE guid = ?", ConnectionFlags::Async); // Instance saved data. Stores the states of gameobjects in instances to be loaded on server start - PrepareStatement(CHAR_SELECT_INSTANCE_SAVED_DATA, "SELECT id, guid, state FROM instance_saved_go_state_data", CONNECTION_SYNCH); - PrepareStatement(CHAR_UPDATE_INSTANCE_SAVED_DATA, "UPDATE instance_saved_go_state_data SET state = ? WHERE guid = ? AND id = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_INSERT_INSTANCE_SAVED_DATA, "INSERT INTO instance_saved_go_state_data (id, guid, state) VALUES (?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_DELETE_INSTANCE_SAVED_DATA, "DELETE FROM instance_saved_go_state_data WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_SANITIZE_INSTANCE_SAVED_DATA, "DELETE FROM instance_saved_go_state_data WHERE id NOT IN (SELECT instance.id FROM instance)", CONNECTION_ASYNC); -} - -CharacterDatabaseConnection::CharacterDatabaseConnection(MySQLConnectionInfo& connInfo) : MySQLConnection(connInfo) -{ -} - -CharacterDatabaseConnection::CharacterDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo) : MySQLConnection(q, connInfo) -{ -} - -CharacterDatabaseConnection::~CharacterDatabaseConnection() -{ + PrepareStatement(CHAR_SELECT_INSTANCE_SAVED_DATA, "SELECT id, guid, state FROM instance_saved_go_state_data", ConnectionFlags::Sync); + PrepareStatement(CHAR_UPDATE_INSTANCE_SAVED_DATA, "UPDATE instance_saved_go_state_data SET state = ? WHERE guid = ? AND id = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_INSERT_INSTANCE_SAVED_DATA, "INSERT INTO instance_saved_go_state_data (id, guid, state) VALUES (?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(CHAR_DELETE_INSTANCE_SAVED_DATA, "DELETE FROM instance_saved_go_state_data WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(CHAR_SANITIZE_INSTANCE_SAVED_DATA, "DELETE FROM instance_saved_go_state_data WHERE id NOT IN (SELECT instance.id FROM instance)", ConnectionFlags::Async); } diff --git a/src/server/database/Database/Implementation/CharacterDatabase.h b/src/server/database/Database/Implementation/CharacterDatabase.h index 6a85c7aba1fd4d..f1510bb0aac252 100644 --- a/src/server/database/Database/Implementation/CharacterDatabase.h +++ b/src/server/database/Database/Implementation/CharacterDatabase.h @@ -18,7 +18,7 @@ #ifndef _CHARACTERDATABASE_H #define _CHARACTERDATABASE_H -#include "MySQLConnection.h" +#include "DatabaseWorkerPool.h" enum CharacterDatabaseStatements : uint32 { @@ -522,21 +522,20 @@ enum CharacterDatabaseStatements : uint32 CHAR_DELETE_INSTANCE_SAVED_DATA, CHAR_SANITIZE_INSTANCE_SAVED_DATA, - MAX_CHARACTERDATABASE_STATEMENTS + MAX_CHARACTER_DATABASE_STATEMENTS }; -class AC_DATABASE_API CharacterDatabaseConnection : public MySQLConnection +class AC_DATABASE_API CharacterDatabasePool : public DatabaseWorkerPool { public: - typedef CharacterDatabaseStatements Statements; - - //- Constructors for sync and async connections - CharacterDatabaseConnection(MySQLConnectionInfo& connInfo); - CharacterDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo); - ~CharacterDatabaseConnection() override; + CharacterDatabasePool() : DatabaseWorkerPool(DatabaseType::Character) { } + ~CharacterDatabasePool() = default; //- Loads database type specific prepared statements void DoPrepareStatements() override; }; +/// Accessor to the character database +AC_DATABASE_API extern CharacterDatabasePool CharacterDatabase; + #endif diff --git a/src/server/database/Database/Implementation/LoginDatabase.cpp b/src/server/database/Database/Implementation/LoginDatabase.cpp index 3dbb2ced2c222d..3e4fc5bdce17ee 100644 --- a/src/server/database/Database/Implementation/LoginDatabase.cpp +++ b/src/server/database/Database/Implementation/LoginDatabase.cpp @@ -16,12 +16,12 @@ */ #include "LoginDatabase.h" -#include "MySQLPreparedStatement.h" -void LoginDatabaseConnection::DoPrepareStatements() +LoginDatabasePool LoginDatabase; + +void LoginDatabasePool::DoPrepareStatements() { - if (!m_reconnecting) - m_stmts.resize(MAX_LOGINDATABASE_STATEMENTS); + SetStatementSize(MAX_LOGIN_DATABASE_STATEMENTS); PrepareStatement(LOGIN_SEL_LOGONCHALLENGE, "SELECT a.id, a.username, a.locked, a.lock_country, a.last_ip, a.failed_logins, " @@ -32,7 +32,7 @@ void LoginDatabaseConnection::DoPrepareStatements() "LEFT JOIN account_access aa ON a.id = aa.id " "LEFT JOIN account_banned ab ON ab.id = a.id AND ab.active = 1 " "LEFT JOIN ip_banned ipb ON ipb.ip = ? " - "WHERE a.username = ?", CONNECTION_ASYNC); + "WHERE a.username = ?", ConnectionFlags::Async); PrepareStatement(LOGIN_SEL_RECONNECTCHALLENGE, "SELECT a.id, a.username, a.locked, a.lock_country, a.last_ip, a.failed_logins, " "ab.unbandate > UNIX_TIMESTAMP() OR ab.unbandate = ab.bandate, ab.unbandate = ab.bandate, " @@ -42,112 +42,100 @@ void LoginDatabaseConnection::DoPrepareStatements() "LEFT JOIN account_access aa ON a.id = aa.id " "LEFT JOIN account_banned ab ON ab.id = a.id AND ab.active = 1 " "LEFT JOIN ip_banned ipb ON ipb.ip = ? " - "WHERE a.username = ? AND a.session_key IS NOT NULL", CONNECTION_ASYNC); + "WHERE a.username = ? AND a.session_key IS NOT NULL", ConnectionFlags::Async); PrepareStatement(LOGIN_SEL_ACCOUNT_INFO_BY_NAME, "SELECT a.id, a.session_key, a.last_ip, a.locked, a.lock_country, a.expansion, a.mutetime, a.locale, a.recruiter, a.os, a.totaltime, " "aa.gmlevel, ab.unbandate > UNIX_TIMESTAMP() OR ab.unbandate = ab.bandate, r.id FROM account a LEFT JOIN account_access aa ON a.id = aa.id AND aa.RealmID IN (-1, ?) " "LEFT JOIN account_banned ab ON a.id = ab.id AND ab.active = 1 LEFT JOIN account r ON a.id = r.recruiter WHERE a.username = ? " - "AND a.session_key IS NOT NULL ORDER BY aa.RealmID DESC LIMIT 1", CONNECTION_ASYNC); - PrepareStatement(LOGIN_SEL_IP_INFO, "SELECT unbandate > UNIX_TIMESTAMP() OR unbandate = bandate AS banned, NULL as country FROM ip_banned WHERE ip = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_SEL_REALMLIST, "SELECT id, name, address, localAddress, localSubnetMask, port, icon, flag, timezone, allowedSecurityLevel, population, gamebuild FROM realmlist WHERE flag <> 3 ORDER BY name", CONNECTION_SYNCH); - PrepareStatement(LOGIN_DEL_EXPIRED_IP_BANS, "DELETE FROM ip_banned WHERE unbandate<>bandate AND unbandate<=UNIX_TIMESTAMP()", CONNECTION_ASYNC); - PrepareStatement(LOGIN_UPD_EXPIRED_ACCOUNT_BANS, "UPDATE account_banned SET active = 0 WHERE active = 1 AND unbandate<>bandate AND unbandate<=UNIX_TIMESTAMP()", CONNECTION_ASYNC); - PrepareStatement(LOGIN_SEL_IP_BANNED, "SELECT * FROM ip_banned WHERE ip = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_INS_IP_AUTO_BANNED, "INSERT INTO ip_banned (ip, bandate, unbandate, bannedby, banreason) VALUES (?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, 'realmd', 'Failed login autoban')", CONNECTION_ASYNC); - PrepareStatement(LOGIN_SEL_IP_BANNED_ALL, "SELECT ip, bandate, unbandate, bannedby, banreason FROM ip_banned WHERE (bandate = unbandate OR unbandate > UNIX_TIMESTAMP()) ORDER BY unbandate", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_IP_BANNED_BY_IP, "SELECT ip, bandate, unbandate, bannedby, banreason FROM ip_banned WHERE (bandate = unbandate OR unbandate > UNIX_TIMESTAMP()) AND ip LIKE CONCAT('%%', ?, '%%') ORDER BY unbandate", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_ACCOUNT_BANNED, "SELECT bandate, unbandate FROM account_banned WHERE id = ? AND active = 1", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_ACCOUNT_BANNED_ALL, "SELECT account.id, username FROM account, account_banned WHERE account.id = account_banned.id AND active = 1 GROUP BY account.id", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_ACCOUNT_BANNED_BY_USERNAME, "SELECT account.id, username FROM account, account_banned WHERE account.id = account_banned.id AND active = 1 AND username LIKE CONCAT('%%', ?, '%%') GROUP BY account.id", CONNECTION_SYNCH); - PrepareStatement(LOGIN_INS_ACCOUNT_AUTO_BANNED, "INSERT INTO account_banned VALUES (?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, 'realmd', 'Failed login autoban', 1)", CONNECTION_ASYNC); - PrepareStatement(LOGIN_DEL_ACCOUNT_BANNED, "DELETE FROM account_banned WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_UPD_LOGON, "UPDATE account SET salt = ?, verifier = ? WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_UPD_LOGONPROOF, "UPDATE account SET session_key = ?, last_ip = ?, last_login = NOW(), locale = ?, failed_logins = 0, os = ? WHERE username = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_UPD_FAILEDLOGINS, "UPDATE account SET failed_logins = failed_logins + 1 WHERE username = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_SEL_FAILEDLOGINS, "SELECT id, failed_logins FROM account WHERE username = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_ACCOUNT_ID_BY_NAME, "SELECT id FROM account WHERE username = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_ACCOUNT_LIST_BY_NAME, "SELECT id, username FROM account WHERE username = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_ACCOUNT_LIST_BY_EMAIL, "SELECT id, username FROM account WHERE email = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_NUM_CHARS_ON_REALM, "SELECT numchars FROM realmcharacters WHERE realmid = ? AND acctid= ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_REALM_CHARACTER_COUNTS, "SELECT realmid, numchars FROM realmcharacters WHERE acctid = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_SEL_ACCOUNT_BY_IP, "SELECT id, username FROM account WHERE last_ip = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_ACCOUNT_BY_ID, "SELECT 1 FROM account WHERE id = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_INS_IP_BANNED, "INSERT INTO ip_banned (ip, bandate, unbandate, bannedby, banreason) VALUES (?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(LOGIN_DEL_IP_NOT_BANNED, "DELETE FROM ip_banned WHERE ip = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_INS_ACCOUNT_BANNED, "INSERT INTO account_banned VALUES (?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, ?, ?, 1)", CONNECTION_ASYNC); - PrepareStatement(LOGIN_UPD_ACCOUNT_NOT_BANNED, "UPDATE account_banned SET active = 0 WHERE id = ? AND active != 0", CONNECTION_ASYNC); - PrepareStatement(LOGIN_DEL_REALM_CHARACTERS, "DELETE FROM realmcharacters WHERE acctid = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_REP_REALM_CHARACTERS, "REPLACE INTO realmcharacters (numchars, acctid, realmid) VALUES (?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(LOGIN_SEL_SUM_REALM_CHARACTERS, "SELECT SUM(numchars) FROM realmcharacters WHERE acctid = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_INS_ACCOUNT, "INSERT INTO account(username, salt, verifier, expansion, joindate) VALUES(?, ?, ?, ?, NOW())", CONNECTION_ASYNC); - PrepareStatement(LOGIN_INS_REALM_CHARACTERS_INIT, "INSERT INTO realmcharacters (realmid, acctid, numchars) SELECT realmlist.id, account.id, 0 FROM realmlist, account LEFT JOIN realmcharacters ON acctid=account.id WHERE acctid IS NULL", CONNECTION_ASYNC); - PrepareStatement(LOGIN_UPD_EXPANSION, "UPDATE account SET expansion = ? WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_UPD_ACCOUNT_LOCK, "UPDATE account SET locked = ? WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_UPD_ACCOUNT_LOCK_COUNTRY, "UPDATE account SET lock_country = ? WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_UPD_USERNAME, "UPDATE account SET username = ? WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_UPD_MUTE_TIME, "UPDATE account SET mutetime = ? , mutereason = ? , muteby = ? WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_UPD_MUTE_TIME_LOGIN, "UPDATE account SET mutetime = ? WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_UPD_LAST_IP, "UPDATE account SET last_ip = ? WHERE username = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_UPD_LAST_ATTEMPT_IP, "UPDATE account SET last_attempt_ip = ? WHERE username = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_UPD_ACCOUNT_ONLINE, "UPDATE account SET online = ? WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_UPD_UPTIME_PLAYERS, "UPDATE uptime SET uptime = ?, maxplayers = ? WHERE realmid = ? AND starttime = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_DEL_OLD_LOGS, "DELETE FROM logs WHERE (time + ?) < ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_DEL_ACCOUNT_ACCESS, "DELETE FROM account_access WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_DEL_ACCOUNT_ACCESS_BY_REALM, "DELETE FROM account_access WHERE id = ? AND (RealmID = ? OR RealmID = -1)", CONNECTION_ASYNC); - PrepareStatement(LOGIN_INS_ACCOUNT_ACCESS, "INSERT INTO account_access (id,gmlevel,RealmID) VALUES (?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(LOGIN_GET_ACCOUNT_ID_BY_USERNAME, "SELECT id FROM account WHERE username = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_GET_ACCOUNT_ACCESS_GMLEVEL, "SELECT gmlevel FROM account_access WHERE id = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_GET_GMLEVEL_BY_REALMID, "SELECT gmlevel FROM account_access WHERE id = ? AND (RealmID = ? OR RealmID = -1)", CONNECTION_SYNCH); - PrepareStatement(LOGIN_GET_USERNAME_BY_ID, "SELECT username FROM account WHERE id = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_CHECK_PASSWORD, "SELECT salt, verifier FROM account WHERE id = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_CHECK_PASSWORD_BY_NAME, "SELECT salt, verifier FROM account WHERE username = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_PINFO, "SELECT a.username, aa.gmlevel, a.email, a.reg_mail, a.last_ip, DATE_FORMAT(a.last_login, '%Y-%m-%d %T'), a.mutetime, a.mutereason, a.muteby, a.failed_logins, a.locked, a.OS FROM account a LEFT JOIN account_access aa ON (a.id = aa.id AND (aa.RealmID = ? OR aa.RealmID = -1)) WHERE a.id = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_PINFO_BANS, "SELECT unbandate, bandate = unbandate, bannedby, banreason FROM account_banned WHERE id = ? AND active ORDER BY bandate ASC LIMIT 1", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_GM_ACCOUNTS, "SELECT a.username, aa.gmlevel FROM account a, account_access aa WHERE a.id=aa.id AND aa.gmlevel >= ? AND (aa.realmid = -1 OR aa.realmid = ?)", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_ACCOUNT_INFO, "SELECT a.username, a.last_ip, aa.gmlevel, a.expansion FROM account a LEFT JOIN account_access aa ON (a.id = aa.id) WHERE a.id = ? ORDER BY a.last_ip", CONNECTION_SYNCH); // Only used in ".account onlinelist" command - PrepareStatement(LOGIN_SEL_ACCOUNT_ACCESS_GMLEVEL_TEST, "SELECT 1 FROM account_access WHERE id = ? AND gmlevel > ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_ACCOUNT_ACCESS, "SELECT a.id, aa.gmlevel, aa.RealmID FROM account a LEFT JOIN account_access aa ON (a.id = aa.id) WHERE a.username = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_ACCOUNT_RECRUITER, "SELECT 1 FROM account WHERE recruiter = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_BANS, "SELECT 1 FROM account_banned WHERE id = ? AND active = 1 UNION SELECT 1 FROM ip_banned WHERE ip = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_ACCOUNT_WHOIS, "SELECT username, email, last_ip FROM account WHERE id = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_LAST_ATTEMPT_IP, "SELECT last_attempt_ip FROM account WHERE id = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_LAST_IP, "SELECT last_ip FROM account WHERE id = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_REALMLIST_SECURITY_LEVEL, "SELECT allowedSecurityLevel from realmlist WHERE id = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_DEL_ACCOUNT, "DELETE FROM account WHERE id = ?", CONNECTION_ASYNC); - PrepareStatement(LOGIN_SEL_AUTOBROADCAST, "SELECT id, weight, text FROM autobroadcast WHERE realmid = ? OR realmid = -1", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_MOTD, "SELECT text FROM motd WHERE realmid = ? OR realmid = -1 ORDER BY realmid DESC", CONNECTION_SYNCH); - PrepareStatement(LOGIN_REP_MOTD, "REPLACE INTO motd (realmid, text) VALUES (?, ?)", CONNECTION_ASYNC); - PrepareStatement(LOGIN_INS_ACCOUNT_MUTE, "INSERT INTO account_muted VALUES (?, UNIX_TIMESTAMP(), ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(LOGIN_SEL_ACCOUNT_MUTE_INFO, "SELECT mutedate, mutetime, mutereason, mutedby FROM account_muted WHERE guid = ? ORDER BY mutedate ASC", CONNECTION_SYNCH); - PrepareStatement(LOGIN_DEL_ACCOUNT_MUTED, "DELETE FROM account_muted WHERE guid = ?", CONNECTION_ASYNC); + "AND a.session_key IS NOT NULL ORDER BY aa.RealmID DESC LIMIT 1", ConnectionFlags::Async); + PrepareStatement(LOGIN_SEL_IP_INFO, "SELECT unbandate > UNIX_TIMESTAMP() OR unbandate = bandate AS banned, NULL as country FROM ip_banned WHERE ip = ?", ConnectionFlags::Async); + PrepareStatement(LOGIN_SEL_REALMLIST, "SELECT id, name, address, localAddress, localSubnetMask, port, icon, flag, timezone, allowedSecurityLevel, population, gamebuild FROM realmlist WHERE flag <> 3 ORDER BY name", ConnectionFlags::Sync); + PrepareStatement(LOGIN_DEL_EXPIRED_IP_BANS, "DELETE FROM ip_banned WHERE unbandate<>bandate AND unbandate<=UNIX_TIMESTAMP()", ConnectionFlags::Async); + PrepareStatement(LOGIN_UPD_EXPIRED_ACCOUNT_BANS, "UPDATE account_banned SET active = 0 WHERE active = 1 AND unbandate<>bandate AND unbandate<=UNIX_TIMESTAMP()", ConnectionFlags::Async); + PrepareStatement(LOGIN_SEL_IP_BANNED, "SELECT * FROM ip_banned WHERE ip = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_INS_IP_AUTO_BANNED, "INSERT INTO ip_banned (ip, bandate, unbandate, bannedby, banreason) VALUES (?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, 'realmd', 'Failed login autoban')", ConnectionFlags::Async); + PrepareStatement(LOGIN_SEL_IP_BANNED_ALL, "SELECT ip, bandate, unbandate, bannedby, banreason FROM ip_banned WHERE (bandate = unbandate OR unbandate > UNIX_TIMESTAMP()) ORDER BY unbandate", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_IP_BANNED_BY_IP, "SELECT ip, bandate, unbandate, bannedby, banreason FROM ip_banned WHERE (bandate = unbandate OR unbandate > UNIX_TIMESTAMP()) AND ip LIKE CONCAT('%%', ?, '%%') ORDER BY unbandate", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_ACCOUNT_BANNED, "SELECT bandate, unbandate FROM account_banned WHERE id = ? AND active = 1", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_ACCOUNT_BANNED_ALL, "SELECT account.id, username FROM account, account_banned WHERE account.id = account_banned.id AND active = 1 GROUP BY account.id", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_ACCOUNT_BANNED_BY_USERNAME, "SELECT account.id, username FROM account, account_banned WHERE account.id = account_banned.id AND active = 1 AND username LIKE CONCAT('%%', ?, '%%') GROUP BY account.id", ConnectionFlags::Sync); + PrepareStatement(LOGIN_INS_ACCOUNT_AUTO_BANNED, "INSERT INTO account_banned VALUES (?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, 'realmd', 'Failed login autoban', 1)", ConnectionFlags::Async); + PrepareStatement(LOGIN_DEL_ACCOUNT_BANNED, "DELETE FROM account_banned WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(LOGIN_UPD_LOGON, "UPDATE account SET salt = ?, verifier = ? WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(LOGIN_UPD_LOGONPROOF, "UPDATE account SET session_key = ?, last_ip = ?, last_login = NOW(), locale = ?, failed_logins = 0, os = ? WHERE username = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_UPD_FAILEDLOGINS, "UPDATE account SET failed_logins = failed_logins + 1 WHERE username = ?", ConnectionFlags::Async); + PrepareStatement(LOGIN_SEL_FAILEDLOGINS, "SELECT id, failed_logins FROM account WHERE username = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_ACCOUNT_ID_BY_NAME, "SELECT id FROM account WHERE username = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_ACCOUNT_LIST_BY_NAME, "SELECT id, username FROM account WHERE username = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_ACCOUNT_LIST_BY_EMAIL, "SELECT id, username FROM account WHERE email = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_NUM_CHARS_ON_REALM, "SELECT numchars FROM realmcharacters WHERE realmid = ? AND acctid= ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_REALM_CHARACTER_COUNTS, "SELECT realmid, numchars FROM realmcharacters WHERE acctid = ?", ConnectionFlags::Async); + PrepareStatement(LOGIN_SEL_ACCOUNT_BY_IP, "SELECT id, username FROM account WHERE last_ip = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_ACCOUNT_BY_ID, "SELECT 1 FROM account WHERE id = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_INS_IP_BANNED, "INSERT INTO ip_banned (ip, bandate, unbandate, bannedby, banreason) VALUES (?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(LOGIN_DEL_IP_NOT_BANNED, "DELETE FROM ip_banned WHERE ip = ?", ConnectionFlags::Async); + PrepareStatement(LOGIN_INS_ACCOUNT_BANNED, "INSERT INTO account_banned VALUES (?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, ?, ?, 1)", ConnectionFlags::Async); + PrepareStatement(LOGIN_UPD_ACCOUNT_NOT_BANNED, "UPDATE account_banned SET active = 0 WHERE id = ? AND active != 0", ConnectionFlags::Async); + PrepareStatement(LOGIN_DEL_REALM_CHARACTERS, "DELETE FROM realmcharacters WHERE acctid = ?", ConnectionFlags::Async); + PrepareStatement(LOGIN_REP_REALM_CHARACTERS, "REPLACE INTO realmcharacters (numchars, acctid, realmid) VALUES (?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(LOGIN_SEL_SUM_REALM_CHARACTERS, "SELECT SUM(numchars) FROM realmcharacters WHERE acctid = ?", ConnectionFlags::Async); + PrepareStatement(LOGIN_INS_ACCOUNT, "INSERT INTO account(username, salt, verifier, expansion, joindate) VALUES(?, ?, ?, ?, NOW())", ConnectionFlags::Async); + PrepareStatement(LOGIN_INS_REALM_CHARACTERS_INIT, "INSERT INTO realmcharacters (realmid, acctid, numchars) SELECT realmlist.id, account.id, 0 FROM realmlist, account LEFT JOIN realmcharacters ON acctid=account.id WHERE acctid IS NULL", ConnectionFlags::Async); + PrepareStatement(LOGIN_UPD_EXPANSION, "UPDATE account SET expansion = ? WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(LOGIN_UPD_ACCOUNT_LOCK, "UPDATE account SET locked = ? WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(LOGIN_UPD_ACCOUNT_LOCK_COUNTRY, "UPDATE account SET lock_country = ? WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(LOGIN_UPD_USERNAME, "UPDATE account SET username = ? WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(LOGIN_UPD_MUTE_TIME, "UPDATE account SET mutetime = ? , mutereason = ? , muteby = ? WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(LOGIN_UPD_MUTE_TIME_LOGIN, "UPDATE account SET mutetime = ? WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(LOGIN_UPD_LAST_IP, "UPDATE account SET last_ip = ? WHERE username = ?", ConnectionFlags::Async); + PrepareStatement(LOGIN_UPD_LAST_ATTEMPT_IP, "UPDATE account SET last_attempt_ip = ? WHERE username = ?", ConnectionFlags::Async); + PrepareStatement(LOGIN_UPD_ACCOUNT_ONLINE, "UPDATE account SET online = ? WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(LOGIN_UPD_UPTIME_PLAYERS, "UPDATE uptime SET uptime = ?, maxplayers = ? WHERE realmid = ? AND starttime = ?", ConnectionFlags::Async); + PrepareStatement(LOGIN_DEL_OLD_LOGS, "DELETE FROM logs WHERE (time + ?) < ?", ConnectionFlags::Async); + PrepareStatement(LOGIN_DEL_ACCOUNT_ACCESS, "DELETE FROM account_access WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(LOGIN_DEL_ACCOUNT_ACCESS_BY_REALM, "DELETE FROM account_access WHERE id = ? AND (RealmID = ? OR RealmID = -1)", ConnectionFlags::Async); + PrepareStatement(LOGIN_INS_ACCOUNT_ACCESS, "INSERT INTO account_access (id,gmlevel,RealmID) VALUES (?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(LOGIN_GET_ACCOUNT_ID_BY_USERNAME, "SELECT id FROM account WHERE username = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_GET_ACCOUNT_ACCESS_GMLEVEL, "SELECT gmlevel FROM account_access WHERE id = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_GET_GMLEVEL_BY_REALMID, "SELECT gmlevel FROM account_access WHERE id = ? AND (RealmID = ? OR RealmID = -1)", ConnectionFlags::Sync); + PrepareStatement(LOGIN_GET_USERNAME_BY_ID, "SELECT username FROM account WHERE id = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_CHECK_PASSWORD, "SELECT salt, verifier FROM account WHERE id = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_CHECK_PASSWORD_BY_NAME, "SELECT salt, verifier FROM account WHERE username = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_PINFO, "SELECT a.username, aa.gmlevel, a.email, a.reg_mail, a.last_ip, DATE_FORMAT(a.last_login, '%Y-%m-%d %T'), a.mutetime, a.mutereason, a.muteby, a.failed_logins, a.locked, a.OS FROM account a LEFT JOIN account_access aa ON (a.id = aa.id AND (aa.RealmID = ? OR aa.RealmID = -1)) WHERE a.id = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_PINFO_BANS, "SELECT unbandate, bandate = unbandate, bannedby, banreason FROM account_banned WHERE id = ? AND active ORDER BY bandate ASC LIMIT 1", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_GM_ACCOUNTS, "SELECT a.username, aa.gmlevel FROM account a, account_access aa WHERE a.id=aa.id AND aa.gmlevel >= ? AND (aa.realmid = -1 OR aa.realmid = ?)", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_ACCOUNT_INFO, "SELECT a.username, a.last_ip, aa.gmlevel, a.expansion FROM account a LEFT JOIN account_access aa ON (a.id = aa.id) WHERE a.id = ? ORDER BY a.last_ip", ConnectionFlags::Sync); // Only used in ".account onlinelist" command + PrepareStatement(LOGIN_SEL_ACCOUNT_ACCESS_GMLEVEL_TEST, "SELECT 1 FROM account_access WHERE id = ? AND gmlevel > ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_ACCOUNT_ACCESS, "SELECT a.id, aa.gmlevel, aa.RealmID FROM account a LEFT JOIN account_access aa ON (a.id = aa.id) WHERE a.username = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_ACCOUNT_RECRUITER, "SELECT 1 FROM account WHERE recruiter = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_BANS, "SELECT 1 FROM account_banned WHERE id = ? AND active = 1 UNION SELECT 1 FROM ip_banned WHERE ip = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_ACCOUNT_WHOIS, "SELECT username, email, last_ip FROM account WHERE id = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_LAST_ATTEMPT_IP, "SELECT last_attempt_ip FROM account WHERE id = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_LAST_IP, "SELECT last_ip FROM account WHERE id = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_REALMLIST_SECURITY_LEVEL, "SELECT allowedSecurityLevel from realmlist WHERE id = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_DEL_ACCOUNT, "DELETE FROM account WHERE id = ?", ConnectionFlags::Async); + PrepareStatement(LOGIN_SEL_AUTOBROADCAST, "SELECT id, weight, text FROM autobroadcast WHERE realmid = ? OR realmid = -1", ConnectionFlags::Sync); + PrepareStatement(LOGIN_SEL_MOTD, "SELECT text FROM motd WHERE realmid = ? OR realmid = -1 ORDER BY realmid DESC", ConnectionFlags::Sync); + PrepareStatement(LOGIN_REP_MOTD, "REPLACE INTO motd (realmid, text) VALUES (?, ?)", ConnectionFlags::Async); + PrepareStatement(LOGIN_INS_ACCOUNT_MUTE, "INSERT INTO account_muted VALUES (?, UNIX_TIMESTAMP(), ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(LOGIN_SEL_ACCOUNT_MUTE_INFO, "SELECT mutedate, mutetime, mutereason, mutedby FROM account_muted WHERE guid = ? ORDER BY mutedate ASC", ConnectionFlags::Sync); + PrepareStatement(LOGIN_DEL_ACCOUNT_MUTED, "DELETE FROM account_muted WHERE guid = ?", ConnectionFlags::Async); // 0: uint32, 1: uint32, 2: uint8, 3: uint32, 4: string // Complete name: "Login_Insert_AccountLoginDeLete_IP_Logging" - PrepareStatement(LOGIN_INS_ALDL_IP_LOGGING, "INSERT INTO logs_ip_actions (account_id,character_guid,type,ip,systemnote,unixtime,time) VALUES (?, ?, ?, (SELECT last_ip FROM account WHERE id = ?), ?, unix_timestamp(NOW()), NOW())", CONNECTION_ASYNC); + PrepareStatement(LOGIN_INS_ALDL_IP_LOGGING, "INSERT INTO logs_ip_actions (account_id,character_guid,type,ip,systemnote,unixtime,time) VALUES (?, ?, ?, (SELECT last_ip FROM account WHERE id = ?), ?, unix_timestamp(NOW()), NOW())", ConnectionFlags::Async); // 0: uint32, 1: uint32, 2: uint8, 3: uint32, 4: string // Complete name: "Login_Insert_FailedAccountLogin_IP_Logging" - PrepareStatement(LOGIN_INS_FACL_IP_LOGGING, "INSERT INTO logs_ip_actions (account_id,character_guid,type,ip,systemnote,unixtime,time) VALUES (?, ?, ?, (SELECT last_attempt_ip FROM account WHERE id = ?), ?, unix_timestamp(NOW()), NOW())", CONNECTION_ASYNC); + PrepareStatement(LOGIN_INS_FACL_IP_LOGGING, "INSERT INTO logs_ip_actions (account_id,character_guid,type,ip,systemnote,unixtime,time) VALUES (?, ?, ?, (SELECT last_attempt_ip FROM account WHERE id = ?), ?, unix_timestamp(NOW()), NOW())", ConnectionFlags::Async); // 0: uint32, 1: uint32, 2: uint8, 3: string, 4: string // Complete name: "Login_Insert_CharacterDelete_IP_Logging" - PrepareStatement(LOGIN_INS_CHAR_IP_LOGGING, "INSERT INTO logs_ip_actions (account_id,character_guid,type,ip,systemnote,unixtime,time) VALUES (?, ?, ?, ?, ?, unix_timestamp(NOW()), NOW())", CONNECTION_ASYNC); + PrepareStatement(LOGIN_INS_CHAR_IP_LOGGING, "INSERT INTO logs_ip_actions (account_id,character_guid,type,ip,systemnote,unixtime,time) VALUES (?, ?, ?, ?, ?, unix_timestamp(NOW()), NOW())", ConnectionFlags::Async); // 0: string, 1: string, 2: string // Complete name: "Login_Insert_Failed_Account_Login_due_password_IP_Logging" - PrepareStatement(LOGIN_INS_FALP_IP_LOGGING, "INSERT INTO logs_ip_actions (account_id,character_guid,type,ip,systemnote,unixtime,time) VALUES (?, 0, 1, ?, ?, unix_timestamp(NOW()), NOW())", CONNECTION_ASYNC); + PrepareStatement(LOGIN_INS_FALP_IP_LOGGING, "INSERT INTO logs_ip_actions (account_id,character_guid,type,ip,systemnote,unixtime,time) VALUES (?, 0, 1, ?, ?, unix_timestamp(NOW()), NOW())", ConnectionFlags::Async); // DB logging - PrepareStatement(LOGIN_INS_LOG, "INSERT INTO logs (time, realm, type, level, string) VALUES (?, ?, ?, ?, ?)", CONNECTION_ASYNC); + PrepareStatement(LOGIN_INS_LOG, "INSERT INTO logs (time, realm, type, level, string) VALUES (?, ?, ?, ?, ?)", ConnectionFlags::Async); // TOTP - PrepareStatement(LOGIN_SEL_SECRET_DIGEST, "SELECT digest FROM secret_digest WHERE id = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_INS_SECRET_DIGEST, "INSERT INTO secret_digest (id, digest) VALUES (?,?)", CONNECTION_ASYNC); - PrepareStatement(LOGIN_DEL_SECRET_DIGEST, "DELETE FROM secret_digest WHERE id = ?", CONNECTION_ASYNC); - - PrepareStatement(LOGIN_SEL_ACCOUNT_TOTP_SECRET, "SELECT totp_secret FROM account WHERE id = ?", CONNECTION_SYNCH); - PrepareStatement(LOGIN_UPD_ACCOUNT_TOTP_SECRET, "UPDATE account SET totp_secret = ? WHERE id = ?", CONNECTION_ASYNC); -} - -LoginDatabaseConnection::LoginDatabaseConnection(MySQLConnectionInfo& connInfo) : MySQLConnection(connInfo) -{ -} + PrepareStatement(LOGIN_SEL_SECRET_DIGEST, "SELECT digest FROM secret_digest WHERE id = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_INS_SECRET_DIGEST, "INSERT INTO secret_digest (id, digest) VALUES (?,?)", ConnectionFlags::Async); + PrepareStatement(LOGIN_DEL_SECRET_DIGEST, "DELETE FROM secret_digest WHERE id = ?", ConnectionFlags::Async); -LoginDatabaseConnection::LoginDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo) : MySQLConnection(q, connInfo) -{ -} - -LoginDatabaseConnection::~LoginDatabaseConnection() -{ + PrepareStatement(LOGIN_SEL_ACCOUNT_TOTP_SECRET, "SELECT totp_secret FROM account WHERE id = ?", ConnectionFlags::Sync); + PrepareStatement(LOGIN_UPD_ACCOUNT_TOTP_SECRET, "UPDATE account SET totp_secret = ? WHERE id = ?", ConnectionFlags::Async); } diff --git a/src/server/database/Database/Implementation/LoginDatabase.h b/src/server/database/Database/Implementation/LoginDatabase.h index c7fb2be4834bac..a11871194d0e28 100644 --- a/src/server/database/Database/Implementation/LoginDatabase.h +++ b/src/server/database/Database/Implementation/LoginDatabase.h @@ -18,7 +18,7 @@ #ifndef _LOGINDATABASE_H #define _LOGINDATABASE_H -#include "MySQLConnection.h" +#include "DatabaseWorkerPool.h" enum LoginDatabaseStatements : uint32 { @@ -118,21 +118,20 @@ enum LoginDatabaseStatements : uint32 LOGIN_SEL_ACCOUNT_TOTP_SECRET, LOGIN_UPD_ACCOUNT_TOTP_SECRET, - MAX_LOGINDATABASE_STATEMENTS + MAX_LOGIN_DATABASE_STATEMENTS }; -class AC_DATABASE_API LoginDatabaseConnection : public MySQLConnection +class AC_DATABASE_API LoginDatabasePool : public DatabaseWorkerPool { public: - typedef LoginDatabaseStatements Statements; - - //- Constructors for sync and async connections - LoginDatabaseConnection(MySQLConnectionInfo& connInfo); - LoginDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo); - ~LoginDatabaseConnection() override; + LoginDatabasePool() : DatabaseWorkerPool(DatabaseType::Auth) { } + ~LoginDatabasePool() = default; //- Loads database type specific prepared statements void DoPrepareStatements() override; }; +/// Accessor to the realm/login database +AC_DATABASE_API extern LoginDatabasePool LoginDatabase; + #endif diff --git a/src/server/database/Database/Implementation/WorldDatabase.cpp b/src/server/database/Database/Implementation/WorldDatabase.cpp index 623533a2a4f053..d7c747ac64c6df 100644 --- a/src/server/database/Database/Implementation/WorldDatabase.cpp +++ b/src/server/database/Database/Implementation/WorldDatabase.cpp @@ -16,95 +16,84 @@ */ #include "WorldDatabase.h" -#include "MySQLPreparedStatement.h" -void WorldDatabaseConnection::DoPrepareStatements() -{ - if (!m_reconnecting) - m_stmts.resize(MAX_WORLDDATABASE_STATEMENTS); +WorldDatabasePool WorldDatabase; - PrepareStatement(WORLD_SEL_QUEST_POOLS, "SELECT entry, pool_entry FROM pool_quest", CONNECTION_SYNCH); - PrepareStatement(WORLD_DEL_CRELINKED_RESPAWN, "DELETE FROM linked_respawn WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_REP_CREATURE_LINKED_RESPAWN, "REPLACE INTO linked_respawn (guid, linkedGuid) VALUES (?, ?)", CONNECTION_ASYNC); - PrepareStatement(WORLD_SEL_CREATURE_TEXT, "SELECT CreatureID, GroupID, ID, Text, Type, Language, Probability, Emote, Duration, Sound, BroadcastTextId, TextRange FROM creature_text", CONNECTION_SYNCH); - PrepareStatement(WORLD_SEL_SMART_SCRIPTS, "SELECT entryorguid, source_type, id, link, event_type, event_phase_mask, event_chance, event_flags, event_param1, event_param2, event_param3, event_param4, event_param5, action_type, action_param1, action_param2, action_param3, action_param4, action_param5, action_param6, target_type, target_param1, target_param2, target_param3, target_param4, target_x, target_y, target_z, target_o FROM smart_scripts ORDER BY entryorguid, source_type, id, link", CONNECTION_SYNCH); - PrepareStatement(WORLD_SEL_SMARTAI_WP, "SELECT entry, pointid, position_x, position_y, position_z, orientation, delay FROM waypoints ORDER BY entry, pointid", CONNECTION_SYNCH); - PrepareStatement(WORLD_DEL_GAMEOBJECT, "DELETE FROM gameobject WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_DEL_EVENT_GAMEOBJECT, "DELETE FROM game_event_gameobject WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_INS_GRAVEYARD_ZONE, "INSERT INTO graveyard_zone (ID, GhostZone, Faction) VALUES (?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(WORLD_DEL_GRAVEYARD_ZONE, "DELETE FROM graveyard_zone WHERE ID = ? AND GhostZone = ? AND Faction = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_INS_GAME_TELE, "INSERT INTO game_tele (id, position_x, position_y, position_z, orientation, map, name) VALUES (?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(WORLD_DEL_GAME_TELE, "DELETE FROM game_tele WHERE name = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_INS_NPC_VENDOR, "INSERT INTO npc_vendor (entry, item, maxcount, incrtime, extendedcost) VALUES(?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(WORLD_DEL_NPC_VENDOR, "DELETE FROM npc_vendor WHERE entry = ? AND item = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_SEL_NPC_VENDOR_REF, "SELECT item, maxcount, incrtime, ExtendedCost FROM npc_vendor WHERE entry = ? ORDER BY slot ASC", CONNECTION_SYNCH); - PrepareStatement(WORLD_UPD_CREATURE_MOVEMENT_TYPE, "UPDATE creature SET MovementType = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_UPD_CREATURE_FACTION, "UPDATE creature_template SET faction = ? WHERE entry = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_UPD_CREATURE_NPCFLAG, "UPDATE creature_template SET npcflag = ? WHERE entry = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_UPD_CREATURE_POSITION, "UPDATE creature SET position_x = ?, position_y = ?, position_z = ?, orientation = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_UPD_CREATURE_WANDER_DISTANCE, "UPDATE creature SET wander_distance = ?, MovementType = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_UPD_CREATURE_SPAWN_TIME_SECS, "UPDATE creature SET spawntimesecs = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_INS_CREATURE_FORMATION, "INSERT INTO creature_formations (leaderGUID, memberGUID, dist, angle, groupAI) VALUES (?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(WORLD_INS_WAYPOINT_DATA, "INSERT INTO waypoint_data (id, point, position_x, position_y, position_z) VALUES (?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(WORLD_DEL_WAYPOINT_DATA, "DELETE FROM waypoint_data WHERE id = ? AND point = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_UPD_WAYPOINT_DATA_POINT, "UPDATE waypoint_data SET point = point - 1 WHERE id = ? AND point > ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_UPD_WAYPOINT_DATA_POSITION, "UPDATE waypoint_data SET position_x = ?, position_y = ?, position_z = ? where id = ? AND point = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_UPD_WAYPOINT_DATA_WPGUID, "UPDATE waypoint_data SET wpguid = ? WHERE id = ? and point = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_SEL_WAYPOINT_DATA_MAX_ID, "SELECT MAX(id) FROM waypoint_data", CONNECTION_SYNCH); - PrepareStatement(WORLD_SEL_WAYPOINT_DATA_MAX_POINT, "SELECT MAX(point) FROM waypoint_data WHERE id = ?", CONNECTION_SYNCH); - PrepareStatement(WORLD_SEL_WAYPOINT_DATA_BY_ID, "SELECT point, position_x, position_y, position_z, orientation, move_type, delay, action, action_chance FROM waypoint_data WHERE id = ? ORDER BY point", CONNECTION_SYNCH); - PrepareStatement(WORLD_SEL_WAYPOINT_DATA_POS_BY_ID, "SELECT point, position_x, position_y, position_z FROM waypoint_data WHERE id = ?", CONNECTION_SYNCH); - PrepareStatement(WORLD_SEL_WAYPOINT_DATA_POS_FIRST_BY_ID, "SELECT position_x, position_y, position_z FROM waypoint_data WHERE point = 1 AND id = ?", CONNECTION_SYNCH); - PrepareStatement(WORLD_SEL_WAYPOINT_DATA_POS_LAST_BY_ID, "SELECT position_x, position_y, position_z, orientation FROM waypoint_data WHERE id = ? ORDER BY point DESC LIMIT 1", CONNECTION_SYNCH); - PrepareStatement(WORLD_SEL_WAYPOINT_DATA_BY_WPGUID, "SELECT id, point FROM waypoint_data WHERE wpguid = ?", CONNECTION_SYNCH); - PrepareStatement(WORLD_SEL_WAYPOINT_DATA_ALL_BY_WPGUID, "SELECT id, point, delay, move_type, action, action_chance FROM waypoint_data WHERE wpguid = ?", CONNECTION_SYNCH); - PrepareStatement(WORLD_UPD_WAYPOINT_DATA_ALL_WPGUID, "UPDATE waypoint_data SET wpguid = 0", CONNECTION_ASYNC); - PrepareStatement(WORLD_SEL_WAYPOINT_DATA_BY_POS, "SELECT id, point FROM waypoint_data WHERE (abs(position_x - ?) <= ?) and (abs(position_y - ?) <= ?) and (abs(position_z - ?) <= ?)", CONNECTION_SYNCH); - PrepareStatement(WORLD_SEL_WAYPOINT_DATA_WPGUID_BY_ID, "SELECT wpguid FROM waypoint_data WHERE id = ? and wpguid <> 0", CONNECTION_SYNCH); - PrepareStatement(WORLD_SEL_WAYPOINT_DATA_ACTION, "SELECT DISTINCT action FROM waypoint_data", CONNECTION_SYNCH); - PrepareStatement(WORLD_SEL_WAYPOINT_SCRIPTS_MAX_ID, "SELECT MAX(guid) FROM waypoint_scripts", CONNECTION_SYNCH); - PrepareStatement(WORLD_INS_CREATURE_ADDON, "INSERT INTO creature_addon(guid, path_id) VALUES (?, ?)", CONNECTION_ASYNC); - PrepareStatement(WORLD_UPD_CREATURE_ADDON_PATH, "UPDATE creature_addon SET path_id = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_DEL_CREATURE_ADDON, "DELETE FROM creature_addon WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_SEL_CREATURE_ADDON_BY_GUID, "SELECT guid FROM creature_addon WHERE guid = ?", CONNECTION_SYNCH); - PrepareStatement(WORLD_INS_WAYPOINT_SCRIPT, "INSERT INTO waypoint_scripts (guid) VALUES (?)", CONNECTION_ASYNC); - PrepareStatement(WORLD_DEL_WAYPOINT_SCRIPT, "DELETE FROM waypoint_scripts WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_UPD_WAYPOINT_SCRIPT_ID, "UPDATE waypoint_scripts SET id = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_UPD_WAYPOINT_SCRIPT_X, "UPDATE waypoint_scripts SET x = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_UPD_WAYPOINT_SCRIPT_Y, "UPDATE waypoint_scripts SET y = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_UPD_WAYPOINT_SCRIPT_Z, "UPDATE waypoint_scripts SET z = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_UPD_WAYPOINT_SCRIPT_O, "UPDATE waypoint_scripts SET o = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_SEL_WAYPOINT_SCRIPT_ID_BY_GUID, "SELECT id FROM waypoint_scripts WHERE guid = ?", CONNECTION_SYNCH); - PrepareStatement(WORLD_DEL_CREATURE, "DELETE FROM creature WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_SEL_COMMANDS, "SELECT name, security, help FROM command", CONNECTION_SYNCH); - PrepareStatement(WORLD_SEL_CREATURE_TEMPLATE, "SELECT entry, difficulty_entry_1, difficulty_entry_2, difficulty_entry_3, KillCredit1, KillCredit2, modelid1, modelid2, modelid3, modelid4, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, exp, faction, npcflag, speed_walk, speed_run, speed_swim, speed_flight, detection_range, scale, `rank`, dmgschool, DamageModifier, BaseAttackTime, RangeAttackTime, BaseVariance, RangeVariance, unit_class, unit_flags, unit_flags2, dynamicflags, family, trainer_type, trainer_spell, trainer_class, trainer_race, type, type_flags, lootid, pickpocketloot, skinloot, PetSpellDataId, VehicleId, mingold, maxgold, AIName, MovementType, ctm.Ground, ctm.Swim, ctm.Flight, ctm.Rooted, ctm.Chase, ctm.Random, ctm.InteractionPauseTimer, HoverHeight, HealthModifier, ManaModifier, ArmorModifier, ExperienceModifier, RacialLeader, movementId, RegenHealth, mechanic_immune_mask, spell_school_immune_mask, flags_extra, ScriptName FROM creature_template ct LEFT JOIN creature_template_movement ctm ON ct.entry = ctm.CreatureId WHERE entry = ?", CONNECTION_SYNCH); - PrepareStatement(WORLD_SEL_WAYPOINT_SCRIPT_BY_ID, "SELECT guid, delay, command, datalong, datalong2, dataint, x, y, z, o FROM waypoint_scripts WHERE id = ?", CONNECTION_SYNCH); - PrepareStatement(WORLD_SEL_ITEM_TEMPLATE_BY_NAME, "SELECT entry FROM item_template WHERE name = ?", CONNECTION_SYNCH); - PrepareStatement(WORLD_SEL_CREATURE_BY_ID, "SELECT guid FROM creature WHERE id1 = ? OR id2 = ? OR id3 = ?", CONNECTION_SYNCH); - PrepareStatement(WORLD_SEL_GAMEOBJECT_NEAREST, "SELECT guid, id, position_x, position_y, position_z, map, (POW(position_x - ?, 2) + POW(position_y - ?, 2) + POW(position_z - ?, 2)) AS order_ FROM gameobject WHERE map = ? AND (POW(position_x - ?, 2) + POW(position_y - ?, 2) + POW(position_z - ?, 2)) <= ? AND (phaseMask & ?) <> 0 ORDER BY order_", CONNECTION_SYNCH); - PrepareStatement(WORLD_SEL_CREATURE_NEAREST, "SELECT guid, id1, id2, id3, position_x, position_y, position_z, map, (POW(position_x - ?, 2) + POW(position_y - ?, 2) + POW(position_z - ?, 2)) AS order_ FROM creature WHERE map = ? AND (POW(position_x - ?, 2) + POW(position_y - ?, 2) + POW(position_z - ?, 2)) <= ? AND (phaseMask & ?) <> 0 ORDER BY order_", CONNECTION_SYNCH); - PrepareStatement(WORLD_INS_CREATURE, "INSERT INTO creature (guid, id1, id2, id3, map, spawnMask, phaseMask, equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, wander_distance, currentwaypoint, curhealth, curmana, MovementType, npcflag, unit_flags, dynamicflags) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(WORLD_DEL_GAME_EVENT_CREATURE, "DELETE FROM game_event_creature WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_DEL_GAME_EVENT_MODEL_EQUIP, "DELETE FROM game_event_model_equip WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_INS_GAMEOBJECT, "INSERT INTO gameobject (guid, id, map, spawnMask, phaseMask, position_x, position_y, position_z, orientation, rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(WORLD_INS_DISABLES, "INSERT INTO disables (entry, sourceType, flags, comment) VALUES (?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(WORLD_SEL_DISABLES, "SELECT entry FROM disables WHERE entry = ? AND sourceType = ?", CONNECTION_SYNCH); - PrepareStatement(WORLD_DEL_DISABLES, "DELETE FROM disables WHERE entry = ? AND sourceType = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_UPD_CREATURE_ZONE_AREA_DATA, "UPDATE creature SET zoneId = ?, areaId = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_UPD_GAMEOBJECT_ZONE_AREA_DATA, "UPDATE gameobject SET zoneId = ?, areaId = ? WHERE guid = ?", CONNECTION_ASYNC); - PrepareStatement(WORLD_INS_GAMEOBJECT_ADDON, "INSERT INTO gameobject_addon (guid, invisibilityType, invisibilityValue) VALUES (?, 0, 0)", CONNECTION_ASYNC); - // 0: uint8 - PrepareStatement(WORLD_SEL_REQ_XP, "SELECT Experience FROM player_xp_for_level WHERE Level = ?", CONNECTION_SYNCH); -} - -WorldDatabaseConnection::WorldDatabaseConnection(MySQLConnectionInfo& connInfo) : MySQLConnection(connInfo) +void WorldDatabasePool::DoPrepareStatements() { -} + SetStatementSize(MAX_WORLD_DATABASE_STATEMENTS); -WorldDatabaseConnection::WorldDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo) : MySQLConnection(q, connInfo) -{ -} + PrepareStatement(WORLD_SEL_QUEST_POOLS, "SELECT entry, pool_entry FROM pool_quest", ConnectionFlags::Sync); + PrepareStatement(WORLD_DEL_CRELINKED_RESPAWN, "DELETE FROM linked_respawn WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_REP_CREATURE_LINKED_RESPAWN, "REPLACE INTO linked_respawn (guid, linkedGuid) VALUES (?, ?)", ConnectionFlags::Async); + PrepareStatement(WORLD_SEL_CREATURE_TEXT, "SELECT CreatureID, GroupID, ID, Text, Type, Language, Probability, Emote, Duration, Sound, BroadcastTextId, TextRange FROM creature_text", ConnectionFlags::Sync); + PrepareStatement(WORLD_SEL_SMART_SCRIPTS, "SELECT entryorguid, source_type, id, link, event_type, event_phase_mask, event_chance, event_flags, event_param1, event_param2, event_param3, event_param4, event_param5, action_type, action_param1, action_param2, action_param3, action_param4, action_param5, action_param6, target_type, target_param1, target_param2, target_param3, target_param4, target_x, target_y, target_z, target_o FROM smart_scripts ORDER BY entryorguid, source_type, id, link", ConnectionFlags::Sync); + PrepareStatement(WORLD_SEL_SMARTAI_WP, "SELECT entry, pointid, position_x, position_y, position_z, orientation, delay FROM waypoints ORDER BY entry, pointid", ConnectionFlags::Sync); + PrepareStatement(WORLD_DEL_GAMEOBJECT, "DELETE FROM gameobject WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_DEL_EVENT_GAMEOBJECT, "DELETE FROM game_event_gameobject WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_INS_GRAVEYARD_ZONE, "INSERT INTO graveyard_zone (ID, GhostZone, Faction) VALUES (?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(WORLD_DEL_GRAVEYARD_ZONE, "DELETE FROM graveyard_zone WHERE ID = ? AND GhostZone = ? AND Faction = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_INS_GAME_TELE, "INSERT INTO game_tele (id, position_x, position_y, position_z, orientation, map, name) VALUES (?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(WORLD_DEL_GAME_TELE, "DELETE FROM game_tele WHERE name = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_INS_NPC_VENDOR, "INSERT INTO npc_vendor (entry, item, maxcount, incrtime, extendedcost) VALUES(?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(WORLD_DEL_NPC_VENDOR, "DELETE FROM npc_vendor WHERE entry = ? AND item = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_SEL_NPC_VENDOR_REF, "SELECT item, maxcount, incrtime, ExtendedCost FROM npc_vendor WHERE entry = ? ORDER BY slot ASC", ConnectionFlags::Sync); + PrepareStatement(WORLD_UPD_CREATURE_MOVEMENT_TYPE, "UPDATE creature SET MovementType = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_UPD_CREATURE_FACTION, "UPDATE creature_template SET faction = ? WHERE entry = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_UPD_CREATURE_NPCFLAG, "UPDATE creature_template SET npcflag = ? WHERE entry = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_UPD_CREATURE_POSITION, "UPDATE creature SET position_x = ?, position_y = ?, position_z = ?, orientation = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_UPD_CREATURE_WANDER_DISTANCE, "UPDATE creature SET wander_distance = ?, MovementType = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_UPD_CREATURE_SPAWN_TIME_SECS, "UPDATE creature SET spawntimesecs = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_INS_CREATURE_FORMATION, "INSERT INTO creature_formations (leaderGUID, memberGUID, dist, angle, groupAI) VALUES (?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(WORLD_INS_WAYPOINT_DATA, "INSERT INTO waypoint_data (id, point, position_x, position_y, position_z) VALUES (?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(WORLD_DEL_WAYPOINT_DATA, "DELETE FROM waypoint_data WHERE id = ? AND point = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_UPD_WAYPOINT_DATA_POINT, "UPDATE waypoint_data SET point = point - 1 WHERE id = ? AND point > ?", ConnectionFlags::Async); + PrepareStatement(WORLD_UPD_WAYPOINT_DATA_POSITION, "UPDATE waypoint_data SET position_x = ?, position_y = ?, position_z = ? where id = ? AND point = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_UPD_WAYPOINT_DATA_WPGUID, "UPDATE waypoint_data SET wpguid = ? WHERE id = ? and point = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_SEL_WAYPOINT_DATA_MAX_ID, "SELECT MAX(id) FROM waypoint_data", ConnectionFlags::Sync); + PrepareStatement(WORLD_SEL_WAYPOINT_DATA_MAX_POINT, "SELECT MAX(point) FROM waypoint_data WHERE id = ?", ConnectionFlags::Sync); + PrepareStatement(WORLD_SEL_WAYPOINT_DATA_BY_ID, "SELECT point, position_x, position_y, position_z, orientation, move_type, delay, action, action_chance FROM waypoint_data WHERE id = ? ORDER BY point", ConnectionFlags::Sync); + PrepareStatement(WORLD_SEL_WAYPOINT_DATA_POS_BY_ID, "SELECT point, position_x, position_y, position_z FROM waypoint_data WHERE id = ?", ConnectionFlags::Sync); + PrepareStatement(WORLD_SEL_WAYPOINT_DATA_POS_FIRST_BY_ID, "SELECT position_x, position_y, position_z FROM waypoint_data WHERE point = 1 AND id = ?", ConnectionFlags::Sync); + PrepareStatement(WORLD_SEL_WAYPOINT_DATA_POS_LAST_BY_ID, "SELECT position_x, position_y, position_z, orientation FROM waypoint_data WHERE id = ? ORDER BY point DESC LIMIT 1", ConnectionFlags::Sync); + PrepareStatement(WORLD_SEL_WAYPOINT_DATA_BY_WPGUID, "SELECT id, point FROM waypoint_data WHERE wpguid = ?", ConnectionFlags::Sync); + PrepareStatement(WORLD_SEL_WAYPOINT_DATA_ALL_BY_WPGUID, "SELECT id, point, delay, move_type, action, action_chance FROM waypoint_data WHERE wpguid = ?", ConnectionFlags::Sync); + PrepareStatement(WORLD_UPD_WAYPOINT_DATA_ALL_WPGUID, "UPDATE waypoint_data SET wpguid = 0", ConnectionFlags::Async); + PrepareStatement(WORLD_SEL_WAYPOINT_DATA_BY_POS, "SELECT id, point FROM waypoint_data WHERE (abs(position_x - ?) <= ?) and (abs(position_y - ?) <= ?) and (abs(position_z - ?) <= ?)", ConnectionFlags::Sync); + PrepareStatement(WORLD_SEL_WAYPOINT_DATA_WPGUID_BY_ID, "SELECT wpguid FROM waypoint_data WHERE id = ? and wpguid <> 0", ConnectionFlags::Sync); + PrepareStatement(WORLD_SEL_WAYPOINT_DATA_ACTION, "SELECT DISTINCT action FROM waypoint_data", ConnectionFlags::Sync); + PrepareStatement(WORLD_SEL_WAYPOINT_SCRIPTS_MAX_ID, "SELECT MAX(guid) FROM waypoint_scripts", ConnectionFlags::Sync); + PrepareStatement(WORLD_INS_CREATURE_ADDON, "INSERT INTO creature_addon(guid, path_id) VALUES (?, ?)", ConnectionFlags::Async); + PrepareStatement(WORLD_UPD_CREATURE_ADDON_PATH, "UPDATE creature_addon SET path_id = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_DEL_CREATURE_ADDON, "DELETE FROM creature_addon WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_SEL_CREATURE_ADDON_BY_GUID, "SELECT guid FROM creature_addon WHERE guid = ?", ConnectionFlags::Sync); + PrepareStatement(WORLD_INS_WAYPOINT_SCRIPT, "INSERT INTO waypoint_scripts (guid) VALUES (?)", ConnectionFlags::Async); + PrepareStatement(WORLD_DEL_WAYPOINT_SCRIPT, "DELETE FROM waypoint_scripts WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_UPD_WAYPOINT_SCRIPT_ID, "UPDATE waypoint_scripts SET id = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_UPD_WAYPOINT_SCRIPT_X, "UPDATE waypoint_scripts SET x = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_UPD_WAYPOINT_SCRIPT_Y, "UPDATE waypoint_scripts SET y = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_UPD_WAYPOINT_SCRIPT_Z, "UPDATE waypoint_scripts SET z = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_UPD_WAYPOINT_SCRIPT_O, "UPDATE waypoint_scripts SET o = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_SEL_WAYPOINT_SCRIPT_ID_BY_GUID, "SELECT id FROM waypoint_scripts WHERE guid = ?", ConnectionFlags::Sync); + PrepareStatement(WORLD_DEL_CREATURE, "DELETE FROM creature WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_SEL_COMMANDS, "SELECT name, security, help FROM command", ConnectionFlags::Sync); + PrepareStatement(WORLD_SEL_CREATURE_TEMPLATE, "SELECT entry, difficulty_entry_1, difficulty_entry_2, difficulty_entry_3, KillCredit1, KillCredit2, modelid1, modelid2, modelid3, modelid4, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, exp, faction, npcflag, speed_walk, speed_run, speed_swim, speed_flight, detection_range, scale, `rank`, dmgschool, DamageModifier, BaseAttackTime, RangeAttackTime, BaseVariance, RangeVariance, unit_class, unit_flags, unit_flags2, dynamicflags, family, trainer_type, trainer_spell, trainer_class, trainer_race, type, type_flags, lootid, pickpocketloot, skinloot, PetSpellDataId, VehicleId, mingold, maxgold, AIName, MovementType, ctm.Ground, ctm.Swim, ctm.Flight, ctm.Rooted, ctm.Chase, ctm.Random, ctm.InteractionPauseTimer, HoverHeight, HealthModifier, ManaModifier, ArmorModifier, ExperienceModifier, RacialLeader, movementId, RegenHealth, mechanic_immune_mask, spell_school_immune_mask, flags_extra, ScriptName FROM creature_template ct LEFT JOIN creature_template_movement ctm ON ct.entry = ctm.CreatureId WHERE entry = ?", ConnectionFlags::Sync); + PrepareStatement(WORLD_SEL_WAYPOINT_SCRIPT_BY_ID, "SELECT guid, delay, command, datalong, datalong2, dataint, x, y, z, o FROM waypoint_scripts WHERE id = ?", ConnectionFlags::Sync); + PrepareStatement(WORLD_SEL_ITEM_TEMPLATE_BY_NAME, "SELECT entry FROM item_template WHERE name = ?", ConnectionFlags::Sync); + PrepareStatement(WORLD_SEL_CREATURE_BY_ID, "SELECT guid FROM creature WHERE id1 = ? OR id2 = ? OR id3 = ?", ConnectionFlags::Sync); + PrepareStatement(WORLD_SEL_GAMEOBJECT_NEAREST, "SELECT guid, id, position_x, position_y, position_z, map, (POW(position_x - ?, 2) + POW(position_y - ?, 2) + POW(position_z - ?, 2)) AS order_ FROM gameobject WHERE map = ? AND (POW(position_x - ?, 2) + POW(position_y - ?, 2) + POW(position_z - ?, 2)) <= ? AND (phaseMask & ?) <> 0 ORDER BY order_", ConnectionFlags::Sync); + PrepareStatement(WORLD_SEL_CREATURE_NEAREST, "SELECT guid, id1, id2, id3, position_x, position_y, position_z, map, (POW(position_x - ?, 2) + POW(position_y - ?, 2) + POW(position_z - ?, 2)) AS order_ FROM creature WHERE map = ? AND (POW(position_x - ?, 2) + POW(position_y - ?, 2) + POW(position_z - ?, 2)) <= ? AND (phaseMask & ?) <> 0 ORDER BY order_", ConnectionFlags::Sync); + PrepareStatement(WORLD_INS_CREATURE, "INSERT INTO creature (guid, id1, id2, id3, map, spawnMask, phaseMask, equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, wander_distance, currentwaypoint, curhealth, curmana, MovementType, npcflag, unit_flags, dynamicflags) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(WORLD_DEL_GAME_EVENT_CREATURE, "DELETE FROM game_event_creature WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_DEL_GAME_EVENT_MODEL_EQUIP, "DELETE FROM game_event_model_equip WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_INS_GAMEOBJECT, "INSERT INTO gameobject (guid, id, map, spawnMask, phaseMask, position_x, position_y, position_z, orientation, rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(WORLD_INS_DISABLES, "INSERT INTO disables (entry, sourceType, flags, comment) VALUES (?, ?, ?, ?)", ConnectionFlags::Async); + PrepareStatement(WORLD_SEL_DISABLES, "SELECT entry FROM disables WHERE entry = ? AND sourceType = ?", ConnectionFlags::Sync); + PrepareStatement(WORLD_DEL_DISABLES, "DELETE FROM disables WHERE entry = ? AND sourceType = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_UPD_CREATURE_ZONE_AREA_DATA, "UPDATE creature SET zoneId = ?, areaId = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_UPD_GAMEOBJECT_ZONE_AREA_DATA, "UPDATE gameobject SET zoneId = ?, areaId = ? WHERE guid = ?", ConnectionFlags::Async); + PrepareStatement(WORLD_INS_GAMEOBJECT_ADDON, "INSERT INTO gameobject_addon (guid, invisibilityType, invisibilityValue) VALUES (?, 0, 0)", ConnectionFlags::Async); -WorldDatabaseConnection::~WorldDatabaseConnection() -{ + // 0: uint8 + PrepareStatement(WORLD_SEL_REQ_XP, "SELECT Experience FROM player_xp_for_level WHERE Level = ?", ConnectionFlags::Sync); } diff --git a/src/server/database/Database/Implementation/WorldDatabase.h b/src/server/database/Database/Implementation/WorldDatabase.h index 527d74764b9f32..c1c54fac33fb30 100644 --- a/src/server/database/Database/Implementation/WorldDatabase.h +++ b/src/server/database/Database/Implementation/WorldDatabase.h @@ -18,7 +18,7 @@ #ifndef _WORLDDATABASE_H #define _WORLDDATABASE_H -#include "MySQLConnection.h" +#include "DatabaseWorkerPool.h" enum WorldDatabaseStatements : uint32 { @@ -101,21 +101,20 @@ enum WorldDatabaseStatements : uint32 WORLD_SEL_REQ_XP, WORLD_INS_GAMEOBJECT_ADDON, - MAX_WORLDDATABASE_STATEMENTS + MAX_WORLD_DATABASE_STATEMENTS }; -class AC_DATABASE_API WorldDatabaseConnection : public MySQLConnection +class AC_DATABASE_API WorldDatabasePool : public DatabaseWorkerPool { public: - typedef WorldDatabaseStatements Statements; - - //- Constructors for sync and async connections - WorldDatabaseConnection(MySQLConnectionInfo& connInfo); - WorldDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo); - ~WorldDatabaseConnection() override; + WorldDatabasePool() : DatabaseWorkerPool(DatabaseType::World) { } + ~WorldDatabasePool() = default; //- Loads database type specific prepared statements void DoPrepareStatements() override; }; +/// Accessor to the world database +AC_DATABASE_API extern WorldDatabasePool WorldDatabase; + #endif diff --git a/src/server/database/Database/MySQLConnection.cpp b/src/server/database/Database/MySQLConnection.cpp index 20c410de0adb80..7a750c3f4964f5 100644 --- a/src/server/database/Database/MySQLConnection.cpp +++ b/src/server/database/Database/MySQLConnection.cpp @@ -16,20 +16,40 @@ */ #include "MySQLConnection.h" -#include "DatabaseWorker.h" +#include "DatabaseAsyncOperation.h" +#include "DatabaseAsyncQueueWorker.h" +#include "Errors.h" #include "Log.h" #include "MySQLHacks.h" #include "MySQLPreparedStatement.h" -#include "MySQLWorkaround.h" +#include "PCQueue.h" #include "PreparedStatement.h" #include "QueryResult.h" +#include "StopWatch.h" #include "StringConvert.h" -#include "Timer.h" #include "Tokenize.h" #include "Transaction.h" -#include "Util.h" #include +#include #include +#include + +namespace +{ + constexpr auto DB_DEFAULT_CHARSET = "utf8mb4"; + constexpr auto DYNAMIC_CONNECTION_TIMEOUT = 1s; + + std::string GetConnectionFlagString(ConnectionFlags flag) + { + switch (flag) + { + case ConnectionFlags::Async: return "Async"; + case ConnectionFlags::Sync: return "Sync"; + case ConnectionFlags::Both: return "Both"; + default: return "Unknown"; + } + } +} MySQLConnectionInfo::MySQLConnectionInfo(std::string_view infoString) { @@ -38,333 +58,450 @@ MySQLConnectionInfo::MySQLConnectionInfo(std::string_view infoString) if (tokens.size() != 5 && tokens.size() != 6) return; - host.assign(tokens.at(0)); - port_or_socket.assign(tokens.at(1)); - user.assign(tokens.at(2)); - password.assign(tokens.at(3)); - database.assign(tokens.at(4)); + Host.assign(tokens.at(0)); + PortOrSocket.assign(tokens.at(1)); + User.assign(tokens.at(2)); + Password.assign(tokens.at(3)); + Database.assign(tokens.at(4)); if (tokens.size() == 6) - ssl.assign(tokens.at(5)); + SSL.assign(tokens.at(5)); } -MySQLConnection::MySQLConnection(MySQLConnectionInfo& connInfo) : - m_reconnecting(false), - m_prepareError(false), - m_Mysql(nullptr), - m_queue(nullptr), - m_connectionInfo(connInfo), - m_connectionFlags(CONNECTION_SYNCH) { } - -MySQLConnection::MySQLConnection(ProducerConsumerQueue* queue, MySQLConnectionInfo& connInfo) : - m_reconnecting(false), - m_prepareError(false), - m_Mysql(nullptr), - m_queue(queue), - m_connectionInfo(connInfo), - m_connectionFlags(CONNECTION_ASYNC) +MySQLConnection::MySQLConnection(MySQLConnectionInfo& connInfo, ProducerConsumerQueue* dbQueue, bool isDynamic /*= false*/) : + _connectionInfo(connInfo), + _isDynamic(isDynamic), + _connectionFlags(dbQueue ? ConnectionFlags::Async : ConnectionFlags::Sync), + _queue(dbQueue) { - m_worker = std::make_unique(m_queue, this); + if (_queue) + _asyncQueueWorker = std::make_unique(_queue, this); + + UpdateLastUseTime(); } MySQLConnection::~MySQLConnection() { Close(); + LOG_DEBUG("db.connection", "> Close {} connection to '{}' db", GetConnectionFlagString(_connectionFlags), _connectionInfo.Database); } void MySQLConnection::Close() { - // Stop the worker thread before the statements are cleared - m_worker.reset(); - m_stmts.clear(); + _asyncQueueWorker.reset(); - if (m_Mysql) + if (_mysqlHandle) { - mysql_close(m_Mysql); - m_Mysql = nullptr; + mysql_close(_mysqlHandle); + _mysqlHandle = nullptr; } } uint32 MySQLConnection::Open() { - MYSQL* mysqlInit = mysql_init(nullptr); + auto mysqlInit = mysql_init(nullptr); if (!mysqlInit) { - LOG_ERROR("sql.driver", "Could not initialize Mysql connection to database `{}`", m_connectionInfo.database); + LOG_ERROR("db.connection", "Could not initialize Mysql connection to database `{}`", _connectionInfo.Database); return CR_UNKNOWN_ERROR; } - uint32 port; - char const* unix_socket; + uint32 port{}; + char const* unix_socket{ nullptr }; - mysql_options(mysqlInit, MYSQL_SET_CHARSET_NAME, "utf8"); + mysql_options(mysqlInit, MYSQL_SET_CHARSET_NAME, DB_DEFAULT_CHARSET); -#ifdef _WIN32 - if (m_connectionInfo.host == ".") // named pipe use option (Windows) + if (_connectionInfo.Host == ".") { +#if AC_PLATFORM == AC_PLATFORM_WINDOWS unsigned int opt = MYSQL_PROTOCOL_PIPE; - mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt); - port = 0; - unix_socket = 0; - } - else // generic case - { - port = *Acore::StringTo(m_connectionInfo.port_or_socket); - unix_socket = 0; - } #else - if (m_connectionInfo.host == ".") // socket use option (Unix/Linux) - { unsigned int opt = MYSQL_PROTOCOL_SOCKET; +#endif mysql_options(mysqlInit, MYSQL_OPT_PROTOCOL, (char const*)&opt); - m_connectionInfo.host = "localhost"; - port = 0; - unix_socket = m_connectionInfo.port_or_socket.c_str(); - } - else // generic case - { - port = *Acore::StringTo(m_connectionInfo.port_or_socket); - unix_socket = nullptr; - } + +#if AC_PLATFORM != AC_PLATFORM_WINDOWS + _connectionInfo.Host = "localhost"; + unix_socket = _connectionInfo.PortOrSocket.c_str(); #endif + } + else + port = *Acore::StringTo(_connectionInfo.PortOrSocket); - if (m_connectionInfo.ssl != "") + if (!_connectionInfo.SSL.empty() && _connectionInfo.SSL == "ssl") { #if !defined(MARIADB_VERSION_ID) && MYSQL_VERSION_ID >= 80000 mysql_ssl_mode opt_use_ssl = SSL_MODE_DISABLED; - if (m_connectionInfo.ssl == "ssl") - { - opt_use_ssl = SSL_MODE_REQUIRED; - } - mysql_options(mysqlInit, MYSQL_OPT_SSL_MODE, (char const*)&opt_use_ssl); #else - MySQLBool opt_use_ssl = MySQLBool(0); - if (m_connectionInfo.ssl == "ssl") - { - opt_use_ssl = MySQLBool(1); - } - + auto opt_use_ssl = MySQLBool(1); mysql_options(mysqlInit, MYSQL_OPT_SSL_ENFORCE, (char const*)&opt_use_ssl); #endif } - m_Mysql = reinterpret_cast(mysql_real_connect(mysqlInit, m_connectionInfo.host.c_str(), m_connectionInfo.user.c_str(), - m_connectionInfo.password.c_str(), m_connectionInfo.database.c_str(), port, unix_socket, 0)); + _mysqlHandle = reinterpret_cast(mysql_real_connect(mysqlInit, _connectionInfo.Host.c_str(), _connectionInfo.User.c_str(), + _connectionInfo.Password.c_str(), _connectionInfo.Database.c_str(), port, unix_socket, 0)); - if (m_Mysql) + if (_mysqlHandle) { - if (!m_reconnecting) - { - LOG_INFO("sql.sql", "MySQL client library: {}", mysql_get_client_info()); - LOG_INFO("sql.sql", "MySQL server ver: {} ", mysql_get_server_info(m_Mysql)); - } - - LOG_INFO("sql.sql", "Connected to MySQL database at {}", m_connectionInfo.host); - mysql_autocommit(m_Mysql, 1); + LOG_MESSAGE_BODY("db.connection", _isDynamic ? LOG_LEVEL_DEBUG : LOG_LEVEL_INFO, "Open new {} connect to {} DB at {}", GetConnectionFlagString(_connectionFlags), _connectionInfo.Database, _connectionInfo.Host); + mysql_autocommit(_mysqlHandle, 1); // set connection properties to UTF8 to properly handle locales for different // server configs - core sends data in UTF8, so MySQL must expect UTF8 too - mysql_set_character_set(m_Mysql, "utf8mb4"); + mysql_set_character_set(_mysqlHandle, DB_DEFAULT_CHARSET); return 0; } else { - LOG_ERROR("sql.driver", "Could not connect to MySQL database at {}: {}", m_connectionInfo.host, mysql_error(mysqlInit)); uint32 errorCode = mysql_errno(mysqlInit); + LOG_ERROR("db.connection", "[{}]: Could not connect to MySQL database {} at {}: {}", errorCode, _connectionInfo.Database, _connectionInfo.Host, mysql_error(mysqlInit)); mysql_close(mysqlInit); return errorCode; } } -bool MySQLConnection::PrepareStatements() -{ - DoPrepareStatements(); - return !m_prepareError; -} - bool MySQLConnection::Execute(std::string_view sql) { - if (!m_Mysql) + if (!_mysqlHandle || sql.empty()) return false; { - uint32 _s = getMSTime(); + StopWatch sw; - if (mysql_query(m_Mysql, std::string(sql).c_str())) + if (mysql_query(_mysqlHandle, sql.data())) { - uint32 lErrno = mysql_errno(m_Mysql); + uint32 err = mysql_errno(_mysqlHandle); - LOG_INFO("sql.sql", "SQL: {}", sql); - LOG_ERROR("sql.sql", "[{}] {}", lErrno, mysql_error(m_Mysql)); + LOG_ERROR("db.query", "[{}] {}", err, mysql_error(_mysqlHandle)); + LOG_ERROR("db.query", "Query: {}", sql); - if (_HandleMySQLErrno(lErrno)) // If it returns true, an error was handled successfully (i.e. reconnection) - return Execute(sql); // Try again + if (HandleMySQLError(err)) // If it returns true, an error was handled successfully (i.e. reconnection) + return Execute(sql); // Try again return false; } else - LOG_DEBUG("sql.sql", "[{} ms] SQL: {}", getMSTimeDiff(_s, getMSTime()), sql); + LOG_DEBUG("db.query", "[{}] Query: {}", sw, sql); } + UpdateLastUseTime(); return true; } -bool MySQLConnection::Execute(PreparedStatementBase* stmt) +bool MySQLConnection::Execute(PreparedStatement stmt) { - if (!m_Mysql) + if (!_mysqlHandle || !stmt) return false; uint32 index = stmt->GetIndex(); - MySQLPreparedStatement* m_mStmt = GetPreparedStatement(index); - ASSERT(m_mStmt); // Can only be null if preparation failed, server side error or bad query + MySQLPreparedStatement* mStmt = GetPreparedStatement(index); + ASSERT(mStmt); // Can only be null if preparation failed, server side error or bad query - m_mStmt->BindParameters(stmt); + mStmt->BindParameters(stmt); - MYSQL_STMT* msql_STMT = m_mStmt->GetSTMT(); - MYSQL_BIND* msql_BIND = m_mStmt->GetBind(); + MYSQL_STMT* msql_STMT = mStmt->GetSTMT(); + MYSQL_BIND* msql_BIND = mStmt->GetBind(); - uint32 _s = getMSTime(); + StopWatch sw; if (mysql_stmt_bind_param(msql_STMT, msql_BIND)) { - uint32 lErrno = mysql_errno(m_Mysql); - LOG_ERROR("sql.sql", "SQL(p): {}\n [ERROR]: [{}] {}", m_mStmt->getQueryString(), lErrno, mysql_stmt_error(msql_STMT)); + uint32 err = mysql_errno(_mysqlHandle); + LOG_ERROR("db.query", "[{}] {}", err, mysql_stmt_error(msql_STMT)); + LOG_ERROR("db.query", "Query(p): {}", mStmt->getQueryString()); - if (_HandleMySQLErrno(lErrno)) // If it returns true, an error was handled successfully (i.e. reconnection) - return Execute(stmt); // Try again + if (HandleMySQLError(err)) // If it returns true, an error was handled successfully (i.e. reconnection) + return Execute(stmt); // Try again - m_mStmt->ClearParameters(); + mStmt->ClearParameters(); return false; } if (mysql_stmt_execute(msql_STMT)) { - uint32 lErrno = mysql_errno(m_Mysql); - LOG_ERROR("sql.sql", "SQL(p): {}\n [ERROR]: [{}] {}", m_mStmt->getQueryString(), lErrno, mysql_stmt_error(msql_STMT)); + uint32 err = mysql_errno(_mysqlHandle); + LOG_ERROR("db.query", "[{}] {}", err, mysql_stmt_error(msql_STMT)); + LOG_ERROR("db.query", "Query(p): {}", mStmt->getQueryString()); - if (_HandleMySQLErrno(lErrno)) // If it returns true, an error was handled successfully (i.e. reconnection) - return Execute(stmt); // Try again + if (HandleMySQLError(err)) // If it returns true, an error was handled successfully (i.e. reconnection) + return Execute(stmt); // Try again - m_mStmt->ClearParameters(); + mStmt->ClearParameters(); return false; } - LOG_DEBUG("sql.sql", "[{} ms] SQL(p): {}", getMSTimeDiff(_s, getMSTime()), m_mStmt->getQueryString()); + LOG_DEBUG("db.query", "[{}] Query(p): {}", sw, mStmt->getQueryString()); - m_mStmt->ClearParameters(); + mStmt->ClearParameters(); + UpdateLastUseTime(); return true; } -bool MySQLConnection::_Query(PreparedStatementBase* stmt, MySQLPreparedStatement** mysqlStmt, MySQLResult** pResult, uint64* pRowCount, uint32* pFieldCount) +QueryResult MySQLConnection::Query(std::string_view sql) +{ + if (sql.empty()) + return nullptr; + + MySQLResult* result = nullptr; + MySQLField* fields = nullptr; + uint64 rowCount = 0; + uint32 fieldCount = 0; + + if (!Query(sql, &result, &fields, &rowCount, &fieldCount)) + return nullptr; + + UpdateLastUseTime(); + return std::make_shared(result, fields, rowCount, fieldCount); +} + +PreparedQueryResult MySQLConnection::Query(PreparedStatement stmt) +{ + MySQLPreparedStatement* mysqlStmt = nullptr; + MySQLResult* result = nullptr; + uint64 rowCount = 0; + uint32 fieldCount = 0; + + if (!Query(std::move(stmt), &mysqlStmt, &result, &rowCount, &fieldCount)) + return nullptr; + + if (mysql_more_results(_mysqlHandle)) + mysql_next_result(_mysqlHandle); + + UpdateLastUseTime(); + return std::make_shared(mysqlStmt->GetSTMT(), result, rowCount, fieldCount); +} + +bool MySQLConnection::Query(std::string_view sql, MySQLResult** result, MySQLField** fields, uint64* rowCount, uint32* fieldCount) { - if (!m_Mysql) + if (!_mysqlHandle || sql.empty()) + return false; + + { + StopWatch sw; + + if (mysql_query(_mysqlHandle, sql.data())) + { + uint32 err = mysql_errno(_mysqlHandle); + LOG_ERROR("db.query", "[{}] {}", err, mysql_error(_mysqlHandle)); + LOG_ERROR("db.query", "Query: {}", sql); + + if (HandleMySQLError(err)) // If it returns true, an error was handled successfully (i.e. reconnection) + return Query(sql, result, fields, rowCount, fieldCount); // We try again + + return false; + } + else + LOG_DEBUG("db.query", "[{}] Query: {}", sw, sql); + + *result = reinterpret_cast(mysql_store_result(_mysqlHandle)); + *rowCount = mysql_affected_rows(_mysqlHandle); + *fieldCount = mysql_field_count(_mysqlHandle); + } + + if (!*result) + return false; + + if (!*rowCount) + { + mysql_free_result(*result); + return false; + } + + *fields = reinterpret_cast(mysql_fetch_fields(*result)); + return true; +} + +bool MySQLConnection::Query(PreparedStatement stmt, MySQLPreparedStatement** mysqlStmt, MySQLResult** result, uint64* rowCount, uint32* fieldCount) +{ + if (!_mysqlHandle) return false; uint32 index = stmt->GetIndex(); - MySQLPreparedStatement* m_mStmt = GetPreparedStatement(index); - ASSERT(m_mStmt); // Can only be null if preparation failed, server side error or bad query + MySQLPreparedStatement* mStmt = GetPreparedStatement(index); + ASSERT(mStmt); // Can only be null if preparation failed, server side error or bad query - m_mStmt->BindParameters(stmt); - *mysqlStmt = m_mStmt; + mStmt->BindParameters(stmt); + *mysqlStmt = mStmt; - MYSQL_STMT* msql_STMT = m_mStmt->GetSTMT(); - MYSQL_BIND* msql_BIND = m_mStmt->GetBind(); + MYSQL_STMT* msql_STMT = mStmt->GetSTMT(); + MYSQL_BIND* msql_BIND = mStmt->GetBind(); - uint32 _s = getMSTime(); + StopWatch sw; if (mysql_stmt_bind_param(msql_STMT, msql_BIND)) { - uint32 lErrno = mysql_errno(m_Mysql); - LOG_ERROR("sql.sql", "SQL(p): {}\n [ERROR]: [{}] {}", m_mStmt->getQueryString(), lErrno, mysql_stmt_error(msql_STMT)); + uint32 err = mysql_errno(_mysqlHandle); + LOG_ERROR("db.query", "[{}] {}", err, mysql_stmt_error(msql_STMT)); + LOG_ERROR("db.query", "Query: {}", mStmt->getQueryString()); - if (_HandleMySQLErrno(lErrno)) // If it returns true, an error was handled successfully (i.e. reconnection) - return _Query(stmt, mysqlStmt, pResult, pRowCount, pFieldCount); // Try again + if (HandleMySQLError(err)) // If it returns true, an error was handled successfully (i.e. reconnection) + return Query(stmt, mysqlStmt, result, rowCount, fieldCount); // Try again - m_mStmt->ClearParameters(); + mStmt->ClearParameters(); return false; } if (mysql_stmt_execute(msql_STMT)) { - uint32 lErrno = mysql_errno(m_Mysql); - LOG_ERROR("sql.sql", "SQL(p): {}\n [ERROR]: [{}] {}", m_mStmt->getQueryString(), lErrno, mysql_stmt_error(msql_STMT)); + uint32 err = mysql_errno(_mysqlHandle); + LOG_ERROR("db.query", "[{}] {}", err, mysql_stmt_error(msql_STMT)); + LOG_ERROR("db.query", "Query: {}", mStmt->getQueryString()); - if (_HandleMySQLErrno(lErrno)) // If it returns true, an error was handled successfully (i.e. reconnection) - return _Query(stmt, mysqlStmt, pResult, pRowCount, pFieldCount); // Try again + if (HandleMySQLError(err)) // If it returns true, an error was handled successfully (i.e. reconnection) + return Query(stmt, mysqlStmt, result, rowCount, fieldCount); // Try again - m_mStmt->ClearParameters(); + mStmt->ClearParameters(); return false; } - LOG_DEBUG("sql.sql", "[{} ms] SQL(p): {}", getMSTimeDiff(_s, getMSTime()), m_mStmt->getQueryString()); - - m_mStmt->ClearParameters(); + LOG_DEBUG("db.query", "[{}] Query(p): {}", sw, mStmt->getQueryString()); - *pResult = reinterpret_cast(mysql_stmt_result_metadata(msql_STMT)); - *pRowCount = mysql_stmt_affected_rows(msql_STMT); - *pFieldCount = mysql_stmt_field_count(msql_STMT); + mStmt->ClearParameters(); + *result = reinterpret_cast(mysql_stmt_result_metadata(msql_STMT)); + *rowCount = mysql_stmt_num_rows(msql_STMT); + *fieldCount = mysql_stmt_field_count(msql_STMT); return true; } -ResultSet* MySQLConnection::Query(std::string_view sql) +/*static*/ std::string_view MySQLConnection::GetClientInfo() { - if (sql.empty()) - return nullptr; - - MySQLResult* result = nullptr; - MySQLField* fields = nullptr; - uint64 rowCount = 0; - uint32 fieldCount = 0; - - if (!_Query(sql, &result, &fields, &rowCount, &fieldCount)) - return nullptr; - - return new ResultSet(result, fields, rowCount, fieldCount); + return { mysql_get_client_info() }; } -bool MySQLConnection::_Query(std::string_view sql, MySQLResult** pResult, MySQLField** pFields, uint64* pRowCount, uint32* pFieldCount) +std::string_view MySQLConnection::GetServerInfo() { - if (!m_Mysql) - return false; + return { mysql_get_server_info(_mysqlHandle) }; +} +bool MySQLConnection::HandleMySQLError(uint32 errNo, uint8 attempts /*= 5*/) +{ + switch (errNo) { - uint32 _s = getMSTime(); + case CR_SERVER_GONE_ERROR: + case CR_SERVER_LOST: + case CR_SERVER_LOST_EXTENDED: + { + if (_mysqlHandle) + { + LOG_ERROR("db.connection", "Lost the connection to the MySQL server!"); - if (mysql_query(m_Mysql, std::string(sql).c_str())) + mysql_close(_mysqlHandle); + _mysqlHandle = nullptr; + } + [[fallthrough]]; + } + case CR_CONN_HOST_ERROR: { - uint32 lErrno = mysql_errno(m_Mysql); - LOG_INFO("sql.sql", "SQL: {}", sql); - LOG_ERROR("sql.sql", "[{}] {}", lErrno, mysql_error(m_Mysql)); + LOG_INFO("db.connection", "Attempting to reconnect to the MySQL server..."); - if (_HandleMySQLErrno(lErrno)) // If it returns true, an error was handled successfully (i.e. reconnection) - return _Query(sql, pResult, pFields, pRowCount, pFieldCount); // We try again + uint32 const lErrno = Open(); + if (!lErrno) + { + if (!this->PrepareStatements()) + { + LOG_FATAL("db.connection", "Could not re-prepare statements!"); + ABORT("Could not re-prepare statements!"); + } - return false; + LOG_INFO("db.connection", "Successfully reconnected to {} @{}:{} Connection flags: {}.", + _connectionInfo.Database, _connectionInfo.Host, _connectionInfo.PortOrSocket, (uint8)_connectionFlags); + + return true; + } + + if ((--attempts) == 0) + { + // Shut down the server when the mysql server isn't + // reachable for some time + LOG_FATAL("db.connection", "Failed to reconnect to the MySQL server, terminating the server to prevent data corruption!"); + + // We could also initiate a shutdown through using std::raise(SIGTERM) + ABORT("Failed to reconnect to the MySQL server, terminating the server to prevent data corruption!"); + } + else + { + // It's possible this attempted to reconnect throws 2006 at us. + // To prevent crazy recursive calls, sleep here. + std::this_thread::sleep_for(3s); // Sleep 3 seconds + return HandleMySQLError(lErrno, attempts); // Call self (recursive) + } } - else - LOG_DEBUG("sql.sql", "[{} ms] SQL: {}", getMSTimeDiff(_s, getMSTime()), sql); - *pResult = reinterpret_cast(mysql_store_result(m_Mysql)); - *pRowCount = mysql_affected_rows(m_Mysql); - *pFieldCount = mysql_field_count(m_Mysql); + case ER_LOCK_DEADLOCK: // Implemented in TransactionTask::Execute and DatabaseWorkerPool::DirectCommitTransaction + case ER_WRONG_VALUE_COUNT: // Query related errors - skip query + case ER_DUP_ENTRY: + return false; + + // Outdated table or database structure - terminate core + case ER_BAD_FIELD_ERROR: + case ER_NO_SUCH_TABLE: + LOG_ERROR("db.connection", "Your database structure is not up to date. Please make sure you've executed all queries in the sql/updates folders."); + ABORT("Your database structure is not up to date. Please make sure you've executed all queries in the sql/updates folders."); + return false; + + case ER_PARSE_ERROR: + LOG_ERROR("db.connection", "Error while parsing SQL. Core fix required."); + ABORT("Error while parsing SQL. Core fix required."); + return false; + default: + LOG_ERROR("db.connection", "Unhandled MySQL errno {}. Unexpected behaviour possible.", errNo); + return false; } +} - if (!*pResult) - return false; +bool MySQLConnection::PrepareStatements() const +{ + return !_prepareError; +} + +MySQLPreparedStatement* MySQLConnection::GetPreparedStatement(uint32 index) +{ + ASSERT(index < _stmtList.size(), "Tried to access invalid prepared statement index {} (max index {}) on database `{}`, connection type: {}", + index, _stmtList.size(), _connectionInfo.Database, GetConnectionFlagString(_connectionFlags)); + + MySQLPreparedStatement* ret = _stmtList[index].get(); + + if (!ret) + LOG_ERROR("db.connection", "Could not fetch prepared statement {} on database `{}`, connection type: {}.", + index, _connectionInfo.Database, GetConnectionFlagString(_connectionFlags)); + + return ret; +} - if (!*pRowCount) +void MySQLConnection::PrepareStatement(uint32 index, std::string_view sql, ConnectionFlags flags) +{ + // Check if specified query should be prepared on this connection + // i.e. don't prepare async statements on synchronous connections + // to save memory that will not be used. + if (!((uint8)_connectionFlags & (uint8)flags)) { - mysql_free_result(*pResult); - return false; + _stmtList[index].reset(); + return; } - *pFields = reinterpret_cast(mysql_fetch_fields(*pResult)); - - return true; + MYSQL_STMT* stmt = mysql_stmt_init(_mysqlHandle); + if (!stmt) + { + LOG_ERROR("db.connection", "In mysql_stmt_init() id: {}, sql: \"{}\"", index, sql); + LOG_ERROR("db.connection", "{}", mysql_error(_mysqlHandle)); + _prepareError = true; + } + else + { + if (mysql_stmt_prepare(stmt, sql.data(), static_cast(sql.size()))) + { + LOG_ERROR("db.connection", "In mysql_stmt_prepare() id: {}, sql: \"{}\"", index, sql); + LOG_ERROR("db.connection", "{}", mysql_stmt_error(stmt)); + mysql_stmt_close(stmt); + _prepareError = true; + } + else + _stmtList[index] = std::make_unique(reinterpret_cast(stmt), sql); + } } void MySQLConnection::BeginTransaction() @@ -382,38 +519,38 @@ void MySQLConnection::CommitTransaction() Execute("COMMIT"); } -int MySQLConnection::ExecuteTransaction(std::shared_ptr transaction) +int32 MySQLConnection::ExecuteTransaction(SQLTransaction transaction) { - std::vector const& queries = transaction->m_queries; - if (queries.empty()) + auto const& queries = transaction->GetQueries(); + if (queries->empty()) return -1; BeginTransaction(); - for (auto const& data : queries) + for (auto const& data : *queries) { switch (data.type) { case SQL_ELEMENT_PREPARED: { - PreparedStatementBase* stmt = nullptr; + PreparedStatement stmt; try { - stmt = std::get(data.element); + stmt = std::get(data.element); } catch (const std::bad_variant_access& ex) { - LOG_FATAL("sql.sql", "> PreparedStatementBase not found in SQLElementData. {}", ex.what()); - ABORT(); + LOG_FATAL("db.query", "> PreparedStatementBase not found in SQLElementData. {}", ex.what()); + ABORT("> PreparedStatementBase not found in SQLElementData. {}", ex.what()); } ASSERT(stmt); if (!Execute(stmt)) { - LOG_WARN("sql.sql", "Transaction aborted. {} queries not executed.", queries.size()); - int errorCode = GetLastError(); + LOG_WARN("db.query", "Transaction aborted. {} queries not executed.", queries->size()); + int32 errorCode = GetLastError(); RollbackTransaction(); return errorCode; } @@ -421,7 +558,7 @@ int MySQLConnection::ExecuteTransaction(std::shared_ptr transac break; case SQL_ELEMENT_RAW: { - std::string sql{}; + std::string sql; try { @@ -429,16 +566,16 @@ int MySQLConnection::ExecuteTransaction(std::shared_ptr transac } catch (const std::bad_variant_access& ex) { - LOG_FATAL("sql.sql", "> std::string not found in SQLElementData. {}", ex.what()); - ABORT(); + LOG_FATAL("db.query", "> std::string not found in SQLElementData. {}", ex.what()); + ABORT("> std::string not found in SQLElementData. {}", ex.what()); } ASSERT(!sql.empty()); if (!Execute(sql)) { - LOG_WARN("sql.sql", "Transaction aborted. {} queries not executed.", queries.size()); - uint32 errorCode = GetLastError(); + LOG_WARN("db.query", "Transaction aborted. {} queries not executed.", queries->size()); + int32 errorCode = GetLastError(); RollbackTransaction(); return errorCode; } @@ -451,188 +588,43 @@ int MySQLConnection::ExecuteTransaction(std::shared_ptr transac // we might want to restart the transaction. So to prevent data loss, we only clean up when it's all done. // This is done in calling functions DatabaseWorkerPool::DirectCommitTransaction and TransactionTask::Execute, // and not while iterating over every element. - CommitTransaction(); return 0; } -size_t MySQLConnection::EscapeString(char* to, const char* from, size_t length) +std::size_t MySQLConnection::EscapeString(char* to, const char* from, std::size_t length) { - return mysql_real_escape_string(m_Mysql, to, from, length); + return mysql_real_escape_string(_mysqlHandle, to, from, length); } void MySQLConnection::Ping() { - mysql_ping(m_Mysql); -} - -uint32 MySQLConnection::GetLastError() -{ - return mysql_errno(m_Mysql); -} - -bool MySQLConnection::LockIfReady() -{ - return m_Mutex.try_lock(); + mysql_ping(_mysqlHandle); } -void MySQLConnection::Unlock() +int32 MySQLConnection::GetLastError() { - m_Mutex.unlock(); + return mysql_errno(_mysqlHandle); } uint32 MySQLConnection::GetServerVersion() const { - return mysql_get_server_version(m_Mysql); -} - -MySQLPreparedStatement* MySQLConnection::GetPreparedStatement(uint32 index) -{ - ASSERT(index < m_stmts.size(), "Tried to access invalid prepared statement index {} (max index {}) on database `{}`, connection type: {}", - index, m_stmts.size(), m_connectionInfo.database, (m_connectionFlags & CONNECTION_ASYNC) ? "asynchronous" : "synchronous"); - - MySQLPreparedStatement* ret = m_stmts[index].get(); - - if (!ret) - LOG_ERROR("sql.sql", "Could not fetch prepared statement {} on database `{}`, connection type: {}.", - index, m_connectionInfo.database, (m_connectionFlags & CONNECTION_ASYNC) ? "asynchronous" : "synchronous"); - - return ret; + return mysql_get_server_version(_mysqlHandle); } -void MySQLConnection::PrepareStatement(uint32 index, std::string_view sql, ConnectionFlags flags) +bool MySQLConnection::CanRemoveConnection() { - // Check if specified query should be prepared on this connection - // i.e. don't prepare async statements on synchronous connections - // to save memory that will not be used. - if (!(m_connectionFlags & flags)) - { - m_stmts[index].reset(); - return; - } - - MYSQL_STMT* stmt = mysql_stmt_init(m_Mysql); - if (!stmt) - { - LOG_ERROR("sql.sql", "In mysql_stmt_init() id: {}, sql: \"{}\"", index, sql); - LOG_ERROR("sql.sql", "{}", mysql_error(m_Mysql)); - m_prepareError = true; - } - else - { - if (mysql_stmt_prepare(stmt, std::string(sql).c_str(), static_cast(sql.size()))) - { - LOG_ERROR("sql.sql", "In mysql_stmt_prepare() id: {}, sql: \"{}\"", index, sql); - LOG_ERROR("sql.sql", "{}", mysql_stmt_error(stmt)); - mysql_stmt_close(stmt); - m_prepareError = true; - } - else - m_stmts[index] = std::make_unique(reinterpret_cast(stmt), sql); - } -} - -PreparedResultSet* MySQLConnection::Query(PreparedStatementBase* stmt) -{ - MySQLPreparedStatement* mysqlStmt = nullptr; - MySQLResult* result = nullptr; - uint64 rowCount = 0; - uint32 fieldCount = 0; - - if (!_Query(stmt, &mysqlStmt, &result, &rowCount, &fieldCount)) - return nullptr; - - if (mysql_more_results(m_Mysql)) - { - mysql_next_result(m_Mysql); - } + if (!IsDynamic()) + return false; - return new PreparedResultSet(mysqlStmt->GetSTMT(), result, rowCount, fieldCount); + Milliseconds diff = std::chrono::duration_cast(std::chrono::system_clock::now() - _lastUseTime); + return diff >= DYNAMIC_CONNECTION_TIMEOUT; } -bool MySQLConnection::_HandleMySQLErrno(uint32 errNo, uint8 attempts /*= 5*/) +std::size_t MySQLConnection::GetQueueSize() const { - switch (errNo) - { - case CR_SERVER_GONE_ERROR: - case CR_SERVER_LOST: - case CR_SERVER_LOST_EXTENDED: - { - if (m_Mysql) - { - LOG_ERROR("sql.sql", "Lost the connection to the MySQL server!"); - - mysql_close(m_Mysql); - m_Mysql = nullptr; - } - [[fallthrough]]; - } - case CR_CONN_HOST_ERROR: - { - LOG_INFO("sql.sql", "Attempting to reconnect to the MySQL server..."); - - m_reconnecting = true; - - uint32 const lErrno = Open(); - if (!lErrno) - { - // Don't remove 'this' pointer unless you want to skip loading all prepared statements... - if (!this->PrepareStatements()) - { - LOG_FATAL("sql.sql", "Could not re-prepare statements!"); - std::this_thread::sleep_for(10s); - std::abort(); - } - - LOG_INFO("sql.sql", "Successfully reconnected to {} @{}:{} ({}).", - m_connectionInfo.database, m_connectionInfo.host, m_connectionInfo.port_or_socket, - (m_connectionFlags & CONNECTION_ASYNC) ? "asynchronous" : "synchronous"); - - m_reconnecting = false; - return true; - } - - if ((--attempts) == 0) - { - // Shut down the server when the mysql server isn't - // reachable for some time - LOG_FATAL("sql.sql", "Failed to reconnect to the MySQL server, terminating the server to prevent data corruption!"); - - // We could also initiate a shutdown through using std::raise(SIGTERM) - std::this_thread::sleep_for(10s); - std::abort(); - } - else - { - // It's possible this attempted reconnect throws 2006 at us. - // To prevent crazy recursive calls, sleep here. - std::this_thread::sleep_for(3s); // Sleep 3 seconds - return _HandleMySQLErrno(lErrno, attempts); // Call self (recursive) - } - } - - case ER_LOCK_DEADLOCK: - return false; // Implemented in TransactionTask::Execute and DatabaseWorkerPool::DirectCommitTransaction - - // Query related errors - skip query - case ER_WRONG_VALUE_COUNT: - case ER_DUP_ENTRY: - return false; + if (!_queue) + return 0; - // Outdated table or database structure - terminate core - case ER_BAD_FIELD_ERROR: - case ER_NO_SUCH_TABLE: - LOG_ERROR("sql.sql", "Your database structure is not up to date. Please make sure you've executed all queries in the sql/updates folders."); - std::this_thread::sleep_for(10s); - std::abort(); - return false; - case ER_PARSE_ERROR: - LOG_ERROR("sql.sql", "Error while parsing SQL. Core fix required."); - std::this_thread::sleep_for(10s); - std::abort(); - return false; - default: - LOG_ERROR("sql.sql", "Unhandled MySQL errno {}. Unexpected behaviour possible.", errNo); - return false; - } + return _queue->Size(); } diff --git a/src/server/database/Database/MySQLConnection.h b/src/server/database/Database/MySQLConnection.h index 6e437e2e89f763..139c0972a066e9 100644 --- a/src/server/database/Database/MySQLConnection.h +++ b/src/server/database/Database/MySQLConnection.h @@ -15,104 +15,99 @@ * with this program. If not, see . */ -#ifndef _MYSQLCONNECTION_H -#define _MYSQLCONNECTION_H +#ifndef _WH_MYSQL_CONNECTION_H_ +#define _WH_MYSQL_CONNECTION_H_ #include "DatabaseEnvFwd.h" -#include "Define.h" -#include -#include +#include "Duration.h" #include #include +#include +#include #include template class ProducerConsumerQueue; -class DatabaseWorker; -class MySQLPreparedStatement; -class SQLOperation; +class AsyncOperation; +class AsyncDBQueueWorker; -enum ConnectionFlags -{ - CONNECTION_ASYNC = 0x1, - CONNECTION_SYNCH = 0x2, - CONNECTION_BOTH = CONNECTION_ASYNC | CONNECTION_SYNCH -}; +using PreparedStatementList = std::vector>; struct AC_DATABASE_API MySQLConnectionInfo { explicit MySQLConnectionInfo(std::string_view infoString); - std::string user; - std::string password; - std::string database; - std::string host; - std::string port_or_socket; - std::string ssl; + std::string User; + std::string Password; + std::string Database; + std::string Host; + std::string PortOrSocket; + std::string SSL; }; class AC_DATABASE_API MySQLConnection { -template -friend class DatabaseWorkerPool; - -friend class PingOperation; - public: - MySQLConnection(MySQLConnectionInfo& connInfo); //! Constructor for synchronous connections. - MySQLConnection(ProducerConsumerQueue* queue, MySQLConnectionInfo& connInfo); //! Constructor for asynchronous connections. + explicit MySQLConnection(MySQLConnectionInfo& connInfo, ProducerConsumerQueue* dbQueue, bool isDynamic = false); virtual ~MySQLConnection(); virtual uint32 Open(); void Close(); - bool PrepareStatements(); + [[nodiscard]] bool PrepareStatements() const; bool Execute(std::string_view sql); - bool Execute(PreparedStatementBase* stmt); - ResultSet* Query(std::string_view sql); - PreparedResultSet* Query(PreparedStatementBase* stmt); - bool _Query(std::string_view sql, MySQLResult** pResult, MySQLField** pFields, uint64* pRowCount, uint32* pFieldCount); - bool _Query(PreparedStatementBase* stmt, MySQLPreparedStatement** mysqlStmt, MySQLResult** pResult, uint64* pRowCount, uint32* pFieldCount); + bool Execute(PreparedStatement stmt); + + QueryResult Query(std::string_view sql); + PreparedQueryResult Query(PreparedStatement stmt); + + MySQLPreparedStatement* GetPreparedStatement(uint32 index); + void PrepareStatement(uint32 index, std::string_view sql, ConnectionFlags flags); + + inline PreparedStatementList* GetPreparedStatementList() { return &_stmtList; } void BeginTransaction(); void RollbackTransaction(); void CommitTransaction(); - int ExecuteTransaction(std::shared_ptr transaction); - size_t EscapeString(char* to, const char* from, size_t length); + int32 ExecuteTransaction(SQLTransaction transaction); + std::size_t EscapeString(char* to, const char* from, std::size_t length); void Ping(); - uint32 GetLastError(); + int32 GetLastError(); -protected: /// Tries to acquire lock. If lock is acquired by another thread /// the calling parent will just try another connection - bool LockIfReady(); + inline bool LockIfReady() { return _mutex.try_lock(); } - /// Called by parent databasepool. Will let other threads access this connection - void Unlock(); + /// Called by parent database pool. Will let other threads access this connection + inline void Unlock() { return _mutex.unlock(); } + static std::string_view GetClientInfo(); + std::string_view GetServerInfo(); [[nodiscard]] uint32 GetServerVersion() const; - MySQLPreparedStatement* GetPreparedStatement(uint32 index); - void PrepareStatement(uint32 index, std::string_view sql, ConnectionFlags flags); - - virtual void DoPrepareStatements() = 0; - virtual bool _HandleMySQLErrno(uint32 errNo, uint8 attempts = 5); - - typedef std::vector> PreparedStatementContainer; - PreparedStatementContainer m_stmts; //! PreparedStatements storage - bool m_reconnecting; //! Are we reconnecting? - bool m_prepareError; //! Was there any error while preparing statements? - MySQLHandle* m_Mysql; //! MySQL Handle. + [[nodiscard]] inline bool IsDynamic() const { return _isDynamic; } + [[nodiscard]] bool CanRemoveConnection(); + [[nodiscard]] std::size_t GetQueueSize() const; private: - ProducerConsumerQueue* m_queue; //! Queue shared with other asynchronous connections. - std::unique_ptr m_worker; //! Core worker task. - MySQLConnectionInfo& m_connectionInfo; //! Connection info (used for logging) - ConnectionFlags m_connectionFlags; //! Connection flags (for preparing relevant statements) - std::mutex m_Mutex; + bool Query(std::string_view sql, MySQLResult** result, MySQLField** fields, uint64* rowCount, uint32* fieldCount); + bool Query(PreparedStatement stmt, MySQLPreparedStatement** mysqlStmt, MySQLResult** pResult, uint64* pRowCount, uint32* pFieldCount); + bool HandleMySQLError(uint32 errNo, uint8 attempts = 5); + inline void UpdateLastUseTime() { _lastUseTime = std::chrono::system_clock::now(); } + + MySQLHandle* _mysqlHandle{ nullptr }; + MySQLConnectionInfo& _connectionInfo; + ConnectionFlags _connectionFlags{ ConnectionFlags::Sync }; + PreparedStatementList _stmtList; + std::mutex _mutex; + bool _isDynamic{}; + bool _prepareError{}; //! Was there any error while preparing statements? + SystemTimePoint _lastUseTime; + ProducerConsumerQueue* _queue{ nullptr }; + std::unique_ptr _asyncQueueWorker; MySQLConnection(MySQLConnection const& right) = delete; MySQLConnection& operator=(MySQLConnection const& right) = delete; diff --git a/src/server/database/Database/MySQLPreparedStatement.cpp b/src/server/database/Database/MySQLPreparedStatement.cpp index 0335cf5cbc183c..b1b5f478430091 100644 --- a/src/server/database/Database/MySQLPreparedStatement.cpp +++ b/src/server/database/Database/MySQLPreparedStatement.cpp @@ -36,38 +36,37 @@ template<> struct MySQLType : std::integral_constant struct MySQLType : std::integral_constant { }; MySQLPreparedStatement::MySQLPreparedStatement(MySQLStmt* stmt, std::string_view queryString) : - m_stmt(nullptr), - m_Mstmt(stmt), - m_bind(nullptr), - m_queryString(std::string(queryString)) + _mysqlStmt(stmt), + _queryString(queryString) { /// Initialize variable parameters - m_paramCount = mysql_stmt_param_count(stmt); - m_paramsSet.assign(m_paramCount, false); - m_bind = new MySQLBind[m_paramCount]; - memset(m_bind, 0, sizeof(MySQLBind) * m_paramCount); + _paramCount = mysql_stmt_param_count(stmt); + _paramsSet.assign(_paramCount, false); + + _bind = new MySQLBind[_paramCount]; + memset(_bind, 0, sizeof(MySQLBind) * _paramCount); /// "If set to 1, causes mysql_stmt_store_result() to update the metadata MYSQL_FIELD->max_length value." - MySQLBool bool_tmp = MySQLBool(1); + auto bool_tmp = MySQLBool(1); mysql_stmt_attr_set(stmt, STMT_ATTR_UPDATE_MAX_LENGTH, &bool_tmp); } MySQLPreparedStatement::~MySQLPreparedStatement() { ClearParameters(); - if (m_Mstmt->bind_result_done) + if (_mysqlStmt->bind_result_done) { - delete[] m_Mstmt->bind->length; - delete[] m_Mstmt->bind->is_null; + delete[] _mysqlStmt->bind->length; + delete[] _mysqlStmt->bind->is_null; } - mysql_stmt_close(m_Mstmt); - delete[] m_bind; + mysql_stmt_close(_mysqlStmt); + delete[] _bind; } -void MySQLPreparedStatement::BindParameters(PreparedStatementBase* stmt) +void MySQLPreparedStatement::BindParameters(PreparedStatement stmt) { - m_stmt = stmt; // Cross reference them for debug output + _stmt = stmt; // Cross-reference them for debug output uint8 pos = 0; for (PreparedStatementData const& data : stmt->GetParameters()) @@ -82,25 +81,25 @@ void MySQLPreparedStatement::BindParameters(PreparedStatementBase* stmt) #ifdef _DEBUG if (pos < m_paramCount) - LOG_WARN("sql.sql", "[WARNING]: BindParameters() for statement {} did not bind all allocated parameters", stmt->GetIndex()); + LOG_WARN("db.query", "BindParameters() for statement {} did not bind all allocated parameters", stmt->GetIndex()); #endif } void MySQLPreparedStatement::ClearParameters() { - for (uint32 i=0; i < m_paramCount; ++i) + for (uint32 i = 0; i < _paramCount; ++i) { - delete m_bind[i].length; - m_bind[i].length = nullptr; - delete[] (char*)m_bind[i].buffer; - m_bind[i].buffer = nullptr; - m_paramsSet[i] = false; + delete _bind[i].length; + _bind[i].length = nullptr; + delete[] (char*)_bind[i].buffer; + _bind[i].buffer = nullptr; + _paramsSet[i] = false; } } static bool ParamenterIndexAssertFail(uint32 stmtIndex, uint8 index, uint32 paramCount) { - LOG_ERROR("sql.driver", "Attempted to bind parameter {}{} on a PreparedStatement {} (statement has only {} parameters)", + LOG_ERROR("db.query", "Attempted to bind parameter {}{} on a PreparedStatementBase {} (statement has only {} parameters)", uint32(index) + 1, (index == 1 ? "st" : (index == 2 ? "nd" : (index == 3 ? "rd" : "nd"))), stmtIndex, paramCount); return false; @@ -109,19 +108,19 @@ static bool ParamenterIndexAssertFail(uint32 stmtIndex, uint8 index, uint32 para //- Bind on mysql level void MySQLPreparedStatement::AssertValidIndex(uint8 index) { - ASSERT(index < m_paramCount || ParamenterIndexAssertFail(m_stmt->GetIndex(), index, m_paramCount)); + ASSERT(index < _paramCount || ParamenterIndexAssertFail(_stmt->GetIndex(), index, _paramCount)); - if (m_paramsSet[index]) - LOG_ERROR("sql.sql", "[ERROR] Prepared Statement (id: {}) trying to bind value on already bound index ({}).", m_stmt->GetIndex(), index); + if (_paramsSet[index]) + LOG_ERROR("db.query", "Prepared Statement (id: {}) trying to bind value on already bound index ({}).", _stmt->GetIndex(), index); } template void MySQLPreparedStatement::SetParameter(const uint8 index, T value) { AssertValidIndex(index); - m_paramsSet[index] = true; - MYSQL_BIND* param = &m_bind[index]; - uint32 len = uint32(sizeof(T)); + _paramsSet[index] = true; + MYSQL_BIND* param = &_bind[index]; + auto len = uint32(sizeof(T)); param->buffer_type = MySQLType::value; delete[] static_cast(param->buffer); param->buffer = new char[len]; @@ -133,16 +132,16 @@ void MySQLPreparedStatement::SetParameter(const uint8 index, T value) memcpy(param->buffer, &value, len); } -void MySQLPreparedStatement::SetParameter(const uint8 index, bool value) +void MySQLPreparedStatement::SetParameter(uint8 index, bool value) { SetParameter(index, uint8(value ? 1 : 0)); } -void MySQLPreparedStatement::SetParameter(const uint8 index, std::nullptr_t /*value*/) +void MySQLPreparedStatement::SetParameter(uint8 index, std::nullptr_t /*value*/) { AssertValidIndex(index); - m_paramsSet[index] = true; - MYSQL_BIND* param = &m_bind[index]; + _paramsSet[index] = true; + MYSQL_BIND* param = &_bind[index]; param->buffer_type = MYSQL_TYPE_NULL; delete[] static_cast(param->buffer); param->buffer = nullptr; @@ -155,9 +154,9 @@ void MySQLPreparedStatement::SetParameter(const uint8 index, std::nullptr_t /*va void MySQLPreparedStatement::SetParameter(uint8 index, std::string const& value) { AssertValidIndex(index); - m_paramsSet[index] = true; - MYSQL_BIND* param = &m_bind[index]; - uint32 len = uint32(value.size()); + _paramsSet[index] = true; + MYSQL_BIND* param = &_bind[index]; + auto len = uint32(value.size()); param->buffer_type = MYSQL_TYPE_VAR_STRING; delete[] static_cast(param->buffer); param->buffer = new char[len]; @@ -172,9 +171,9 @@ void MySQLPreparedStatement::SetParameter(uint8 index, std::string const& value) void MySQLPreparedStatement::SetParameter(uint8 index, std::vector const& value) { AssertValidIndex(index); - m_paramsSet[index] = true; - MYSQL_BIND* param = &m_bind[index]; - uint32 len = uint32(value.size()); + _paramsSet[index] = true; + MYSQL_BIND* param = &_bind[index]; + auto len = uint32(value.size()); param->buffer_type = MYSQL_TYPE_BLOB; delete[] static_cast(param->buffer); param->buffer = new char[len]; @@ -188,11 +187,10 @@ void MySQLPreparedStatement::SetParameter(uint8 index, std::vector const& std::string MySQLPreparedStatement::getQueryString() const { - std::string queryString(m_queryString); - - size_t pos = 0; + std::string queryString(_queryString); + std::size_t pos{}; - for (PreparedStatementData const& data : m_stmt->GetParameters()) + for (PreparedStatementData const& data : _stmt->GetParameters()) { pos = queryString.find('?', pos); diff --git a/src/server/database/Database/MySQLPreparedStatement.h b/src/server/database/Database/MySQLPreparedStatement.h index 7bb6ce7725fd60..4bf38275fc9a1a 100644 --- a/src/server/database/Database/MySQLPreparedStatement.h +++ b/src/server/database/Database/MySQLPreparedStatement.h @@ -19,7 +19,6 @@ #define MySQLPreparedStatement_h__ #include "DatabaseEnvFwd.h" -#include "Define.h" #include "MySQLWorkaround.h" #include #include @@ -32,39 +31,38 @@ class PreparedStatementBase; //- is executed. class AC_DATABASE_API MySQLPreparedStatement { -friend class MySQLConnection; -friend class PreparedStatementBase; + friend class MySQLConnection; public: MySQLPreparedStatement(MySQLStmt* stmt, std::string_view queryString); ~MySQLPreparedStatement(); - void BindParameters(PreparedStatementBase* stmt); + void BindParameters(PreparedStatement stmt); - uint32 GetParameterCount() const { return m_paramCount; } + [[nodiscard]] uint32 GetParameterCount() const { return _paramCount; } protected: - void SetParameter(const uint8 index, bool value); - void SetParameter(const uint8 index, std::nullptr_t /*value*/); - void SetParameter(const uint8 index, std::string const& value); - void SetParameter(const uint8 index, std::vector const& value); + void SetParameter(uint8 index, bool value); + void SetParameter(uint8 index, std::nullptr_t /*value*/); + void SetParameter(uint8 index, std::string const& value); + void SetParameter(uint8 index, std::vector const& value); template - void SetParameter(const uint8 index, T value); + void SetParameter(uint8 index, T value); - MySQLStmt* GetSTMT() { return m_Mstmt; } - MySQLBind* GetBind() { return m_bind; } - PreparedStatementBase* m_stmt; + MySQLStmt* GetSTMT() { return _mysqlStmt; } + MySQLBind* GetBind() { return _bind; } + PreparedStatement _stmt; void ClearParameters(); - void AssertValidIndex(const uint8 index); - std::string getQueryString() const; + void AssertValidIndex(uint8 index); + [[nodiscard]] std::string getQueryString() const; private: - MySQLStmt* m_Mstmt; - uint32 m_paramCount; - std::vector m_paramsSet; - MySQLBind* m_bind; - std::string m_queryString{}; + MySQLStmt* _mysqlStmt{ nullptr }; + uint32 _paramCount{}; + std::vector _paramsSet; + MySQLBind* _bind{ nullptr }; + std::string _queryString; MySQLPreparedStatement(MySQLPreparedStatement const& right) = delete; MySQLPreparedStatement& operator=(MySQLPreparedStatement const& right) = delete; diff --git a/src/server/database/Database/PreparedStatement.cpp b/src/server/database/Database/PreparedStatement.cpp index 4059509dcbab85..35cdb288f500f5 100644 --- a/src/server/database/Database/PreparedStatement.cpp +++ b/src/server/database/Database/PreparedStatement.cpp @@ -17,88 +17,58 @@ #include "PreparedStatement.h" #include "Errors.h" -#include "Log.h" -#include "MySQLConnection.h" -#include "MySQLPreparedStatement.h" -#include "MySQLWorkaround.h" -#include "QueryResult.h" PreparedStatementBase::PreparedStatementBase(uint32 index, uint8 capacity) : - m_index(index), - statement_data(capacity) { } - -PreparedStatementBase::~PreparedStatementBase() { } + _index(index), + _statementData(capacity) +{ + _paramsSet.assign(capacity, false); +} //- Bind to buffer template Acore::Types::is_non_string_view_v PreparedStatementBase::SetValidData(const uint8 index, T const& value) { - ASSERT(index < statement_data.size()); - statement_data[index].data.emplace(value); + ASSERT(index < _statementData.size()); + _statementData[index].data.emplace(value); + _paramsSet[index] = true; } // Non template functions void PreparedStatementBase::SetValidData(const uint8 index) { - ASSERT(index < statement_data.size()); - statement_data[index].data.emplace(nullptr); + ASSERT(index < _statementData.size()); + _statementData[index].data.emplace(nullptr); + _paramsSet[index] = true; } void PreparedStatementBase::SetValidData(const uint8 index, std::string_view value) { - ASSERT(index < statement_data.size()); - statement_data[index].data.emplace(value); -} - -template void PreparedStatementBase::SetValidData(const uint8 index, uint8 const& value); -template void PreparedStatementBase::SetValidData(const uint8 index, int8 const& value); -template void PreparedStatementBase::SetValidData(const uint8 index, uint16 const& value); -template void PreparedStatementBase::SetValidData(const uint8 index, int16 const& value); -template void PreparedStatementBase::SetValidData(const uint8 index, uint32 const& value); -template void PreparedStatementBase::SetValidData(const uint8 index, int32 const& value); -template void PreparedStatementBase::SetValidData(const uint8 index, uint64 const& value); -template void PreparedStatementBase::SetValidData(const uint8 index, int64 const& value); -template void PreparedStatementBase::SetValidData(const uint8 index, bool const& value); -template void PreparedStatementBase::SetValidData(const uint8 index, float const& value); -template void PreparedStatementBase::SetValidData(const uint8 index, std::string const& value); -template void PreparedStatementBase::SetValidData(const uint8 index, std::vector const& value); - -//- Execution -PreparedStatementTask::PreparedStatementTask(PreparedStatementBase* stmt, bool async) : - m_stmt(stmt), - m_result(nullptr) -{ - m_has_result = async; // If it's async, then there's a result - - if (async) - m_result = new PreparedQueryResultPromise(); + ASSERT(index < _statementData.size(), "> Incorrect index ({}). Statement data size: {}", index, _statementData.size()); + _statementData[index].data.emplace(value); + _paramsSet[index] = true; } -PreparedStatementTask::~PreparedStatementTask() +template AC_DATABASE_API void PreparedStatementBase::SetValidData(const uint8 index, uint8 const& value); +template AC_DATABASE_API void PreparedStatementBase::SetValidData(const uint8 index, int8 const& value); +template AC_DATABASE_API void PreparedStatementBase::SetValidData(const uint8 index, uint16 const& value); +template AC_DATABASE_API void PreparedStatementBase::SetValidData(const uint8 index, int16 const& value); +template AC_DATABASE_API void PreparedStatementBase::SetValidData(const uint8 index, uint32 const& value); +template AC_DATABASE_API void PreparedStatementBase::SetValidData(const uint8 index, int32 const& value); +template AC_DATABASE_API void PreparedStatementBase::SetValidData(const uint8 index, uint64 const& value); +template AC_DATABASE_API void PreparedStatementBase::SetValidData(const uint8 index, int64 const& value); +template AC_DATABASE_API void PreparedStatementBase::SetValidData(const uint8 index, bool const& value); +template AC_DATABASE_API void PreparedStatementBase::SetValidData(const uint8 index, float const& value); +template AC_DATABASE_API void PreparedStatementBase::SetValidData(const uint8 index, std::string const& value); +template AC_DATABASE_API void PreparedStatementBase::SetValidData(const uint8 index, std::vector const& value); + +std::pair PreparedStatementBase::IsAllParamsSet() const { - delete m_stmt; + for (std::size_t index{}; index < _paramsSet.size(); index++) + if (!_paramsSet[index]) + return { false, index }; - if (m_has_result && m_result) - delete m_result; -} - -bool PreparedStatementTask::Execute() -{ - if (m_has_result) - { - PreparedResultSet* result = m_conn->Query(m_stmt); - if (!result || !result->GetRowCount()) - { - delete result; - m_result->set_value(PreparedQueryResult(nullptr)); - return false; - } - - m_result->set_value(PreparedQueryResult(result)); - return true; - } - - return m_conn->Execute(m_stmt); + return { true, {} }; } template @@ -113,20 +83,20 @@ std::string PreparedStatementData::ToString(std::vector /*value*/) return "BINARY"; } -template std::string PreparedStatementData::ToString(uint8); -template std::string PreparedStatementData::ToString(uint16); -template std::string PreparedStatementData::ToString(uint32); -template std::string PreparedStatementData::ToString(uint64); -template std::string PreparedStatementData::ToString(int8); -template std::string PreparedStatementData::ToString(int16); -template std::string PreparedStatementData::ToString(int32); -template std::string PreparedStatementData::ToString(int64); -template std::string PreparedStatementData::ToString(std::string); -template std::string PreparedStatementData::ToString(float); -template std::string PreparedStatementData::ToString(double); -template std::string PreparedStatementData::ToString(bool); - std::string PreparedStatementData::ToString(std::nullptr_t /*value*/) { return "NULL"; } + +template AC_DATABASE_API std::string PreparedStatementData::ToString(uint8); +template AC_DATABASE_API std::string PreparedStatementData::ToString(uint16); +template AC_DATABASE_API std::string PreparedStatementData::ToString(uint32); +template AC_DATABASE_API std::string PreparedStatementData::ToString(uint64); +template AC_DATABASE_API std::string PreparedStatementData::ToString(int8); +template AC_DATABASE_API std::string PreparedStatementData::ToString(int16); +template AC_DATABASE_API std::string PreparedStatementData::ToString(int32); +template AC_DATABASE_API std::string PreparedStatementData::ToString(int64); +template AC_DATABASE_API std::string PreparedStatementData::ToString(std::string); +template AC_DATABASE_API std::string PreparedStatementData::ToString(float); +template AC_DATABASE_API std::string PreparedStatementData::ToString(double); +template AC_DATABASE_API std::string PreparedStatementData::ToString(bool); diff --git a/src/server/database/Database/PreparedStatement.h b/src/server/database/Database/PreparedStatement.h index 766a8e8e261740..ef2ad9c39b4904 100644 --- a/src/server/database/Database/PreparedStatement.h +++ b/src/server/database/Database/PreparedStatement.h @@ -20,9 +20,8 @@ #include "Define.h" #include "Duration.h" -#include "Optional.h" -#include "SQLOperation.h" -#include +#include +#include #include #include #include @@ -67,13 +66,11 @@ struct PreparedStatementData //- Upper-level class that is used in code class AC_DATABASE_API PreparedStatementBase { -friend class PreparedStatementTask; - public: explicit PreparedStatementBase(uint32 index, uint8 capacity); - virtual ~PreparedStatementBase(); + virtual ~PreparedStatementBase() = default; - // Set numerlic and default binary + // Set numeric and default binary template inline Acore::Types::is_default SetData(const uint8 index, T value) { @@ -108,8 +105,8 @@ friend class PreparedStatementTask; } // Set duration - template - inline void SetData(const uint8 index, std::chrono::duration<_Rep, _Period> const& value, bool convertToUin32 = true) + template + inline void SetData(const uint8 index, std::chrono::duration const& value, bool convertToUin32 = true) { SetValidData(index, convertToUin32 ? static_cast(value.count()) : value.count()); } @@ -121,18 +118,19 @@ friend class PreparedStatementTask; SetDataTuple(std::make_tuple(std::forward(args)...)); } - [[nodiscard]] uint32 GetIndex() const { return m_index; } - [[nodiscard]] std::vector const& GetParameters() const { return statement_data; } + [[nodiscard]] uint32 GetIndex() const { return _index; } + [[nodiscard]] std::vector const& GetParameters() const { return _statementData; } + [[nodiscard]] std::pair IsAllParamsSet() const; protected: template - Acore::Types::is_non_string_view_v SetValidData(const uint8 index, T const& value); + Acore::Types::is_non_string_view_v SetValidData(uint8 index, T const& value); - void SetValidData(const uint8 index); - void SetValidData(const uint8 index, std::string_view value); + void SetValidData(uint8 index); + void SetValidData(uint8 index, std::string_view value); template - inline void SetDataTuple(std::tuple const& argsList) + void SetDataTuple(std::tuple const& argsList) { std::apply ( @@ -144,42 +142,14 @@ friend class PreparedStatementTask; ); } - uint32 m_index; + uint32 _index; + std::vector _paramsSet; //- Buffer of parameters, not tied to MySQL in any way yet - std::vector statement_data; + std::vector _statementData; PreparedStatementBase(PreparedStatementBase const& right) = delete; PreparedStatementBase& operator=(PreparedStatementBase const& right) = delete; }; -template -class PreparedStatement : public PreparedStatementBase -{ -public: - explicit PreparedStatement(uint32 index, uint8 capacity) : PreparedStatementBase(index, capacity) - { - } - -private: - PreparedStatement(PreparedStatement const& right) = delete; - PreparedStatement& operator=(PreparedStatement const& right) = delete; -}; - -//- Lower-level class, enqueuable operation -class AC_DATABASE_API PreparedStatementTask : public SQLOperation -{ -public: - PreparedStatementTask(PreparedStatementBase* stmt, bool async = false); - ~PreparedStatementTask() override; - - bool Execute() override; - PreparedQueryResultFuture GetFuture() { return m_result->get_future(); } - -protected: - PreparedStatementBase* m_stmt; - bool m_has_result; - PreparedQueryResultPromise* m_result; -}; - #endif diff --git a/src/server/database/Database/QueryCallback.cpp b/src/server/database/Database/QueryCallback.cpp index 2dd0525d569fd6..c7d7f55ee5d91d 100644 --- a/src/server/database/Database/QueryCallback.cpp +++ b/src/server/database/Database/QueryCallback.cpp @@ -65,8 +65,8 @@ struct QueryCallback::QueryCallbackData public: friend class QueryCallback; - QueryCallbackData(std::function&& callback) : _string(std::move(callback)), _isPrepared(false) { } - QueryCallbackData(std::function&& callback) : _prepared(std::move(callback)), _isPrepared(true) { } + explicit QueryCallbackData(std::function&& callback) : _string(std::move(callback)), _isPrepared(false) { } + explicit QueryCallbackData(std::function&& callback) : _prepared(std::move(callback)), _isPrepared(true) { } QueryCallbackData(QueryCallbackData&& right) noexcept { @@ -107,6 +107,7 @@ struct QueryCallback::QueryCallbackData std::function _string; std::function _prepared; }; + bool _isPrepared; }; @@ -127,8 +128,8 @@ QueryCallback::QueryCallback(QueryCallback&& right) noexcept { _isPrepared = right._isPrepared; ConstructActiveMember(this); - MoveFrom(this, std::move(right)); _callbacks = std::move(right._callbacks); + MoveFrom(this, std::move(right)); } QueryCallback& QueryCallback::operator=(QueryCallback&& right) noexcept @@ -142,8 +143,8 @@ QueryCallback& QueryCallback::operator=(QueryCallback&& right) noexcept ConstructActiveMember(this); } - MoveFrom(this, std::move(right)); _callbacks = std::move(right._callbacks); + MoveFrom(this, std::move(right)); } return *this; diff --git a/src/server/database/Database/QueryCallback.h b/src/server/database/Database/QueryCallback.h index c1ee4ea98d5881..5a3213c3b04852 100644 --- a/src/server/database/Database/QueryCallback.h +++ b/src/server/database/Database/QueryCallback.h @@ -19,12 +19,9 @@ #define _QUERY_CALLBACK_H #include "DatabaseEnvFwd.h" -#include "Define.h" #include -#include #include #include -#include class AC_DATABASE_API QueryCallback { diff --git a/src/server/database/Database/QueryHolder.cpp b/src/server/database/Database/QueryHolder.cpp index c3c54aad878440..4916fc4d739aff 100644 --- a/src/server/database/Database/QueryHolder.cpp +++ b/src/server/database/Database/QueryHolder.cpp @@ -16,80 +16,126 @@ */ #include "QueryHolder.h" -#include "Errors.h" +#include "Containers.h" #include "Log.h" #include "MySQLConnection.h" #include "PreparedStatement.h" #include "QueryResult.h" +#include -bool SQLQueryHolderBase::SetPreparedQueryImpl(size_t index, PreparedStatementBase* stmt) +QueryResult SQLQueryHolderBase::GetResult(std::size_t index) const { - if (m_queries.size() <= index) + auto const& itr = _queries.find(index); + if (itr == _queries.end()) { - LOG_ERROR("sql.sql", "Query index ({}) out of range (size: {}) for prepared statement", uint32(index), (uint32)m_queries.size()); - return false; + LOG_ERROR("db.query", "Query holder result tried to access non exist index {}. Holder name: {}. Type: QueryResult", index, _name); + return nullptr; } - m_queries[index].first = stmt; - return true; + try + { + auto result{ std::get(itr->second.HolderResult) }; + if (!result || !result->GetRowCount() || !result->NextRow()) + return nullptr; + + return result; + } + catch (...) { } + + return nullptr; } -PreparedQueryResult SQLQueryHolderBase::GetPreparedResult(size_t index) const +PreparedQueryResult SQLQueryHolderBase::GetPreparedResult(std::size_t index) const { - // Don't call to this function if the index is of a prepared statement - ASSERT(index < m_queries.size(), "Query holder result index out of range, tried to access index {} but there are only {} results", - index, m_queries.size()); + auto const& itr = _queries.find(index); + if (itr == _queries.end()) + { + LOG_ERROR("db.query", "Query holder result tried to access non exist index {}. Holder name: {}. Type: PreparedQueryResult", index, _name); + return nullptr; + } - return m_queries[index].second; + try + { + auto result{ std::get(itr->second.HolderResult) }; + if (!result || !result->GetRowCount()) + return nullptr; + + return result; + } + catch (...) { } + + return nullptr; } -void SQLQueryHolderBase::SetPreparedResult(size_t index, PreparedResultSet* result) +void SQLQueryHolderBase::SetResult(std::size_t index, QueryResult result) { if (result && !result->GetRowCount()) - { - delete result; - result = nullptr; - } + result.reset(); + + /// store the result in the holder + if (auto query = Acore::Containers::MapGetValuePtr(_queries, index)) + query->HolderResult = std::move(result); +} + +void SQLQueryHolderBase::SetPreparedResult(std::size_t index, PreparedQueryResult result) +{ + if (result && !result->GetRowCount()) + result.reset(); /// store the result in the holder - if (index < m_queries.size()) - m_queries[index].second = PreparedQueryResult(result); + if (auto query = Acore::Containers::MapGetValuePtr(_queries, index)) + query->HolderResult = std::move(result); } -SQLQueryHolderBase::~SQLQueryHolderBase() +bool SQLQueryHolderBase::AddQuery(std::size_t index, std::string_view sql) { - for (std::pair& query : m_queries) + if (_queries.contains(index)) { - /// if the result was never used, free the resources - /// results used already (getresult called) are expected to be deleted - delete query.first; + LOG_ERROR("db.query", "Trying add query holder with index {} exist. Holder name: {}. Type: QueryResult", index, _name); + return false; } + + SQLQueryHolderQuery query{}; + query.HolderQuery.emplace(sql); + + _queries.emplace(index, std::move(query)); + return true; } -void SQLQueryHolderBase::SetSize(size_t size) +bool SQLQueryHolderBase::AddPreparedQuery(std::size_t index, PreparedStatement stmt) { - /// to optimize push_back, reserve the number of queries about to be executed - m_queries.resize(size); -} + if (_queries.contains(index)) + { + LOG_ERROR("db.query", "Trying add query holder with index {} exist. Holder name: {}. Type: PreparedQueryResult", index, _name); + return false; + } -SQLQueryHolderTask::~SQLQueryHolderTask() = default; + SQLQueryHolderQuery query{}; + query.HolderQuery = std::move(stmt); + + _queries.emplace(index, std::move(query)); + return true; +} -bool SQLQueryHolderTask::Execute() +void SQLQueryHolderTask::ExecuteQuery() { /// execute all queries in the holder and pass the results - for (size_t i = 0; i < m_holder->m_queries.size(); ++i) - if (PreparedStatementBase* stmt = m_holder->m_queries[i].first) - m_holder->SetPreparedResult(i, m_conn->Query(stmt)); + for (auto const& [index, query] : _holder->_queries) + { + if (std::holds_alternative(query.HolderQuery)) + _holder->SetResult(index, _connection->Query(std::get(query.HolderQuery))); + else + _holder->SetPreparedResult(index, _connection->Query(std::get(query.HolderQuery))); + } - m_result.set_value(); - return true; + _result.set_value(); } bool SQLQueryHolderCallback::InvokeIfReady() { - if (m_future.valid() && m_future.wait_for(std::chrono::seconds(0)) == std::future_status::ready) + if (_future.valid() && _future.wait_for(0s) == std::future_status::ready) { - m_callback(*m_holder); + _callback(*_holder); return true; } diff --git a/src/server/database/Database/QueryHolder.h b/src/server/database/Database/QueryHolder.h index 63994b487cb14a..09c6a4928c880f 100644 --- a/src/server/database/Database/QueryHolder.h +++ b/src/server/database/Database/QueryHolder.h @@ -18,72 +18,80 @@ #ifndef _QUERYHOLDER_H #define _QUERYHOLDER_H -#include "SQLOperation.h" -#include +#include "DatabaseAsyncOperation.h" +#include "StringFormat.h" +#include +#include + +struct SQLQueryHolderQuery +{ + std::variant HolderQuery; + std::variant HolderResult; +}; class AC_DATABASE_API SQLQueryHolderBase { -friend class SQLQueryHolderTask; + friend class SQLQueryHolderTask; public: - SQLQueryHolderBase() = default; - virtual ~SQLQueryHolderBase(); - void SetSize(size_t size); - PreparedQueryResult GetPreparedResult(size_t index) const; - void SetPreparedResult(size_t index, PreparedResultSet* result); + SQLQueryHolderBase(std::string_view name) : _name(name) { } + virtual ~SQLQueryHolderBase() = default; -protected: - bool SetPreparedQueryImpl(size_t index, PreparedStatementBase* stmt); + [[nodiscard]] PreparedQueryResult GetPreparedResult(std::size_t index) const; + [[nodiscard]] QueryResult GetResult(std::size_t index) const; -private: - std::vector> m_queries; -}; + void SetPreparedResult(std::size_t index, PreparedQueryResult result); + void SetResult(std::size_t index, QueryResult result); -template -class SQLQueryHolder : public SQLQueryHolderBase -{ -public: - bool SetPreparedQuery(size_t index, PreparedStatement* stmt) + bool AddPreparedQuery(std::size_t index, PreparedStatement stmt); + bool AddQuery(std::size_t index, std::string_view sql); + + template + inline bool AddQuery(std::size_t index, std::string_view fmt, Args&&... args) { - return SetPreparedQueryImpl(index, stmt); + return AddQuery(index, Acore::StringFormatFmt(fmt, std::forward(args)...)); } + +private: + std::unordered_map _queries; + std::string _name; }; -class AC_DATABASE_API SQLQueryHolderTask : public SQLOperation +class AC_DATABASE_API SQLQueryHolderTask : public AsyncOperation { public: - explicit SQLQueryHolderTask(std::shared_ptr holder) - : m_holder(std::move(holder)) { } + explicit SQLQueryHolderTask(SQLQueryHolder holder) : + AsyncOperation(), _holder(std::move(holder)) { } - ~SQLQueryHolderTask(); + ~SQLQueryHolderTask() override = default; - bool Execute() override; - QueryResultHolderFuture GetFuture() { return m_result.get_future(); } + void ExecuteQuery() override; + QueryResultHolderFuture GetFuture() { return _result.get_future(); } private: - std::shared_ptr m_holder; - QueryResultHolderPromise m_result; + std::shared_ptr _holder; + QueryResultHolderPromise _result; }; class AC_DATABASE_API SQLQueryHolderCallback { public: - SQLQueryHolderCallback(std::shared_ptr&& holder, QueryResultHolderFuture&& future) - : m_holder(std::move(holder)), m_future(std::move(future)) { } + SQLQueryHolderCallback(SQLQueryHolder&& holder, QueryResultHolderFuture&& future) : + _holder(std::move(holder)), _future(std::move(future)) { } SQLQueryHolderCallback(SQLQueryHolderCallback&&) = default; SQLQueryHolderCallback& operator=(SQLQueryHolderCallback&&) = default; - void AfterComplete(std::function callback) & + void AfterComplete(std::function&& callback) { - m_callback = std::move(callback); + _callback = std::move(callback); } bool InvokeIfReady(); - std::shared_ptr m_holder; - QueryResultHolderFuture m_future; - std::function m_callback; + SQLQueryHolder _holder; + QueryResultHolderFuture _future; + std::function _callback; }; #endif diff --git a/src/server/database/Database/QueryResult.cpp b/src/server/database/Database/QueryResult.cpp index 0e8d3c8c18a310..ebc1c94f154ff9 100644 --- a/src/server/database/Database/QueryResult.cpp +++ b/src/server/database/Database/QueryResult.cpp @@ -17,14 +17,12 @@ #include "QueryResult.h" #include "Errors.h" -#include "Field.h" #include "Log.h" #include "MySQLHacks.h" -#include "MySQLWorkaround.h" namespace { - static uint32 SizeForType(MYSQL_FIELD* field) + uint32 SizeForType(MYSQL_FIELD* field) { switch (field->type) { @@ -69,7 +67,7 @@ namespace MYSQL_TYPE_SET: */ default: - LOG_WARN("sql.sql", "SQL::SizeForType(): invalid field type {}", uint32(field->type)); + LOG_WARN("db.query", "SQL::SizeForType(): invalid field type {}", uint32(field->type)); return 0; } } @@ -111,14 +109,14 @@ namespace case MYSQL_TYPE_VAR_STRING: return DatabaseFieldTypes::Binary; default: - LOG_WARN("sql.sql", "MysqlTypeToFieldType(): invalid field type {}", uint32(type)); + LOG_WARN("db.query", "MysqlTypeToFieldType(): invalid field type {}", uint32(type)); break; } return DatabaseFieldTypes::Null; } - static std::string FieldTypeToString(enum_field_types type) + std::string FieldTypeToString(enum_field_types type) { switch (type) { @@ -171,12 +169,12 @@ ResultSet::ResultSet(MySQLResult* result, MySQLField* fields, uint64 rowCount, u _fields(fields) { _fieldMetadata.resize(_fieldCount); - _currentRow = new Field[_fieldCount]; + _currRow = std::make_unique(_fieldCount); for (uint32 i = 0; i < _fieldCount; i++) { InitializeDatabaseFieldMetadata(&_fieldMetadata[i], &_fields[i], i); - _currentRow[i].SetMetadata(&_fieldMetadata[i]); + _currRow[i].SetMetadata(&_fieldMetadata[i]); } } @@ -187,12 +185,10 @@ ResultSet::~ResultSet() bool ResultSet::NextRow() { - MYSQL_ROW row; - if (!_result) return false; - row = mysql_fetch_row(_result); + auto row = mysql_fetch_row(_result); if (!row) { CleanUp(); @@ -202,13 +198,13 @@ bool ResultSet::NextRow() unsigned long* lengths = mysql_fetch_lengths(_result); if (!lengths) { - LOG_WARN("sql.sql", "{}:mysql_fetch_lengths, cannot retrieve value lengths. Error {}.", __FUNCTION__, mysql_error(_result->handle)); + LOG_WARN("db.query", "{}:mysql_fetch_lengths, cannot retrieve value lengths. Error {}.", __FUNCTION__, mysql_error(_result->handle)); CleanUp(); return false; } for (uint32 i = 0; i < _fieldCount; i++) - _currentRow[i].SetStructuredValue(row[i], lengths[i]); + _currRow[i].SetStructuredValue(row[i], lengths[i]); return true; } @@ -221,12 +217,6 @@ std::string ResultSet::GetFieldName(uint32 index) const void ResultSet::CleanUp() { - if (_currentRow) - { - delete[] _currentRow; - _currentRow = nullptr; - } - if (_result) { mysql_free_result(_result); @@ -237,144 +227,142 @@ void ResultSet::CleanUp() Field const& ResultSet::operator[](std::size_t index) const { ASSERT(index < _fieldCount); - return _currentRow[index]; + return _currRow[index]; } -void ResultSet::AssertRows(std::size_t sizeRows) +void ResultSet::AssertRows(std::size_t sizeRows) const { ASSERT(sizeRows == _fieldCount); } PreparedResultSet::PreparedResultSet(MySQLStmt* stmt, MySQLResult* result, uint64 rowCount, uint32 fieldCount) : - m_rowCount(rowCount), - m_rowPosition(0), - m_fieldCount(fieldCount), - m_rBind(nullptr), - m_stmt(stmt), - m_metadataResult(result) + _rowCount(rowCount), + _fieldCount(fieldCount), + _stmt(stmt), + _metadataResult(result) { - if (!m_metadataResult) + if (!_metadataResult) return; - if (m_stmt->bind_result_done) + if (_stmt->bind_result_done) { - delete[] m_stmt->bind->length; - delete[] m_stmt->bind->is_null; + delete[] _stmt->bind->length; + delete[] _stmt->bind->is_null; } - m_rBind = new MySQLBind[m_fieldCount]; + _rBind = new MySQLBind[_fieldCount]; //- for future readers wondering where this is freed - mysql_stmt_bind_result moves pointers to these // from m_rBind to m_stmt->bind and it is later freed by the `if (m_stmt->bind_result_done)` block just above here // MYSQL_STMT lifetime is equal to connection lifetime - MySQLBool* m_isNull = new MySQLBool[m_fieldCount]; - unsigned long* m_length = new unsigned long[m_fieldCount]; + auto* isNull = new MySQLBool[_fieldCount]; + auto* length = new unsigned long[_fieldCount]; - memset(m_isNull, 0, sizeof(MySQLBool) * m_fieldCount); - memset(m_rBind, 0, sizeof(MySQLBind) * m_fieldCount); - memset(m_length, 0, sizeof(unsigned long) * m_fieldCount); + memset(isNull, 0, sizeof(MySQLBool) * _fieldCount); + memset(_rBind, 0, sizeof(MySQLBind) * _fieldCount); + memset(length, 0, sizeof(unsigned long) * _fieldCount); //- This is where we store the (entire) resultset - if (mysql_stmt_store_result(m_stmt)) + if (mysql_stmt_store_result(_stmt)) { - LOG_WARN("sql.sql", "{}:mysql_stmt_store_result, cannot bind result from MySQL server. Error: {}", __FUNCTION__, mysql_stmt_error(m_stmt)); - delete[] m_rBind; - delete[] m_isNull; - delete[] m_length; + LOG_WARN("db.query", "{}:mysql_stmt_store_result, cannot bind result from MySQL server. Error: {}", __FUNCTION__, mysql_stmt_error(_stmt)); + delete[] _rBind; + delete[] isNull; + delete[] length; return; } - m_rowCount = mysql_stmt_num_rows(m_stmt); + _rowCount = mysql_stmt_num_rows(_stmt); //- This is where we prepare the buffer based on metadata - MySQLField* field = reinterpret_cast(mysql_fetch_fields(m_metadataResult)); - m_fieldMetadata.resize(m_fieldCount); + auto* field = reinterpret_cast(mysql_fetch_fields(_metadataResult)); + _fieldMetadata.resize(_fieldCount); std::size_t rowSize = 0; - for (uint32 i = 0; i < m_fieldCount; ++i) + for (uint32 i = 0; i < _fieldCount; ++i) { uint32 size = SizeForType(&field[i]); rowSize += size; - InitializeDatabaseFieldMetadata(&m_fieldMetadata[i], &field[i], i); + InitializeDatabaseFieldMetadata(&_fieldMetadata[i], &field[i], i); - m_rBind[i].buffer_type = field[i].type; - m_rBind[i].buffer_length = size; - m_rBind[i].length = &m_length[i]; - m_rBind[i].is_null = &m_isNull[i]; - m_rBind[i].error = nullptr; - m_rBind[i].is_unsigned = field[i].flags & UNSIGNED_FLAG; + _rBind[i].buffer_type = field[i].type; + _rBind[i].buffer_length = size; + _rBind[i].length = &length[i]; + _rBind[i].is_null = &isNull[i]; + _rBind[i].error = nullptr; + _rBind[i].is_unsigned = field[i].flags & UNSIGNED_FLAG; } - char* dataBuffer = new char[rowSize * m_rowCount]; - for (uint32 i = 0, offset = 0; i < m_fieldCount; ++i) + char* dataBuffer = new char[rowSize * _rowCount]; + for (uint32 i = 0, offset = 0; i < _fieldCount; ++i) { - m_rBind[i].buffer = dataBuffer + offset; - offset += m_rBind[i].buffer_length; + _rBind[i].buffer = dataBuffer + offset; + offset += _rBind[i].buffer_length; } //- This is where we bind the bind the buffer to the statement - if (mysql_stmt_bind_result(m_stmt, m_rBind)) + if (mysql_stmt_bind_result(_stmt, _rBind)) { - LOG_WARN("sql.sql", "{}:mysql_stmt_bind_result, cannot bind result from MySQL server. Error: {}", __FUNCTION__, mysql_stmt_error(m_stmt)); - mysql_stmt_free_result(m_stmt); + LOG_WARN("db.query", "{}:mysql_stmt_bind_result, cannot bind result from MySQL server. Error: {}", __FUNCTION__, mysql_stmt_error(_stmt)); + mysql_stmt_free_result(_stmt); CleanUp(); - delete[] m_isNull; - delete[] m_length; + delete[] isNull; + delete[] length; return; } - m_rows.resize(uint32(m_rowCount) * m_fieldCount); + _rows.resize(uint32(_rowCount) * _fieldCount); while (_NextRow()) { - for (uint32 fIndex = 0; fIndex < m_fieldCount; ++fIndex) + for (uint32 fIndex = 0; fIndex < _fieldCount; ++fIndex) { - m_rows[uint32(m_rowPosition) * m_fieldCount + fIndex].SetMetadata(&m_fieldMetadata[fIndex]); + _rows[uint32(_rowPosition) * _fieldCount + fIndex].SetMetadata(&_fieldMetadata[fIndex]); - unsigned long buffer_length = m_rBind[fIndex].buffer_length; - unsigned long fetched_length = *m_rBind[fIndex].length; - if (!*m_rBind[fIndex].is_null) + unsigned long buffer_length = _rBind[fIndex].buffer_length; + unsigned long fetched_length = *_rBind[fIndex].length; + if (!*_rBind[fIndex].is_null) { - void* buffer = m_stmt->bind[fIndex].buffer; - switch (m_rBind[fIndex].buffer_type) + void* buffer = _stmt->bind[fIndex].buffer; + switch (_rBind[fIndex].buffer_type) { - case MYSQL_TYPE_TINY_BLOB: - case MYSQL_TYPE_MEDIUM_BLOB: - case MYSQL_TYPE_LONG_BLOB: - case MYSQL_TYPE_BLOB: - case MYSQL_TYPE_STRING: - case MYSQL_TYPE_VAR_STRING: - // warning - the string will not be null-terminated if there is no space for it in the buffer - // when mysql_stmt_fetch returned MYSQL_DATA_TRUNCATED - // we cannot blindly null-terminate the data either as it may be retrieved as binary blob and not specifically a string - // in this case using Field::GetCString will result in garbage - /// @todo: remove Field::GetCString and use std::string_view in C++17 - if (fetched_length < buffer_length) - *((char*)buffer + fetched_length) = '\0'; - break; - default: - break; + case MYSQL_TYPE_TINY_BLOB: + case MYSQL_TYPE_MEDIUM_BLOB: + case MYSQL_TYPE_LONG_BLOB: + case MYSQL_TYPE_BLOB: + case MYSQL_TYPE_STRING: + case MYSQL_TYPE_VAR_STRING: + // warning - the string will not be null-terminated if there is no space for it in the buffer + // when mysql_stmt_fetch returned MYSQL_DATA_TRUNCATED + // we cannot blindly null-terminate the data either as it may be retrieved as binary blob and not specifically a string + // in this case using Field::GetCString will result in garbage + // TODO: remove Field::GetCString and use std::string_view in C++17 + if (fetched_length < buffer_length) + *((char*)buffer + fetched_length) = '\0'; + break; + default: + break; } - m_rows[uint32(m_rowPosition) * m_fieldCount + fIndex].SetByteValue((char const*)buffer, fetched_length); + _rows[uint32(_rowPosition) * _fieldCount + fIndex].SetByteValue((char const*)buffer, fetched_length); // move buffer pointer to next part - m_stmt->bind[fIndex].buffer = (char*)buffer + rowSize; + _stmt->bind[fIndex].buffer = (char*)buffer + rowSize; } else { - m_rows[uint32(m_rowPosition) * m_fieldCount + fIndex].SetByteValue(nullptr, *m_rBind[fIndex].length); + _rows[uint32(_rowPosition) * _fieldCount + fIndex].SetByteValue(nullptr, *_rBind[fIndex].length); } } - m_rowPosition++; + _rowPosition++; } - m_rowPosition = 0; + _rowPosition = 0; /// All data is buffered, let go of mysql c api structures - mysql_stmt_free_result(m_stmt); + mysql_stmt_free_result(_stmt); } PreparedResultSet::~PreparedResultSet() @@ -386,7 +374,7 @@ bool PreparedResultSet::NextRow() { /// Only updates the m_rowPosition so upper level code knows in which element /// of the rows vector to look - if (++m_rowPosition >= m_rowCount) + if (++_rowPosition >= _rowCount) return false; return true; @@ -396,41 +384,41 @@ bool PreparedResultSet::_NextRow() { /// Only called in low-level code, namely the constructor /// Will iterate over every row of data and buffer it - if (m_rowPosition >= m_rowCount) + if (_rowPosition >= _rowCount) return false; - int retval = mysql_stmt_fetch(m_stmt); - return retval == 0 || retval == MYSQL_DATA_TRUNCATED; + int mysqlStmtFetch = mysql_stmt_fetch(_stmt); + return mysqlStmtFetch == 0 || mysqlStmtFetch == MYSQL_DATA_TRUNCATED; } Field* PreparedResultSet::Fetch() const { - ASSERT(m_rowPosition < m_rowCount); - return const_cast(&m_rows[uint32(m_rowPosition) * m_fieldCount]); + ASSERT(_rowPosition < _rowCount); + return const_cast(&_rows[uint32(_rowPosition) * _fieldCount]); } Field const& PreparedResultSet::operator[](std::size_t index) const { - ASSERT(m_rowPosition < m_rowCount); - ASSERT(index < m_fieldCount); - return m_rows[uint32(m_rowPosition) * m_fieldCount + index]; + ASSERT(_rowPosition < _rowCount); + ASSERT(index < _fieldCount); + return _rows[uint32(_rowPosition) * _fieldCount + index]; } void PreparedResultSet::CleanUp() { - if (m_metadataResult) - mysql_free_result(m_metadataResult); + if (_metadataResult) + mysql_free_result(_metadataResult); - if (m_rBind) + if (_rBind) { - delete[](char*)m_rBind->buffer; - delete[] m_rBind; - m_rBind = nullptr; + delete[] (char*)_rBind->buffer; + delete[] _rBind; + _rBind = nullptr; } } -void PreparedResultSet::AssertRows(std::size_t sizeRows) +void PreparedResultSet::AssertRows(std::size_t sizeRows) const { - ASSERT(m_rowPosition < m_rowCount); - ASSERT(sizeRows == m_fieldCount, "> Tuple size != count fields"); + ASSERT(_rowPosition < _rowCount); + ASSERT(sizeRows == _fieldCount, "> Tuple size != count fields"); } diff --git a/src/server/database/Database/QueryResult.h b/src/server/database/Database/QueryResult.h index f0cf4e9b5ce67f..d9b849245543b6 100644 --- a/src/server/database/Database/QueryResult.h +++ b/src/server/database/Database/QueryResult.h @@ -19,10 +19,8 @@ #define QUERYRESULT_H #include "DatabaseEnvFwd.h" -#include "Define.h" #include "Field.h" -#include -#include +#include template struct ResultIterator @@ -56,7 +54,7 @@ class AC_DATABASE_API ResultSet [[nodiscard]] uint32 GetFieldCount() const { return _fieldCount; } [[nodiscard]] std::string GetFieldName(uint32 index) const; - [[nodiscard]] Field* Fetch() const { return _currentRow; } + [[nodiscard]] auto* Fetch() const { return _currRow.get(); } Field const& operator[](std::size_t index) const; template @@ -64,12 +62,12 @@ class AC_DATABASE_API ResultSet { AssertRows(sizeof...(Ts)); - std::tuple theTuple = {}; + std::tuple theTuple{}; std::apply([this](Ts&... args) { - uint8 index{ 0 }; - ((args = _currentRow[index].Get(), index++), ...); + uint8 index{}; + ((args = _currRow[index].Get(), index++), ...); }, theTuple); return theTuple; @@ -81,12 +79,12 @@ class AC_DATABASE_API ResultSet protected: std::vector _fieldMetadata; uint64 _rowCount; - Field* _currentRow; + std::unique_ptr _currRow; uint32 _fieldCount; private: void CleanUp(); - void AssertRows(std::size_t sizeRows); + void AssertRows(std::size_t sizeRows) const; MySQLResult* _result; MySQLField* _fields; @@ -102,8 +100,8 @@ class AC_DATABASE_API PreparedResultSet ~PreparedResultSet(); bool NextRow(); - [[nodiscard]] uint64 GetRowCount() const { return m_rowCount; } - [[nodiscard]] uint32 GetFieldCount() const { return m_fieldCount; } + [[nodiscard]] uint64 GetRowCount() const { return _rowCount; } + [[nodiscard]] uint32 GetFieldCount() const { return _fieldCount; } [[nodiscard]] Field* Fetch() const; Field const& operator[](std::size_t index) const; @@ -118,7 +116,7 @@ class AC_DATABASE_API PreparedResultSet std::apply([this](Ts&... args) { uint8 index{ 0 }; - ((args = m_rows[uint32(m_rowPosition) * m_fieldCount + index].Get(), index++), ...); + ((args = _rows[uint32(_rowPosition) * _fieldCount + index].Get(), index++), ...); }, theTuple); return theTuple; @@ -128,21 +126,21 @@ class AC_DATABASE_API PreparedResultSet static auto end() { return ResultIterator(nullptr); } protected: - std::vector m_fieldMetadata; - std::vector m_rows; - uint64 m_rowCount; - uint64 m_rowPosition; - uint32 m_fieldCount; + std::vector _fieldMetadata; + std::vector _rows; + uint64 _rowCount; + uint64 _rowPosition{}; + uint32 _fieldCount; private: - MySQLBind* m_rBind; - MySQLStmt* m_stmt; - MySQLResult* m_metadataResult; ///< Field metadata, returned by mysql_stmt_result_metadata + MySQLBind* _rBind{ nullptr }; + MySQLStmt* _stmt; + MySQLResult* _metadataResult; ///< Field metadata, returned by mysql_stmt_result_metadata void CleanUp(); bool _NextRow(); - void AssertRows(std::size_t sizeRows); + void AssertRows(std::size_t sizeRows) const; PreparedResultSet(PreparedResultSet const& right) = delete; PreparedResultSet& operator=(PreparedResultSet const& right) = delete; diff --git a/src/server/database/Database/SQLOperation.h b/src/server/database/Database/SQLOperation.h deleted file mode 100644 index 89542886b3200f..00000000000000 --- a/src/server/database/Database/SQLOperation.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU Affero General Public License as published by the - * Free Software Foundation; either version 3 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see . - */ - -#ifndef _SQLOPERATION_H -#define _SQLOPERATION_H - -#include "DatabaseEnvFwd.h" -#include "Define.h" -#include - -//- Type specifier of our element data -enum SQLElementDataType -{ - SQL_ELEMENT_RAW, - SQL_ELEMENT_PREPARED -}; - -//- The element -struct SQLElementData -{ - std::variant element; - SQLElementDataType type; -}; - -class MySQLConnection; - -class AC_DATABASE_API SQLOperation -{ -public: - SQLOperation() = default; - virtual ~SQLOperation() = default; - - virtual int call() - { - Execute(); - return 0; - } - - virtual bool Execute() = 0; - virtual void SetConnection(MySQLConnection* con) { m_conn = con; } - - MySQLConnection* m_conn{nullptr}; - -private: - SQLOperation(SQLOperation const& right) = delete; - SQLOperation& operator=(SQLOperation const& right) = delete; -}; - -#endif diff --git a/src/server/database/Database/Transaction.cpp b/src/server/database/Database/Transaction.cpp index d5cf4fcebf849e..af0e9f64fb5b7d 100644 --- a/src/server/database/Database/Transaction.cpp +++ b/src/server/database/Database/Transaction.cpp @@ -26,34 +26,33 @@ #include std::mutex TransactionTask::_deadlockLock; - constexpr Milliseconds DEADLOCK_MAX_RETRY_TIME_MS = 1min; //- Append a raw ad-hoc query to the transaction -void TransactionBase::Append(std::string_view sql) +void Transaction::Append(std::string_view sql) { - SQLElementData data = {}; + SQLElementData data{}; data.type = SQL_ELEMENT_RAW; - data.element = std::string(sql); - m_queries.emplace_back(data); + data.element = std::string{ sql }; + _queries.emplace_back(data); } //- Append a prepared statement to the transaction -void TransactionBase::AppendPreparedStatement(PreparedStatementBase* stmt) +void Transaction::Append(PreparedStatement stmt) { - SQLElementData data = {}; + SQLElementData data{}; data.type = SQL_ELEMENT_PREPARED; data.element = stmt; - m_queries.emplace_back(data); + _queries.emplace_back(data); } -void TransactionBase::Cleanup() +void Transaction::Cleanup() { - // This might be called by explicit calls to Cleanup or by the auto-destructor + // This might be called by explicit calls to Clean up or by the auto-destructor if (_cleanedUp) return; - for (SQLElementData& data : m_queries) + for (SQLElementData& data : _queries) { switch (data.type) { @@ -61,15 +60,13 @@ void TransactionBase::Cleanup() { try { - PreparedStatementBase* stmt = std::get(data.element); + auto stmt = std::get(data.element); ASSERT(stmt); - - delete stmt; } catch (const std::bad_variant_access& ex) { - LOG_FATAL("sql.sql", "> PreparedStatementBase not found in SQLElementData. {}", ex.what()); - ABORT(); + LOG_FATAL("db.query", "> PreparedStatementBase not found in SQLElementData. {}", ex.what()); + ABORT(""); } } break; @@ -81,24 +78,23 @@ void TransactionBase::Cleanup() } catch (const std::bad_variant_access& ex) { - LOG_FATAL("sql.sql", "> std::string not found in SQLElementData. {}", ex.what()); - ABORT(); + LOG_FATAL("db.query", "> std::string not found in SQLElementData. {}", ex.what()); + ABORT(""); } } break; } } - m_queries.clear(); + _queries.clear(); _cleanedUp = true; } -bool TransactionTask::Execute() +void TransactionTask::ExecuteQuery() { int errorCode = TryExecute(); - if (!errorCode) - return true; + return; if (errorCode == ER_LOCK_DEADLOCK) { @@ -107,44 +103,42 @@ bool TransactionTask::Execute() std::string threadId = threadIdStream.str(); { - // Make sure only 1 async thread retries a transaction so they don't keep dead-locking each other + // Make sure only 1 async thread retries a transaction, so they don't keep deadlocking each other std::lock_guard lock(_deadlockLock); - for (Milliseconds loopDuration{}, startMSTime = GetTimeMS(); loopDuration <= DEADLOCK_MAX_RETRY_TIME_MS; loopDuration = GetMSTimeDiffToNow(startMSTime)) + for (Milliseconds loopDuration = 0s, startMSTime = GetTimeMS(); loopDuration <= DEADLOCK_MAX_RETRY_TIME_MS; loopDuration = GetMSTimeDiffToNow(startMSTime)) { if (!TryExecute()) - return true; + return; - LOG_WARN("sql.sql", "Deadlocked SQL Transaction, retrying. Loop timer: {} ms, Thread Id: {}", loopDuration.count(), threadId); + LOG_WARN("db.query", "Deadlocked SQL Transaction, retrying. Loop timer: {} ms, Thread Id: {}", loopDuration.count(), threadId); } } - LOG_ERROR("sql.sql", "Fatal deadlocked SQL Transaction, it will not be retried anymore. Thread Id: {}", threadId); + LOG_ERROR("db.query", "Fatal deadlocked SQL Transaction, it will not be retried anymore. Thread Id: {}", threadId); } // Clean up now. CleanupOnFailure(); - - return false; } -int TransactionTask::TryExecute() +int32 TransactionTask::TryExecute() { - return m_conn->ExecuteTransaction(m_trans); + return _connection->ExecuteTransaction(_trans); } void TransactionTask::CleanupOnFailure() { - m_trans->Cleanup(); + _trans->Cleanup(); } -bool TransactionWithResultTask::Execute() +void TransactionWithResultTask::ExecuteQuery() { int errorCode = TryExecute(); if (!errorCode) { - m_result.set_value(true); - return true; + _result.set_value(true); + return; } if (errorCode == ER_LOCK_DEADLOCK) @@ -154,36 +148,34 @@ bool TransactionWithResultTask::Execute() std::string threadId = threadIdStream.str(); { - // Make sure only 1 async thread retries a transaction so they don't keep dead-locking each other + // Make sure only 1 async thread retries a transaction, so they don't keep deadlocking each other std::lock_guard lock(_deadlockLock); - for (Milliseconds loopDuration{}, startMSTime = GetTimeMS(); loopDuration <= DEADLOCK_MAX_RETRY_TIME_MS; loopDuration = GetMSTimeDiffToNow(startMSTime)) + for (Milliseconds loopDuration = 0s, startMSTime = GetTimeMS(); loopDuration <= DEADLOCK_MAX_RETRY_TIME_MS; loopDuration = GetMSTimeDiffToNow(startMSTime)) { if (!TryExecute()) { - m_result.set_value(true); - return true; + _result.set_value(true); + return; } - LOG_WARN("sql.sql", "Deadlocked SQL Transaction, retrying. Loop timer: {} ms, Thread Id: {}", loopDuration.count(), threadId); + LOG_WARN("db.query", "Deadlocked SQL Transaction, retrying. Loop timer: {} ms, Thread Id: {}", loopDuration.count(), threadId); } } - LOG_ERROR("sql.sql", "Fatal deadlocked SQL Transaction, it will not be retried anymore. Thread Id: {}", threadId); + LOG_ERROR("db.query", "Fatal deadlocked SQL Transaction, it will not be retried anymore. Thread Id: {}", threadId); } // Clean up now. CleanupOnFailure(); - m_result.set_value(false); - - return false; + _result.set_value(false); } bool TransactionCallback::InvokeIfReady() { - if (m_future.valid() && m_future.wait_for(0s) == std::future_status::ready) + if (_future.valid() && _future.wait_for(0s) == std::future_status::ready) { - m_callback(m_future.get()); + _callback(_future.get()); return true; } diff --git a/src/server/database/Database/Transaction.h b/src/server/database/Database/Transaction.h index 5d82703ae984d2..9349aedf3c14db 100644 --- a/src/server/database/Database/Transaction.h +++ b/src/server/database/Database/Transaction.h @@ -18,27 +18,32 @@ #ifndef _TRANSACTION_H #define _TRANSACTION_H -#include "DatabaseEnvFwd.h" -#include "Define.h" -#include "SQLOperation.h" +#include "DatabaseAsyncOperation.h" #include "StringFormat.h" #include #include -#include +#include #include -/*! Transactions, high level class. */ -class AC_DATABASE_API TransactionBase +//- Type specifier of our element data +enum SQLElementDataType { - friend class TransactionTask; - friend class MySQLConnection; + SQL_ELEMENT_RAW, + SQL_ELEMENT_PREPARED +}; - template - friend class DatabaseWorkerPool; +//- The element +struct SQLElementData +{ + std::variant element; + SQLElementDataType type; +}; +class AC_DATABASE_API Transaction +{ public: - TransactionBase() = default; - virtual ~TransactionBase() { Cleanup(); } + Transaction() = default; + virtual ~Transaction() { Cleanup(); } void Append(std::string_view sql); @@ -48,81 +53,65 @@ class AC_DATABASE_API TransactionBase Append(Acore::StringFormatFmt(sql, std::forward(args)...)); } - [[nodiscard]] std::size_t GetSize() const { return m_queries.size(); } + void Append(PreparedStatement stmt); + + [[nodiscard]] std::size_t GetSize() const { return _queries.size(); } + auto GetQueries() { return &_queries; } -protected: - void AppendPreparedStatement(PreparedStatementBase* statement); void Cleanup(); - std::vector m_queries; private: + std::vector _queries; bool _cleanedUp{false}; }; -template -class Transaction : public TransactionBase +class AC_DATABASE_API TransactionTask : public AsyncOperation { public: - using TransactionBase::Append; - - void Append(PreparedStatement* statement) - { - AppendPreparedStatement(statement); - } -}; + explicit TransactionTask(SQLTransaction trans) : + AsyncOperation(), _trans(std::move(trans)) { } -/*! Low level class*/ -class AC_DATABASE_API TransactionTask : public SQLOperation -{ - template - friend class DatabaseWorkerPool; - - friend class DatabaseWorker; - friend class TransactionCallback; - -public: - TransactionTask(std::shared_ptr trans) : m_trans(std::move(trans)) { } ~TransactionTask() override = default; protected: - bool Execute() override; - int TryExecute(); + void ExecuteQuery() override; + int32 TryExecute(); void CleanupOnFailure(); - std::shared_ptr m_trans; + std::shared_ptr _trans; static std::mutex _deadlockLock; }; class AC_DATABASE_API TransactionWithResultTask : public TransactionTask { public: - TransactionWithResultTask(std::shared_ptr trans) : TransactionTask(trans) { } + explicit TransactionWithResultTask(SQLTransaction trans) : TransactionTask(trans) { } - TransactionFuture GetFuture() { return m_result.get_future(); } + TransactionFuture GetFuture() { return _result.get_future(); } protected: - bool Execute() override; + void ExecuteQuery() override; - TransactionPromise m_result; + TransactionPromise _result; }; class AC_DATABASE_API TransactionCallback { public: - TransactionCallback(TransactionFuture&& future) : m_future(std::move(future)) { } + TransactionCallback(TransactionFuture&& future) : _future(std::move(future)) { } TransactionCallback(TransactionCallback&&) = default; TransactionCallback& operator=(TransactionCallback&&) = default; - void AfterComplete(std::function callback) & + void AfterComplete(std::function&& callback) { - m_callback = std::move(callback); + _callback = std::move(callback); } bool InvokeIfReady(); - TransactionFuture m_future; - std::function m_callback; + TransactionFuture _future; + std::function _callback; }; #endif diff --git a/src/server/database/Logging/AppenderDB.cpp b/src/server/database/Logging/AppenderDB.cpp index 1878bb3637acfb..66179dc240d567 100644 --- a/src/server/database/Logging/AppenderDB.cpp +++ b/src/server/database/Logging/AppenderDB.cpp @@ -18,20 +18,19 @@ #include "AppenderDB.h" #include "DatabaseEnv.h" #include "LogMessage.h" -#include "PreparedStatement.h" AppenderDB::AppenderDB(uint8 id, std::string const& name, LogLevel level, AppenderFlags /*flags*/, std::vector const& /*args*/) : Appender(id, name, level), realmId(0), enabled(false) { } -AppenderDB::~AppenderDB() { } +AppenderDB::~AppenderDB() = default; void AppenderDB::_write(LogMessage const* message) { - // Avoid infinite loop, Execute triggers Logging with "sql.sql" type - if (!enabled || (message->type.find("sql") != std::string::npos)) + // Avoid infinite loop, Execute triggers Logging with "db.query" type + if (!enabled || (message->type.find("db") != std::string::npos) || (message->type.find("sql") != std::string::npos)) return; - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_LOG); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_LOG); stmt->SetData(0, message->mtime.count()); stmt->SetData(1, realmId); stmt->SetData(2, message->type); diff --git a/src/server/database/Logging/AppenderDB.h b/src/server/database/Logging/AppenderDB.h index fbafc635c170c4..b6d3974963713a 100644 --- a/src/server/database/Logging/AppenderDB.h +++ b/src/server/database/Logging/AppenderDB.h @@ -26,10 +26,10 @@ class AppenderDB : public Appender static constexpr AppenderType type = APPENDER_DB; AppenderDB(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, std::vector const& args); - ~AppenderDB(); + ~AppenderDB() override; void setRealmId(uint32 realmId) override; - AppenderType getType() const override { return type; } + [[nodiscard]] AppenderType getType() const override { return type; } private: uint32 realmId; diff --git a/src/server/database/PrecompiledHeaders/databasePCH.h b/src/server/database/PrecompiledHeaders/databasePCH.h index eeecef21204c96..b3293ec8af7017 100644 --- a/src/server/database/PrecompiledHeaders/databasePCH.h +++ b/src/server/database/PrecompiledHeaders/databasePCH.h @@ -15,6 +15,7 @@ * with this program. If not, see . */ +#include "DatabaseAsyncOperation.h" #include "DatabaseEnvFwd.h" #include "Define.h" #include "Errors.h" @@ -25,11 +26,11 @@ #include "MySQLWorkaround.h" #include "PreparedStatement.h" #include "QueryResult.h" -#include "SQLOperation.h" #include "Transaction.h" +#include +#include + #ifdef _WIN32 // hack for broken mysql.h not including the correct winsock header for SOCKET definition, fixed in 5.7 #include #endif #include -#include -#include diff --git a/src/server/database/Updater/DBUpdater.cpp b/src/server/database/Updater/DBUpdater.cpp index 30eea96e2d4e98..c1bf2ef240acb4 100644 --- a/src/server/database/Updater/DBUpdater.cpp +++ b/src/server/database/Updater/DBUpdater.cpp @@ -19,22 +19,22 @@ #include "BuiltInConfig.h" #include "Config.h" #include "DatabaseEnv.h" -#include "DatabaseLoader.h" #include "GitRevision.h" #include "Log.h" -#include "QueryResult.h" +#include "MySQLConnection.h" #include "StartProcess.h" #include "UpdateFetcher.h" -#include #include #include +constexpr auto SQL_BASE_DIR = "/data/sql/base/"; + std::string DBUpdaterUtil::GetCorrectedMySQLExecutable() { if (!corrected_path().empty()) return corrected_path(); - else - return BuiltInConfig::GetMySQLExecutable(); + + return BuiltInConfig::GetMySQLExecutable(); } bool DBUpdaterUtil::CheckExecutable() @@ -50,11 +50,12 @@ bool DBUpdaterUtil::CheckExecutable() return true; } - LOG_FATAL("sql.updates", "Didn't find any executable MySQL binary at \'{}\' or in path, correct the path in the *.conf (\"MySQLExecutable\").", + LOG_FATAL("db.update", "Didn't find any executable MySQL binary at \'{}\' or in path, correct the path in the *.conf (\"MySQLExecutable\").", absolute(exe).generic_string()); return false; } + return true; } @@ -64,126 +65,71 @@ std::string& DBUpdaterUtil::corrected_path() return path; } -// Auth Database -template<> -std::string DBUpdater::GetConfigEntry() +std::string DBUpdater::GetConfigEntry(DatabaseWorkerPool const& pool) { - return "Updates.Auth"; -} + if (pool.GetType() == DatabaseType::Auth) + return "Updates.Auth"; -template<> -std::string DBUpdater::GetTableName() -{ - return "Auth"; + return "Updates." + std::string{ pool.GetPoolName() }; } -template<> -std::string DBUpdater::GetBaseFilesDirectory() +std::string DBUpdater::GetTableName(DatabaseWorkerPool const& pool) { - return BuiltInConfig::GetSourceDirectory() + "/data/sql/base/db_auth/"; + return std::string{ pool.GetPoolName() }; } -template<> -bool DBUpdater::IsEnabled(uint32 const updateMask) +std::string DBUpdater::GetBaseFilesDirectory(DatabaseWorkerPool const& pool) { - // This way silences warnings under msvc - return (updateMask & DatabaseLoader::DATABASE_LOGIN) ? true : false; -} + std::string folderName{ "db_" }; -template<> -std::string DBUpdater::GetDBModuleName() -{ - return "db-auth"; -} - -// World Database -template<> -std::string DBUpdater::GetConfigEntry() -{ - return "Updates.World"; -} - -template<> -std::string DBUpdater::GetTableName() -{ - return "World"; -} + if (pool.GetType() == DatabaseType::Auth) // Workaround for AC + folderName += "auth"; + else if (pool.GetType() == DatabaseType::Character) + folderName += "characters"; + else + std::transform(pool.GetPoolName().begin(), pool.GetPoolName().end(), std::back_inserter(folderName), ::tolower); -template<> -std::string DBUpdater::GetBaseFilesDirectory() -{ - return BuiltInConfig::GetSourceDirectory() + "/data/sql/base/db_world/"; + folderName += "/"; + return BuiltInConfig::GetSourceDirectory() + SQL_BASE_DIR + folderName; } -template<> -bool DBUpdater::IsEnabled(uint32 const updateMask) +bool DBUpdater::IsEnabled(DatabaseWorkerPool& pool, uint32 updateMask) { // This way silences warnings under msvc - return (updateMask & DatabaseLoader::DATABASE_WORLD) ? true : false; -} - -template<> -std::string DBUpdater::GetDBModuleName() -{ - return "db-world"; -} - -// Character Database -template<> -std::string DBUpdater::GetConfigEntry() -{ - return "Updates.Character"; -} - -template<> -std::string DBUpdater::GetTableName() -{ - return "Character"; -} - -template<> -std::string DBUpdater::GetBaseFilesDirectory() -{ - return BuiltInConfig::GetSourceDirectory() + "/data/sql/base/db_characters/"; + return (updateMask & (uint32)pool.GetType()) != 0; } -template<> -bool DBUpdater::IsEnabled(uint32 const updateMask) +std::string DBUpdater::GetDBModuleName(DatabaseWorkerPool const& pool) { - // This way silences warnings under msvc - return (updateMask & DatabaseLoader::DATABASE_CHARACTER) ? true : false; -} + std::string folderName{ "db_" }; -template<> -std::string DBUpdater::GetDBModuleName() -{ - return "db-characters"; -} + if (pool.GetType() == DatabaseType::Auth) // Workaround for AC + folderName += "auth"; + else if (pool.GetType() == DatabaseType::Character) + folderName += "characters"; + else + std::transform(pool.GetPoolName().begin(), pool.GetPoolName().end(), std::back_inserter(folderName), ::tolower); -// All -template -BaseLocation DBUpdater::GetBaseLocationType() -{ - return LOCATION_REPOSITORY; + folderName += "/"; + return folderName; } -template -bool DBUpdater::Create(DatabaseWorkerPool& pool) +bool DBUpdater::Create(DatabaseWorkerPool& pool) { - LOG_WARN("sql.updates", "Database \"{}\" does not exist", pool.GetConnectionInfo()->database); + LOG_WARN("db.update", "Database \"{}\" does not exist, do you want to create it? [yes (default) / no]: ", + pool.GetConnectionInfo()->Database); const char* disableInteractive = std::getenv("AC_DISABLE_INTERACTIVE"); if (!sConfigMgr->isDryRun() && (disableInteractive == nullptr || std::strcmp(disableInteractive, "1") != 0)) { - std::cout << "Do you want to create it? [yes (default) / no]:" << std::endl; std::string answer; std::getline(std::cin, answer); if (!answer.empty() && !(answer.substr(0, 1) == "y")) return false; } - LOG_INFO("sql.updates", "Creating database \"{}\"...", pool.GetConnectionInfo()->database); + LOG_INFO("db.update", "Creating database \"{}\"...", pool.GetConnectionInfo()->Database); // Path of temp file static Path const temp("create_table.sql"); @@ -192,64 +138,63 @@ bool DBUpdater::Create(DatabaseWorkerPool& pool) std::ofstream file(temp.generic_string()); if (!file.is_open()) { - LOG_FATAL("sql.updates", "Failed to create temporary query file \"{}\"!", temp.generic_string()); + LOG_FATAL("db.update", "Failed to create temporary query file \"{}\"!", temp.generic_string()); return false; } - file << "CREATE DATABASE `" << pool.GetConnectionInfo()->database << "` DEFAULT CHARACTER SET UTF8MB4 COLLATE utf8mb4_general_ci;\n\n"; + file << "CREATE DATABASE `" << pool.GetConnectionInfo()->Database << "` DEFAULT CHARACTER SET UTF8MB4 COLLATE utf8mb4_general_ci;\n\n"; file.close(); try { - DBUpdater::ApplyFile(pool, pool.GetConnectionInfo()->host, pool.GetConnectionInfo()->user, pool.GetConnectionInfo()->password, - pool.GetConnectionInfo()->port_or_socket, "", pool.GetConnectionInfo()->ssl, temp); + DBUpdater::ApplyFile(pool, pool.GetConnectionInfo()->Host, pool.GetConnectionInfo()->User, pool.GetConnectionInfo()->Password, + pool.GetConnectionInfo()->PortOrSocket, "", pool.GetConnectionInfo()->SSL, temp); } - catch (UpdateException&) + catch (UpdateException const&) { - LOG_FATAL("sql.updates", "Failed to create database {}! Does the user (named in *.conf) have `CREATE`, `ALTER`, `DROP`, `INSERT` and `DELETE` privileges on the MySQL server?", pool.GetConnectionInfo()->database); + LOG_FATAL("db.update", "Failed to create database {}! Does the user (named in *.conf) have `CREATE`, `ALTER`, `DROP`, `INSERT` and `DELETE` privileges on the MySQL server?", pool.GetConnectionInfo()->Database); std::filesystem::remove(temp); return false; } - LOG_INFO("sql.updates", "Done."); - LOG_INFO("sql.updates", " "); + LOG_INFO("db.update", "Done."); + LOG_INFO("db.update", " "); std::filesystem::remove(temp); return true; } -template -bool DBUpdater::Update(DatabaseWorkerPool& pool, std::string_view modulesList /*= {}*/) +bool DBUpdater::Update(DatabaseWorkerPool& pool, std::string_view modulesList /*= {}*/) { if (!DBUpdaterUtil::CheckExecutable()) return false; - LOG_INFO("sql.updates", "Updating {} database...", DBUpdater::GetTableName()); + LOG_INFO("db.update", "Updating {} database...", DBUpdater::GetTableName(pool)); Path const sourceDirectory(BuiltInConfig::GetSourceDirectory()); if (!is_directory(sourceDirectory)) { - LOG_ERROR("sql.updates", "DBUpdater: The given source directory {} does not exist, change the path to the directory where your sql directory exists (for example c:\\source\\azerothcore). Shutting down.", - sourceDirectory.generic_string()); + LOG_ERROR("db.update", "DBUpdater: The given source directory {} does not exist, change the path to the directory where your sql directory exists (for example c:\\source\\trinitycore). Shutting down.", + sourceDirectory.generic_string()); return false; } auto CheckUpdateTable = [&](std::string const& tableName) { - auto checkTable = DBUpdater::Retrieve(pool, Acore::StringFormatFmt("SHOW TABLES LIKE '{}'", tableName)); + auto checkTable = DBUpdater::Retrieve(pool, Acore::StringFormatFmt("SHOW TABLES LIKE '{}'", tableName)); if (!checkTable) { - LOG_WARN("sql.updates", "> Table '{}' not exist! Try add based table", tableName); + LOG_WARN("db.update", "> Table '{}' not exist! Try add based table", tableName); - Path const temp(GetBaseFilesDirectory() + tableName + ".sql"); + Path const temp(GetBaseFilesDirectory(pool) + tableName + ".sql"); try { - DBUpdater::ApplyFile(pool, temp); + DBUpdater::ApplyFile(pool, temp); } catch (UpdateException&) { - LOG_FATAL("sql.updates", "Failed apply file to database {}! Does the user (named in *.conf) have `INSERT` and `DELETE` privileges on the MySQL server?", pool.GetConnectionInfo()->database); + LOG_FATAL("db.update", "Failed apply file to database {}! Does the user (named in *.conf) have `INSERT` and `DELETE` privileges on the MySQL server?", pool.GetConnectionInfo()->Database); return false; } @@ -262,18 +207,14 @@ bool DBUpdater::Update(DatabaseWorkerPool& pool, std::string_view modulesL if (!CheckUpdateTable("updates") || !CheckUpdateTable("updates_include")) return false; - UpdateFetcher updateFetcher(sourceDirectory, [&](std::string const & query) { DBUpdater::Apply(pool, query); }, - [&](Path const & file) { DBUpdater::ApplyFile(pool, file); }, - [&](std::string const & query) -> QueryResult { return DBUpdater::Retrieve(pool, query); }, DBUpdater::GetDBModuleName(), modulesList); + UpdateFetcher updateFetcher(sourceDirectory, [&pool](std::string_view query) { DBUpdater::Apply(pool, query); }, + [&pool](Path const& file) { DBUpdater::ApplyFile(pool, file); }, + [&pool](std::string_view query) -> QueryResult { return DBUpdater::Retrieve(pool, query); }, DBUpdater::GetDBModuleName(pool), modulesList); UpdateResult result; try { - result = updateFetcher.Update( - sConfigMgr->GetOption("Updates.Redundancy", true), - sConfigMgr->GetOption("Updates.AllowRehash", true), - sConfigMgr->GetOption("Updates.ArchivedRedundancy", false), - sConfigMgr->GetOption("Updates.CleanDeadRefMaxCount", 3)); + result = updateFetcher.Update(); } catch (UpdateException&) { @@ -283,38 +224,32 @@ bool DBUpdater::Update(DatabaseWorkerPool& pool, std::string_view modulesL std::string const info = Acore::StringFormatFmt("Containing {} new and {} archived updates.", result.recent, result.archived); if (!result.updated) - LOG_INFO("sql.updates", ">> {} database is up-to-date! {}", DBUpdater::GetTableName(), info); + LOG_INFO("db.update", ">> {} database is up-to-date! {}", DBUpdater::GetTableName(pool), info); else - LOG_INFO("sql.updates", ">> Applied {} {}. {}", result.updated, result.updated == 1 ? "query" : "queries", info); - - LOG_INFO("sql.updates", " "); + LOG_INFO("db.update", ">> Applied {} {}. {}", result.updated, result.updated == 1 ? "query" : "queries", info); + LOG_INFO("db.update", " "); return true; } -template -bool DBUpdater::Update(DatabaseWorkerPool& pool, std::vector const* setDirectories) +bool DBUpdater::Update(DatabaseWorkerPool& pool, std::vector const* setDirectories) { if (!DBUpdaterUtil::CheckExecutable()) - { return false; - } Path const sourceDirectory(BuiltInConfig::GetSourceDirectory()); if (!is_directory(sourceDirectory)) - { return false; - } auto CheckUpdateTable = [&](std::string const& tableName) { - auto checkTable = DBUpdater::Retrieve(pool, Acore::StringFormatFmt("SHOW TABLES LIKE '{}'", tableName)); + auto checkTable = DBUpdater::Retrieve(pool, Acore::StringFormatFmt("SHOW TABLES LIKE '{}'", tableName)); if (!checkTable) { - Path const temp(GetBaseFilesDirectory() + tableName + ".sql"); + Path const temp(GetBaseFilesDirectory(pool) + tableName + ".sql"); try { - DBUpdater::ApplyFile(pool, temp); + DBUpdater::ApplyFile(pool, temp); } catch (UpdateException&) { @@ -332,18 +267,14 @@ bool DBUpdater::Update(DatabaseWorkerPool& pool, std::vector return false; } - UpdateFetcher updateFetcher(sourceDirectory, [&](std::string const & query) { DBUpdater::Apply(pool, query); }, - [&](Path const & file) { DBUpdater::ApplyFile(pool, file); }, - [&](std::string const & query) -> QueryResult { return DBUpdater::Retrieve(pool, query); }, DBUpdater::GetDBModuleName(), setDirectories); + UpdateFetcher updateFetcher(sourceDirectory, [&pool](std::string_view query) { DBUpdater::Apply(pool, query); }, + [&pool](Path const& file) { DBUpdater::ApplyFile(pool, file); }, + [&pool](std::string_view query) -> QueryResult { return DBUpdater::Retrieve(pool, query); }, DBUpdater::GetDBModuleName(pool), setDirectories); UpdateResult result; try { - result = updateFetcher.Update( - sConfigMgr->GetOption("Updates.Redundancy", true), - sConfigMgr->GetOption("Updates.AllowRehash", true), - sConfigMgr->GetOption("Updates.ArchivedRedundancy", false), - sConfigMgr->GetOption("Updates.CleanDeadRefMaxCount", 3)); + result = updateFetcher.Update(); } catch (UpdateException&) { @@ -353,8 +284,7 @@ bool DBUpdater::Update(DatabaseWorkerPool& pool, std::vector return true; } -template -bool DBUpdater::Populate(DatabaseWorkerPool& pool) +bool DBUpdater::Populate(DatabaseWorkerPool& pool) { { QueryResult const result = Retrieve(pool, "SHOW TABLES"); @@ -365,48 +295,48 @@ bool DBUpdater::Populate(DatabaseWorkerPool& pool) if (!DBUpdaterUtil::CheckExecutable()) return false; - LOG_INFO("sql.updates", "Database {} is empty, auto populating it...", DBUpdater::GetTableName()); + LOG_INFO("db.update", "Database {} is empty, auto populating it...", DBUpdater::GetTableName(pool)); - std::string const DirPathStr = DBUpdater::GetBaseFilesDirectory(); + std::string const dirPathStr = DBUpdater::GetBaseFilesDirectory(pool); - Path const DirPath(DirPathStr); - if (!std::filesystem::is_directory(DirPath)) + Path const dirPath(dirPathStr); + if (dirPath.empty()) { - LOG_ERROR("sql.updates", ">> Directory \"{}\" not exist", DirPath.generic_string()); + LOG_ERROR("db.update", ">> Directory \"{}\" is empty", dirPath.generic_string()); return false; } - if (DirPath.empty()) + if (!std::filesystem::is_directory(dirPath)) { - LOG_ERROR("sql.updates", ">> Directory \"{}\" is empty", DirPath.generic_string()); + LOG_ERROR("db.update", ">> Directory \"{}\" not exist", dirPath.generic_string()); return false; } - std::filesystem::directory_iterator const DirItr; - uint32 FilesCount = 0; + std::size_t filesCount{ 0 }; - for (std::filesystem::directory_iterator itr(DirPath); itr != DirItr; ++itr) + for (auto const& dirEntry : std::filesystem::directory_iterator(dirPath)) { - if (itr->path().extension() == ".sql") - FilesCount++; + if (dirEntry.path().extension() == ".sql") + filesCount++; } - if (!FilesCount) + if (!filesCount) { - LOG_ERROR("sql.updates", ">> In directory \"{}\" not exist '*.sql' files", DirPath.generic_string()); + LOG_ERROR("db.update", ">> In directory \"{}\" not exist '*.sql' files", dirPath.generic_string()); return false; } - for (std::filesystem::directory_iterator itr(DirPath); itr != DirItr; ++itr) + for (auto const& dirEntry : std::filesystem::directory_iterator(dirPath)) { - if (itr->path().extension() != ".sql") + auto const& path = dirEntry.path(); + if (path.extension() != ".sql") continue; - LOG_INFO("sql.updates", ">> Applying \'{}\'...", itr->path().filename().generic_string()); + LOG_INFO("db.update", ">> Applying \'{}\'...", path.filename().generic_string()); try { - ApplyFile(pool, itr->path()); + ApplyFile(pool, path); } catch (UpdateException&) { @@ -414,123 +344,93 @@ bool DBUpdater::Populate(DatabaseWorkerPool& pool) } } - LOG_INFO("sql.updates", ">> Done!"); - LOG_INFO("sql.updates", " "); + LOG_INFO("db.update", ">> Done!"); + LOG_INFO("db.update", " "); return true; } -template -QueryResult DBUpdater::Retrieve(DatabaseWorkerPool& pool, std::string const& query) +QueryResult DBUpdater::Retrieve(DatabaseWorkerPool& pool, std::string_view query) { - return pool.Query(query.c_str()); + return pool.Query(query); } -template -void DBUpdater::Apply(DatabaseWorkerPool& pool, std::string const& query) +void DBUpdater::Apply(DatabaseWorkerPool& pool, std::string_view query) { - pool.DirectExecute(query.c_str()); + pool.DirectExecute(query); } -template -void DBUpdater::ApplyFile(DatabaseWorkerPool& pool, Path const& path) +void DBUpdater::ApplyFile(DatabaseWorkerPool& pool, Path const& path) { - DBUpdater::ApplyFile(pool, pool.GetConnectionInfo()->host, pool.GetConnectionInfo()->user, pool.GetConnectionInfo()->password, - pool.GetConnectionInfo()->port_or_socket, pool.GetConnectionInfo()->database, pool.GetConnectionInfo()->ssl, path); + DBUpdater::ApplyFile(pool, pool.GetConnectionInfo()->Host, pool.GetConnectionInfo()->User, pool.GetConnectionInfo()->Password, + pool.GetConnectionInfo()->PortOrSocket, pool.GetConnectionInfo()->Database, pool.GetConnectionInfo()->SSL, path); } -template -void DBUpdater::ApplyFile(DatabaseWorkerPool& pool, std::string const& host, std::string const& user, - std::string const& password, std::string const& port_or_socket, std::string const& database, std::string const& ssl, Path const& path) +void DBUpdater::ApplyFile(DatabaseWorkerPool& pool, std::string_view host, std::string_view user, std::string_view password, + std::string_view port_or_socket, std::string_view database, std::string_view ssl, Path const& path) { - std::string configTempDir = sConfigMgr->GetOption("TempDir", ""); - - auto tempDir = configTempDir.empty() ? std::filesystem::temp_directory_path().string() : configTempDir; - - tempDir = Acore::String::AddSuffixIfNotExists(tempDir, std::filesystem::path::preferred_separator); - - std::string confFileName = "mysql_ac.conf"; - - std::ofstream outfile (tempDir + confFileName); - - outfile << "[client]\npassword = \"" << password << '"' << std::endl; - - outfile.close(); - std::vector args; args.reserve(9); - args.emplace_back("--defaults-extra-file="+tempDir + confFileName+""); + // Add password from extra file + args.emplace_back(Acore::StringFormatFmt("--defaults-extra-file={}", pool.GetPathToExtraFile())); // CLI Client connection info - args.emplace_back("-h" + host); - args.emplace_back("-u" + user); + args.emplace_back("-h" + std::string{ host }); + args.emplace_back("-u" + std::string{ user }); // Check if we want to connect through ip or socket (Unix only) -#ifdef _WIN32 - +#if AC_PLATFORM == AC_PLATFORM_WINDOWS if (host == ".") args.emplace_back("--protocol=PIPE"); else - args.emplace_back("-P" + port_or_socket); - + args.emplace_back("-P" + std::string{ port_or_socket }); #else - if (!std::isdigit(port_or_socket[0])) { // We can't check if host == "." here, because it is named localhost if socket option is enabled args.emplace_back("-P0"); args.emplace_back("--protocol=SOCKET"); - args.emplace_back("-S" + port_or_socket); + args.emplace_back("-S" + std::string{ port_or_socket }); } else // generic case - args.emplace_back("-P" + port_or_socket); - + args.emplace_back("-P" + std::string{ port_or_socket }); #endif // Set the default charset to utf8 - args.emplace_back("--default-character-set=utf8"); + args.emplace_back("--default-character-set=utf8mb4"); // Set max allowed packet to 1 GB args.emplace_back("--max-allowed-packet=1GB"); #if !defined(MARIADB_VERSION_ID) && MYSQL_VERSION_ID >= 80000 - if (ssl == "ssl") args.emplace_back("--ssl-mode=REQUIRED"); - #else - if (ssl == "ssl") args.emplace_back("--ssl"); - #endif // Execute sql file args.emplace_back("-e"); - args.emplace_back(Acore::StringFormat("BEGIN; SOURCE %s; COMMIT;", path.generic_string().c_str())); + args.emplace_back(Acore::StringFormatFmt("BEGIN; SOURCE {}; COMMIT;", path.generic_string())); // Database if (!database.empty()) args.emplace_back(database); // Invokes a mysql process which doesn't leak credentials to logs - int const ret = Acore::StartProcess(DBUpdaterUtil::GetCorrectedMySQLExecutable(), args, - "sql.updates", "", true); + int const ret = Acore::StartProcess(DBUpdaterUtil::GetCorrectedMySQLExecutable(), args, "db.update", "", true); if (ret != EXIT_SUCCESS) { - LOG_FATAL("sql.updates", "Applying of file \'{}\' to database \'{}\' failed!" \ + LOG_FATAL("db.update", "Applying of file \'{}\' to database \'{}\' failed!" \ " If you are a user, please pull the latest revision from the repository. " "Also make sure you have not applied any of the databases with your sql client. " "You cannot use auto-update system and import sql files from AzerothCore repository with your sql client. " "If you are a developer, please fix your sql query.", - path.generic_string(), pool.GetConnectionInfo()->database); + path.generic_string(), pool.GetConnectionInfo()->Database); throw UpdateException("update failed"); } } - -template class AC_DATABASE_API DBUpdater; -template class AC_DATABASE_API DBUpdater; -template class AC_DATABASE_API DBUpdater; diff --git a/src/server/database/Updater/DBUpdater.h b/src/server/database/Updater/DBUpdater.h index 62af83df1ead66..65eb7473fe8a86 100644 --- a/src/server/database/Updater/DBUpdater.h +++ b/src/server/database/Updater/DBUpdater.h @@ -23,71 +23,54 @@ #include #include -template class DatabaseWorkerPool; -namespace boost -{ - namespace filesystem - { - class path; - } -} - class AC_DATABASE_API UpdateException : public std::exception { public: - UpdateException(std::string const& msg) : _msg(msg) { } - ~UpdateException() throw() { } + explicit UpdateException(std::string_view msg) : _msg(msg) { } + ~UpdateException() noexcept override = default; - char const* what() const throw() override { return _msg.c_str(); } + [[nodiscard]] char const* what() const noexcept override { return _msg.c_str(); } + [[nodiscard]] std::string_view GetMessage() const noexcept { return _msg; } private: - std::string const _msg; -}; - -enum BaseLocation -{ - LOCATION_REPOSITORY, - LOCATION_DOWNLOAD + std::string _msg; }; class AC_DATABASE_API DBUpdaterUtil { public: static std::string GetCorrectedMySQLExecutable(); - static bool CheckExecutable(); private: static std::string& corrected_path(); }; -template class AC_DATABASE_API DBUpdater { public: using Path = std::filesystem::path; - static inline std::string GetConfigEntry(); - static inline std::string GetTableName(); - static std::string GetBaseFilesDirectory(); - static bool IsEnabled(uint32 const updateMask); - static BaseLocation GetBaseLocationType(); - static bool Create(DatabaseWorkerPool& pool); - static bool Update(DatabaseWorkerPool& pool, std::string_view modulesList = {}); - static bool Update(DatabaseWorkerPool& pool, std::vector const* setDirectories); - static bool Populate(DatabaseWorkerPool& pool); + static std::string GetConfigEntry(DatabaseWorkerPool const& pool); + static std::string GetTableName(DatabaseWorkerPool const& pool); + static std::string GetBaseFilesDirectory(DatabaseWorkerPool const& pool); + static bool IsEnabled(DatabaseWorkerPool& pool, uint32 updateMask); + static bool Create(DatabaseWorkerPool& pool); + static bool Update(DatabaseWorkerPool& pool, std::string_view modulesList = {}); + static bool Update(DatabaseWorkerPool& pool, std::vector const* setDirectories); + static bool Populate(DatabaseWorkerPool& pool); // module - static std::string GetDBModuleName(); + static std::string GetDBModuleName(DatabaseWorkerPool const& pool); private: - static QueryResult Retrieve(DatabaseWorkerPool& pool, std::string const& query); - static void Apply(DatabaseWorkerPool& pool, std::string const& query); - static void ApplyFile(DatabaseWorkerPool& pool, Path const& path); - static void ApplyFile(DatabaseWorkerPool& pool, std::string const& host, std::string const& user, - std::string const& password, std::string const& port_or_socket, std::string const& database, std::string const& ssl, Path const& path); + static QueryResult Retrieve(DatabaseWorkerPool& pool, std::string_view query); + static void Apply(DatabaseWorkerPool& pool, std::string_view query); + static void ApplyFile(DatabaseWorkerPool& pool, Path const& path); + static void ApplyFile(DatabaseWorkerPool& pool, std::string_view host, std::string_view user, + std::string_view password, std::string_view port_or_socket, std::string_view database, std::string_view ssl, Path const& path); }; #endif // DBUpdater_h__ diff --git a/src/server/database/Updater/UpdateFetcher.cpp b/src/server/database/Updater/UpdateFetcher.cpp index 3e128ebb56fa60..7d90ea533111b5 100644 --- a/src/server/database/Updater/UpdateFetcher.cpp +++ b/src/server/database/Updater/UpdateFetcher.cpp @@ -16,89 +16,102 @@ */ #include "UpdateFetcher.h" +#include "Config.h" #include "CryptoHash.h" #include "DBUpdater.h" -#include "Field.h" #include "Log.h" +#include "StopWatch.h" #include "Tokenize.h" #include "Util.h" +#include #include #include +#include -using namespace std::filesystem; +namespace fs = std::filesystem; struct UpdateFetcher::DirectoryEntry { - DirectoryEntry(Path const& path_, State state_) : path(path_), state(state_) { } + DirectoryEntry(Path path_, State state_) : path(std::move(path_)), state(state_) { } Path const path; State const state; }; UpdateFetcher::UpdateFetcher(Path const& sourceDirectory, - std::function const& apply, - std::function const& applyFile, - std::function const& retrieve, std::string const& dbModuleName, std::vector const* setDirectories /*= nullptr*/) : + std::function const& apply, + std::function const& applyFile, + std::function const& retrieve, std::string_view dbNameForModule, std::vector const* setDirectories /*= nullptr*/) : _sourceDirectory(std::make_unique(sourceDirectory)), _apply(apply), _applyFile(applyFile), - _retrieve(retrieve), _dbModuleName(dbModuleName), _setDirectories(setDirectories) + _retrieve(retrieve), _dbModuleName(dbNameForModule), _setDirectories(setDirectories) { } UpdateFetcher::UpdateFetcher(Path const& sourceDirectory, - std::function const& apply, + std::function const& apply, std::function const& applyFile, - std::function const& retrieve, - std::string const& dbModuleName, + std::function const& retrieve, + std::string_view dbNameForModule, std::string_view modulesList /*= {}*/) : _sourceDirectory(std::make_unique(sourceDirectory)), _apply(apply), _applyFile(applyFile), - _retrieve(retrieve), _dbModuleName(dbModuleName), _setDirectories(nullptr), _modulesList(modulesList) -{ -} - -UpdateFetcher::~UpdateFetcher() + _retrieve(retrieve), _dbModuleName(dbNameForModule), _setDirectories(nullptr), _modulesList(modulesList) { } UpdateFetcher::LocaleFileStorage UpdateFetcher::GetFileList() const { - LocaleFileStorage files; DirectoryStorage directories = ReceiveIncludedDirectories(); + if (directories.empty()) + { + LOG_ERROR("db.update", "> Not found all includes directory. Try reapply `updates_include`"); + + fs::path updateFile = *_sourceDirectory; + updateFile /= "data"; + updateFile /= "sql"; + updateFile /= "base"; + updateFile /= _dbModuleName; + updateFile /= "updates_include.sql"; + + _applyFile(updateFile); + + directories = ReceiveIncludedDirectories(); + if (directories.empty()) + ABORT("Can't find all includes directory"); + else + LOG_INFO("db.update", "> Successful restored includes directory"); + } + + LocaleFileStorage files; + for (auto const& entry : directories) FillFileListRecursively(entry.path, files, entry.state, 1); return files; } -void UpdateFetcher::FillFileListRecursively(Path const& path, LocaleFileStorage& storage, State const state, uint32 const depth) const +void UpdateFetcher::FillFileListRecursively(Path const& path, LocaleFileStorage& storage, State const state, uint32 const depth) { - static uint32 const MAX_DEPTH = 10; - static directory_iterator const end; - - for (directory_iterator itr(path); itr != end; ++itr) + for (auto const& dirEntry : fs::recursive_directory_iterator(path)) { - if (is_directory(itr->path())) - { - if (depth < MAX_DEPTH) - FillFileListRecursively(itr->path(), storage, state, depth + 1); - } - else if (itr->path().extension() == ".sql") - { - LOG_TRACE("sql.updates", "Added locale file \"{}\" state '{}'.", itr->path().filename().generic_string(), AppliedFileEntry::StateConvert(state)); + auto const& dirPath = dirEntry.path(); + if (!dirPath.has_extension() || dirPath.extension() != ".sql") + continue; - LocaleFileEntry const entry = { itr->path(), state }; + LOG_TRACE("db.update", "Added locale file \"{}\" state '{}'.", dirPath.filename().generic_string(), AppliedFileEntry::StateConvert(state)); - // Check for doubled filenames - // Because elements are only compared by their filenames, this is ok - if (storage.find(entry) != storage.end()) - { - LOG_FATAL("sql.updates", "Duplicate filename \"{}\" occurred. Because updates are ordered " \ - "by their filenames, every name needs to be unique!", itr->path().generic_string()); + LocaleFileEntry const entry = {dirPath, state }; - throw UpdateException("Updating failed, see the log for details."); - } + // Check for doubled filenames + // Because elements are only compared by their filenames, this is ok + if (storage.find(entry) != storage.end()) + { + LOG_FATAL("db.update", "Duplicate filename \"{}\" occurred. Because updates are ordered " \ + "by their filenames, every name needs to be unique!", dirPath.generic_string()); - storage.insert(entry); + throw UpdateException("Updating failed, see the log for details."); } + + storage.emplace(entry); } } @@ -113,68 +126,71 @@ UpdateFetcher::DirectoryStorage UpdateFetcher::ReceiveIncludedDirectories() cons std::string path = _sourceDirectory->generic_string() + itr; Path const p(path); - if (!is_directory(p)) + if (!fs::is_directory(p)) continue; DirectoryEntry const entry = {p, AppliedFileEntry::StateConvert("MODULE")}; directories.push_back(entry); - LOG_TRACE("sql.updates", "Added applied extra file \"{}\" from remote.", p.filename().generic_string()); + LOG_TRACE("db.update", "Added applied extra file \"{}\" from remote.", p.filename().generic_string()); } + + return directories; } - else + + QueryResult const result = _retrieve("SELECT `path`, `state` FROM `updates_include`"); + if (!result) + return directories; + + for (auto& resultSet : *result) { - QueryResult const result = _retrieve("SELECT `path`, `state` FROM `updates_include`"); - if (!result) - return directories; + auto [path, state] = resultSet.FetchTuple(); - do - { - Field* fields = result->Fetch(); + if (path.substr(0, 1) == "$") + path = _sourceDirectory->generic_string() + path.substr(1); - std::string path = fields[0].Get(); - std::string state = fields[1].Get(); - if (path.substr(0, 1) == "$") - path = _sourceDirectory->generic_string() + path.substr(1); + Path const p(path); + if (!fs::is_directory(p)) + { + LOG_WARN("db.update", "DBUpdater: Given update include directory \"{}\" does not exist, skipped!", p.generic_string()); + continue; + } - Path const p(path); + DirectoryEntry const entry = { p, AppliedFileEntry::StateConvert(state) }; + directories.push_back(entry); - if (!is_directory(p)) - { - LOG_WARN("sql.updates", "DBUpdater: Given update include directory \"{}\" does not exist, skipped!", p.generic_string()); - continue; - } + LOG_TRACE("db.update", "Added applied file \"{}\" '{}' state from remote.", p.filename().generic_string(), state); + } - DirectoryEntry const entry = {p, AppliedFileEntry::StateConvert(state)}; - directories.push_back(entry); + if (directories.empty() || _modulesList.empty()) + return directories; - LOG_TRACE("sql.updates", "Added applied file \"{}\" '{}' state from remote.", p.filename().generic_string(), state); + std::vector moduleList; - } while (result->NextRow()); + for (auto const& itr : Acore::Tokenize(_modulesList, ',', true)) + moduleList.emplace_back(itr); - std::vector moduleList; + // data/sql + for (auto const& name : moduleList) + { + Path moduleDir{ *_sourceDirectory }; + moduleDir /= "modules"; + moduleDir /= name; + moduleDir /= "sql"; - for (auto const& itr : Acore::Tokenize(_modulesList, ',', true)) - { - moduleList.emplace_back(itr); - } + // Skip check if not exist sql dir in module + if (!is_directory(moduleDir)) + continue; - // data/sql - for (auto const& itr : moduleList) - { - std::string path = _sourceDirectory->generic_string() + "/modules/" + itr + "/data/sql/" + _dbModuleName; // modules/mod-name/data/sql/db-world + moduleDir /= _dbModuleName; // modules/mod-name/sql/db-world - Path const p(path); - if (!is_directory(p)) - { - continue; - } + if (!fs::is_directory(moduleDir)) + continue; - DirectoryEntry const entry = { p, AppliedFileEntry::StateConvert("MODULE") }; - directories.push_back(entry); + DirectoryEntry const entry = { moduleDir, MODULE }; + directories.emplace_back(entry); - LOG_TRACE("sql.updates", "Added applied modules file \"{}\" from remote.", p.filename().generic_string()); - } + LOG_TRACE("db.update", "Added applied modules file \"{}\" from remote.", moduleDir.filename().generic_string()); } return directories; @@ -188,27 +204,22 @@ UpdateFetcher::AppliedFileStorage UpdateFetcher::ReceiveAppliedFiles() const if (!result) return map; - do + for (auto& resultSet : *result) { - Field* fields = result->Fetch(); - - AppliedFileEntry const entry = - { - fields[0].Get(), fields[1].Get(), AppliedFileEntry::StateConvert(fields[2].Get()), fields[3].Get() - }; - + auto const& [name, hash, state, timestamp] = resultSet.FetchTuple(); + AppliedFileEntry entry{ name, hash, AppliedFileEntry::StateConvert(state), timestamp }; map.emplace(entry.name, entry); - } while (result->NextRow()); + } return map; } -std::string UpdateFetcher::ReadSQLUpdate(Path const& file) const +std::string UpdateFetcher::ReadSQLUpdate(Path const& file) { std::ifstream in(file.c_str()); if (!in.is_open()) { - LOG_FATAL("sql.updates", "Failed to open the sql update \"{}\" for reading! " + LOG_FATAL("db.update", "Failed to open the sql update \"{}\" for reading! " "Stopping the server to keep the database integrity, " "try to identify and solve the issue or disable the database updater.", file.generic_string()); @@ -227,16 +238,13 @@ std::string UpdateFetcher::ReadSQLUpdate(Path const& file) const return update; } -UpdateResult UpdateFetcher::Update(bool const redundancyChecks, - bool const allowRehash, - bool const archivedRedundancy, - int32 const cleanDeadReferencesMaxCount) const +UpdateResult UpdateFetcher::Update() const { + auto const cleanDeadReferencesMaxCount = sConfigMgr->GetOption("Updates.CleanDeadRefMaxCount", 3); + LocaleFileStorage const available = GetFileList(); if (_setDirectories && available.empty()) - { - return UpdateResult(); - } + return {}; AppliedFileStorage applied = ReceiveAppliedFiles(); @@ -252,33 +260,30 @@ UpdateResult UpdateFetcher::Update(bool const redundancyChecks, // Fill hash to name cache HashToFileNameStorage hashToName; - for (auto& entry : applied) - hashToName.insert(std::make_pair(entry.second.hash, entry.first)); + for (const auto& entry : applied) + hashToName.emplace(entry.second.hash, entry.first); size_t importedUpdates = 0; - auto ApplyUpdateFile = [&](LocaleFileEntry const& sqlFile) + auto ApplyUpdateFile = [this, &applied, &hashToName, &available, &importedUpdates](Path const& filePath, State const fileState) { - auto filePath = sqlFile.first; - auto fileState = sqlFile.second; + bool const redundancyChecks = sConfigMgr->GetOption("Updates.Redundancy", true); + bool const allowRehash = sConfigMgr->GetOption("Updates.AllowRehash", true); + bool const archivedRedundancy = sConfigMgr->GetOption("Updates.ArchivedRedundancy", false); - LOG_DEBUG("sql.updates", "Checking update \"{}\"...", filePath.filename().generic_string()); - - AppliedFileStorage::const_iterator iter = applied.find(filePath.filename().string()); + auto const& iter = applied.find(filePath.filename().string()); if (iter != applied.end()) { // If redundancy is disabled, skip it, because the update is already applied. if (!redundancyChecks) { - LOG_DEBUG("sql.updates", ">> Update is already applied, skipping redundancy checks."); applied.erase(iter); return; } // If the update is in an archived directory and is marked as archived in our database, skip redundancy checks (archived updates never change). - if (!archivedRedundancy && (iter->second.state == ARCHIVED) && (sqlFile.second == ARCHIVED)) + if (!archivedRedundancy && (iter->second.state == ARCHIVED) && (fileState == ARCHIVED)) { - LOG_DEBUG("sql.updates", ">> Update is archived and marked as archived in database, skipping redundancy checks."); applied.erase(iter); return; } @@ -292,7 +297,7 @@ UpdateResult UpdateFetcher::Update(bool const redundancyChecks, if (iter == applied.end()) { // Catch renames (different filename, but same hash) - HashToFileNameStorage::const_iterator const hashIter = hashToName.find(hash); + auto const& hashIter = hashToName.find(hash); if (hashIter != hashToName.end()) { // Check if the original file was removed. If not, we've got a problem. @@ -305,14 +310,13 @@ UpdateResult UpdateFetcher::Update(bool const redundancyChecks, // Conflict! if (localeIter != available.end()) { - LOG_WARN("sql.updates", ">> It seems like the update \"{}\" \'{}\' was renamed, but the old file is still there! " \ + LOG_WARN("db.update", ">> It seems like the update \"{}\" \'{}\' was renamed, but the old file is still there! " \ "Treating it as a new file! (It is probably an unmodified copy of the file \"{}\")", - filePath.filename().string(), hash.substr(0, 7), - localeIter->first.filename().string()); + filePath.filename().string(), hash.substr(0, 7), localeIter->first.filename().string()); } else // It is safe to treat the file as renamed here { - LOG_INFO("sql.updates", ">> Renaming update \"{}\" to \"{}\" \'{}\'.", + LOG_INFO("db.update", ">> Renaming update \"{}\" to \"{}\" \'{}\'.", hashIter->second, filePath.filename().string(), hash.substr(0, 7)); RenameEntry(hashIter->second, filePath.filename().string()); @@ -320,48 +324,38 @@ UpdateResult UpdateFetcher::Update(bool const redundancyChecks, return; } } - // Apply the update if it was never seen before. else { - LOG_INFO("sql.updates", ">> Applying update \"{}\" \'{}\'...", - filePath.filename().string(), hash.substr(0, 7)); + LOG_INFO("db.update", ">> Applying update \"{}\" \'{}\'...", filePath.filename().string(), hash.substr(0, 7)); } + } // Rehash the update entry if it exists in our database with an empty hash. else if (allowRehash && iter->second.hash.empty()) { mode = MODE_REHASH; - - LOG_INFO("sql.updates", ">> Re-hashing update \"{}\" \'{}\'...", filePath.filename().string(), - hash.substr(0, 7)); + LOG_INFO("db.update", ">> Re-hashing update \"{}\" \'{}\'...", filePath.filename().string(), hash.substr(0, 7)); } else { // If the hash of the files differs from the one stored in our database, reapply the update (because it changed). if (iter->second.hash != hash) { - LOG_INFO("sql.updates", ">> Reapplying update \"{}\" \'{}\' -> \'{}\' (it changed)...", filePath.filename().string(), - iter->second.hash.substr(0, 7), hash.substr(0, 7)); + LOG_INFO("db.update", ">> Reapplying update \"{}\" \'{}\' -> \'{}\' (it changed)...", + filePath.filename().string(), iter->second.hash.substr(0, 7), hash.substr(0, 7)); } else { // If the file wasn't changed and just moved, update its state (if necessary). if (iter->second.state != fileState) - { - LOG_DEBUG("sql.updates", ">> Updating the state of \"{}\" to \'{}\'...", - filePath.filename().string(), AppliedFileEntry::StateConvert(fileState)); - UpdateState(filePath.filename().string(), fileState); - } - - LOG_DEBUG("sql.updates", ">> Update is already applied and matches the hash \'{}\'.", hash.substr(0, 7)); applied.erase(iter); return; } } - uint32 speed = 0; + Milliseconds speed{}; AppliedFileEntry const file = { filePath.filename().string(), hash, fileState, 0 }; switch (mode) @@ -382,17 +376,30 @@ UpdateResult UpdateFetcher::Update(bool const redundancyChecks, }; // Apply default updates - for (auto const& availableQuery : available) + for (auto const& [path, state] : available) { - if (availableQuery.second != CUSTOM && availableQuery.second != MODULE) - ApplyUpdateFile(availableQuery); + if (state == RELEASED || state == ARCHIVED) + { + ApplyUpdateFile(path, state); + } } - // Apply only custom/module updates - for (auto const& availableQuery : available) + // Apply only custom updates + for (auto const& [path, state] : available) { - if (availableQuery.second == CUSTOM || availableQuery.second == MODULE) - ApplyUpdateFile(availableQuery); + if (state == CUSTOM) + { + ApplyUpdateFile(path, state); + } + } + + // Apply only module updates + for (auto const& [path, state] : available) + { + if (state == MODULE) + { + ApplyUpdateFile(path, state); + } } // Cleanup up orphaned entries (if enabled) @@ -405,14 +412,12 @@ UpdateResult UpdateFetcher::Update(bool const redundancyChecks, { if (entry.second.state != MODULE) { - LOG_WARN("sql.updates", - ">> The file \'{}\' was applied to the database, but is missing in" - " your update directory now!", - entry.first); + LOG_WARN("db.update", ">> The file \'{}\' was applied to the database, but is missing in your update directory now!", + entry.first); if (doCleanup) { - LOG_INFO("sql.updates", "Deleting orphaned entry \'{}\'...", entry.first); + LOG_INFO("db.update", "Deleting orphaned entry \'{}\'...", entry.first); toCleanup.insert(entry); } } @@ -424,35 +429,30 @@ UpdateResult UpdateFetcher::Update(bool const redundancyChecks, CleanUp(toCleanup); else { - LOG_ERROR("sql.updates", - "Cleanup is disabled! There were {} dirty files applied to your database, " - "but they are now missing in your source directory!", - toCleanup.size()); + LOG_ERROR("db.update", "Cleanup is disabled! There were {} dirty files applied to your database, " + "but they are now missing in your source directory!", toCleanup.size()); } } } - return UpdateResult(importedUpdates, countRecentUpdates, countArchivedUpdates); + return UpdateResult{ importedUpdates, countRecentUpdates, countArchivedUpdates }; } -uint32 UpdateFetcher::Apply(Path const& path) const +Milliseconds UpdateFetcher::Apply(Path const& path) const { - using Time = std::chrono::high_resolution_clock; - - // Benchmark query speed - auto const begin = Time::now(); + StopWatch sw; // Update database _applyFile(path); // Return the time it took the query to apply - return uint32(std::chrono::duration_cast(Time::now() - begin).count()); + return Milliseconds{ sw.Elapsed().count() / 1000 }; } -void UpdateFetcher::UpdateEntry(AppliedFileEntry const& entry, uint32 const speed) const +void UpdateFetcher::UpdateEntry(AppliedFileEntry const& entry, Milliseconds speed) const { - std::string const update = "REPLACE INTO `updates` (`name`, `hash`, `state`, `speed`) VALUES (\"" + - entry.name + "\", \"" + entry.hash + "\", \'" + entry.GetStateAsString() + "\', " + std::to_string(speed) + ")"; + auto update = Acore::StringFormatFmt("REPLACE INTO `updates` (`name`, `hash`, `state`, `speed`) VALUES ('{}', '{}', '{}', '{}')", + entry.name, entry.hash, entry.GetStateAsString(), speed.count()); // Update database _apply(update); @@ -483,7 +483,7 @@ void UpdateFetcher::CleanUp(AppliedFileStorage const& storage) const return; std::stringstream update; - size_t remaining = storage.size(); + std::size_t remaining = storage.size(); update << "DELETE FROM `updates` WHERE `name` IN("; diff --git a/src/server/database/Updater/UpdateFetcher.h b/src/server/database/Updater/UpdateFetcher.h index ca9918f4846ec6..d9346b8c371e81 100644 --- a/src/server/database/Updater/UpdateFetcher.h +++ b/src/server/database/Updater/UpdateFetcher.h @@ -24,19 +24,18 @@ #include #include #include +#include #include struct AC_DATABASE_API UpdateResult { - UpdateResult() - : updated(0), recent(0), archived(0) { } - + UpdateResult() = default; UpdateResult(size_t const updated_, size_t const recent_, size_t const archived_) : updated(updated_), recent(recent_), archived(archived_) { } - size_t updated; - size_t recent; - size_t archived; + size_t updated{}; + size_t recent{}; + size_t archived{}; }; class AC_DATABASE_API UpdateFetcher @@ -45,21 +44,20 @@ class AC_DATABASE_API UpdateFetcher public: UpdateFetcher(Path const& updateDirectory, - std::function const& apply, - std::function const& applyFile, - std::function const& retrieve, std::string const& dbModuleName, std::vector const* setDirectories = nullptr); + std::function const& apply, + std::function const& applyFile, + std::function const& retrieve, std::string_view dbNameForModule, std::vector const* setDirectories = nullptr); UpdateFetcher(Path const& updateDirectory, - std::function const& apply, - std::function const& applyFile, - std::function const& retrieve, - std::string const& dbModuleName, - std::string_view modulesList = {}); + std::function const& apply, + std::function const& applyFile, + std::function const& retrieve, + std::string_view dbNameForModule, + std::string_view modulesList = {}); - ~UpdateFetcher(); + ~UpdateFetcher() = default; - UpdateResult Update(bool const redundancyChecks, bool const allowRehash, - bool const archivedRedundancy, int32 const cleanDeadReferencesMaxCount) const; + [[nodiscard]] UpdateResult Update() const; private: enum UpdateMode @@ -78,15 +76,15 @@ class AC_DATABASE_API UpdateFetcher struct AppliedFileEntry { - AppliedFileEntry(std::string const& name_, std::string const& hash_, State state_, uint64 timestamp_) - : name(name_), hash(hash_), state(state_), timestamp(timestamp_) { } + AppliedFileEntry(std::string_view name_, std::string_view hash_, State state_, uint64 timestamp_) + : name(name_), hash(hash_), state(state_), timestamp(timestamp_) { } std::string const name; std::string const hash; State const state; uint64 const timestamp; - static inline State StateConvert(std::string const& state) + static inline State StateConvert(std::string_view state) { if (state == "RELEASED") return RELEASED; @@ -115,7 +113,7 @@ class AC_DATABASE_API UpdateFetcher } } - std::string GetStateAsString() const + [[nodiscard]] std::string GetStateAsString() const { return StateConvert(state); } @@ -135,33 +133,32 @@ class AC_DATABASE_API UpdateFetcher typedef std::unordered_map AppliedFileStorage; typedef std::vector DirectoryStorage; - LocaleFileStorage GetFileList() const; - void FillFileListRecursively(Path const& path, LocaleFileStorage& storage, - State const state, uint32 const depth) const; + [[nodiscard]] LocaleFileStorage GetFileList() const; + static void FillFileListRecursively(Path const& path, LocaleFileStorage& storage, + State state, uint32 depth) ; - DirectoryStorage ReceiveIncludedDirectories() const; - AppliedFileStorage ReceiveAppliedFiles() const; + [[nodiscard]] DirectoryStorage ReceiveIncludedDirectories() const; + [[nodiscard]] AppliedFileStorage ReceiveAppliedFiles() const; - std::string ReadSQLUpdate(Path const& file) const; + [[nodiscard]] static std::string ReadSQLUpdate(Path const& file) ; - uint32 Apply(Path const& path) const; + [[nodiscard]] Milliseconds Apply(Path const& path) const; - void UpdateEntry(AppliedFileEntry const& entry, uint32 const speed = 0) const; + void UpdateEntry(AppliedFileEntry const& entry, Milliseconds speed = 0ms) const; void RenameEntry(std::string const& from, std::string const& to) const; void CleanUp(AppliedFileStorage const& storage) const; - void UpdateState(std::string const& name, State const state) const; + void UpdateState(std::string const& name, State state) const; std::unique_ptr const _sourceDirectory; - - std::function const _apply; + std::function const _apply; std::function const _applyFile; - std::function const _retrieve; + std::function const _retrieve; // modules std::string const _dbModuleName; std::vector const* _setDirectories; - std::string_view _modulesList = {}; + std::string _modulesList; }; #endif // UpdateFetcher_h__ diff --git a/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp b/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp index fc8212b0cd22ea..41eb78dc5e7002 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp +++ b/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp @@ -470,7 +470,7 @@ void npc_escortAI::Start(bool isActiveAttacker /* = true*/, bool run /* = false if (WaypointList.empty()) { - LOG_ERROR("sql.sql", "EscortAI (script: {}, creature entry: {}) starts with 0 waypoints (possible missing entry in script_waypoint. Quest: {}).", + LOG_ERROR("db.query", "EscortAI (script: {}, creature entry: {}) starts with 0 waypoints (possible missing entry in script_waypoint. Quest: {}).", me->GetScriptName(), me->GetEntry(), quest ? quest->GetQuestId() : 0); return; } diff --git a/src/server/game/AI/SmartScripts/SmartAI.cpp b/src/server/game/AI/SmartScripts/SmartAI.cpp index 717b8ee73522bc..fef811bbcd67a1 100644 --- a/src/server/game/AI/SmartScripts/SmartAI.cpp +++ b/src/server/game/AI/SmartScripts/SmartAI.cpp @@ -1163,7 +1163,7 @@ void SmartGameObjectAI::Reset() // Called when a player opens a gossip dialog with the gameobject. bool SmartGameObjectAI::GossipHello(Player* player, bool reportUse) { - LOG_DEBUG("sql.sql", "SmartGameObjectAI::GossipHello"); + LOG_DEBUG("db.query", "SmartGameObjectAI::GossipHello"); GetScript()->ProcessEventsFor(SMART_EVENT_GOSSIP_HELLO, player, (uint32)reportUse, 0, false, nullptr, me); return false; } @@ -1253,7 +1253,7 @@ class SmartTrigger : public AreaTriggerScript if (!player->IsAlive()) return false; - LOG_DEBUG("sql.sql", "AreaTrigger {} is using SmartTrigger script", trigger->entry); + LOG_DEBUG("db.query", "AreaTrigger {} is using SmartTrigger script", trigger->entry); SmartScript script; script.OnInitialize(nullptr, trigger); script.ProcessEventsFor(SMART_EVENT_AREATRIGGER_ONTRIGGER, player, trigger->entry); diff --git a/src/server/game/AI/SmartScripts/SmartScript.cpp b/src/server/game/AI/SmartScripts/SmartScript.cpp index 53f46cfcd557b3..b3a151019ae8ac 100644 --- a/src/server/game/AI/SmartScripts/SmartScript.cpp +++ b/src/server/game/AI/SmartScripts/SmartScript.cpp @@ -126,7 +126,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u mLastInvoker = unit->GetGUID(); if (Unit* tempInvoker = GetLastInvoker()) - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction: Invoker: {} ({})", tempInvoker->GetName(), tempInvoker->GetGUID().ToString()); + LOG_DEBUG("db.query", "SmartScript::ProcessAction: Invoker: {} ({})", tempInvoker->GetName(), tempInvoker->GetGUID().ToString()); bool isControlled = e.action.moveToPos.controlled > 0; @@ -169,7 +169,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (!sCreatureTextMgr->TextExist(talker->GetEntry(), uint8(e.action.talk.textGroupID))) { - LOG_ERROR("sql.sql", "SmartScript::ProcessAction: SMART_ACTION_TALK: EntryOrGuid {} SourceType {} EventType {} TargetType {} using non-existent Text id {} for talker {}, ignored.", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetTargetType(), e.action.talk.textGroupID, talker->GetEntry()); + LOG_ERROR("db.query", "SmartScript::ProcessAction: SMART_ACTION_TALK: EntryOrGuid {} SourceType {} EventType {} TargetType {} using non-existent Text id {} for talker {}, ignored.", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetTargetType(), e.action.talk.textGroupID, talker->GetEntry()); break; } @@ -178,7 +178,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u mTextTimer = e.action.talk.duration; mUseTextTimer = true; sCreatureTextMgr->SendChat(talker, uint8(e.action.talk.textGroupID), talkTarget); - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction: SMART_ACTION_TALK: talker: {} ({}), textId: {}", talker->GetName(), talker->GetGUID().ToString(), mLastTextID); + LOG_DEBUG("db.query", "SmartScript::ProcessAction: SMART_ACTION_TALK: talker: {} ({}), textId: {}", talker->GetName(), talker->GetGUID().ToString(), mLastTextID); break; } case SMART_ACTION_SIMPLE_TALK: @@ -193,7 +193,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u sCreatureTextMgr->SendChat(me, uint8(e.action.simpleTalk.textGroupID), IsPlayer(templastInvoker) ? templastInvoker : 0, CHAT_MSG_ADDON, LANG_ADDON, TEXT_RANGE_NORMAL, 0, TEAM_NEUTRAL, false, target->ToPlayer()); } - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction:: SMART_ACTION_SIMPLE_TALK: talker: {} ({}), textGroupId: {}", + LOG_DEBUG("db.query", "SmartScript::ProcessAction:: SMART_ACTION_SIMPLE_TALK: talker: {} ({}), textGroupId: {}", target->GetName(), target->GetGUID().ToString(), uint8(e.action.simpleTalk.textGroupID)); } break; @@ -205,7 +205,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (IsUnit(target)) { target->ToUnit()->HandleEmoteCommand(e.action.emote.emote); - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction:: SMART_ACTION_PLAY_EMOTE: target: {} ({}), emote: {}", + LOG_DEBUG("db.query", "SmartScript::ProcessAction:: SMART_ACTION_PLAY_EMOTE: target: {} ({}), emote: {}", target->GetName(), target->GetGUID().ToString(), e.action.emote.emote); } } @@ -221,7 +221,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u target->PlayDistanceSound(e.action.sound.sound, e.action.sound.onlySelf ? target->ToPlayer() : nullptr); else target->PlayDirectSound(e.action.sound.sound, e.action.sound.onlySelf ? target->ToPlayer() : nullptr); - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction:: SMART_ACTION_SOUND: target: {} ({}), sound: {}, onlyself: {}", + LOG_DEBUG("db.query", "SmartScript::ProcessAction:: SMART_ACTION_SOUND: target: {} ({}), sound: {}, onlyself: {}", target->GetName(), target->GetGUID().ToString(), e.action.sound.sound, e.action.sound.onlySelf); } } @@ -256,7 +256,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u { uint32 sound = temp[urand(0, count - 1)]; target->PlayDirectSound(sound, e.action.randomSound.onlySelf ? target->ToPlayer() : nullptr); - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction:: SMART_ACTION_RANDOM_SOUND: target: {} ({}), sound: {}, onlyself: {}", + LOG_DEBUG("db.query", "SmartScript::ProcessAction:: SMART_ACTION_RANDOM_SOUND: target: {} ({}), sound: {}, onlyself: {}", target->GetName(), target->GetGUID().ToString(), sound, e.action.randomSound.onlySelf); } } @@ -302,7 +302,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (IsUnit(target)) { target->SendPlayMusic(e.action.music.sound, e.action.music.onlySelf > 0); - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction:: SMART_ACTION_MUSIC: target: {} ({}), sound: {}, onlySelf: {}, type: {}", + LOG_DEBUG("db.query", "SmartScript::ProcessAction:: SMART_ACTION_MUSIC: target: {} ({}), sound: {}, onlySelf: {}, type: {}", target->GetName(), target->GetGUID().ToString(), e.action.music.sound, e.action.music.onlySelf, e.action.music.type); } } @@ -371,7 +371,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u { uint32 sound = temp[urand(0, count - 1)]; target->SendPlayMusic(sound, e.action.randomMusic.onlySelf > 0); - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction:: SMART_ACTION_RANDOM_MUSIC: target: {} ({}), sound: {}, onlyself: {}, type: {}", + LOG_DEBUG("db.query", "SmartScript::ProcessAction:: SMART_ACTION_RANDOM_MUSIC: target: {} ({}), sound: {}, onlyself: {}, type: {}", target->GetName(), target->GetGUID().ToString(), sound, e.action.randomMusic.onlySelf, e.action.randomMusic.type); } } @@ -528,7 +528,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (Unit* target = ObjectAccessor::GetUnit(*me, (*i)->getUnitGuid())) { me->GetThreatMgr().ModifyThreatByPercent(target, e.action.threatPCT.threatINC ? (int32)e.action.threatPCT.threatINC : -(int32)e.action.threatPCT.threatDEC); - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction:: SMART_ACTION_THREAT_ALL_PCT: Creature {} modify threat for unit {}, value {}", + LOG_DEBUG("db.query", "SmartScript::ProcessAction:: SMART_ACTION_THREAT_ALL_PCT: Creature {} modify threat for unit {}, value {}", me->GetGUID().ToString(), target->GetGUID().ToString(), e.action.threatPCT.threatINC ? (int32)e.action.threatPCT.threatINC : -(int32)e.action.threatPCT.threatDEC); } } @@ -767,7 +767,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u } go->UseDoorOrButton(0, !!e.action.activateObject.alternative, unit); - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction:: SMART_ACTION_ACTIVATE_GOBJECT. Gameobject {} activated", go->GetGUID().ToString()); + LOG_DEBUG("db.query", "SmartScript::ProcessAction:: SMART_ACTION_ACTIVATE_GOBJECT. Gameobject {} activated", go->GetGUID().ToString()); } } @@ -849,7 +849,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u break; CAST_AI(SmartAI, me->AI())->SetAutoAttack(e.action.autoAttack.attack); - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction:: SMART_ACTION_AUTO_ATTACK: Creature: {} bool on = {}", + LOG_DEBUG("db.query", "SmartScript::ProcessAction:: SMART_ACTION_AUTO_ATTACK: Creature: {} bool on = {}", me->GetGUID().ToString(), e.action.autoAttack.attack); break; } @@ -867,7 +867,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u } else CAST_AI(SmartAI, me->AI())->SetCombatMove(move); - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction:: SMART_ACTION_ALLOW_COMBAT_MOVEMENT: Creature {} bool on = {}", + LOG_DEBUG("db.query", "SmartScript::ProcessAction:: SMART_ACTION_ALLOW_COMBAT_MOVEMENT: Creature {} bool on = {}", me->GetGUID().ToString(), e.action.combatMove.move); break; } @@ -877,7 +877,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u break; SetPhase(e.action.setEventPhase.phase); - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction:: SMART_ACTION_SET_EVENT_PHASE: Creature {} set event phase {}", + LOG_DEBUG("db.query", "SmartScript::ProcessAction:: SMART_ACTION_SET_EVENT_PHASE: Creature {} set event phase {}", GetBaseObject()->GetGUID().ToString(), e.action.setEventPhase.phase); break; } @@ -888,7 +888,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u IncPhase(e.action.incEventPhase.inc); DecPhase(e.action.incEventPhase.dec); - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction:: SMART_ACTION_INC_EVENT_PHASE: Creature {} inc event phase by {}, " + LOG_DEBUG("db.query", "SmartScript::ProcessAction:: SMART_ACTION_INC_EVENT_PHASE: Creature {} inc event phase by {}, " "decrease by {}", GetBaseObject()->GetGUID().ToString(), e.action.incEventPhase.inc, e.action.incEventPhase.dec); break; } @@ -916,7 +916,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u Acore::BroadcastTextBuilder builder(me, CHAT_MSG_MONSTER_EMOTE, BROADCAST_TEXT_FLEE_FOR_ASSIST, me->getGender()); sCreatureTextMgr->SendChatPacket(me, builder, CHAT_MSG_MONSTER_EMOTE); } - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction:: SMART_ACTION_FLEE_FOR_ASSIST: Creature {} DoFleeToGetAssistance", me->GetGUID().ToString()); + LOG_DEBUG("db.query", "SmartScript::ProcessAction:: SMART_ACTION_FLEE_FOR_ASSIST: Creature {} DoFleeToGetAssistance", me->GetGUID().ToString()); break; } case SMART_ACTION_COMBAT_STOP: @@ -1029,7 +1029,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u uint32 phase = urand(e.action.randomPhaseRange.phaseMin, e.action.randomPhaseRange.phaseMax); SetPhase(phase); - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction: SMART_ACTION_RANDOM_PHASE_RANGE: Creature {} sets event phase to {}", + LOG_DEBUG("db.query", "SmartScript::ProcessAction: SMART_ACTION_RANDOM_PHASE_RANGE: Creature {} sets event phase to {}", GetBaseObject()->GetGUID().ToString(), phase); break; } @@ -1038,7 +1038,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (trigger && IsPlayer(unit)) { unit->ToPlayer()->RewardPlayerAndGroupAtEvent(e.action.killedMonster.creature, unit); - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction: SMART_ACTION_CALL_KILLEDMONSTER: (trigger == true) Player {}, Killcredit: {}", + LOG_DEBUG("db.query", "SmartScript::ProcessAction: SMART_ACTION_CALL_KILLEDMONSTER: (trigger == true) Player {}, Killcredit: {}", unit->GetGUID().ToString(), e.action.killedMonster.creature); } else if (e.target.type == SMART_TARGET_NONE || e.target.type == SMART_TARGET_SELF) // Loot recipient and his group members @@ -1049,7 +1049,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (Player* player = me->GetLootRecipient()) { player->RewardPlayerAndGroupAtEvent(e.action.killedMonster.creature, player); - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction: SMART_ACTION_CALL_KILLEDMONSTER: Player {}, Killcredit: {}", + LOG_DEBUG("db.query", "SmartScript::ProcessAction: SMART_ACTION_CALL_KILLEDMONSTER: Player {}, Killcredit: {}", player->GetGUID().ToString(), e.action.killedMonster.creature); } } @@ -1065,7 +1065,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u continue; player->RewardPlayerAndGroupAtEvent(e.action.killedMonster.creature, player); - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction: SMART_ACTION_CALL_KILLEDMONSTER: Player {}, Killcredit: {}", + LOG_DEBUG("db.query", "SmartScript::ProcessAction: SMART_ACTION_CALL_KILLEDMONSTER: Player {}, Killcredit: {}", target->GetGUID().ToString(), e.action.killedMonster.creature); } } @@ -1118,7 +1118,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u InstanceScript* instance = obj->GetInstanceScript(); if (!instance) { - LOG_ERROR("sql.sql", "SmartScript: Event {} attempt to set instance data without instance script. EntryOrGuid {}", e.GetEventType(), e.entryOrGuid); + LOG_ERROR("db.query", "SmartScript: Event {} attempt to set instance data without instance script. EntryOrGuid {}", e.GetEventType(), e.entryOrGuid); break; } @@ -1149,7 +1149,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (me && !me->isDead()) { me->KillSelf(); - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction: SMART_ACTION_DIE: Creature {}", me->GetGUID().ToString()); + LOG_DEBUG("db.query", "SmartScript::ProcessAction: SMART_ACTION_DIE: Creature {}", me->GetGUID().ToString()); } }, Milliseconds(e.action.die.milliseconds)); } @@ -1157,7 +1157,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u else if (me && !me->isDead()) { me->KillSelf(); - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction: SMART_ACTION_DIE: Creature {}", me->GetGUID().ToString()); + LOG_DEBUG("db.query", "SmartScript::ProcessAction: SMART_ACTION_DIE: Creature {}", me->GetGUID().ToString()); } break; } @@ -1218,7 +1218,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (me) { me->SetSheath(SheathState(e.action.setSheath.sheath)); - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction: SMART_ACTION_SET_SHEATH: Creature {}, State: {}", + LOG_DEBUG("db.query", "SmartScript::ProcessAction: SMART_ACTION_SET_SHEATH: Creature {}, State: {}", me->GetGUID().ToString(), e.action.setSheath.sheath); } break; @@ -1560,14 +1560,14 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (SmartAI* ai = CAST_AI(SmartAI, target->ToCreature()->AI())) ai->GetScript()->StoreCounter(e.action.setCounter.counterId, e.action.setCounter.value, e.action.setCounter.reset, e.action.setCounter.subtract); else - LOG_ERROR("sql.sql", "SmartScript: Action target for SMART_ACTION_SET_COUNTER is not using SmartAI, skipping"); + LOG_ERROR("db.query", "SmartScript: Action target for SMART_ACTION_SET_COUNTER is not using SmartAI, skipping"); } else if (IsGameObject(target)) { if (SmartGameObjectAI* ai = CAST_AI(SmartGameObjectAI, target->ToGameObject()->AI())) ai->GetScript()->StoreCounter(e.action.setCounter.counterId, e.action.setCounter.value, e.action.setCounter.reset, e.action.setCounter.subtract); else - LOG_ERROR("sql.sql", "SmartScript: Action target for SMART_ACTION_SET_COUNTER is not using SmartGameObjectAI, skipping"); + LOG_ERROR("db.query", "SmartScript: Action target for SMART_ACTION_SET_COUNTER is not using SmartGameObjectAI, skipping"); } } } @@ -1797,7 +1797,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u EquipmentInfo const* eInfo = sObjectMgr->GetEquipmentInfo(npc->GetEntry(), equipId); if (!eInfo) { - LOG_ERROR("sql.sql", "SmartScript: SMART_ACTION_EQUIP uses non-existent equipment info id {} for creature {}", equipId, npc->GetEntry()); + LOG_ERROR("db.query", "SmartScript: SMART_ACTION_EQUIP uses non-existent equipment info id {} for creature {}", equipId, npc->GetEntry()); break; } @@ -1908,7 +1908,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u { if (e.GetTargetType() == SMART_TARGET_NONE) { - LOG_ERROR("sql.sql", "SmartScript: Entry {} SourceType {} Event {} Action {} is using TARGET_NONE(0) for Script9 target. Please correct target_type in database.", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetActionType()); + LOG_ERROR("db.query", "SmartScript: Entry {} SourceType {} Event {} Action {} is using TARGET_NONE(0) for Script9 target. Please correct target_type in database.", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetActionType()); break; } @@ -1995,7 +1995,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u uint32 id = Acore::Containers::SelectRandomContainerElement(actionLists); if (e.GetTargetType() == SMART_TARGET_NONE) { - LOG_ERROR("sql.sql", "SmartScript: Entry {} SourceType {} Event {} Action {} is using TARGET_NONE(0) for Script9 target. Please correct target_type in database.", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetActionType()); + LOG_ERROR("db.query", "SmartScript: Entry {} SourceType {} Event {} Action {} is using TARGET_NONE(0) for Script9 target. Please correct target_type in database.", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetActionType()); break; } @@ -2019,7 +2019,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u uint32 id = urand(e.action.randTimedActionList.actionLists[0], e.action.randTimedActionList.actionLists[1]); if (e.GetTargetType() == SMART_TARGET_NONE) { - LOG_ERROR("sql.sql", "SmartScript: Entry {} SourceType {} Event {} Action {} is using TARGET_NONE(0) for Script9 target. Please correct target_type in database.", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetActionType()); + LOG_ERROR("db.query", "SmartScript: Entry {} SourceType {} Event {} Action {} is using TARGET_NONE(0) for Script9 target. Please correct target_type in database.", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetActionType()); break; } @@ -2192,14 +2192,14 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (SmartAI* ai = CAST_AI(SmartAI, target->ToCreature()->AI())) ai->GetScript()->StoreTargetList(ObjectVector(*storedTargets), e.action.sendTargetToTarget.id); // store a copy of target list else - LOG_ERROR("sql.sql", "SmartScript: Action target for SMART_ACTION_SEND_TARGET_TO_TARGET is not using SmartAI, skipping"); + LOG_ERROR("db.query", "SmartScript: Action target for SMART_ACTION_SEND_TARGET_TO_TARGET is not using SmartAI, skipping"); } else if (IsGameObject(target)) { if (SmartGameObjectAI* ai = CAST_AI(SmartGameObjectAI, target->ToGameObject()->AI())) ai->GetScript()->StoreTargetList(ObjectVector(*storedTargets), e.action.sendTargetToTarget.id); // store a copy of target list else - LOG_ERROR("sql.sql", "SmartScript: Action target for SMART_ACTION_SEND_TARGET_TO_TARGET is not using SmartGameObjectAI, skipping"); + LOG_ERROR("db.query", "SmartScript: Action target for SMART_ACTION_SEND_TARGET_TO_TARGET is not using SmartGameObjectAI, skipping"); } } break; @@ -2209,7 +2209,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (!GetBaseObject()) break; - LOG_DEBUG("sql.sql", "SmartScript::ProcessAction:: SMART_ACTION_SEND_GOSSIP_MENU: gossipMenuId {}, gossipNpcTextId {}", + LOG_DEBUG("db.query", "SmartScript::ProcessAction:: SMART_ACTION_SEND_GOSSIP_MENU: gossipMenuId {}, gossipNpcTextId {}", e.action.sendGossipMenu.gossipMenuId, e.action.sendGossipMenu.gossipNpcTextId); for (WorldObject* target : targets) @@ -2876,7 +2876,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u break; } default: - LOG_ERROR("sql.sql", "SmartScript::ProcessAction: Entry {} SourceType {}, Event {}, Unhandled Action type {}", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); + LOG_ERROR("db.query", "SmartScript::ProcessAction: Entry {} SourceType {}, Event {}, Unhandled Action type {}", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); break; } @@ -2886,7 +2886,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (linked.GetActionType() && linked.GetEventType() == SMART_EVENT_LINK) ProcessEvent(linked, unit, var0, var1, bvar, spell, gob); else - LOG_ERROR("sql.sql", "SmartScript::ProcessAction: Entry {} SourceType {}, Event {}, Link Event {} not found or invalid, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.link); + LOG_ERROR("db.query", "SmartScript::ProcessAction: Entry {} SourceType {}, Event {}, Link Event {} not found or invalid, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.link); } } @@ -2911,7 +2911,7 @@ void SmartScript::InstallTemplate(SmartScriptHolder const& e) return; if (mTemplate != SMARTAI_TEMPLATE_BASIC) { - LOG_ERROR("sql.sql", "SmartScript::InstallTemplate: Entry {} SourceType {} AI Template can not be set more then once, skipped.", e.entryOrGuid, e.GetScriptType()); + LOG_ERROR("db.query", "SmartScript::InstallTemplate: Entry {} SourceType {} AI Template can not be set more then once, skipped.", e.entryOrGuid, e.GetScriptType()); return; } mTemplate = (SMARTAI_TEMPLATE)e.action.installTtemplate.id; @@ -4044,7 +4044,7 @@ void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, ui } case SMART_EVENT_GOSSIP_SELECT: { - LOG_DEBUG("sql.sql", "SmartScript: Gossip Select: menu {} action {}", var0, var1); //little help for scripters + LOG_DEBUG("db.query", "SmartScript: Gossip Select: menu {} action {}", var0, var1); //little help for scripters if (e.event.gossip.sender != var0 || e.event.gossip.action != var1) return; ProcessAction(e, unit, var0, var1); @@ -4310,7 +4310,7 @@ void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, ui break; } default: - LOG_ERROR("sql.sql", "SmartScript::ProcessEvent: Unhandled Event type {}", e.GetEventType()); + LOG_ERROR("db.query", "SmartScript::ProcessEvent: Unhandled Event type {}", e.GetEventType()); break; } } @@ -4532,10 +4532,10 @@ void SmartScript::FillScript(SmartAIEventList e, WorldObject* obj, AreaTrigger c if (e.empty()) { if (obj) - LOG_DEBUG("sql.sql", "SmartScript: EventMap for Entry {} is empty but is using SmartScript.", obj->GetEntry()); + LOG_DEBUG("db.query", "SmartScript: EventMap for Entry {} is empty but is using SmartScript.", obj->GetEntry()); if (at) - LOG_DEBUG("sql.sql", "SmartScript: EventMap for AreaTrigger {} is empty but is using SmartScript.", at->entry); + LOG_DEBUG("db.query", "SmartScript: EventMap for AreaTrigger {} is empty but is using SmartScript.", at->entry); return; } for (SmartAIEventList::iterator i = e.begin(); i != e.end(); ++i) @@ -4603,12 +4603,12 @@ void SmartScript::OnInitialize(WorldObject* obj, AreaTrigger const* at) case TYPEID_UNIT: mScriptType = SMART_SCRIPT_TYPE_CREATURE; me = obj->ToCreature(); - LOG_DEBUG("sql.sql", "SmartScript::OnInitialize: source is Creature {}", me->GetEntry()); + LOG_DEBUG("db.query", "SmartScript::OnInitialize: source is Creature {}", me->GetEntry()); break; case TYPEID_GAMEOBJECT: mScriptType = SMART_SCRIPT_TYPE_GAMEOBJECT; go = obj->ToGameObject(); - LOG_DEBUG("sql.sql", "SmartScript::OnInitialize: source is GameObject {}", go->GetEntry()); + LOG_DEBUG("db.query", "SmartScript::OnInitialize: source is GameObject {}", go->GetEntry()); break; default: LOG_ERROR("scripts.ai.sai", "SmartScript::OnInitialize: Unhandled TypeID !WARNING!"); @@ -4619,7 +4619,7 @@ void SmartScript::OnInitialize(WorldObject* obj, AreaTrigger const* at) { mScriptType = SMART_SCRIPT_TYPE_AREATRIGGER; trigger = at; - LOG_DEBUG("sql.sql", "SmartScript::OnInitialize: source is AreaTrigger {}", trigger->entry); + LOG_DEBUG("db.query", "SmartScript::OnInitialize: source is AreaTrigger {}", trigger->entry); } else { diff --git a/src/server/game/AI/SmartScripts/SmartScript.h b/src/server/game/AI/SmartScripts/SmartScript.h index 72007ebc48f7c2..2ca698e8300979 100644 --- a/src/server/game/AI/SmartScripts/SmartScript.h +++ b/src/server/game/AI/SmartScripts/SmartScript.h @@ -93,7 +93,7 @@ class SmartScript smart = false; if (!smart) - LOG_ERROR("sql.sql", "SmartScript: Action target Creature(entry: {}) is not using SmartAI, action skipped to prevent crash.", c ? c->GetEntry() : (me ? me->GetEntry() : 0)); + LOG_ERROR("db.query", "SmartScript: Action target Creature(entry: {}) is not using SmartAI, action skipped to prevent crash.", c ? c->GetEntry() : (me ? me->GetEntry() : 0)); return smart; } @@ -107,7 +107,7 @@ class SmartScript if (!go || go->GetAIName() != "SmartGameObjectAI") smart = false; if (!smart) - LOG_ERROR("sql.sql", "SmartScript: Action target GameObject(entry: {}) is not using SmartGameObjectAI, action skipped to prevent crash.", g ? g->GetEntry() : (go ? go->GetEntry() : 0)); + LOG_ERROR("db.query", "SmartScript: Action target GameObject(entry: {}) is not using SmartGameObjectAI, action skipped to prevent crash.", g ? g->GetEntry() : (go ? go->GetEntry() : 0)); return smart; } diff --git a/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp b/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp index f0bba12a914fbf..bc9dfb303d789d 100644 --- a/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp +++ b/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp @@ -33,7 +33,7 @@ { \ if (value > 1) \ { \ - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses param {} of type Boolean with value {}, valid values are 0 or 1, skipped.", \ + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses param {} of type Boolean with value {}, valid values are 0 or 1, skipped.", \ e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), STRINGIZE(value), value); \ return false; \ } \ @@ -59,7 +59,7 @@ void SmartWaypointMgr::LoadFromDB() waypoint_map.clear(); - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_SMARTAI_WP); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_SMARTAI_WP); PreparedQueryResult result = WorldDatabase.Query(stmt); if (!result) @@ -95,7 +95,7 @@ void SmartWaypointMgr::LoadFromDB() } if (last_id != id) - LOG_ERROR("sql.sql", "SmartWaypointMgr::LoadFromDB: Path entry {}, unexpected point id {}, expected {}.", entry, id, last_id); + LOG_ERROR("db.query", "SmartWaypointMgr::LoadFromDB: Path entry {}, unexpected point id {}, expected {}.", entry, id, last_id); last_id++; (*waypoint_map[entry])[id] = new WayPoint(id, x, y, z, o, delay); @@ -132,7 +132,7 @@ void SmartAIMgr::LoadSmartAIFromDB() for (uint8 i = 0; i < SMART_SCRIPT_TYPE_MAX; i++) mEventMap[i].clear(); //Drop Existing SmartAI List - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_SMART_SCRIPTS); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_SMART_SCRIPTS); PreparedQueryResult result = WorldDatabase.Query(stmt); if (!result) @@ -153,14 +153,14 @@ void SmartAIMgr::LoadSmartAIFromDB() temp.entryOrGuid = fields[0].Get(); if (!temp.entryOrGuid) { - LOG_ERROR("sql.sql", "SmartAIMgr::LoadSmartAIFromDB: invalid entryorguid (0), skipped loading."); + LOG_ERROR("db.query", "SmartAIMgr::LoadSmartAIFromDB: invalid entryorguid (0), skipped loading."); continue; } SmartScriptType source_type = (SmartScriptType)fields[1].Get(); if (source_type >= SMART_SCRIPT_TYPE_MAX) { - LOG_ERROR("sql.sql", "SmartAIMgr::LoadSmartAIFromDB: invalid source_type ({}), skipped loading.", uint32(source_type)); + LOG_ERROR("db.query", "SmartAIMgr::LoadSmartAIFromDB: invalid source_type ({}), skipped loading.", uint32(source_type)); continue; } if (temp.entryOrGuid >= 0) @@ -171,7 +171,7 @@ void SmartAIMgr::LoadSmartAIFromDB() { if (!sObjectMgr->GetCreatureTemplate((uint32)temp.entryOrGuid)) { - LOG_ERROR("sql.sql", "SmartAIMgr::LoadSmartAIFromDB: Creature entry ({}) does not exist, skipped loading.", uint32(temp.entryOrGuid)); + LOG_ERROR("db.query", "SmartAIMgr::LoadSmartAIFromDB: Creature entry ({}) does not exist, skipped loading.", uint32(temp.entryOrGuid)); continue; } break; @@ -180,7 +180,7 @@ void SmartAIMgr::LoadSmartAIFromDB() { if (!sObjectMgr->GetGameObjectTemplate((uint32)temp.entryOrGuid)) { - LOG_ERROR("sql.sql", "SmartAIMgr::LoadSmartAIFromDB: GameObject entry ({}) does not exist, skipped loading.", uint32(temp.entryOrGuid)); + LOG_ERROR("db.query", "SmartAIMgr::LoadSmartAIFromDB: GameObject entry ({}) does not exist, skipped loading.", uint32(temp.entryOrGuid)); continue; } break; @@ -189,7 +189,7 @@ void SmartAIMgr::LoadSmartAIFromDB() { if (!sObjectMgr->GetAreaTrigger((uint32)temp.entryOrGuid)) { - LOG_ERROR("sql.sql", "SmartAIMgr::LoadSmartAIFromDB: AreaTrigger entry ({}) does not exist, skipped loading.", uint32(temp.entryOrGuid)); + LOG_ERROR("db.query", "SmartAIMgr::LoadSmartAIFromDB: AreaTrigger entry ({}) does not exist, skipped loading.", uint32(temp.entryOrGuid)); continue; } break; @@ -197,7 +197,7 @@ void SmartAIMgr::LoadSmartAIFromDB() case SMART_SCRIPT_TYPE_TIMED_ACTIONLIST: break;//nothing to check, really default: - LOG_ERROR("sql.sql", "SmartAIMgr::LoadSmartAIFromDB: not yet implemented source_type {}", (uint32)source_type); + LOG_ERROR("db.query", "SmartAIMgr::LoadSmartAIFromDB: not yet implemented source_type {}", (uint32)source_type); continue; } } @@ -205,7 +205,7 @@ void SmartAIMgr::LoadSmartAIFromDB() { if (!sObjectMgr->GetCreatureData(uint32(std::abs(temp.entryOrGuid)))) { - LOG_ERROR("sql.sql", "SmartAIMgr::LoadSmartAIFromDB: Creature guid ({}) does not exist, skipped loading.", uint32(std::abs(temp.entryOrGuid))); + LOG_ERROR("db.query", "SmartAIMgr::LoadSmartAIFromDB: Creature guid ({}) does not exist, skipped loading.", uint32(std::abs(temp.entryOrGuid))); continue; } } @@ -373,7 +373,7 @@ bool SmartAIMgr::IsTargetValid(SmartScriptHolder const& e) { if (e.target.unitDistance.creature && !sObjectMgr->GetCreatureTemplate(e.target.unitDistance.creature)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Creature entry {} as target_param1, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.target.unitDistance.creature); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Creature entry {} as target_param1, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.target.unitDistance.creature); return false; } break; @@ -383,7 +383,7 @@ bool SmartAIMgr::IsTargetValid(SmartScriptHolder const& e) { if (e.target.goDistance.entry && !sObjectMgr->GetGameObjectTemplate(e.target.goDistance.entry)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent GameObject entry {} as target_param1, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.target.goDistance.entry); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent GameObject entry {} as target_param1, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.target.goDistance.entry); return false; } break; @@ -405,7 +405,7 @@ bool SmartAIMgr::IsTargetValid(SmartScriptHolder const& e) { if (e.target.playerDistance.dist == 0) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} has maxDist 0 as target_param1, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} has maxDist 0 as target_param1, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } break; @@ -415,7 +415,7 @@ bool SmartAIMgr::IsTargetValid(SmartScriptHolder const& e) case SMART_TARGET_INVOKER_PARTY: if (e.GetScriptType() != SMART_SCRIPT_TYPE_TIMED_ACTIONLIST && e.GetEventType() != SMART_EVENT_LINK && !EventHasInvoker(e.event.type)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} has invoker target, but event does not provide any invoker!", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetActionType()); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} has invoker target, but event does not provide any invoker!", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetActionType()); return false; } break; @@ -431,7 +431,7 @@ bool SmartAIMgr::IsTargetValid(SmartScriptHolder const& e) { if (e.target.instanceStorage.type != 1 && e.target.instanceStorage.type != 2) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} has invalid instance storage type as target ({}).", + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} has invalid instance storage type as target ({}).", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetActionType(), e.target.instanceStorage.type); return false; } @@ -474,7 +474,7 @@ bool SmartAIMgr::IsTargetValid(SmartScriptHolder const& e) case SMART_TARGET_THREAT_LIST: break; default: - LOG_ERROR("sql.sql", "SmartAIMgr: Not handled target_type({}), Entry {} SourceType {} Event {} Action {}, skipped.", e.GetTargetType(), e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); + LOG_ERROR("db.query", "SmartAIMgr: Not handled target_type({}), Entry {} SourceType {} Event {} Action {}, skipped.", e.GetTargetType(), e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } @@ -581,7 +581,7 @@ bool SmartAIMgr::CheckUnusedEventParams(SmartScriptHolder const& e) case SMART_EVENT_NEAR_UNIT: return sizeof(SmartEvent::nearUnit); case SMART_EVENT_AREA_CASTING: return sizeof(SmartEvent::areaCasting); default: - LOG_WARN("sql.sql", "SmartAIMgr: entryorguid {} source_type {} id {} action_type {} is using an event {} with no unused params specified in SmartAIMgr::CheckUnusedEventParams(), please report this.", + LOG_WARN("db.query", "SmartAIMgr: entryorguid {} source_type {} id {} action_type {} is using an event {} with no unused params specified in SmartAIMgr::CheckUnusedEventParams(), please report this.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.GetEventType()); return sizeof(SmartEvent::raw); } @@ -596,7 +596,7 @@ bool SmartAIMgr::CheckUnusedEventParams(SmartScriptHolder const& e) uint32 value = ((uint32*)&e.event.raw)[index]; if (value != 0) { - LOG_ERROR("sql.sql", "SmartAIMgr: entryorguid {} source_type {} id {} action_type {} has unused event_param{} with value {}, it must be 0, skipped.", + LOG_ERROR("db.query", "SmartAIMgr: entryorguid {} source_type {} id {} action_type {} has unused event_param{} with value {}, it must be 0, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), index + 1, value); valid = false; } @@ -774,7 +774,7 @@ bool SmartAIMgr::CheckUnusedActionParams(SmartScriptHolder const& e) case SMART_ACTION_SET_SCALE: return sizeof(SmartAction::setScale); case SMART_ACTION_SUMMON_RADIAL: return sizeof(SmartAction::radialSummon); default: - LOG_WARN("sql.sql", "SmartAIMgr: entryorguid {} source_type {} id {} action_type {} is using an action with no unused params specified in SmartAIMgr::CheckUnusedActionParams(), please report this.", + LOG_WARN("db.query", "SmartAIMgr: entryorguid {} source_type {} id {} action_type {} is using an action with no unused params specified in SmartAIMgr::CheckUnusedActionParams(), please report this.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return sizeof(SmartAction::raw); } @@ -789,7 +789,7 @@ bool SmartAIMgr::CheckUnusedActionParams(SmartScriptHolder const& e) uint32 value = ((uint32*)&e.action.raw)[index]; if (value != 0) { - LOG_ERROR("sql.sql", "SmartAIMgr: entryorguid {} source_type {} id {} action_type {} has unused action_param{} with value {}, it must be 0, skipped.", + LOG_ERROR("db.query", "SmartAIMgr: entryorguid {} source_type {} id {} action_type {} has unused action_param{} with value {}, it must be 0, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), index + 1, value); valid = false; } @@ -838,7 +838,7 @@ bool SmartAIMgr::CheckUnusedTargetParams(SmartScriptHolder const& e) // case SMART_TARGET_CLOSEST_UNSPAWNED_GAMEOBJECT: return sizeof(SmartTarget::goClosest); case SMART_TARGET_PLAYER_WITH_AURA: return sizeof(SmartTarget::playerWithAura); default: - LOG_WARN("sql.sql", "SmartAIMgr: entryorguid {} source_type {} id {} action_type {} is using a target {} with no unused params specified in SmartAIMgr::CheckUnusedTargetParams(), please report this.", + LOG_WARN("db.query", "SmartAIMgr: entryorguid {} source_type {} id {} action_type {} is using a target {} with no unused params specified in SmartAIMgr::CheckUnusedTargetParams(), please report this.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.GetTargetType()); return sizeof(SmartTarget::raw); } @@ -853,7 +853,7 @@ bool SmartAIMgr::CheckUnusedTargetParams(SmartScriptHolder const& e) uint32 value = ((uint32*)&e.target.raw)[index]; if (value != 0) { - LOG_ERROR("sql.sql", "SmartAIMgr: entryorguid {} source_type {} id {} action_type {} has unused target_param{} with value {}, it must be 0, skipped.", + LOG_ERROR("db.query", "SmartAIMgr: entryorguid {} source_type {} id {} action_type {} has unused target_param{} with value {}, it must be 0, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), index + 1, value); valid = false; } @@ -866,20 +866,20 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if ((e.event.type >= SMART_EVENT_TC_END && e.event.type <= SMART_EVENT_AC_START) || e.event.type >= SMART_EVENT_AC_END) { - LOG_ERROR("sql.sql", "SmartAIMgr: EntryOrGuid {} using event({}) has invalid event type ({}), skipped.", e.entryOrGuid, e.event_id, e.GetEventType()); + LOG_ERROR("db.query", "SmartAIMgr: EntryOrGuid {} using event({}) has invalid event type ({}), skipped.", e.entryOrGuid, e.event_id, e.GetEventType()); return false; } // in SMART_SCRIPT_TYPE_TIMED_ACTIONLIST all event types are overriden by core if (e.GetScriptType() != SMART_SCRIPT_TYPE_TIMED_ACTIONLIST && !(SmartAIEventMask[e.event.type][1] & SmartAITypeMask[e.GetScriptType()][1])) { - LOG_ERROR("sql.sql", "SmartAIMgr: EntryOrGuid {}, event type {} can not be used for Script type {}", e.entryOrGuid, e.GetEventType(), e.GetScriptType()); + LOG_ERROR("db.query", "SmartAIMgr: EntryOrGuid {}, event type {} can not be used for Script type {}", e.entryOrGuid, e.GetEventType(), e.GetScriptType()); return false; } if (e.action.type <= 0 || (e.action.type >= SMART_ACTION_TC_END && e.action.type <= SMART_ACTION_AC_START) || e.action.type >= SMART_ACTION_AC_END) { - LOG_ERROR("sql.sql", "SmartAIMgr: EntryOrGuid {} using event({}) has an invalid action type ({}), skipped.", e.entryOrGuid, e.event_id, e.GetActionType()); + LOG_ERROR("db.query", "SmartAIMgr: EntryOrGuid {} using event({}) has an invalid action type ({}), skipped.", e.entryOrGuid, e.event_id, e.GetActionType()); return false; } switch (e.action.type) @@ -888,7 +888,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) case SMART_ACTION_PLAY_ANIMKIT: case SMART_ACTION_SCENE_PLAY: case SMART_ACTION_SCENE_CANCEL: - LOG_ERROR("sql.sql", "SmartAIMgr: EntryOrGuid {} using event({}) has an action type that is not supported on 3.3.5a ({}), skipped.", + LOG_ERROR("db.query", "SmartAIMgr: EntryOrGuid {} using event({}) has an action type that is not supported on 3.3.5a ({}), skipped.", e.entryOrGuid, e.event_id, e.GetActionType()); return false; case SMART_ACTION_SET_CAN_FLY: @@ -897,7 +897,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) case SMART_ACTION_SPAWN_SPAWNGROUP: case SMART_ACTION_DESPAWN_SPAWNGROUP: case SMART_ACTION_RESPAWN_BY_SPAWNID: - LOG_ERROR("sql.sql", "SmartAIMgr: EntryOrGuid {} using event({}) has an action type that is not yet supported on AzerothCore ({}), skipped.", + LOG_ERROR("db.query", "SmartAIMgr: EntryOrGuid {} using event({}) has an action type that is not yet supported on AzerothCore ({}), skipped.", e.entryOrGuid, e.event_id, e.GetActionType()); return false; default: @@ -905,24 +905,24 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) } if (e.target.type < 0 || (e.target.type >= SMART_TARGET_TC_END && e.target.type < SMART_TARGET_AC_START) || e.target.type >= SMART_TARGET_AC_END) { - LOG_ERROR("sql.sql", "SmartAIMgr: EntryOrGuid {} using event({}) has an invalid target type ({}), skipped.", + LOG_ERROR("db.query", "SmartAIMgr: EntryOrGuid {} using event({}) has an invalid target type ({}), skipped.", e.entryOrGuid, e.event_id, e.GetTargetType()); return false; } if (e.target.type == SMART_TARGET_LOOT_RECIPIENTS) { - LOG_ERROR("sql.sql", "SmartAIMgr: EntryOrGuid {} using event({}) has a target type that is not yet supported on AzerothCore ({}), skipped.", + LOG_ERROR("db.query", "SmartAIMgr: EntryOrGuid {} using event({}) has a target type that is not yet supported on AzerothCore ({}), skipped.", e.entryOrGuid, e.event_id, e.GetTargetType()); return false; } if (e.event.event_phase_mask > SMART_EVENT_PHASE_ALL) { - LOG_ERROR("sql.sql", "SmartAIMgr: EntryOrGuid {} using event({}) has invalid phase mask ({}), skipped.", e.entryOrGuid, e.event_id, e.event.event_phase_mask); + LOG_ERROR("db.query", "SmartAIMgr: EntryOrGuid {} using event({}) has invalid phase mask ({}), skipped.", e.entryOrGuid, e.event_id, e.event.event_phase_mask); return false; } if (e.event.event_flags > SMART_EVENT_FLAGS_ALL) { - LOG_ERROR("sql.sql", "SmartAIMgr: EntryOrGuid {} using event({}) has invalid event flags ({}), skipped.", e.entryOrGuid, e.event_id, e.event.event_flags); + LOG_ERROR("db.query", "SmartAIMgr: EntryOrGuid {} using event({}) has invalid event flags ({}), skipped.", e.entryOrGuid, e.event_id, e.event.event_flags); return false; } if (e.GetScriptType() == SMART_SCRIPT_TYPE_TIMED_ACTIONLIST) @@ -969,12 +969,12 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(e.event.spellHit.spell); if (!spellInfo) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Spell entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.spellHit.spell); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Spell entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.spellHit.spell); return false; } if (e.event.spellHit.school && (e.event.spellHit.school & spellInfo->SchoolMask) != spellInfo->SchoolMask) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses Spell entry {} with invalid school mask, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.spellHit.spell); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses Spell entry {} with invalid school mask, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.spellHit.spell); return false; } } @@ -990,7 +990,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) if (e.event.los.hostilityMode >= AsUnderlyingType(SmartEvent::LOSHostilityMode::End)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses hostilityMode with invalid value {} (max allowed value {}), skipped.", + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses hostilityMode with invalid value {} (max allowed value {}), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.los.hostilityMode, AsUnderlyingType(SmartEvent::LOSHostilityMode::End) - 1); return false; } @@ -1000,12 +1000,12 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) case SMART_EVENT_RESPAWN: if (e.event.respawn.type == SMART_SCRIPT_RESPAWN_CONDITION_MAP && !sMapStore.LookupEntry(e.event.respawn.map)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Map entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.respawn.map); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Map entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.respawn.map); return false; } if (e.event.respawn.type == SMART_SCRIPT_RESPAWN_CONDITION_AREA && !sAreaTableStore.LookupEntry(e.event.respawn.area)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Area entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.respawn.area); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Area entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.respawn.area); return false; } break; @@ -1116,7 +1116,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if (e.event.movementInform.type > NULL_MOTION_TYPE) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses invalid Motion type {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.movementInform.type); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses invalid Motion type {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.movementInform.type); return false; } break; @@ -1140,7 +1140,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if (e.link && e.link == e.event_id) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {}, Event {}, Link Event is linking self (infinite loop), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {}, Event {}, Link Event is linking self (infinite loop), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id); return false; } break; @@ -1149,19 +1149,19 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if (!e.event.eventPhaseChange.phasemask) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} has no param set, event won't be executed!.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} has no param set, event won't be executed!.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } if (e.event.eventPhaseChange.phasemask > SMART_EVENT_PHASE_ALL) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses invalid phasemask {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.eventPhaseChange.phasemask); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses invalid phasemask {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.eventPhaseChange.phasemask); return false; } if (e.event.event_phase_mask && !(e.event.event_phase_mask & e.event.eventPhaseChange.phasemask)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses event phasemask {} and incompatible event_param1 {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.event_phase_mask, e.event.eventPhaseChange.phasemask); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses event phasemask {} and incompatible event_param1 {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.event_phase_mask, e.event.eventPhaseChange.phasemask); return false; } break; @@ -1182,7 +1182,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if (e.event.doAction.eventId > EVENT_CHARGE) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses invalid event id {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.doAction.eventId); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses invalid event id {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.event.doAction.eventId); return false; } break; @@ -1193,7 +1193,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) if (e.event.friendlyHealthPct.maxHpPct > 100 || e.event.friendlyHealthPct.minHpPct > 100) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} has pct value above 100, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} has pct value above 100, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } @@ -1215,57 +1215,57 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) } break; default: - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses invalid target_type {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.GetTargetType()); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses invalid target_type {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.GetTargetType()); return false; } break; case SMART_EVENT_DISTANCE_CREATURE: if (e.event.distance.guid == 0 && e.event.distance.entry == 0) { - LOG_ERROR("sql.sql", "SmartAIMgr: Event SMART_EVENT_DISTANCE_CREATURE did not provide creature guid or entry, skipped."); + LOG_ERROR("db.query", "SmartAIMgr: Event SMART_EVENT_DISTANCE_CREATURE did not provide creature guid or entry, skipped."); return false; } if (e.event.distance.guid != 0 && e.event.distance.entry != 0) { - LOG_ERROR("sql.sql", "SmartAIMgr: Event SMART_EVENT_DISTANCE_CREATURE provided both an entry and guid, skipped."); + LOG_ERROR("db.query", "SmartAIMgr: Event SMART_EVENT_DISTANCE_CREATURE provided both an entry and guid, skipped."); return false; } if (e.event.distance.guid != 0 && !sObjectMgr->GetCreatureData(e.event.distance.guid)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Event SMART_EVENT_DISTANCE_CREATURE using invalid creature guid {}, skipped.", e.event.distance.guid); + LOG_ERROR("db.query", "SmartAIMgr: Event SMART_EVENT_DISTANCE_CREATURE using invalid creature guid {}, skipped.", e.event.distance.guid); return false; } if (e.event.distance.entry != 0 && !sObjectMgr->GetCreatureTemplate(e.event.distance.entry)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Event SMART_EVENT_DISTANCE_CREATURE using invalid creature entry {}, skipped.", e.event.distance.entry); + LOG_ERROR("db.query", "SmartAIMgr: Event SMART_EVENT_DISTANCE_CREATURE using invalid creature entry {}, skipped.", e.event.distance.entry); return false; } break; case SMART_EVENT_DISTANCE_GAMEOBJECT: if (e.event.distance.guid == 0 && e.event.distance.entry == 0) { - LOG_ERROR("sql.sql", "SmartAIMgr: Event SMART_EVENT_DISTANCE_GAMEOBJECT did not provide gameobject guid or entry, skipped."); + LOG_ERROR("db.query", "SmartAIMgr: Event SMART_EVENT_DISTANCE_GAMEOBJECT did not provide gameobject guid or entry, skipped."); return false; } if (e.event.distance.guid != 0 && e.event.distance.entry != 0) { - LOG_ERROR("sql.sql", "SmartAIMgr: Event SMART_EVENT_DISTANCE_GAMEOBJECT provided both an entry and guid, skipped."); + LOG_ERROR("db.query", "SmartAIMgr: Event SMART_EVENT_DISTANCE_GAMEOBJECT provided both an entry and guid, skipped."); return false; } if (e.event.distance.guid != 0 && !sObjectMgr->GetGameObjectData(e.event.distance.guid)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Event SMART_EVENT_DISTANCE_GAMEOBJECT using invalid gameobject guid {}, skipped.", e.event.distance.guid); + LOG_ERROR("db.query", "SmartAIMgr: Event SMART_EVENT_DISTANCE_GAMEOBJECT using invalid gameobject guid {}, skipped.", e.event.distance.guid); return false; } if (e.event.distance.entry != 0 && !sObjectMgr->GetGameObjectTemplate(e.event.distance.entry)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Event SMART_EVENT_DISTANCE_GAMEOBJECT using invalid gameobject entry {}, skipped.", e.event.distance.entry); + LOG_ERROR("db.query", "SmartAIMgr: Event SMART_EVENT_DISTANCE_GAMEOBJECT using invalid gameobject entry {}, skipped.", e.event.distance.entry); return false; } break; @@ -1275,13 +1275,13 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) if (e.event.counter.id == 0) { - LOG_ERROR("sql.sql", "SmartAIMgr: Event SMART_EVENT_COUNTER_SET using invalid counter id {}, skipped.", e.event.counter.id); + LOG_ERROR("db.query", "SmartAIMgr: Event SMART_EVENT_COUNTER_SET using invalid counter id {}, skipped.", e.event.counter.id); return false; } if (e.event.counter.value == 0) { - LOG_ERROR("sql.sql", "SmartAIMgr: Event SMART_EVENT_COUNTER_SET using invalid value {}, skipped.", e.event.counter.value); + LOG_ERROR("db.query", "SmartAIMgr: Event SMART_EVENT_COUNTER_SET using invalid value {}, skipped.", e.event.counter.value); return false; } break; @@ -1326,7 +1326,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) case SMART_EVENT_ON_SPELLCLICK: break; default: - LOG_ERROR("sql.sql", "SmartAIMgr: Not handled event_type({}), Entry {} SourceType {} Event {} Action {}, skipped.", e.GetEventType(), e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); + LOG_ERROR("db.query", "SmartAIMgr: Not handled event_type({}), Entry {} SourceType {} Event {} Action {}, skipped.", e.GetEventType(), e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } } @@ -1341,7 +1341,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) case SMART_ACTION_SET_FACTION: if (e.action.faction.factionID && !sFactionTemplateStore.LookupEntry(e.action.faction.factionID)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Faction {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.faction.factionID); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Faction {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.faction.factionID); return false; } break; @@ -1351,7 +1351,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if (e.action.morphOrMount.creature > 0 && !sObjectMgr->GetCreatureTemplate(e.action.morphOrMount.creature)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Creature entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.morphOrMount.creature); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Creature entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.morphOrMount.creature); return false; } @@ -1359,12 +1359,12 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if (e.action.morphOrMount.creature) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} has ModelID set with also set CreatureId, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} has ModelID set with also set CreatureId, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } else if (!sCreatureDisplayInfoStore.LookupEntry(e.action.morphOrMount.model)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Model id {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.morphOrMount.model); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Model id {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.morphOrMount.model); return false; } } @@ -1424,7 +1424,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if (!sTaxiPathStore.LookupEntry(e.action.taxi.id)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses invalid Taxi path ID {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.taxi.id); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses invalid Taxi path ID {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.taxi.id); return false; } break; @@ -1433,7 +1433,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if (std::all_of(e.action.randomEmote.emotes.begin(), e.action.randomEmote.emotes.end(), [](uint32 emote) { return emote == 0; })) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} does not have any non-zero emote", + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} does not have any non-zero emote", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } @@ -1447,7 +1447,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if (std::all_of(e.action.randTimedActionList.actionLists.begin(), e.action.randTimedActionList.actionLists.end(), [](uint32 actionList) { return actionList == 0; })) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} does not have any non-zero action list", + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} does not have any non-zero action list", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } @@ -1457,7 +1457,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if (std::all_of(e.action.closestWaypointFromList.wps.begin(), e.action.closestWaypointFromList.wps.end(), [](uint32 wp) { return wp == 0; })) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} does not have any non-zero waypoint id", + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} does not have any non-zero waypoint id", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } @@ -1466,7 +1466,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) case SMART_ACTION_INVOKER_CAST: if (e.GetScriptType() != SMART_SCRIPT_TYPE_TIMED_ACTIONLIST && e.GetEventType() != SMART_EVENT_LINK && !EventHasInvoker(e.event.type)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} has invoker cast action, but event does not provide any invoker!", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetActionType()); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} has invoker cast action, but event does not provide any invoker!", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetActionType()); return false; } break; @@ -1489,32 +1489,32 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if (!qid->HasSpecialFlag(QUEST_SPECIAL_FLAGS_EXPLORATION_OR_EVENT)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} SpecialFlags for Quest entry {} does not include FLAGS_EXPLORATION_OR_EVENT(2), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.quest.quest); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} SpecialFlags for Quest entry {} does not include FLAGS_EXPLORATION_OR_EVENT(2), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.quest.quest); return false; } } else { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Quest entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.quest.quest); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Quest entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.quest.quest); return false; } break; case SMART_ACTION_SET_EVENT_PHASE: if (e.action.setEventPhase.phase >= SMART_EVENT_PHASE_MAX) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} attempts to set phase {}. Phase mask cannot be used past phase {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.setEventPhase.phase, SMART_EVENT_PHASE_MAX - 1); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} attempts to set phase {}. Phase mask cannot be used past phase {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.setEventPhase.phase, SMART_EVENT_PHASE_MAX - 1); return false; } break; case SMART_ACTION_INC_EVENT_PHASE: if (!e.action.incEventPhase.inc && !e.action.incEventPhase.dec) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} is incrementing phase by 0, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} is incrementing phase by 0, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } else if (e.action.incEventPhase.inc > SMART_EVENT_PHASE_MAX || e.action.incEventPhase.dec > SMART_EVENT_PHASE_MAX) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} attempts to increment phase by too large value, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} attempts to increment phase by too large value, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } break; @@ -1526,14 +1526,14 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if (std::all_of(e.action.randomPhase.phases.begin(), e.action.randomPhase.phases.end(), [](uint32 phase) { return phase == 0; })) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} does not have any non-zero phase", + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} does not have any non-zero phase", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } if (std::any_of(e.action.randomPhase.phases.begin(), e.action.randomPhase.phases.end(), [](uint32 phase) { return phase >= SMART_EVENT_PHASE_MAX; })) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} attempts to set invalid phase, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} attempts to set invalid phase, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } break; @@ -1543,7 +1543,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) if (e.action.randomPhaseRange.phaseMin >= SMART_EVENT_PHASE_MAX || e.action.randomPhaseRange.phaseMax >= SMART_EVENT_PHASE_MAX) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} attempts to set invalid phase, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} attempts to set invalid phase, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } @@ -1556,7 +1556,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) return false; if (e.action.summonCreature.type < TEMPSUMMON_TIMED_OR_DEAD_DESPAWN || e.action.summonCreature.type > TEMPSUMMON_MANUAL_DESPAWN) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses incorrect TempSummonType {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.summonCreature.type); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses incorrect TempSummonType {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.summonCreature.type); return false; } @@ -1574,7 +1574,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) case SMART_ACTION_SET_SHEATH: if (e.action.setSheath.sheath && e.action.setSheath.sheath >= MAX_SHEATH_STATE) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses incorrect Sheath state {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.setSheath.sheath); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses incorrect Sheath state {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.setSheath.sheath); return false; } break; @@ -1582,7 +1582,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if (e.action.react.state > REACT_AGGRESSIVE) { - LOG_ERROR("sql.sql", "SmartAIMgr: Creature {} Event {} Action {} uses invalid React State {}, skipped.", e.entryOrGuid, e.event_id, e.GetActionType(), e.action.react.state); + LOG_ERROR("db.query", "SmartAIMgr: Creature {} Event {} Action {} uses invalid React State {}, skipped.", e.entryOrGuid, e.event_id, e.GetActionType(), e.action.react.state); return false; } break; @@ -1602,14 +1602,14 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) case SMART_ACTION_TELEPORT: if (!sMapStore.LookupEntry(e.action.teleport.mapID)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Map entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.teleport.mapID); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Map entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.teleport.mapID); return false; } break; case SMART_ACTION_INSTALL_AI_TEMPLATE: if (e.action.installTtemplate.id >= SMARTAI_TEMPLATE_END) { - LOG_ERROR("sql.sql", "SmartAIMgr: Creature {} Event {} Action {} uses non-existent AI template id {}, skipped.", e.entryOrGuid, e.event_id, e.GetActionType(), e.action.installTtemplate.id); + LOG_ERROR("db.query", "SmartAIMgr: Creature {} Event {} Action {} uses non-existent AI template id {}, skipped.", e.entryOrGuid, e.event_id, e.GetActionType(), e.action.installTtemplate.id); return false; } break; @@ -1622,7 +1622,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if (!sSmartWaypointMgr->GetPath(e.action.wpStart.pathID)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Creature {} Event {} Action {} uses non-existent WaypointPath id {}, skipped.", e.entryOrGuid, e.event_id, e.GetActionType(), e.action.wpStart.pathID); + LOG_ERROR("db.query", "SmartAIMgr: Creature {} Event {} Action {} uses non-existent WaypointPath id {}, skipped.", e.entryOrGuid, e.event_id, e.GetActionType(), e.action.wpStart.pathID); return false; } if (e.action.wpStart.quest && !IsQuestValid(e, e.action.wpStart.quest)) @@ -1634,7 +1634,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) if (e.action.wpStart.reactState > (REACT_AGGRESSIVE + TEMPORARY_EXTRA_VALUE_FOR_DB_CLEANUP)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Creature {} Event {} Action {} uses invalid React State {}, skipped.", e.entryOrGuid, e.event_id, e.GetActionType(), e.action.wpStart.reactState); + LOG_ERROR("db.query", "SmartAIMgr: Creature {} Event {} Action {} uses invalid React State {}, skipped.", e.entryOrGuid, e.event_id, e.GetActionType(), e.action.wpStart.reactState); return false; } @@ -1733,7 +1733,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if (e.GetScriptType() == SMART_SCRIPT_TYPE_GAMEOBJECT) { - LOG_ERROR("sql.sql", "SmartScript: action_type {} is not allowed with source_type {}. Entry {}, skipped.", e.GetActionType(), e.GetScriptType(), e.entryOrGuid); + LOG_ERROR("db.query", "SmartScript: action_type {} is not allowed with source_type {}. Entry {}, skipped.", e.GetActionType(), e.GetScriptType(), e.entryOrGuid); return false; } break; @@ -1744,13 +1744,13 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if (e.action.setInstanceData.data >= EncounterState::TO_BE_DECIDED) { - LOG_ERROR("sql.sql", "SmartScript: SMART_ACTION_SET_INST_DATA with type 1 (bossState) uses invalid encounter state {}. Source entry {}, type {}", e.action.setInstanceData.data, e.entryOrGuid, e.GetScriptType()); + LOG_ERROR("db.query", "SmartScript: SMART_ACTION_SET_INST_DATA with type 1 (bossState) uses invalid encounter state {}. Source entry {}, type {}", e.action.setInstanceData.data, e.entryOrGuid, e.GetScriptType()); return false; } } else if (e.action.setInstanceData.type > 1) { - LOG_ERROR("sql.sql", "SmartScript: SMART_ACTION_SET_INST_DATA uses unsupported data type {}. Source entry {}, type {}", e.action.setInstanceData.type, e.entryOrGuid, e.GetScriptType()); + LOG_ERROR("db.query", "SmartScript: SMART_ACTION_SET_INST_DATA uses unsupported data type {}. Source entry {}, type {}", e.action.setInstanceData.type, e.entryOrGuid, e.GetScriptType()); return false; } break; @@ -1759,7 +1759,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if (e.action.setHealthPct.percent > 100 || !e.action.setHealthPct.percent) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} is trying to set invalid HP percent {}, skipped.", + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} is trying to set invalid HP percent {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.setHealthPct.percent); return false; } @@ -1769,13 +1769,13 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if (e.action.movementSpeed.movementType >= MAX_MOVE_TYPE) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses invalid movementType {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.movementSpeed.movementType); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses invalid movementType {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), e.action.movementSpeed.movementType); return false; } if (!e.action.movementSpeed.speedInteger && !e.action.movementSpeed.speedFraction) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses speed 0, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses speed 0, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } break; @@ -1948,7 +1948,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) case SMART_ACTION_SUMMON_RADIAL: break; default: - LOG_ERROR("sql.sql", "SmartAIMgr: Not handled action_type({}), event_type({}), Entry {} SourceType {} Event {}, skipped.", e.GetActionType(), e.GetEventType(), e.entryOrGuid, e.GetScriptType(), e.event_id); + LOG_ERROR("db.query", "SmartAIMgr: Not handled action_type({}), event_type({}), Entry {} SourceType {} Event {}, skipped.", e.GetActionType(), e.GetEventType(), e.entryOrGuid, e.GetScriptType(), e.event_id); return false; } @@ -1984,7 +1984,7 @@ bool SmartAIMgr::IsTextValid(SmartScriptHolder const& e, uint32 id) CreatureData const* data = sObjectMgr->GetCreatureData(guid); if (!data) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} using non-existent Creature guid {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), guid); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} using non-existent Creature guid {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), guid); return false; } else @@ -1998,7 +1998,7 @@ bool SmartAIMgr::IsTextValid(SmartScriptHolder const& e, uint32 id) if (!entry || !sCreatureTextMgr->TextExist(entry, uint8(id))) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} using non-existent Text id {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), id); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} using non-existent Text id {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), id); return false; } diff --git a/src/server/game/AI/SmartScripts/SmartScriptMgr.h b/src/server/game/AI/SmartScripts/SmartScriptMgr.h index 6e45ee232247df..3c21cb2fa9cc4f 100644 --- a/src/server/game/AI/SmartScripts/SmartScriptMgr.h +++ b/src/server/game/AI/SmartScripts/SmartScriptMgr.h @@ -1964,7 +1964,7 @@ class SmartAIMgr else { if (entry > 0) //first search is for guid (negative), do not drop error if not found - LOG_DEBUG("sql.sql", "SmartAIMgr::GetScript: Could not load Script for Entry {} ScriptType {}.", entry, uint32(type)); + LOG_DEBUG("db.query", "SmartAIMgr::GetScript: Could not load Script for Entry {} ScriptType {}.", entry, uint32(type)); return temp; } } @@ -1982,7 +1982,7 @@ class SmartAIMgr { if (target < SMART_TARGET_NONE || target >= SMART_TARGET_END) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses invalid Target type {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), target); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses invalid Target type {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), target); return false; } return true; @@ -1992,7 +1992,7 @@ class SmartAIMgr { if (max < min) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses min/max params wrong ({}/{}), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), min, max); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses min/max params wrong ({}/{}), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), min, max); return false; } return true; @@ -2002,7 +2002,7 @@ class SmartAIMgr { if (pct < -100 || pct > 100) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} has invalid Percent set ({}), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), pct); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} has invalid Percent set ({}), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), pct); return false; } return true; @@ -2012,7 +2012,7 @@ class SmartAIMgr { if (!data) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} Parameter can not be nullptr, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} Parameter can not be nullptr, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); return false; } return true; @@ -2022,7 +2022,7 @@ class SmartAIMgr { if (!sObjectMgr->GetCreatureTemplate(entry)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Creature entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Creature entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); return false; } return true; @@ -2032,7 +2032,7 @@ class SmartAIMgr { if (!sObjectMgr->GetQuestTemplate(entry)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Quest entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Quest entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); return false; } return true; @@ -2042,7 +2042,7 @@ class SmartAIMgr { if (!sObjectMgr->GetGameObjectTemplate(entry)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent GameObject entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent GameObject entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); return false; } return true; @@ -2052,7 +2052,7 @@ class SmartAIMgr { if (!sSpellMgr->GetSpellInfo(entry)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Spell entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Spell entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); return false; } return true; @@ -2062,7 +2062,7 @@ class SmartAIMgr { if (!sItemStore.LookupEntry(entry)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Item entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Item entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); return false; } return true; @@ -2072,7 +2072,7 @@ class SmartAIMgr { if (!sEmotesTextStore.LookupEntry(entry)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Text Emote entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Text Emote entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); return false; } return true; @@ -2082,7 +2082,7 @@ class SmartAIMgr { if (!sEmotesStore.LookupEntry(entry)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Emote entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Emote entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); return false; } return true; @@ -2092,7 +2092,7 @@ class SmartAIMgr { if (!sObjectMgr->GetAreaTrigger(entry)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent AreaTrigger entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent AreaTrigger entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); return false; } return true; @@ -2102,7 +2102,7 @@ class SmartAIMgr { if (!sSoundEntriesStore.LookupEntry(entry)) { - LOG_ERROR("sql.sql", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Sound entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + LOG_ERROR("db.query", "SmartAIMgr: Entry {} SourceType {} Event {} Action {} uses non-existent Sound entry {}, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); return false; } return true; diff --git a/src/server/game/Accounts/AccountMgr.cpp b/src/server/game/Accounts/AccountMgr.cpp index 39847b6aeb71fe..a804e537d61259 100644 --- a/src/server/game/Accounts/AccountMgr.cpp +++ b/src/server/game/Accounts/AccountMgr.cpp @@ -41,7 +41,7 @@ namespace AccountMgr if (GetId(username)) return AOR_NAME_ALREADY_EXIST; // username does already exist - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_ACCOUNT); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_ACCOUNT); stmt->SetData(0, username); auto [salt, verifier] = Acore::Crypto::SRP6::MakeRegistrationData(username, password); @@ -61,7 +61,7 @@ namespace AccountMgr AccountOpResult DeleteAccount(uint32 accountId) { // Check if accounts exists - LoginDatabasePreparedStatement* loginStmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_BY_ID); + LoginDatabasePreparedStatement loginStmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_BY_ID); loginStmt->SetData(0, accountId); PreparedQueryResult result = LoginDatabase.Query(loginStmt); @@ -69,7 +69,7 @@ namespace AccountMgr return AOR_NAME_NOT_EXIST; // Obtain accounts characters - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARS_BY_ACCOUNT_ID); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARS_BY_ACCOUNT_ID); stmt->SetData(0, accountId); result = CharacterDatabase.Query(stmt); @@ -135,7 +135,7 @@ namespace AccountMgr AccountOpResult ChangeUsername(uint32 accountId, std::string newUsername, std::string newPassword) { // Check if accounts exists - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_BY_ID); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_BY_ID); stmt->SetData(0, accountId); PreparedQueryResult result = LoginDatabase.Query(stmt); @@ -187,7 +187,7 @@ namespace AccountMgr auto [salt, verifier] = Acore::Crypto::SRP6::MakeRegistrationData(username, newPassword); - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_LOGON); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_LOGON); stmt->SetData(0, salt); stmt->SetData(1, verifier); stmt->SetData(2, accountId); @@ -199,7 +199,7 @@ namespace AccountMgr uint32 GetId(std::string const& username) { - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_GET_ACCOUNT_ID_BY_USERNAME); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_GET_ACCOUNT_ID_BY_USERNAME); stmt->SetData(0, username); PreparedQueryResult result = LoginDatabase.Query(stmt); @@ -208,7 +208,7 @@ namespace AccountMgr uint32 GetSecurity(uint32 accountId) { - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_GET_ACCOUNT_ACCESS_GMLEVEL); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_GET_ACCOUNT_ACCESS_GMLEVEL); stmt->SetData(0, accountId); PreparedQueryResult result = LoginDatabase.Query(stmt); @@ -217,7 +217,7 @@ namespace AccountMgr uint32 GetSecurity(uint32 accountId, int32 realmId) { - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_GET_GMLEVEL_BY_REALMID); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_GET_GMLEVEL_BY_REALMID); stmt->SetData(0, accountId); stmt->SetData(1, realmId); PreparedQueryResult result = LoginDatabase.Query(stmt); @@ -227,7 +227,7 @@ namespace AccountMgr bool GetName(uint32 accountId, std::string& name) { - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_GET_USERNAME_BY_ID); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_GET_USERNAME_BY_ID); stmt->SetData(0, accountId); PreparedQueryResult result = LoginDatabase.Query(stmt); @@ -250,7 +250,7 @@ namespace AccountMgr Utf8ToUpperOnlyLatin(username); Utf8ToUpperOnlyLatin(password); - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_CHECK_PASSWORD); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_CHECK_PASSWORD); stmt->SetData(0, accountId); if (PreparedQueryResult result = LoginDatabase.Query(stmt)) { @@ -266,7 +266,7 @@ namespace AccountMgr uint32 GetCharactersCount(uint32 accountId) { // check character count - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_SUM_CHARS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_SUM_CHARS); stmt->SetData(0, accountId); PreparedQueryResult result = CharacterDatabase.Query(stmt); diff --git a/src/server/game/Achievements/AchievementMgr.cpp b/src/server/game/Achievements/AchievementMgr.cpp index 111f6a0919f0de..665b2e01e45819 100644 --- a/src/server/game/Achievements/AchievementMgr.cpp +++ b/src/server/game/Achievements/AchievementMgr.cpp @@ -49,7 +49,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) { if (dataType >= MAX_ACHIEVEMENT_CRITERIA_DATA_TYPE) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` for criteria (Entry: {}) has wrong data type ({}), ignored.", criteria->ID, dataType); + LOG_ERROR("db.query", "Table `achievement_criteria_data` for criteria (Entry: {}) has wrong data type ({}), ignored.", criteria->ID, dataType); return false; } @@ -86,7 +86,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) default: if (dataType != ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` has data for non-supported criteria type (Entry: {} Type: {}), ignored.", criteria->ID, criteria->requiredType); + LOG_ERROR("db.query", "Table `achievement_criteria_data` has data for non-supported criteria type (Entry: {} Type: {}), ignored.", criteria->ID, criteria->requiredType); return false; } break; @@ -101,7 +101,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_CREATURE: if (!creature.id || !sObjectMgr->GetCreatureTemplate(creature.id)) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_CREATURE ({}) has non-existing creature id in value1 ({}), ignored.", + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_CREATURE ({}) has non-existing creature id in value1 ({}), ignored.", criteria->ID, criteria->requiredType, dataType, creature.id); return false; } @@ -109,13 +109,13 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE: if (classRace.class_id && ((1 << (classRace.class_id - 1)) & CLASSMASK_ALL_PLAYABLE) == 0) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE ({}) has non-existing class in value1 ({}), ignored.", + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE ({}) has non-existing class in value1 ({}), ignored.", criteria->ID, criteria->requiredType, dataType, classRace.class_id); return false; } if (classRace.race_id && ((1 << (classRace.race_id - 1)) & RACEMASK_ALL_PLAYABLE) == 0) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE ({}) has non-existing race in value2 ({}), ignored.", + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE ({}) has non-existing race in value2 ({}), ignored.", criteria->ID, criteria->requiredType, dataType, classRace.race_id); return false; } @@ -123,7 +123,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_LESS_HEALTH: if (health.percent < 1 || health.percent > 100) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_PLAYER_LESS_HEALTH ({}) has wrong percent value in value1 ({}), ignored.", + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_PLAYER_LESS_HEALTH ({}) has wrong percent value in value1 ({}), ignored.", criteria->ID, criteria->requiredType, dataType, health.percent); return false; } @@ -131,7 +131,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_DEAD: if (player_dead.own_team_flag > 1) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_DEAD ({}) has wrong boolean value1 ({}).", + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_DEAD ({}) has wrong boolean value1 ({}).", criteria->ID, criteria->requiredType, dataType, player_dead.own_team_flag); return false; } @@ -142,19 +142,19 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) SpellInfo const* spellEntry = sSpellMgr->GetSpellInfo(aura.spell_id); if (!spellEntry) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type {} ({}) has wrong spell id in value1 ({}), ignored.", + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type {} ({}) has wrong spell id in value1 ({}), ignored.", criteria->ID, criteria->requiredType, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA ? "ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA" : "ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.spell_id); return false; } if (aura.effect_idx >= 3) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type {} ({}) has wrong spell effect index in value2 ({}), ignored.", + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type {} ({}) has wrong spell effect index in value2 ({}), ignored.", criteria->ID, criteria->requiredType, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA ? "ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA" : "ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.effect_idx); return false; } if (!spellEntry->Effects[aura.effect_idx].ApplyAuraName) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type {} ({}) has non-aura spell effect (ID: {} Effect: {}), ignores.", + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type {} ({}) has non-aura spell effect (ID: {} Effect: {}), ignores.", criteria->ID, criteria->requiredType, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA ? "ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA" : "ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.spell_id, aura.effect_idx); return false; } @@ -163,7 +163,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AREA: if (!sAreaTableStore.LookupEntry(area.id)) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AREA ({}) has wrong area id in value1 ({}), ignored.", + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AREA ({}) has wrong area id in value1 ({}), ignored.", criteria->ID, criteria->requiredType, dataType, area.id); return false; } @@ -171,7 +171,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_VALUE: if (value.compType >= COMP_TYPE_MAX) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_VALUE ({}) has wrong ComparisionType in value2 ({}), ignored.", + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_VALUE ({}) has wrong ComparisionType in value2 ({}), ignored.", value.compType, criteria->requiredType, dataType, value.value); return false; } @@ -179,7 +179,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL: if (level.minlevel > STRONG_MAX_LEVEL) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL ({}) has wrong minlevel in value1 ({}), ignored.", + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL ({}) has wrong minlevel in value1 ({}), ignored.", criteria->ID, criteria->requiredType, dataType, level.minlevel); return false; } @@ -187,7 +187,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER: if (gender.gender > GENDER_NONE) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER ({}) has wrong gender in value1 ({}), ignored.", + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER ({}) has wrong gender in value1 ({}), ignored.", criteria->ID, criteria->requiredType, dataType, gender.gender); return false; } @@ -195,7 +195,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT: if (!ScriptId) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT ({}) does not have ScriptName set, ignored.", + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT ({}) does not have ScriptName set, ignored.", criteria->ID, criteria->requiredType, dataType); return false; } @@ -203,7 +203,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_DIFFICULTY: if (difficulty.difficulty >= MAX_DIFFICULTY) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_DIFFICULTY ({}) has wrong difficulty in value1 ({}), ignored.", + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_DIFFICULTY ({}) has wrong difficulty in value1 ({}), ignored.", criteria->ID, criteria->requiredType, dataType, difficulty.difficulty); return false; } @@ -211,7 +211,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT: if (map_players.maxcount <= 0) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT ({}) has wrong max players count in value1 ({}), ignored.", + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT ({}) has wrong max players count in value1 ({}), ignored.", criteria->ID, criteria->requiredType, dataType, map_players.maxcount); return false; } @@ -219,7 +219,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM: if (team.team != ALLIANCE && team.team != HORDE) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM ({}) has unknown team in value1 ({}), ignored.", + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM ({}) has unknown team in value1 ({}), ignored.", criteria->ID, criteria->requiredType, dataType, team.team); return false; } @@ -227,7 +227,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK: if (drunk.state >= MAX_DRUNKEN) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK ({}) has unknown drunken state in value1 ({}), ignored.", + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK ({}) has unknown drunken state in value1 ({}), ignored.", criteria->ID, criteria->requiredType, dataType, drunk.state); return false; } @@ -235,7 +235,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY: if (!sHolidaysStore.LookupEntry(holiday.id)) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY ({}) has unknown holiday in value1 ({}), ignored.", + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY ({}) has unknown holiday in value1 ({}), ignored.", criteria->ID, criteria->requiredType, dataType, holiday.id); return false; } @@ -247,7 +247,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_ITEM_QUALITY: if (equipped_item.item_quality >= MAX_ITEM_QUALITY) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_requirement` (Entry: {} Type: {}) for requirement ACHIEVEMENT_CRITERIA_REQUIRE_S_EQUIPED_ITEM ({}) has unknown quality state in value1 ({}), ignored.", + LOG_ERROR("db.query", "Table `achievement_criteria_requirement` (Entry: {} Type: {}) for requirement ACHIEVEMENT_CRITERIA_REQUIRE_S_EQUIPED_ITEM ({}) has unknown quality state in value1 ({}), ignored.", criteria->ID, criteria->requiredType, dataType, equipped_item.item_quality); return false; } @@ -255,7 +255,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_ID: if (!sMapStore.LookupEntry(map_id.mapId)) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_requirement` (Entry: {} Type: {}) for requirement ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_ID ({}) has unknown map id in value1 ({}), ignored.", + LOG_ERROR("db.query", "Table `achievement_criteria_requirement` (Entry: {} Type: {}) for requirement ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_ID ({}) has unknown map id in value1 ({}), ignored.", criteria->ID, criteria->requiredType, dataType, map_id.mapId); return false; } @@ -263,19 +263,19 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE: if (!classRace.class_id && !classRace.race_id) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE ({}) must not have 0 in either value field, ignored.", + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE ({}) must not have 0 in either value field, ignored.", criteria->ID, criteria->requiredType, dataType); return false; } if (classRace.class_id && ((1 << (classRace.class_id - 1)) & CLASSMASK_ALL_PLAYABLE) == 0) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE ({}) has non-existing class in value1 ({}), ignored.", + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE ({}) has non-existing class in value1 ({}), ignored.", criteria->ID, criteria->requiredType, dataType, classRace.class_id); return false; } if (classRace.race_id && ((1 << (classRace.race_id - 1)) & RACEMASK_ALL_PLAYABLE) == 0) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE ({}) has non-existing race in value2 ({}), ignored.", + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE ({}) has non-existing race in value2 ({}), ignored.", criteria->ID, criteria->requiredType, dataType, classRace.race_id); return false; } @@ -284,14 +284,14 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) { if (!sCharTitlesStore.LookupEntry(known_title.title_id)) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_requirement` (Entry: {} Type: {}) for requirement ACHIEVEMENT_CRITERIA_DATA_TYPE_S_KNOWN_TITLE ({}) have unknown title_id in value1 ({}), ignore.", + LOG_ERROR("db.query", "Table `achievement_criteria_requirement` (Entry: {} Type: {}) for requirement ACHIEVEMENT_CRITERIA_DATA_TYPE_S_KNOWN_TITLE ({}) have unknown title_id in value1 ({}), ignore.", criteria->ID, criteria->requiredType, dataType, known_title.title_id); return false; } return true; } default: - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: {} Type: {}) has data for non-supported data type ({}), ignored.", criteria->ID, criteria->requiredType, dataType); + LOG_ERROR("db.query", "Table `achievement_criteria_data` (Entry: {} Type: {}) has data for non-supported data type ({}), ignored.", criteria->ID, criteria->requiredType, dataType); return false; } } @@ -397,14 +397,14 @@ bool AchievementCriteriaData::Meets(uint32 criteria_id, Player const* source, Un Map* map = source->GetMap(); if (!map->IsDungeon()) { - LOG_ERROR("sql.sql", "Achievement system call ACHIEVEMENT_CRITERIA_DATA_TYPE_INSTANCE_SCRIPT ({}) for achievement criteria {} for non-dungeon/non-raid map {}", + LOG_ERROR("db.query", "Achievement system call ACHIEVEMENT_CRITERIA_DATA_TYPE_INSTANCE_SCRIPT ({}) for achievement criteria {} for non-dungeon/non-raid map {}", ACHIEVEMENT_CRITERIA_DATA_TYPE_INSTANCE_SCRIPT, criteria_id, map->GetId()); return false; } InstanceScript* instance = map->ToInstanceMap()->GetInstanceScript(); if (!instance) { - LOG_ERROR("sql.sql", "Achievement system call ACHIEVEMENT_CRITERIA_DATA_TYPE_INSTANCE_SCRIPT ({}) for achievement criteria {} for map {} but map does not have a instance script", + LOG_ERROR("db.query", "Achievement system call ACHIEVEMENT_CRITERIA_DATA_TYPE_INSTANCE_SCRIPT ({}) for achievement criteria {} for map {} but map does not have a instance script", ACHIEVEMENT_CRITERIA_DATA_TYPE_INSTANCE_SCRIPT, criteria_id, map->GetId()); return false; } @@ -541,7 +541,7 @@ void AchievementMgr::DeleteFromDB(ObjectGuid::LowType lowguid) { CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENT); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENT); stmt->SetData(0, lowguid); trans->Append(stmt); @@ -561,7 +561,7 @@ void AchievementMgr::SaveToDB(CharacterDatabaseTransaction trans) if (!iter->second.changed) continue; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENT_BY_ACHIEVEMENT); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENT_BY_ACHIEVEMENT); stmt->SetData(0, iter->first); stmt->SetData(1, GetPlayer()->GetGUID().GetCounter()); trans->Append(stmt); @@ -585,7 +585,7 @@ void AchievementMgr::SaveToDB(CharacterDatabaseTransaction trans) if (!iter->second.changed) continue; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENT_PROGRESS_BY_CRITERIA); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENT_PROGRESS_BY_CRITERIA); stmt->SetData(0, GetPlayer()->GetGUID().GetCounter()); stmt->SetData(1, iter->first); trans->Append(stmt); @@ -650,7 +650,7 @@ void AchievementMgr::LoadFromDB(PreparedQueryResult achievementResult, PreparedQ // we will remove not existed criteria for all characters LOG_ERROR("achievement", "Non-existing achievement criteria {} data removed from table `character_achievement_progress`.", id); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_ACHIEV_PROGRESS_CRITERIA); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_ACHIEV_PROGRESS_CRITERIA); stmt->SetData(0, uint16(id)); @@ -2671,7 +2671,7 @@ void AchievementGlobalMgr::LoadAchievementCriteriaData() if (!criteria) { - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` has data for non-existing criteria (Entry: {}), ignore.", criteria_id); + LOG_ERROR("db.query", "Table `achievement_criteria_data` has data for non-existing criteria (Entry: {}), ignore.", criteria_id); continue; } @@ -2681,7 +2681,7 @@ void AchievementGlobalMgr::LoadAchievementCriteriaData() if (scriptName.length()) // not empty { if (dataType != ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT) - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` has ScriptName set for non-scripted data type (Entry: {}, type {}), useless data.", criteria_id, dataType); + LOG_ERROR("db.query", "Table `achievement_criteria_data` has ScriptName set for non-scripted data type (Entry: {}, type {}), useless data.", criteria_id, dataType); else scriptId = sObjectMgr->GetScriptId(scriptName); } @@ -2773,7 +2773,7 @@ void AchievementGlobalMgr::LoadAchievementCriteriaData() } if (!GetCriteriaDataSet(criteria) && !DisableMgr::IsDisabledFor(DISABLE_TYPE_ACHIEVEMENT_CRITERIA, entryId, nullptr)) - LOG_ERROR("sql.sql", "Table `achievement_criteria_data` does not have expected data for criteria (Entry: {} Type: {}) for achievement {}.", criteria->ID, criteria->requiredType, criteria->referredAchievement); + LOG_ERROR("db.query", "Table `achievement_criteria_data` does not have expected data for criteria (Entry: {} Type: {}) for achievement {}.", criteria->ID, criteria->requiredType, criteria->referredAchievement); } LOG_INFO("server.loading", ">> Loaded {} additional achievement criteria data in {} ms", count, GetMSTimeDiffToNow(oldMSTime)); @@ -2812,7 +2812,7 @@ void AchievementGlobalMgr::LoadCompletedAchievements() // Remove non existent achievements from all characters LOG_ERROR("achievement", "Non-existing achievement {} data removed from table `character_achievement`.", achievementId); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_ACHIEVMENT); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_ACHIEVMENT); stmt->SetData(0, uint16(achievementId)); CharacterDatabase.Execute(stmt); @@ -2852,7 +2852,7 @@ void AchievementGlobalMgr::LoadRewards() AchievementEntry const* achievement = sAchievementStore.LookupEntry(entry); if (!achievement) { - LOG_ERROR("sql.sql", "Table `achievement_reward` has wrong achievement (Entry: {}). Ignoring.", entry); + LOG_ERROR("db.query", "Table `achievement_reward` has wrong achievement (Entry: {}). Ignoring.", entry); continue; } @@ -2868,7 +2868,7 @@ void AchievementGlobalMgr::LoadRewards() // Must reward a title or send a mail else, skip it. if (!reward.titleId[0] && !reward.titleId[1] && !reward.sender) { - LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: {}) does not have any title or item reward data. Ignoring.", entry); + LOG_ERROR("db.query", "Table `achievement_reward` (Entry: {}) does not have any title or item reward data. Ignoring.", entry); continue; } @@ -2880,7 +2880,7 @@ void AchievementGlobalMgr::LoadRewards() CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(reward.titleId[0]); if (!titleEntry) { - LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: {}) has invalid title id ({}) in `title_A`. Setting it to 0.", entry, reward.titleId[0]); + LOG_ERROR("db.query", "Table `achievement_reward` (Entry: {}) has invalid title id ({}) in `title_A`. Setting it to 0.", entry, reward.titleId[0]); reward.titleId[0] = 0; } } @@ -2890,7 +2890,7 @@ void AchievementGlobalMgr::LoadRewards() CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(reward.titleId[1]); if (!titleEntry) { - LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: {}) has invalid title id ({}) in `title_H`. Setting it to 0.", entry, reward.titleId[1]); + LOG_ERROR("db.query", "Table `achievement_reward` (Entry: {}) has invalid title id ({}) in `title_H`. Setting it to 0.", entry, reward.titleId[1]); reward.titleId[1] = 0; } } @@ -2900,34 +2900,34 @@ void AchievementGlobalMgr::LoadRewards() { if (!sObjectMgr->GetCreatureTemplate(reward.sender)) { - LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: {}) has invalid creature_template entry {} as Sender. Will not send the mail reward.", entry, reward.sender); + LOG_ERROR("db.query", "Table `achievement_reward` (Entry: {}) has invalid creature_template entry {} as Sender. Will not send the mail reward.", entry, reward.sender); reward.sender = 0; } } else { if (reward.itemId) - LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: {}) has itemId reward set but does not have Sender data set. Item will not be sent.", entry); + LOG_ERROR("db.query", "Table `achievement_reward` (Entry: {}) has itemId reward set but does not have Sender data set. Item will not be sent.", entry); if (!reward.subject.empty()) - LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: {}) has mail Subject but does not have Sender data set.", entry); // Maybe add "Mail will not be sent." ? + LOG_ERROR("db.query", "Table `achievement_reward` (Entry: {}) has mail Subject but does not have Sender data set.", entry); // Maybe add "Mail will not be sent." ? if (!reward.text.empty()) - LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: {}) has mail text (Body) set but does not have Sender data set.", entry); // Maybe add "Mail will not be sent." ? + LOG_ERROR("db.query", "Table `achievement_reward` (Entry: {}) has mail text (Body) set but does not have Sender data set.", entry); // Maybe add "Mail will not be sent." ? if (reward.mailTemplate) - LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: {}) has mailTemplate set does not have Sender data set.", entry); // Maybe add "Mail will not be sent." ? + LOG_ERROR("db.query", "Table `achievement_reward` (Entry: {}) has mailTemplate set does not have Sender data set.", entry); // Maybe add "Mail will not be sent." ? } if (reward.mailTemplate) { if (!sMailTemplateStore.LookupEntry(reward.mailTemplate)) { - LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: {}) has invalid mailTemplate ({}) (check the DBC).", entry, reward.mailTemplate); + LOG_ERROR("db.query", "Table `achievement_reward` (Entry: {}) has invalid mailTemplate ({}) (check the DBC).", entry, reward.mailTemplate); reward.mailTemplate = 0; } else if (!reward.subject.empty() || !reward.text.empty()) - LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: {}) has mailTemplate ({}) and mail Subject/Body. To use the column mailTemplate, Subject and Body must be empty.", entry, reward.mailTemplate); + LOG_ERROR("db.query", "Table `achievement_reward` (Entry: {}) has mailTemplate ({}) and mail Subject/Body. To use the column mailTemplate, Subject and Body must be empty.", entry, reward.mailTemplate); } if (reward.itemId) @@ -2935,7 +2935,7 @@ void AchievementGlobalMgr::LoadRewards() if (!sObjectMgr->GetItemTemplate(reward.itemId)) { // Not sure it's an error, it's probably an outDebug instead, because we can simply send a mail with no reward, right? - LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: {}) has invalid item_template id {}. Reward mail will not contain any item.", entry, reward.itemId); + LOG_ERROR("db.query", "Table `achievement_reward` (Entry: {}) has invalid item_template id {}. Reward mail will not contain any item.", entry, reward.itemId); reward.itemId = 0; } } @@ -2971,7 +2971,7 @@ void AchievementGlobalMgr::LoadRewardLocales() uint32 ID = fields[0].Get(); if (_achievementRewards.find(ID) == _achievementRewards.end()) { - LOG_ERROR("sql.sql", "Table `achievement_reward_locale` (Entry: {}) has locale strings for non-existing achievement reward.", ID); + LOG_ERROR("db.query", "Table `achievement_reward_locale` (Entry: {}) has locale strings for non-existing achievement reward.", ID); continue; } diff --git a/src/server/game/Achievements/AchievementMgr.h b/src/server/game/Achievements/AchievementMgr.h index 39e2dd6a9a8827..2f68245abce848 100644 --- a/src/server/game/Achievements/AchievementMgr.h +++ b/src/server/game/Achievements/AchievementMgr.h @@ -21,7 +21,7 @@ #include "Common.h" #include "DBCEnums.h" #include "DBCStores.h" -#include "DatabaseEnv.h" +#include "DatabaseEnvFwd.h" #include "ObjectGuid.h" #include #include diff --git a/src/server/game/Addons/AddonMgr.cpp b/src/server/game/Addons/AddonMgr.cpp index 918b1b51721dfe..afa4b94df6c977 100644 --- a/src/server/game/Addons/AddonMgr.cpp +++ b/src/server/game/Addons/AddonMgr.cpp @@ -96,7 +96,7 @@ namespace AddonMgr { std::string name = addon.Name; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ADDON); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ADDON); stmt->SetData(0, name); stmt->SetData(1, addon.CRC); diff --git a/src/server/game/AuctionHouse/AuctionHouseMgr.cpp b/src/server/game/AuctionHouse/AuctionHouseMgr.cpp index 6c9f77eadb83e6..40ab83fa4d50f7 100644 --- a/src/server/game/AuctionHouse/AuctionHouseMgr.cpp +++ b/src/server/game/AuctionHouse/AuctionHouseMgr.cpp @@ -311,7 +311,7 @@ void AuctionHouseMgr::SendAuctionWonMail(AuctionEntry* auction, CharacterDatabas sScriptMgr->OnBeforeAuctionHouseMgrSendAuctionWonMail(this, auction, bidder, bidder_accId, sendNotification, updateAchievementCriteria, sendMail); // set owner to bidder (to prevent delete item with sender char deleting) // owner in `data` will set at mail receive and item extracting - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ITEM_OWNER); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ITEM_OWNER); stmt->SetData(0, auction->bidder.GetCounter()); stmt->SetData(1, pItem->GetGUID().GetCounter()); trans->Append(stmt); @@ -488,7 +488,7 @@ void AuctionHouseMgr::LoadAuctionItems() } // data needs to be at first place for Item::LoadFromDB - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_AUCTION_ITEMS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_AUCTION_ITEMS); PreparedQueryResult result = CharacterDatabase.Query(stmt); if (!result) @@ -533,7 +533,7 @@ void AuctionHouseMgr::LoadAuctions() { uint32 oldMSTime = getMSTime(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_AUCTIONS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_AUCTIONS); PreparedQueryResult result = CharacterDatabase.Query(stmt); if (!result) @@ -975,14 +975,14 @@ uint32 AuctionEntry::GetAuctionOutBid() const void AuctionEntry::DeleteFromDB(CharacterDatabaseTransaction trans) const { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_AUCTION); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_AUCTION); stmt->SetData(0, Id); trans->Append(stmt); } void AuctionEntry::SaveToDB(CharacterDatabaseTransaction trans) const { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_AUCTION); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_AUCTION); stmt->SetData(0, Id); stmt->SetData(1, houseId); stmt->SetData(2, item_guid.GetCounter()); diff --git a/src/server/game/AuctionHouse/AuctionHouseMgr.h b/src/server/game/AuctionHouse/AuctionHouseMgr.h index d765cf1213ac87..0d121887132f02 100644 --- a/src/server/game/AuctionHouse/AuctionHouseMgr.h +++ b/src/server/game/AuctionHouse/AuctionHouseMgr.h @@ -20,7 +20,7 @@ #include "Common.h" #include "DBCStructure.h" -#include "DatabaseEnv.h" +#include "DatabaseEnvFwd.h" #include "EventProcessor.h" #include "ObjectGuid.h" #include "WorldPacket.h" diff --git a/src/server/game/Autobroadcast/AutobroadcastMgr.cpp b/src/server/game/Autobroadcast/AutobroadcastMgr.cpp index 846f8cb5425dff..27299363fe7f05 100644 --- a/src/server/game/Autobroadcast/AutobroadcastMgr.cpp +++ b/src/server/game/Autobroadcast/AutobroadcastMgr.cpp @@ -20,6 +20,7 @@ #include "Chat.h" #include "Player.h" #include "GridNotifiers.h" +#include "DatabaseEnv.h" AutobroadcastMgr* AutobroadcastMgr::instance() { @@ -35,7 +36,7 @@ void AutobroadcastMgr::LoadAutobroadcasts() _autobroadcastsWeights.clear(); uint32 realmId = sConfigMgr->GetOption("RealmID", 0); - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_AUTOBROADCAST); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_AUTOBROADCAST); stmt->SetData(0, realmId); PreparedQueryResult result = LoginDatabase.Query(stmt); diff --git a/src/server/game/Battlefield/Battlefield.cpp b/src/server/game/Battlefield/Battlefield.cpp index 254720eb5e4c69..4e3587e9df2635 100644 --- a/src/server/game/Battlefield/Battlefield.cpp +++ b/src/server/game/Battlefield/Battlefield.cpp @@ -789,7 +789,7 @@ Creature* Battlefield::SpawnCreature(uint32 entry, float x, float y, float z, fl CreatureTemplate const* cinfo = sObjectMgr->GetCreatureTemplate(entry); if (!cinfo) { - LOG_ERROR("sql.sql", "Battlefield::SpawnCreature: entry {} does not exist.", entry); + LOG_ERROR("db.query", "Battlefield::SpawnCreature: entry {} does not exist.", entry); return nullptr; } @@ -827,7 +827,7 @@ GameObject* Battlefield::SpawnGameObject(uint32 entry, float x, float y, float z GameObject* go = sObjectMgr->IsGameObjectStaticTransport(entry) ? new StaticTransport() : new GameObject(); if (!go->Create(map->GenerateLowGuid(), entry, map, PHASEMASK_NORMAL, x, y, z, o, G3D::Quat(), 100, GO_STATE_READY)) { - LOG_ERROR("sql.sql", "Battlefield::SpawnGameObject: Gameobject template {} not found in database! Battlefield not created!", entry); + LOG_ERROR("db.query", "Battlefield::SpawnGameObject: Gameobject template {} not found in database! Battlefield not created!", entry); LOG_ERROR("bg.battlefield", "Battlefield::SpawnGameObject: Cannot create gameobject template {}! Battlefield not created!", entry); delete go; return nullptr; diff --git a/src/server/game/Battlegrounds/Arena.cpp b/src/server/game/Battlegrounds/Arena.cpp index dfb84271dc5820..2cc146195dfa88 100644 --- a/src/server/game/Battlegrounds/Arena.cpp +++ b/src/server/game/Battlegrounds/Arena.cpp @@ -24,6 +24,7 @@ #include "WorldSession.h" #include "Pet.h" #include "ScriptMgr.h" +#include "DatabaseEnv.h" //#include "WorldStatePackets.h" void ArenaScore::AppendToPacket(WorldPacket& data) @@ -182,7 +183,7 @@ void Arena::EndBattleground(TeamId winnerTeamId) uint32 currOnline = sWorld->GetActiveSessionCount(); CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt2 = CharacterDatabase.GetPreparedStatement(CHAR_INS_ARENA_LOG_FIGHT); + CharacterDatabasePreparedStatement stmt2 = CharacterDatabase.GetPreparedStatement(CHAR_INS_ARENA_LOG_FIGHT); stmt2->SetData(0, fightId); stmt2->SetData(1, GetArenaType()); stmt2->SetData(2, ((GetStartTime() <= startDelay ? 0 : GetStartTime() - startDelay) / 1000)); diff --git a/src/server/game/Battlegrounds/ArenaTeam.cpp b/src/server/game/Battlegrounds/ArenaTeam.cpp index fdcf3924a4e0cb..350b764221e6b1 100644 --- a/src/server/game/Battlegrounds/ArenaTeam.cpp +++ b/src/server/game/Battlegrounds/ArenaTeam.cpp @@ -27,6 +27,7 @@ #include "World.h" #include "WorldPacket.h" #include "WorldSession.h" +#include "DatabaseEnv.h" ArenaTeam::ArenaTeam() : TeamId(0), Type(0), TeamName(), BackgroundColor(0), EmblemStyle(0), EmblemColor(0), @@ -68,7 +69,7 @@ bool ArenaTeam::Create(ObjectGuid captainGuid, uint8 type, std::string const& te BorderColor = borderColor; // Save arena team to db - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ARENA_TEAM); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ARENA_TEAM); stmt->SetData(0, TeamId); stmt->SetData(1, TeamName); stmt->SetData(2, captainGuid.GetCounter()); @@ -134,7 +135,7 @@ bool ArenaTeam::AddMember(ObjectGuid playerGuid) // xinef: sync query // Try to get player's match maker rating from db and fall back to config setting if not found - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_MATCH_MAKER_RATING); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_MATCH_MAKER_RATING); stmt->SetData(0, playerGuid.GetCounter()); stmt->SetData(1, GetSlot()); PreparedQueryResult result = CharacterDatabase.Query(stmt); @@ -255,7 +256,7 @@ bool ArenaTeam::LoadMembersFromDB(QueryResult result) // Delete member if character information is missing if (fields[6].Get().empty()) { - LOG_ERROR("sql.sql", "ArenaTeam {} has member with empty name - probably player {} doesn't exist, deleting him from memberlist!", arenaTeamId, newMember.Guid.ToString()); + LOG_ERROR("db.query", "ArenaTeam {} has member with empty name - probably player {} doesn't exist, deleting him from memberlist!", arenaTeamId, newMember.Guid.ToString()); this->DelMember(newMember.Guid, true); continue; } @@ -285,7 +286,7 @@ bool ArenaTeam::SetName(std::string const& name) return false; TeamName = name; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ARENA_TEAM_NAME); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ARENA_TEAM_NAME); stmt->SetData(0, TeamName); stmt->SetData(1, GetId()); CharacterDatabase.Execute(stmt); @@ -303,7 +304,7 @@ void ArenaTeam::SetCaptain(ObjectGuid guid) CaptainGuid = guid; // Update database - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ARENA_TEAM_CAPTAIN); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ARENA_TEAM_CAPTAIN); stmt->SetData(0, guid.GetCounter()); stmt->SetData(1, GetId()); CharacterDatabase.Execute(stmt); @@ -373,7 +374,7 @@ void ArenaTeam::DelMember(ObjectGuid guid, bool cleanDb) // Only used for single member deletion, for arena team disband we use a single query for more efficiency if (cleanDb) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ARENA_TEAM_MEMBER); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ARENA_TEAM_MEMBER); stmt->SetData(0, GetId()); stmt->SetData(1, guid.GetCounter()); CharacterDatabase.Execute(stmt); @@ -395,7 +396,7 @@ void ArenaTeam::Disband(WorldSession* session) // Update database CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ARENA_TEAM); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ARENA_TEAM); stmt->SetData(0, TeamId); trans->Append(stmt); @@ -418,7 +419,7 @@ void ArenaTeam::Disband() // Update database CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ARENA_TEAM); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ARENA_TEAM); stmt->SetData(0, TeamId); trans->Append(stmt); @@ -937,7 +938,7 @@ void ArenaTeam::SaveToDB(bool forceMemberSave) CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ARENA_TEAM_STATS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ARENA_TEAM_STATS); stmt->SetData(0, Stats.Rating); stmt->SetData(1, Stats.WeekGames); stmt->SetData(2, Stats.WeekWins); diff --git a/src/server/game/Battlegrounds/ArenaTeamMgr.cpp b/src/server/game/Battlegrounds/ArenaTeamMgr.cpp index 629296d2e62a77..12a4c939aeb56f 100644 --- a/src/server/game/Battlegrounds/ArenaTeamMgr.cpp +++ b/src/server/game/Battlegrounds/ArenaTeamMgr.cpp @@ -211,7 +211,7 @@ void ArenaTeamMgr::DistributeArenaPoints() CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt; + CharacterDatabasePreparedStatement stmt; // Cycle that gives points to all players for (std::map::iterator playerItr = PlayerPoints.begin(); playerItr != PlayerPoints.end(); ++playerItr) diff --git a/src/server/game/Battlegrounds/Battleground.cpp b/src/server/game/Battlegrounds/Battleground.cpp index 3723778ea691be..7d04cb4ae78420 100644 --- a/src/server/game/Battlegrounds/Battleground.cpp +++ b/src/server/game/Battlegrounds/Battleground.cpp @@ -47,6 +47,7 @@ #include "World.h" #include "WorldPacket.h" #include "WorldStatePackets.h" +#include "DatabaseEnv.h" namespace Acore { @@ -803,7 +804,7 @@ void Battleground::EndBattleground(PvPTeamId winnerTeamId) PlaySoundToAll(SOUND_HORDE_WINS); // horde wins sound } - CharacterDatabasePreparedStatement* stmt = nullptr; + CharacterDatabasePreparedStatement stmt = nullptr; uint64 battlegroundId = 1; if (isBattleground() && sWorld->getBoolConfig(CONFIG_BATTLEGROUND_STORE_STATISTICS_ENABLE)) { @@ -1381,7 +1382,7 @@ bool Battleground::AddObject(uint32 type, uint32 entry, float x, float y, float if (!go->Create(map->GenerateLowGuid(), entry, GetBgMap(), PHASEMASK_NORMAL, x, y, z, o, G3D::Quat(rotation0, rotation1, rotation2, rotation3), 100, goState)) { - LOG_ERROR("sql.sql", "Battleground::AddObject: cannot create gameobject (entry: {}) for BG (map: {}, instance id: {})!", + LOG_ERROR("db.query", "Battleground::AddObject: cannot create gameobject (entry: {}) for BG (map: {}, instance id: {})!", entry, m_MapId, m_InstanceID); LOG_ERROR("bg.battleground", "Battleground::AddObject: cannot create gameobject (entry: {}) for BG (map: {}, instance id: {})!", entry, m_MapId, m_InstanceID); diff --git a/src/server/game/Battlegrounds/BattlegroundMgr.cpp b/src/server/game/Battlegrounds/BattlegroundMgr.cpp index 2fb065df7bc76f..c15e52955dfba8 100644 --- a/src/server/game/Battlegrounds/BattlegroundMgr.cpp +++ b/src/server/game/Battlegrounds/BattlegroundMgr.cpp @@ -46,6 +46,7 @@ #include "SharedDefines.h" #include "World.h" #include "WorldPacket.h" +#include "DatabaseEnv.h" #include bool BattlegroundTemplate::IsArena() const @@ -491,7 +492,7 @@ void BattlegroundMgr::LoadBattlegroundTemplates() if (bgTemplate.MaxPlayersPerTeam == 0 || bgTemplate.MinPlayersPerTeam > bgTemplate.MaxPlayersPerTeam) { - LOG_ERROR("sql.sql", "Table `battleground_template` for id {} contains bad values for MinPlayersPerTeam ({}) and MaxPlayersPerTeam({}).", + LOG_ERROR("db.query", "Table `battleground_template` for id {} contains bad values for MinPlayersPerTeam ({}) and MaxPlayersPerTeam({}).", bgTemplate.Id, bgTemplate.MinPlayersPerTeam, bgTemplate.MaxPlayersPerTeam); continue; @@ -499,7 +500,7 @@ void BattlegroundMgr::LoadBattlegroundTemplates() if (bgTemplate.MinLevel == 0 || bgTemplate.MaxLevel == 0 || bgTemplate.MinLevel > bgTemplate.MaxLevel) { - LOG_ERROR("sql.sql", "Table `battleground_template` for id {} has bad values for LevelMin ({}) and LevelMax({})", + LOG_ERROR("db.query", "Table `battleground_template` for id {} has bad values for LevelMin ({}) and LevelMax({})", bgTemplate.Id, bgTemplate.MinLevel, bgTemplate.MaxLevel); continue; } @@ -513,7 +514,7 @@ void BattlegroundMgr::LoadBattlegroundTemplates() } else { - LOG_ERROR("sql.sql", "Table `battleground_template` for id {} contains a non-existing WorldSafeLocs.dbc id {} in field `AllianceStartLoc`. BG not created.", bgTemplate.Id, startId); + LOG_ERROR("db.query", "Table `battleground_template` for id {} contains a non-existing WorldSafeLocs.dbc id {} in field `AllianceStartLoc`. BG not created.", bgTemplate.Id, startId); continue; } @@ -524,7 +525,7 @@ void BattlegroundMgr::LoadBattlegroundTemplates() } else { - LOG_ERROR("sql.sql", "Table `battleground_template` for id {} contains a non-existing WorldSafeLocs.dbc id {} in field `HordeStartLoc`. BG not created.", bgTemplate.Id, startId); + LOG_ERROR("db.query", "Table `battleground_template` for id {} contains a non-existing WorldSafeLocs.dbc id {} in field `HordeStartLoc`. BG not created.", bgTemplate.Id, startId); continue; } } @@ -813,18 +814,18 @@ void BattlegroundMgr::LoadBattleMastersEntry() if (CreatureTemplate const* cInfo = sObjectMgr->GetCreatureTemplate(entry)) { if ((cInfo->npcflag & UNIT_NPC_FLAG_BATTLEMASTER) == 0) - LOG_ERROR("sql.sql", "Creature (Entry: {}) listed in `battlemaster_entry` is not a battlemaster.", entry); + LOG_ERROR("db.query", "Creature (Entry: {}) listed in `battlemaster_entry` is not a battlemaster.", entry); } else { - LOG_ERROR("sql.sql", "Creature (Entry: {}) listed in `battlemaster_entry` does not exist.", entry); + LOG_ERROR("db.query", "Creature (Entry: {}) listed in `battlemaster_entry` does not exist.", entry); continue; } uint32 bgTypeId = fields[1].Get(); if (!sBattlemasterListStore.LookupEntry(bgTypeId)) { - LOG_ERROR("sql.sql", "Table `battlemaster_entry` contain entry {} for not existed battleground type {}, ignored.", entry, bgTypeId); + LOG_ERROR("db.query", "Table `battlemaster_entry` contain entry {} for not existed battleground type {}, ignored.", entry, bgTypeId); continue; } @@ -844,7 +845,7 @@ void BattlegroundMgr::CheckBattleMasters() { if ((itr->second.npcflag & UNIT_NPC_FLAG_BATTLEMASTER) && mBattleMastersMap.find(itr->second.Entry) == mBattleMastersMap.end()) { - LOG_ERROR("sql.sql", "CreatureTemplate (Entry: {}) has UNIT_NPC_FLAG_BATTLEMASTER but no data in `battlemaster_entry` table. Removing flag!", itr->second.Entry); + LOG_ERROR("db.query", "CreatureTemplate (Entry: {}) has UNIT_NPC_FLAG_BATTLEMASTER but no data in `battlemaster_entry` table. Removing flag!", itr->second.Entry); const_cast(&itr->second)->npcflag &= ~UNIT_NPC_FLAG_BATTLEMASTER; } } diff --git a/src/server/game/Battlegrounds/BattlegroundQueue.cpp b/src/server/game/Battlegrounds/BattlegroundQueue.cpp index dc326d78477099..eb6322d1ef1e1f 100644 --- a/src/server/game/Battlegrounds/BattlegroundQueue.cpp +++ b/src/server/game/Battlegrounds/BattlegroundQueue.cpp @@ -24,11 +24,11 @@ #include "Chat.h" #include "GameTime.h" #include "Group.h" -#include "Language.h" #include "Log.h" #include "ObjectMgr.h" #include "Player.h" #include "ScriptMgr.h" +#include "DatabaseEnv.h" #include /*********************************************************/ @@ -1314,7 +1314,7 @@ bool BGQueueRemoveEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/) { if (sWorld->getBoolConfig(CONFIG_BATTLEGROUND_TRACK_DESERTERS)) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_DESERTER_TRACK); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_DESERTER_TRACK); stmt->SetData(0, player->GetGUID().GetCounter()); stmt->SetData(1, BG_DESERTION_TYPE_NO_ENTER_BUTTON); CharacterDatabase.Execute(stmt); diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundAB.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundAB.cpp index c50ab4617c7595..3a7d603041040d 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundAB.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundAB.cpp @@ -445,14 +445,14 @@ bool BattlegroundAB::SetupBattleground() for (uint32 i = BG_AB_OBJECT_BANNER_NEUTRAL; i < BG_AB_OBJECT_MAX; ++i) if (!BgObjects[i]) { - LOG_ERROR("sql.sql", "BatteGroundAB: Failed to spawn some object Battleground not created!"); + LOG_ERROR("db.query", "BatteGroundAB: Failed to spawn some object Battleground not created!"); return false; } for (uint32 i = BG_AB_SPIRIT_ALIANCE; i <= BG_AB_SPIRIT_HORDE; ++i) if (!BgCreatures[i]) { - LOG_ERROR("sql.sql", "BatteGroundAB: Failed to spawn spirit guides Battleground not created!"); + LOG_ERROR("db.query", "BatteGroundAB: Failed to spawn spirit guides Battleground not created!"); return false; } diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundAV.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundAV.cpp index c445ce9582361d..59023a17126d0d 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundAV.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundAV.cpp @@ -1436,7 +1436,7 @@ bool BattlegroundAV::SetupBattleground() // horde gates || !AddObject(BG_AV_OBJECT_DOOR_H, BG_AV_OBJECTID_GATE_H, BG_AV_DoorPositons[1][0], BG_AV_DoorPositons[1][1], BG_AV_DoorPositons[1][2], BG_AV_DoorPositons[1][3], 0, 0, std::sin(BG_AV_DoorPositons[1][3] / 2), cos(BG_AV_DoorPositons[1][3] / 2), RESPAWN_IMMEDIATELY)) { - LOG_ERROR("sql.sql", "BatteGroundAV: Failed to spawn some object Battleground not created!1"); + LOG_ERROR("db.query", "BatteGroundAV: Failed to spawn some object Battleground not created!1"); return false; } diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundBE.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundBE.cpp index 87fba47aaed519..32973623e94056 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundBE.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundBE.cpp @@ -107,7 +107,7 @@ bool BattlegroundBE::SetupBattleground() || !AddObject(BG_BE_OBJECT_READY_MARKER_1, ARENA_READY_MARKER_ENTRY, 6189.47f, 235.54f, 5.52f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300) || !AddObject(BG_BE_OBJECT_READY_MARKER_2, ARENA_READY_MARKER_ENTRY, 6287.19f, 288.25f, 5.33f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300)) { - LOG_ERROR("sql.sql", "BatteGroundBE: Failed to spawn some object!"); + LOG_ERROR("db.query", "BatteGroundBE: Failed to spawn some object!"); return false; } diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundDS.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundDS.cpp index bd84a831e95e2d..a5f226db13a0fa 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundDS.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundDS.cpp @@ -201,7 +201,7 @@ bool BattlegroundDS::SetupBattleground() || !AddObject(BG_DS_OBJECT_READY_MARKER_1, ARENA_READY_MARKER_ENTRY, 1229.44f, 759.35f, 17.89f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300) || !AddObject(BG_DS_OBJECT_READY_MARKER_2, ARENA_READY_MARKER_ENTRY, 1352.90f, 822.77f, 17.96f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300)) { - LOG_ERROR("sql.sql", "BatteGroundDS: Failed to spawn some object!"); + LOG_ERROR("db.query", "BatteGroundDS: Failed to spawn some object!"); return false; } diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp index 2632b1192c1a0e..e738823d75c0f4 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp @@ -333,14 +333,14 @@ bool BattlegroundEY::SetupBattleground() for (uint32 i = BG_EY_OBJECT_DOOR_A; i < BG_EY_OBJECT_MAX; ++i) if (!BgObjects[i]) { - LOG_ERROR("sql.sql", "BatteGroundEY: Failed to spawn some object Battleground not created!"); + LOG_ERROR("db.query", "BatteGroundEY: Failed to spawn some object Battleground not created!"); return false; } for (uint32 i = BG_EY_SPIRIT_MAIN_ALLIANCE; i <= BG_EY_SPIRIT_MAIN_HORDE; ++i) if (!BgCreatures[i]) { - LOG_ERROR("sql.sql", "BatteGroundEY: Failed to spawn spirit guides Battleground not created!"); + LOG_ERROR("db.query", "BatteGroundEY: Failed to spawn spirit guides Battleground not created!"); return false; } diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundNA.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundNA.cpp index 817014607195e5..6baf8c0f9f8919 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundNA.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundNA.cpp @@ -84,7 +84,7 @@ bool BattlegroundNA::SetupBattleground() || !AddObject(BG_NA_OBJECT_READY_MARKER_1, ARENA_READY_MARKER_ENTRY, 4090.46f, 2875.43f, 12.16f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300) || !AddObject(BG_NA_OBJECT_READY_MARKER_2, ARENA_READY_MARKER_ENTRY, 4022.82f, 2966.61f, 12.17f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300)) { - LOG_ERROR("sql.sql", "BatteGroundNA: Failed to spawn some object!"); + LOG_ERROR("db.query", "BatteGroundNA: Failed to spawn some object!"); return false; } diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundRL.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundRL.cpp index 80d36ad75d56eb..103698ab8653f2 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundRL.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundRL.cpp @@ -111,7 +111,7 @@ bool BattlegroundRL::SetupBattleground() || !AddObject(BG_RL_OBJECT_READY_MARKER_1, ARENA_READY_MARKER_ENTRY, 1298.61f, 1598.59f, 31.62f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300) || !AddObject(BG_RL_OBJECT_READY_MARKER_2, ARENA_READY_MARKER_ENTRY, 1273.71f, 1734.05f, 31.61f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300)) { - LOG_ERROR("sql.sql", "BatteGroundRL: Failed to spawn some object!"); + LOG_ERROR("db.query", "BatteGroundRL: Failed to spawn some object!"); return false; } diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundRV.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundRV.cpp index 7cb46a26133fb6..bceadc71af8110 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundRV.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundRV.cpp @@ -250,7 +250,7 @@ bool BattlegroundRV::SetupBattleground() || !AddObject(BG_RV_OBJECT_READY_MARKER_2, ARENA_READY_MARKER_ENTRY, 757.02f, -267.30f, 2.80f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 300) ) { - LOG_ERROR("sql.sql", "BatteGroundRV: Failed to spawn some object!"); + LOG_ERROR("db.query", "BatteGroundRV: Failed to spawn some object!"); return false; } diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundWS.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundWS.cpp index 64b4619f4840b4..e4d3d38cb5fce7 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundWS.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundWS.cpp @@ -458,14 +458,14 @@ bool BattlegroundWS::SetupBattleground() for (uint32 i = BG_WS_OBJECT_DOOR_A_1; i < BG_WS_OBJECT_MAX; ++i) if (!BgObjects[i]) { - LOG_ERROR("sql.sql", "BatteGroundWS: Failed to spawn some object Battleground not created!"); + LOG_ERROR("db.query", "BatteGroundWS: Failed to spawn some object Battleground not created!"); return false; } for (uint32 i = WS_SPIRIT_MAIN_ALLIANCE; i < BG_CREATURES_MAX_WS; ++i) if (!BgCreatures[i]) { - LOG_ERROR("sql.sql", "BatteGroundWS: Failed to spawn spirit guides Battleground not created!"); + LOG_ERROR("db.query", "BatteGroundWS: Failed to spawn spirit guides Battleground not created!"); return false; } diff --git a/src/server/game/Calendar/CalendarMgr.cpp b/src/server/game/Calendar/CalendarMgr.cpp index 6f2c14b465e5ac..0064a2c902a290 100644 --- a/src/server/game/Calendar/CalendarMgr.cpp +++ b/src/server/game/Calendar/CalendarMgr.cpp @@ -22,7 +22,7 @@ #include "ObjectAccessor.h" #include "Opcodes.h" #include "Player.h" -#include "QueryResult.h" +#include "DatabaseEnv.h" #include CalendarInvite::CalendarInvite() : _inviteId(1), _eventId(0), _statusTime(GameTime::GetGameTime().count()), @@ -178,7 +178,7 @@ void CalendarMgr::RemoveEvent(CalendarEvent* calendarEvent, ObjectGuid remover) SendCalendarEventRemovedAlert(*calendarEvent); CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt; + CharacterDatabasePreparedStatement stmt; MailDraft mail(calendarEvent->BuildCalendarMailSubject(remover), calendarEvent->BuildCalendarMailBody()); CalendarInviteStore& eventInvites = _invites[calendarEvent->GetEventId()]; @@ -225,7 +225,7 @@ void CalendarMgr::RemoveInvite(uint64 inviteId, uint64 eventId, ObjectGuid /*rem return; CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CALENDAR_INVITE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CALENDAR_INVITE); stmt->SetData(0, (*itr)->GetInviteId()); trans->Append(stmt); CharacterDatabase.CommitTransaction(trans); @@ -246,7 +246,7 @@ void CalendarMgr::RemoveInvite(uint64 inviteId, uint64 eventId, ObjectGuid /*rem void CalendarMgr::UpdateEvent(CalendarEvent* calendarEvent) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_CALENDAR_EVENT); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_CALENDAR_EVENT); stmt->SetData(0, calendarEvent->GetEventId()); stmt->SetData(1, calendarEvent->GetCreatorGUID().GetCounter()); stmt->SetData(2, calendarEvent->GetTitle()); @@ -261,7 +261,7 @@ void CalendarMgr::UpdateEvent(CalendarEvent* calendarEvent) void CalendarMgr::UpdateInvite(CalendarInvite* invite, CharacterDatabaseTransaction trans) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_CALENDAR_INVITE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_CALENDAR_INVITE); stmt->SetData(0, invite->GetInviteId()); stmt->SetData(1, invite->GetEventId()); stmt->SetData(2, invite->GetInviteeGUID().GetCounter()); diff --git a/src/server/game/Calendar/CalendarMgr.h b/src/server/game/Calendar/CalendarMgr.h index e633b1a310aade..266c8b8afb1f05 100644 --- a/src/server/game/Calendar/CalendarMgr.h +++ b/src/server/game/Calendar/CalendarMgr.h @@ -19,7 +19,7 @@ #define ACORE_CALENDARMGR_H #include "Common.h" -#include "DatabaseEnv.h" +#include "DatabaseEnvFwd.h" #include "ObjectGuid.h" #include "WorldPacket.h" #include diff --git a/src/server/game/Chat/Channels/Channel.cpp b/src/server/game/Chat/Channels/Channel.cpp index 67ea787ae3c4d0..22bec20b31f8d1 100644 --- a/src/server/game/Chat/Channels/Channel.cpp +++ b/src/server/game/Chat/Channels/Channel.cpp @@ -83,7 +83,7 @@ Channel::Channel(std::string const& name, uint32 channelId, uint32 channelDBId, { _channelDBId = ++ChannelMgr::_channelIdMax; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHANNEL); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHANNEL); stmt->SetData(0, _channelDBId); stmt->SetData(1, name); stmt->SetData(2, _teamId); @@ -103,7 +103,7 @@ void Channel::UpdateChannelInDB() const { if (_IsSaved) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHANNEL); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHANNEL); stmt->SetData(0, _announce); stmt->SetData(1, _password); stmt->SetData(2, _channelDBId); @@ -115,14 +115,14 @@ void Channel::UpdateChannelInDB() const void Channel::UpdateChannelUseageInDB() const { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHANNEL_USAGE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHANNEL_USAGE); stmt->SetData(0, _channelDBId); CharacterDatabase.Execute(stmt); } void Channel::AddChannelBanToDB(ObjectGuid guid, uint32 time) const { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHANNEL_BAN); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHANNEL_BAN); stmt->SetData(0, _channelDBId); stmt->SetData(1, guid.GetCounter()); stmt->SetData(2, time); @@ -131,7 +131,7 @@ void Channel::AddChannelBanToDB(ObjectGuid guid, uint32 time) const void Channel::RemoveChannelBanFromDB(ObjectGuid guid) const { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHANNEL_BAN); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHANNEL_BAN); stmt->SetData(0, _channelDBId); stmt->SetData(1, guid.GetCounter()); CharacterDatabase.Execute(stmt); @@ -143,7 +143,7 @@ void Channel::CleanOldChannelsInDB() { CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_OLD_CHANNELS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_OLD_CHANNELS); stmt->SetData(0, sWorld->getIntConfig(CONFIG_PRESERVE_CUSTOM_CHANNEL_DURATION) * DAY); trans->Append(stmt); diff --git a/src/server/game/Chat/Channels/ChannelMgr.cpp b/src/server/game/Chat/Channels/ChannelMgr.cpp index 0e74a451af7722..9c3f878cddd741 100644 --- a/src/server/game/Chat/Channels/ChannelMgr.cpp +++ b/src/server/game/Chat/Channels/ChannelMgr.cpp @@ -21,6 +21,7 @@ #include "World.h" #include "Tokenize.h" #include "StringConvert.h" +#include "DatabaseEnv.h" ChannelMgr::~ChannelMgr() { @@ -108,7 +109,7 @@ void ChannelMgr::LoadChannels() for (auto& pair : toDelete) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHANNEL); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHANNEL); stmt->SetData(0, pair.first); stmt->SetData(1, pair.second); CharacterDatabase.Execute(stmt); diff --git a/src/server/game/Chat/ChatCommands/ChatCommand.cpp b/src/server/game/Chat/ChatCommands/ChatCommand.cpp index ae62f421485c0f..556daa79a99ef8 100644 --- a/src/server/game/Chat/ChatCommands/ChatCommand.cpp +++ b/src/server/game/Chat/ChatCommands/ChatCommand.cpp @@ -105,7 +105,7 @@ static ChatSubCommandMap COMMAND_MAP; } else { - LOG_ERROR("sql.sql", "Table `command` contains data for non-existant command '{}'. Skipped.", name); + LOG_ERROR("db.query", "Table `command` contains data for non-existant command '{}'. Skipped.", name); cmd = nullptr; break; } @@ -116,19 +116,19 @@ static ChatSubCommandMap COMMAND_MAP; if (cmd->_invoker && (cmd->_permission.RequiredLevel != secLevel)) { - LOG_WARN("sql.sql", "Table `command` has permission {} for '{}' which does not match the core ({}). Overriding.", + LOG_WARN("db.query", "Table `command` has permission {} for '{}' which does not match the core ({}). Overriding.", secLevel, name, cmd->_permission.RequiredLevel); cmd->_permission.RequiredLevel = secLevel; } if (std::holds_alternative(cmd->_help)) - LOG_ERROR("sql.sql", "Table `command` contains duplicate data for command '{}'. Skipped.", name); + LOG_ERROR("db.query", "Table `command` contains duplicate data for command '{}'. Skipped.", name); if (std::holds_alternative(cmd->_help)) cmd->_help.emplace(help); else - LOG_ERROR("sql.sql", "Table `command` contains legacy help text for command '{}', which uses `acore_string`. Skipped.", name); + LOG_ERROR("db.query", "Table `command` contains legacy help text for command '{}', which uses `acore_string`. Skipped.", name); } while (result->NextRow()); } @@ -139,7 +139,7 @@ static ChatSubCommandMap COMMAND_MAP; void Acore::Impl::ChatCommands::ChatCommandNode::ResolveNames(std::string name) { if (_invoker && std::holds_alternative(_help)) - LOG_WARN("sql.sql", "Table `command` is missing help text for command '{}'.", name); + LOG_WARN("db.query", "Table `command` is missing help text for command '{}'.", name); _name = name; diff --git a/src/server/game/Conditions/ConditionMgr.cpp b/src/server/game/Conditions/ConditionMgr.cpp index d43a96f5b73d80..76c87f21bd8fc0 100644 --- a/src/server/game/Conditions/ConditionMgr.cpp +++ b/src/server/game/Conditions/ConditionMgr.cpp @@ -28,6 +28,7 @@ #include "Spell.h" #include "SpellAuras.h" #include "SpellMgr.h" +#include "DatabaseEnv.h" // Checks if object meets the condition // Can have CONDITION_SOURCE_TYPE_NONE && !mReferenceId if called from a special event (ie: eventAI) @@ -1089,7 +1090,7 @@ void ConditionMgr::LoadConditions(bool isReload) { if (iConditionTypeOrReference == iSourceTypeOrReferenceId) // self referencing, skip { - LOG_ERROR("sql.sql", "Condition reference {} is referencing self, skipped", iSourceTypeOrReferenceId); + LOG_ERROR("db.query", "Condition reference {} is referencing self, skipped", iSourceTypeOrReferenceId); delete cond; continue; } @@ -1100,19 +1101,19 @@ void ConditionMgr::LoadConditions(bool isReload) rowType = "reference"; // check for useless data if (cond->ConditionTarget) - LOG_ERROR("sql.sql", "Condition {} {} has useless data in ConditionTarget ({})!", rowType, iSourceTypeOrReferenceId, cond->ConditionTarget); + LOG_ERROR("db.query", "Condition {} {} has useless data in ConditionTarget ({})!", rowType, iSourceTypeOrReferenceId, cond->ConditionTarget); if (cond->ConditionValue1) - LOG_ERROR("sql.sql", "Condition {} {} has useless data in value1 ({})!", rowType, iSourceTypeOrReferenceId, cond->ConditionValue1); + LOG_ERROR("db.query", "Condition {} {} has useless data in value1 ({})!", rowType, iSourceTypeOrReferenceId, cond->ConditionValue1); if (cond->ConditionValue2) - LOG_ERROR("sql.sql", "Condition {} {} has useless data in value2 ({})!", rowType, iSourceTypeOrReferenceId, cond->ConditionValue2); + LOG_ERROR("db.query", "Condition {} {} has useless data in value2 ({})!", rowType, iSourceTypeOrReferenceId, cond->ConditionValue2); if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "Condition {} {} has useless data in value3 ({})!", rowType, iSourceTypeOrReferenceId, cond->ConditionValue3); + LOG_ERROR("db.query", "Condition {} {} has useless data in value3 ({})!", rowType, iSourceTypeOrReferenceId, cond->ConditionValue3); if (cond->NegativeCondition) - LOG_ERROR("sql.sql", "Condition {} {} has useless data in NegativeCondition ({})!", rowType, iSourceTypeOrReferenceId, cond->NegativeCondition); + LOG_ERROR("db.query", "Condition {} {} has useless data in NegativeCondition ({})!", rowType, iSourceTypeOrReferenceId, cond->NegativeCondition); if (cond->SourceGroup && iSourceTypeOrReferenceId < 0) - LOG_ERROR("sql.sql", "Condition {} {} has useless data in SourceGroup ({})!", rowType, iSourceTypeOrReferenceId, cond->SourceGroup); + LOG_ERROR("db.query", "Condition {} {} has useless data in SourceGroup ({})!", rowType, iSourceTypeOrReferenceId, cond->SourceGroup); if (cond->SourceEntry && iSourceTypeOrReferenceId < 0) - LOG_ERROR("sql.sql", "Condition {} {} has useless data in SourceEntry ({})!", rowType, iSourceTypeOrReferenceId, cond->SourceEntry); + LOG_ERROR("db.query", "Condition {} {} has useless data in SourceEntry ({})!", rowType, iSourceTypeOrReferenceId, cond->SourceEntry); } else if (!isConditionTypeValid(cond)) // doesn't have reference, validate ConditionType { @@ -1143,13 +1144,13 @@ void ConditionMgr::LoadConditions(bool isReload) // Grouping is only allowed for some types (loot templates, gossip menus, gossip items) if (cond->SourceGroup && !CanHaveSourceGroupSet(cond->SourceType)) { - LOG_ERROR("sql.sql", "Condition type {} has not allowed value of SourceGroup = {}!", uint32(cond->SourceType), cond->SourceGroup); + LOG_ERROR("db.query", "Condition type {} has not allowed value of SourceGroup = {}!", uint32(cond->SourceType), cond->SourceGroup); delete cond; continue; } if (cond->SourceId && !CanHaveSourceIdSet(cond->SourceType)) { - LOG_ERROR("sql.sql", "Condition type {} has not allowed value of SourceId = {}!", uint32(cond->SourceType), cond->SourceId); + LOG_ERROR("db.query", "Condition type {} has not allowed value of SourceId = {}!", uint32(cond->SourceType), cond->SourceId); delete cond; continue; } @@ -1258,7 +1259,7 @@ void ConditionMgr::LoadConditions(bool isReload) if (!valid) { - LOG_ERROR("sql.sql", "Not handled grouped condition, SourceGroup {}", cond->SourceGroup); + LOG_ERROR("db.query", "Not handled grouped condition, SourceGroup {}", cond->SourceGroup); delete cond; } else @@ -1297,14 +1298,14 @@ bool ConditionMgr::addToLootTemplate(Condition* cond, LootTemplate* loot) { if (!loot) { - LOG_ERROR("sql.sql", "ConditionMgr: LootTemplate {} not found", cond->SourceGroup); + LOG_ERROR("db.query", "ConditionMgr: LootTemplate {} not found", cond->SourceGroup); return false; } if (loot->addConditionItem(cond)) return true; - LOG_ERROR("sql.sql", "ConditionMgr: Item {} not found in LootTemplate {}", cond->SourceEntry, cond->SourceGroup); + LOG_ERROR("db.query", "ConditionMgr: Item {} not found in LootTemplate {}", cond->SourceEntry, cond->SourceGroup); return false; } @@ -1324,7 +1325,7 @@ bool ConditionMgr::addToGossipMenus(Condition* cond) } } - LOG_ERROR("sql.sql", "addToGossipMenus: GossipMenu {} not found", cond->SourceGroup); + LOG_ERROR("db.query", "addToGossipMenus: GossipMenu {} not found", cond->SourceGroup); return false; } @@ -1343,7 +1344,7 @@ bool ConditionMgr::addToGossipMenuItems(Condition* cond) } } - LOG_ERROR("sql.sql", "addToGossipMenuItems: GossipMenuId {} Item {} not found", cond->SourceGroup, cond->SourceEntry); + LOG_ERROR("db.query", "addToGossipMenuItems: GossipMenuId {} Item {} not found", cond->SourceGroup, cond->SourceEntry); return false; } @@ -1400,7 +1401,7 @@ bool ConditionMgr::addToSpellImplicitTargetConditions(Condition* cond) // we have overlapping masks in db if (conditionEffMask != *itr) { - LOG_ERROR("sql.sql", + LOG_ERROR("db.query", "SourceEntry {} in `condition` table, has incorrect SourceGroup {} (spell effectMask) set - " "effect masks are overlapping (all SourceGroup values having given bit set must be equal) - ignoring.", cond->SourceEntry, cond->SourceGroup); @@ -1437,7 +1438,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) { if (cond->SourceType == CONDITION_SOURCE_TYPE_NONE || cond->SourceType >= CONDITION_SOURCE_TYPE_MAX) { - LOG_ERROR("sql.sql", "Invalid ConditionSourceType {} in `condition` table, ignoring.", uint32(cond->SourceType)); + LOG_ERROR("db.query", "Invalid ConditionSourceType {} in `condition` table, ignoring.", uint32(cond->SourceType)); return false; } @@ -1447,14 +1448,14 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) case CONDITION_SOURCE_TYPE_PHASE: case CONDITION_SOURCE_TYPE_GRAVEYARD: { - LOG_ERROR("sql.sql", "ConditionSourceType {} in `condition` table is not supported on 3.3.5a, ignoring.", uint32(cond->SourceType)); + LOG_ERROR("db.query", "ConditionSourceType {} in `condition` table is not supported on 3.3.5a, ignoring.", uint32(cond->SourceType)); return false; } case CONDITION_SOURCE_TYPE_CREATURE_LOOT_TEMPLATE: { if (!LootTemplates_Creature.HaveLootFor(cond->SourceGroup)) { - LOG_ERROR("sql.sql", "SourceGroup {} in `condition` table, does not exist in `creature_loot_template`, ignoring.", cond->SourceGroup); + LOG_ERROR("db.query", "SourceGroup {} in `condition` table, does not exist in `creature_loot_template`, ignoring.", cond->SourceGroup); return false; } @@ -1462,7 +1463,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); if (!pItemProto && !loot->isReference(cond->SourceEntry)) { - LOG_ERROR("sql.sql", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + LOG_ERROR("db.query", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); return false; } break; @@ -1471,7 +1472,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) { if (!LootTemplates_Disenchant.HaveLootFor(cond->SourceGroup)) { - LOG_ERROR("sql.sql", "SourceGroup {} in `condition` table, does not exist in `disenchant_loot_template`, ignoring.", cond->SourceGroup); + LOG_ERROR("db.query", "SourceGroup {} in `condition` table, does not exist in `disenchant_loot_template`, ignoring.", cond->SourceGroup); return false; } @@ -1479,7 +1480,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); if (!pItemProto && !loot->isReference(cond->SourceEntry)) { - LOG_ERROR("sql.sql", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + LOG_ERROR("db.query", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); return false; } break; @@ -1488,7 +1489,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) { if (!LootTemplates_Fishing.HaveLootFor(cond->SourceGroup)) { - LOG_ERROR("sql.sql", "SourceGroup {} in `condition` table, does not exist in `fishing_loot_template`, ignoring.", cond->SourceGroup); + LOG_ERROR("db.query", "SourceGroup {} in `condition` table, does not exist in `fishing_loot_template`, ignoring.", cond->SourceGroup); return false; } @@ -1496,7 +1497,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); if (!pItemProto && !loot->isReference(cond->SourceEntry)) { - LOG_ERROR("sql.sql", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + LOG_ERROR("db.query", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); return false; } break; @@ -1505,7 +1506,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) { if (!LootTemplates_Gameobject.HaveLootFor(cond->SourceGroup)) { - LOG_ERROR("sql.sql", "SourceGroup {} in `condition` table, does not exist in `gameobject_loot_template`, ignoring.", cond->SourceGroup); + LOG_ERROR("db.query", "SourceGroup {} in `condition` table, does not exist in `gameobject_loot_template`, ignoring.", cond->SourceGroup); return false; } @@ -1513,7 +1514,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); if (!pItemProto && !loot->isReference(cond->SourceEntry)) { - LOG_ERROR("sql.sql", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + LOG_ERROR("db.query", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); return false; } break; @@ -1522,7 +1523,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) { if (!LootTemplates_Item.HaveLootFor(cond->SourceGroup)) { - LOG_ERROR("sql.sql", "SourceGroup {} in `condition` table, does not exist in `item_loot_template`, ignoring.", cond->SourceGroup); + LOG_ERROR("db.query", "SourceGroup {} in `condition` table, does not exist in `item_loot_template`, ignoring.", cond->SourceGroup); return false; } @@ -1530,7 +1531,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); if (!pItemProto && !loot->isReference(cond->SourceEntry)) { - LOG_ERROR("sql.sql", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + LOG_ERROR("db.query", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); return false; } break; @@ -1539,7 +1540,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) { if (!LootTemplates_Mail.HaveLootFor(cond->SourceGroup)) { - LOG_ERROR("sql.sql", "SourceGroup {} in `condition` table, does not exist in `mail_loot_template`, ignoring.", cond->SourceGroup); + LOG_ERROR("db.query", "SourceGroup {} in `condition` table, does not exist in `mail_loot_template`, ignoring.", cond->SourceGroup); return false; } @@ -1547,7 +1548,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); if (!pItemProto && !loot->isReference(cond->SourceEntry)) { - LOG_ERROR("sql.sql", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + LOG_ERROR("db.query", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); return false; } break; @@ -1556,7 +1557,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) { if (!LootTemplates_Milling.HaveLootFor(cond->SourceGroup)) { - LOG_ERROR("sql.sql", "SourceGroup {} in `condition` table, does not exist in `milling_loot_template`, ignoring.", cond->SourceGroup); + LOG_ERROR("db.query", "SourceGroup {} in `condition` table, does not exist in `milling_loot_template`, ignoring.", cond->SourceGroup); return false; } @@ -1564,7 +1565,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); if (!pItemProto && !loot->isReference(cond->SourceEntry)) { - LOG_ERROR("sql.sql", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + LOG_ERROR("db.query", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); return false; } break; @@ -1573,7 +1574,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) { if (!LootTemplates_Pickpocketing.HaveLootFor(cond->SourceGroup)) { - LOG_ERROR("sql.sql", "SourceGroup {} in `condition` table, does not exist in `pickpocketing_loot_template`, ignoring.", cond->SourceGroup); + LOG_ERROR("db.query", "SourceGroup {} in `condition` table, does not exist in `pickpocketing_loot_template`, ignoring.", cond->SourceGroup); return false; } @@ -1581,7 +1582,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); if (!pItemProto && !loot->isReference(cond->SourceEntry)) { - LOG_ERROR("sql.sql", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + LOG_ERROR("db.query", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); return false; } break; @@ -1590,7 +1591,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) { if (!LootTemplates_Prospecting.HaveLootFor(cond->SourceGroup)) { - LOG_ERROR("sql.sql", "SourceGroup {} in `condition` table, does not exist in `prospecting_loot_template`, ignoring.", cond->SourceGroup); + LOG_ERROR("db.query", "SourceGroup {} in `condition` table, does not exist in `prospecting_loot_template`, ignoring.", cond->SourceGroup); return false; } @@ -1598,7 +1599,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); if (!pItemProto && !loot->isReference(cond->SourceEntry)) { - LOG_ERROR("sql.sql", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + LOG_ERROR("db.query", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); return false; } break; @@ -1607,7 +1608,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) { if (!LootTemplates_Reference.HaveLootFor(cond->SourceGroup)) { - LOG_ERROR("sql.sql", "SourceGroup {} in `condition` table, does not exist in `reference_loot_template`, ignoring.", cond->SourceGroup); + LOG_ERROR("db.query", "SourceGroup {} in `condition` table, does not exist in `reference_loot_template`, ignoring.", cond->SourceGroup); return false; } @@ -1615,7 +1616,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); if (!pItemProto && !loot->isReference(cond->SourceEntry)) { - LOG_ERROR("sql.sql", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + LOG_ERROR("db.query", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); return false; } break; @@ -1624,7 +1625,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) { if (!LootTemplates_Skinning.HaveLootFor(cond->SourceGroup)) { - LOG_ERROR("sql.sql", "SourceGroup {} in `condition` table, does not exist in `skinning_loot_template`, ignoring.", cond->SourceGroup); + LOG_ERROR("db.query", "SourceGroup {} in `condition` table, does not exist in `skinning_loot_template`, ignoring.", cond->SourceGroup); return false; } @@ -1632,7 +1633,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); if (!pItemProto && !loot->isReference(cond->SourceEntry)) { - LOG_ERROR("sql.sql", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + LOG_ERROR("db.query", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); return false; } break; @@ -1641,7 +1642,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) { if (!LootTemplates_Spell.HaveLootFor(cond->SourceGroup)) { - LOG_ERROR("sql.sql", "SourceGroup {} in `condition` table, does not exist in `spell_loot_template`, ignoring.", cond->SourceGroup); + LOG_ERROR("db.query", "SourceGroup {} in `condition` table, does not exist in `spell_loot_template`, ignoring.", cond->SourceGroup); return false; } @@ -1649,7 +1650,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); if (!pItemProto && !loot->isReference(cond->SourceEntry)) { - LOG_ERROR("sql.sql", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + LOG_ERROR("db.query", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); return false; } break; @@ -1659,13 +1660,13 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(cond->SourceEntry); if (!spellInfo) { - LOG_ERROR("sql.sql", "SourceEntry {} in `condition` table, does not exist in `spell.dbc`, ignoring.", cond->SourceEntry); + LOG_ERROR("db.query", "SourceEntry {} in `condition` table, does not exist in `spell.dbc`, ignoring.", cond->SourceEntry); return false; } if ((cond->SourceGroup > MAX_EFFECT_MASK) || !cond->SourceGroup) { - LOG_ERROR("sql.sql", "SourceEntry {} in `condition` table, has incorrect SourceGroup {} (spell effectMask) set , ignoring.", cond->SourceEntry, cond->SourceGroup); + LOG_ERROR("db.query", "SourceEntry {} in `condition` table, has incorrect SourceGroup {} (spell effectMask) set , ignoring.", cond->SourceEntry, cond->SourceGroup); return false; } @@ -1716,7 +1717,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) if (spellInfo->Effects[i].ChainTarget > 1) continue; - LOG_ERROR("sql.sql", "SourceEntry {} SourceGroup {} in `condition` table - spell {} does not have implicit targets of types: _AREA_, _CONE_, _NEARBY_ for effect {}, SourceGroup needs correction, ignoring.", cond->SourceEntry, origGroup, cond->SourceEntry, uint32(i)); + LOG_ERROR("db.query", "SourceEntry {} SourceGroup {} in `condition` table - spell {} does not have implicit targets of types: _AREA_, _CONE_, _NEARBY_ for effect {}, SourceGroup needs correction, ignoring.", cond->SourceEntry, origGroup, cond->SourceEntry, uint32(i)); cond->SourceGroup &= ~(1 << i); } // all effects were removed, no need to add the condition at all @@ -1728,7 +1729,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) { if (!sObjectMgr->GetCreatureTemplate(cond->SourceEntry)) { - LOG_ERROR("sql.sql", "SourceEntry {} in `condition` table, does not exist in `creature_template`, ignoring.", cond->SourceEntry); + LOG_ERROR("db.query", "SourceEntry {} in `condition` table, does not exist in `creature_template`, ignoring.", cond->SourceEntry); return false; } break; @@ -1739,7 +1740,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) SpellInfo const* spellProto = sSpellMgr->GetSpellInfo(cond->SourceEntry); if (!spellProto) { - LOG_ERROR("sql.sql", "SourceEntry {} in `condition` table, does not exist in `spell.dbc`, ignoring.", cond->SourceEntry); + LOG_ERROR("db.query", "SourceEntry {} in `condition` table, does not exist in `spell.dbc`, ignoring.", cond->SourceEntry); return false; } break; @@ -1747,24 +1748,24 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) case CONDITION_SOURCE_TYPE_QUEST_AVAILABLE: if (!sObjectMgr->GetQuestTemplate(cond->SourceEntry)) { - LOG_ERROR("sql.sql", "CONDITION_SOURCE_TYPE_QUEST_AVAILABLE specifies non-existing quest ({}), skipped", cond->SourceEntry); + LOG_ERROR("db.query", "CONDITION_SOURCE_TYPE_QUEST_AVAILABLE specifies non-existing quest ({}), skipped", cond->SourceEntry); return false; } break; case CONDITION_SOURCE_TYPE_UNUSED_20: - LOG_ERROR("sql.sql", "CONDITION_SOURCE_TYPE_UNUSED_20 is not in use. SourceEntry = ({}), skipped", cond->SourceEntry); + LOG_ERROR("db.query", "CONDITION_SOURCE_TYPE_UNUSED_20 is not in use. SourceEntry = ({}), skipped", cond->SourceEntry); break; case CONDITION_SOURCE_TYPE_VEHICLE_SPELL: case CONDITION_SOURCE_TYPE_SPELL_CLICK_EVENT: if (!sObjectMgr->GetCreatureTemplate(cond->SourceGroup)) { - LOG_ERROR("sql.sql", "SourceEntry {} in `condition` table, does not exist in `creature_template`, ignoring.", cond->SourceGroup); + LOG_ERROR("db.query", "SourceEntry {} in `condition` table, does not exist in `creature_template`, ignoring.", cond->SourceGroup); return false; } if (!sSpellMgr->GetSpellInfo(cond->SourceEntry)) { - LOG_ERROR("sql.sql", "SourceEntry {} in `condition` table, does not exist in `spell.dbc`, ignoring.", cond->SourceEntry); + LOG_ERROR("db.query", "SourceEntry {} in `condition` table, does not exist in `spell.dbc`, ignoring.", cond->SourceEntry); return false; } break; @@ -1790,7 +1791,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) { if (!LootTemplates_Player.HaveLootFor(cond->SourceGroup)) { - LOG_ERROR("sql.sql", "SourceGroup {} in `condition` table, does not exist in `player_loot_template`, ignoring.", cond->SourceGroup); + LOG_ERROR("db.query", "SourceGroup {} in `condition` table, does not exist in `player_loot_template`, ignoring.", cond->SourceGroup); return false; } @@ -1798,7 +1799,7 @@ bool ConditionMgr::isSourceTypeValid(Condition* cond) ItemTemplate const* pItemProto = sObjectMgr->GetItemTemplate(cond->SourceEntry); if (!pItemProto && !loot->isReference(cond->SourceEntry)) { - LOG_ERROR("sql.sql", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); + LOG_ERROR("db.query", "SourceType {}, SourceEntry {} in `condition` table, does not exist in `item_template`, ignoring.", cond->SourceType, cond->SourceEntry); return false; } break; @@ -1817,13 +1818,13 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) { if (cond->ConditionType == CONDITION_NONE || (cond->ConditionType >= CONDITION_TC_END && cond->ConditionType <= CONDITION_AC_START) || (cond->ConditionType >= CONDITION_AC_END)) { - LOG_ERROR("sql.sql", "SourceEntry {} in `condition` table has an invalid ConditionType ({}), ignoring.", cond->SourceEntry, uint32(cond->ConditionType)); + LOG_ERROR("db.query", "SourceEntry {} in `condition` table has an invalid ConditionType ({}), ignoring.", cond->SourceEntry, uint32(cond->ConditionType)); return false; } switch (cond->ConditionType) { case CONDITION_TERRAIN_SWAP: - LOG_ERROR("sql.sql", "SourceEntry {} in `condition` table has a ConditionType that is not supported on 3.3.5a ({}), ignoring.", cond->SourceEntry, uint32(cond->ConditionType)); + LOG_ERROR("db.query", "SourceEntry {} in `condition` table has a ConditionType that is not supported on 3.3.5a ({}), ignoring.", cond->SourceEntry, uint32(cond->ConditionType)); return false; default: break; @@ -1831,7 +1832,7 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) if (cond->ConditionTarget >= cond->GetMaxAvailableConditionTargets()) { - LOG_ERROR("sql.sql", "SourceType {}, SourceEntry {} in `condition` table, has incorrect ConditionTarget set, ignoring.", cond->SourceType, cond->SourceEntry); + LOG_ERROR("db.query", "SourceType {}, SourceEntry {} in `condition` table, has incorrect ConditionTarget set, ignoring.", cond->SourceType, cond->SourceEntry); return false; } @@ -1841,17 +1842,17 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) { if (!sSpellMgr->GetSpellInfo(cond->ConditionValue1)) { - LOG_ERROR("sql.sql", "Aura condition has non existing spell (Id: {}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "Aura condition has non existing spell (Id: {}), skipped", cond->ConditionValue1); return false; } if (cond->ConditionValue2 > EFFECT_2) { - LOG_ERROR("sql.sql", "Aura condition has non existing effect index ({}) (must be 0..2), skipped", cond->ConditionValue2); + LOG_ERROR("db.query", "Aura condition has non existing effect index ({}) (must be 0..2), skipped", cond->ConditionValue2); return false; } if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "Aura condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "Aura condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_ITEM: @@ -1859,13 +1860,13 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) ItemTemplate const* proto = sObjectMgr->GetItemTemplate(cond->ConditionValue1); if (!proto) { - LOG_ERROR("sql.sql", "Item condition has non existing item ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "Item condition has non existing item ({}), skipped", cond->ConditionValue1); return false; } if (!cond->ConditionValue2) { - LOG_ERROR("sql.sql", "Item condition has 0 set for item count in value2 ({}), skipped", cond->ConditionValue2); + LOG_ERROR("db.query", "Item condition has 0 set for item count in value2 ({}), skipped", cond->ConditionValue2); return false; } break; @@ -1875,14 +1876,14 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) ItemTemplate const* proto = sObjectMgr->GetItemTemplate(cond->ConditionValue1); if (!proto) { - LOG_ERROR("sql.sql", "ItemEquipped condition has non existing item ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "ItemEquipped condition has non existing item ({}), skipped", cond->ConditionValue1); return false; } if (cond->ConditionValue2) - LOG_ERROR("sql.sql", "ItemEquipped condition has useless data in value2 ({})!", cond->ConditionValue2); + LOG_ERROR("db.query", "ItemEquipped condition has useless data in value2 ({})!", cond->ConditionValue2); if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "ItemEquipped condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "ItemEquipped condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_ZONEID: @@ -1890,20 +1891,20 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) AreaTableEntry const* areaEntry = sAreaTableStore.LookupEntry(cond->ConditionValue1); if (!areaEntry) { - LOG_ERROR("sql.sql", "ZoneID condition has non existing area ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "ZoneID condition has non existing area ({}), skipped", cond->ConditionValue1); return false; } if (areaEntry->zone != 0) { - LOG_ERROR("sql.sql", "ZoneID condition requires to be in area ({}) which is a subzone but zone expected, skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "ZoneID condition requires to be in area ({}) which is a subzone but zone expected, skipped", cond->ConditionValue1); return false; } if (cond->ConditionValue2) - LOG_ERROR("sql.sql", "ZoneID condition has useless data in value2 ({})!", cond->ConditionValue2); + LOG_ERROR("db.query", "ZoneID condition has useless data in value2 ({})!", cond->ConditionValue2); if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "ZoneID condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "ZoneID condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_REPUTATION_RANK: @@ -1911,25 +1912,25 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) FactionEntry const* factionEntry = sFactionStore.LookupEntry(cond->ConditionValue1); if (!factionEntry) { - LOG_ERROR("sql.sql", "Reputation condition has non existing faction ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "Reputation condition has non existing faction ({}), skipped", cond->ConditionValue1); return false; } if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "Reputation condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "Reputation condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_TEAM: { if (cond->ConditionValue1 != ALLIANCE && cond->ConditionValue1 != HORDE) { - LOG_ERROR("sql.sql", "Team condition specifies unknown team ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "Team condition specifies unknown team ({}), skipped", cond->ConditionValue1); return false; } if (cond->ConditionValue2) - LOG_ERROR("sql.sql", "Team condition has useless data in value2 ({})!", cond->ConditionValue2); + LOG_ERROR("db.query", "Team condition has useless data in value2 ({})!", cond->ConditionValue2); if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "Team condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "Team condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_SKILL: @@ -1937,17 +1938,17 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) SkillLineEntry const* pSkill = sSkillLineStore.LookupEntry(cond->ConditionValue1); if (!pSkill) { - LOG_ERROR("sql.sql", "Skill condition specifies non-existing skill ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "Skill condition specifies non-existing skill ({}), skipped", cond->ConditionValue1); return false; } if (cond->ConditionValue2 < 1 || cond->ConditionValue2 > sWorld->GetConfigMaxSkillValue()) { - LOG_ERROR("sql.sql", "Skill condition specifies invalid skill value ({}), skipped", cond->ConditionValue2); + LOG_ERROR("db.query", "Skill condition specifies invalid skill value ({}), skipped", cond->ConditionValue2); return false; } if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "Skill condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "Skill condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_QUESTREWARDED: @@ -1959,24 +1960,24 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) { if (!sObjectMgr->GetQuestTemplate(cond->ConditionValue1)) { - LOG_ERROR("sql.sql", "Quest condition specifies non-existing quest ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "Quest condition specifies non-existing quest ({}), skipped", cond->ConditionValue1); return false; } if (cond->ConditionValue2 > 1) { - LOG_ERROR("sql.sql", "Quest condition has useless data in value2 ({})!", cond->ConditionValue2); + LOG_ERROR("db.query", "Quest condition has useless data in value2 ({})!", cond->ConditionValue2); } if (cond->ConditionValue3) { - LOG_ERROR("sql.sql", "Quest condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "Quest condition has useless data in value3 ({})!", cond->ConditionValue3); } break; } case CONDITION_QUESTSTATE: if (cond->ConditionValue2 >= (1 << MAX_QUEST_STATUS)) { - LOG_ERROR("sql.sql", "ConditionType ({}) has invalid state mask ({}), skipped.", cond->ConditionType, cond->ConditionValue2); + LOG_ERROR("db.query", "ConditionType ({}) has invalid state mask ({}), skipped.", cond->ConditionType, cond->ConditionValue2); return false; } break; @@ -1985,14 +1986,14 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) GameEventMgr::GameEventDataMap const& events = sGameEventMgr->GetEventMap(); if (cond->ConditionValue1 >= events.size() || !events[cond->ConditionValue1].isValid()) { - LOG_ERROR("sql.sql", "ActiveEvent condition has non existing event id ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "ActiveEvent condition has non existing event id ({}), skipped", cond->ConditionValue1); return false; } if (cond->ConditionValue2) - LOG_ERROR("sql.sql", "ActiveEvent condition has useless data in value2 ({})!", cond->ConditionValue2); + LOG_ERROR("db.query", "ActiveEvent condition has useless data in value2 ({})!", cond->ConditionValue2); if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "ActiveEvent condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "ActiveEvent condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_ACHIEVEMENT: @@ -2000,42 +2001,42 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) AchievementEntry const* achievement = sAchievementStore.LookupEntry(cond->ConditionValue1); if (!achievement) { - LOG_ERROR("sql.sql", "Achivement condition has non existing achivement id ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "Achivement condition has non existing achivement id ({}), skipped", cond->ConditionValue1); return false; } if (cond->ConditionValue2) - LOG_ERROR("sql.sql", "Achivement condition has useless data in value2 ({})!", cond->ConditionValue2); + LOG_ERROR("db.query", "Achivement condition has useless data in value2 ({})!", cond->ConditionValue2); if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "Achivement condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "Achivement condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_CLASS: { if (!(cond->ConditionValue1 & CLASSMASK_ALL_PLAYABLE)) { - LOG_ERROR("sql.sql", "Class condition has non existing classmask ({}), skipped", cond->ConditionValue1 & ~CLASSMASK_ALL_PLAYABLE); + LOG_ERROR("db.query", "Class condition has non existing classmask ({}), skipped", cond->ConditionValue1 & ~CLASSMASK_ALL_PLAYABLE); return false; } if (cond->ConditionValue2) - LOG_ERROR("sql.sql", "Class condition has useless data in value2 ({})!", cond->ConditionValue2); + LOG_ERROR("db.query", "Class condition has useless data in value2 ({})!", cond->ConditionValue2); if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "Class condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "Class condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_RACE: { if (!(cond->ConditionValue1 & RACEMASK_ALL_PLAYABLE)) { - LOG_ERROR("sql.sql", "Race condition has non existing racemask ({}), skipped", cond->ConditionValue1 & ~RACEMASK_ALL_PLAYABLE); + LOG_ERROR("db.query", "Race condition has non existing racemask ({}), skipped", cond->ConditionValue1 & ~RACEMASK_ALL_PLAYABLE); return false; } if (cond->ConditionValue2) - LOG_ERROR("sql.sql", "Race condition has useless data in value2 ({})!", cond->ConditionValue2); + LOG_ERROR("db.query", "Race condition has useless data in value2 ({})!", cond->ConditionValue2); if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "Race condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "Race condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_GENDER: @@ -2057,62 +2058,62 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) MapEntry const* mapId = sMapStore.LookupEntry(cond->ConditionValue1); if (!mapId) { - LOG_ERROR("sql.sql", "Map condition has non existing map ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "Map condition has non existing map ({}), skipped", cond->ConditionValue1); return false; } if (cond->ConditionValue2) - LOG_ERROR("sql.sql", "Map condition has useless data in value2 ({})!", cond->ConditionValue2); + LOG_ERROR("db.query", "Map condition has useless data in value2 ({})!", cond->ConditionValue2); if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "Map condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "Map condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_SPELL: { if (!sSpellMgr->GetSpellInfo(cond->ConditionValue1)) { - LOG_ERROR("sql.sql", "Spell condition has non existing spell (Id: {}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "Spell condition has non existing spell (Id: {}), skipped", cond->ConditionValue1); return false; } if (cond->ConditionValue2) - LOG_ERROR("sql.sql", "Spell condition has useless data in value2 ({})!", cond->ConditionValue2); + LOG_ERROR("db.query", "Spell condition has useless data in value2 ({})!", cond->ConditionValue2); if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "Spell condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "Spell condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_LEVEL: { if (cond->ConditionValue2 >= COMP_TYPE_MAX) { - LOG_ERROR("sql.sql", "Level condition has invalid option ({}), skipped", cond->ConditionValue2); + LOG_ERROR("db.query", "Level condition has invalid option ({}), skipped", cond->ConditionValue2); return false; } if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "Level condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "Level condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_DRUNKENSTATE: { if (cond->ConditionValue1 > DRUNKEN_SMASHED) { - LOG_ERROR("sql.sql", "DrunkState condition has invalid state ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "DrunkState condition has invalid state ({}), skipped", cond->ConditionValue1); return false; } if (cond->ConditionValue2) { - LOG_ERROR("sql.sql", "DrunkState condition has useless data in value2 ({})!", cond->ConditionValue2); + LOG_ERROR("db.query", "DrunkState condition has useless data in value2 ({})!", cond->ConditionValue2); return false; } if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "DrunkState condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "DrunkState condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_NEAR_CREATURE: { if (!sObjectMgr->GetCreatureTemplate(cond->ConditionValue1)) { - LOG_ERROR("sql.sql", "NearCreature condition has non existing creature template entry ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "NearCreature condition has non existing creature template entry ({}), skipped", cond->ConditionValue1); return false; } break; @@ -2121,11 +2122,11 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) { if (!sObjectMgr->GetGameObjectTemplate(cond->ConditionValue1)) { - LOG_ERROR("sql.sql", "NearGameObject condition has non existing gameobject template entry ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "NearGameObject condition has non existing gameobject template entry ({}), skipped", cond->ConditionValue1); return false; } if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "NearGameObject condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "NearGameObject condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_OBJECT_ENTRY_GUID: @@ -2135,7 +2136,7 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) case TYPEID_UNIT: if (cond->ConditionValue2 && !sObjectMgr->GetCreatureTemplate(cond->ConditionValue2)) { - LOG_ERROR("sql.sql", "ObjectEntryGuid condition has non existing creature template entry ({}), skipped", cond->ConditionValue2); + LOG_ERROR("db.query", "ObjectEntryGuid condition has non existing creature template entry ({}), skipped", cond->ConditionValue2); return false; } if (cond->ConditionValue3 > 1) @@ -2144,13 +2145,13 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) { if (cond->ConditionValue2 && creatureData->id1 != cond->ConditionValue2) { - LOG_ERROR("sql.sql", "ObjectEntryGuid condition has guid {} set but does not match creature entry ({}), skipped", cond->ConditionValue3, cond->ConditionValue2); + LOG_ERROR("db.query", "ObjectEntryGuid condition has guid {} set but does not match creature entry ({}), skipped", cond->ConditionValue3, cond->ConditionValue2); return false; } } else { - LOG_ERROR("sql.sql", "ObjectEntryGuid condition has non existing creature guid ({}), skipped", cond->ConditionValue3); + LOG_ERROR("db.query", "ObjectEntryGuid condition has non existing creature guid ({}), skipped", cond->ConditionValue3); return false; } } @@ -2158,7 +2159,7 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) case TYPEID_GAMEOBJECT: if (cond->ConditionValue2 && !sObjectMgr->GetGameObjectTemplate(cond->ConditionValue2)) { - LOG_ERROR("sql.sql", "ObjectEntryGuid condition has non existing gameobject template entry ({}), skipped", cond->ConditionValue2); + LOG_ERROR("db.query", "ObjectEntryGuid condition has non existing gameobject template entry ({}), skipped", cond->ConditionValue2); return false; } if (cond->ConditionValue3) @@ -2167,13 +2168,13 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) { if (cond->ConditionValue2 && goData->id != cond->ConditionValue2) { - LOG_ERROR("sql.sql", "ObjectEntryGuid condition has guid {} set but does not match gameobject entry ({}), skipped", cond->ConditionValue3, cond->ConditionValue2); + LOG_ERROR("db.query", "ObjectEntryGuid condition has guid {} set but does not match gameobject entry ({}), skipped", cond->ConditionValue3, cond->ConditionValue2); return false; } } else { - LOG_ERROR("sql.sql", "ObjectEntryGuid condition has non existing gameobject guid ({}), skipped", cond->ConditionValue3); + LOG_ERROR("db.query", "ObjectEntryGuid condition has non existing gameobject guid ({}), skipped", cond->ConditionValue3); return false; } } @@ -2181,12 +2182,12 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) case TYPEID_PLAYER: case TYPEID_CORPSE: if (cond->ConditionValue2) - LOG_ERROR("sql.sql", "ObjectEntryGuid condition has useless data in value2 ({})!", cond->ConditionValue2); + LOG_ERROR("db.query", "ObjectEntryGuid condition has useless data in value2 ({})!", cond->ConditionValue2); if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "ObjectEntryGuid condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "ObjectEntryGuid condition has useless data in value3 ({})!", cond->ConditionValue3); break; default: - LOG_ERROR("sql.sql", "ObjectEntryGuid condition has wrong typeid set ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "ObjectEntryGuid condition has wrong typeid set ({}), skipped", cond->ConditionValue1); return false; } break; @@ -2195,51 +2196,51 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) { if (!cond->ConditionValue1 || (cond->ConditionValue1 & ~(TYPEMASK_UNIT | TYPEMASK_PLAYER | TYPEMASK_GAMEOBJECT | TYPEMASK_CORPSE))) { - LOG_ERROR("sql.sql", "TypeMask condition has invalid typemask set ({}), skipped", cond->ConditionValue2); + LOG_ERROR("db.query", "TypeMask condition has invalid typemask set ({}), skipped", cond->ConditionValue2); return false; } if (cond->ConditionValue2) - LOG_ERROR("sql.sql", "TypeMask condition has useless data in value2 ({})!", cond->ConditionValue2); + LOG_ERROR("db.query", "TypeMask condition has useless data in value2 ({})!", cond->ConditionValue2); if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "TypeMask condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "TypeMask condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_RELATION_TO: { if (cond->ConditionValue1 >= cond->GetMaxAvailableConditionTargets()) { - LOG_ERROR("sql.sql", "RelationTo condition has invalid ConditionValue1(ConditionTarget selection) ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "RelationTo condition has invalid ConditionValue1(ConditionTarget selection) ({}), skipped", cond->ConditionValue1); return false; } if (cond->ConditionValue1 == cond->ConditionTarget) { - LOG_ERROR("sql.sql", "RelationTo condition has ConditionValue1(ConditionTarget selection) set to self ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "RelationTo condition has ConditionValue1(ConditionTarget selection) set to self ({}), skipped", cond->ConditionValue1); return false; } if (cond->ConditionValue2 >= RELATION_MAX) { - LOG_ERROR("sql.sql", "RelationTo condition has invalid ConditionValue2(RelationType) ({}), skipped", cond->ConditionValue2); + LOG_ERROR("db.query", "RelationTo condition has invalid ConditionValue2(RelationType) ({}), skipped", cond->ConditionValue2); return false; } if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "RelationTo condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "RelationTo condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_REACTION_TO: { if (cond->ConditionValue1 >= cond->GetMaxAvailableConditionTargets()) { - LOG_ERROR("sql.sql", "ReactionTo condition has invalid ConditionValue1(ConditionTarget selection) ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "ReactionTo condition has invalid ConditionValue1(ConditionTarget selection) ({}), skipped", cond->ConditionValue1); return false; } if (cond->ConditionValue1 == cond->ConditionTarget) { - LOG_ERROR("sql.sql", "ReactionTo condition has ConditionValue1(ConditionTarget selection) set to self ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "ReactionTo condition has ConditionValue1(ConditionTarget selection) set to self ({}), skipped", cond->ConditionValue1); return false; } if (!cond->ConditionValue2) { - LOG_ERROR("sql.sql", "mConditionValue2 condition has invalid ConditionValue2(rankMask) ({}), skipped", cond->ConditionValue2); + LOG_ERROR("db.query", "mConditionValue2 condition has invalid ConditionValue2(rankMask) ({}), skipped", cond->ConditionValue2); return false; } break; @@ -2248,17 +2249,17 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) { if (cond->ConditionValue1 >= cond->GetMaxAvailableConditionTargets()) { - LOG_ERROR("sql.sql", "DistanceTo condition has invalid ConditionValue1(ConditionTarget selection) ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "DistanceTo condition has invalid ConditionValue1(ConditionTarget selection) ({}), skipped", cond->ConditionValue1); return false; } if (cond->ConditionValue1 == cond->ConditionTarget) { - LOG_ERROR("sql.sql", "DistanceTo condition has ConditionValue1(ConditionTarget selection) set to self ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "DistanceTo condition has ConditionValue1(ConditionTarget selection) set to self ({}), skipped", cond->ConditionValue1); return false; } if (cond->ConditionValue3 >= COMP_TYPE_MAX) { - LOG_ERROR("sql.sql", "DistanceTo condition has invalid ComparisionType ({}), skipped", cond->ConditionValue3); + LOG_ERROR("db.query", "DistanceTo condition has invalid ComparisionType ({}), skipped", cond->ConditionValue3); return false; } break; @@ -2266,38 +2267,38 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) case CONDITION_ALIVE: { if (cond->ConditionValue1) - LOG_ERROR("sql.sql", "Alive condition has useless data in value1 ({})!", cond->ConditionValue1); + LOG_ERROR("db.query", "Alive condition has useless data in value1 ({})!", cond->ConditionValue1); if (cond->ConditionValue2) - LOG_ERROR("sql.sql", "Alive condition has useless data in value2 ({})!", cond->ConditionValue2); + LOG_ERROR("db.query", "Alive condition has useless data in value2 ({})!", cond->ConditionValue2); if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "Alive condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "Alive condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_HP_VAL: { if (cond->ConditionValue2 >= COMP_TYPE_MAX) { - LOG_ERROR("sql.sql", "HpVal condition has invalid ComparisionType ({}), skipped", cond->ConditionValue2); + LOG_ERROR("db.query", "HpVal condition has invalid ComparisionType ({}), skipped", cond->ConditionValue2); return false; } if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "HpVal condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "HpVal condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_HP_PCT: { if (cond->ConditionValue1 > 100) { - LOG_ERROR("sql.sql", "HpPct condition has too big percent value ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "HpPct condition has too big percent value ({}), skipped", cond->ConditionValue1); return false; } if (cond->ConditionValue2 >= COMP_TYPE_MAX) { - LOG_ERROR("sql.sql", "HpPct condition has invalid ComparisionType ({}), skipped", cond->ConditionValue2); + LOG_ERROR("db.query", "HpPct condition has invalid ComparisionType ({}), skipped", cond->ConditionValue2); return false; } if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "HpPct condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "HpPct condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_AREAID: @@ -2306,15 +2307,15 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) case CONDITION_WORLD_STATE: { if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "World state condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "World state condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_PHASEMASK: { if (cond->ConditionValue2) - LOG_ERROR("sql.sql", "Phasemask condition has useless data in value2 ({})!", cond->ConditionValue2); + LOG_ERROR("db.query", "Phasemask condition has useless data in value2 ({})!", cond->ConditionValue2); if (cond->ConditionValue3) - LOG_ERROR("sql.sql", "Phasemask condition has useless data in value3 ({})!", cond->ConditionValue3); + LOG_ERROR("db.query", "Phasemask condition has useless data in value3 ({})!", cond->ConditionValue3); break; } case CONDITION_TITLE: @@ -2322,7 +2323,7 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(cond->ConditionValue1); if (!titleEntry) { - LOG_ERROR("sql.sql", "Title condition has non existing title in value1 ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "Title condition has non existing title in value1 ({}), skipped", cond->ConditionValue1); return false; } break; @@ -2369,25 +2370,25 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) const Quest* quest = sObjectMgr->GetQuestTemplate(cond->ConditionValue1); if (!quest) { - LOG_ERROR("sql.sql", "CONDITION_QUEST_OBJECTIVE_PROGRESS points to non-existing quest ({}), skipped.", cond->ConditionValue1); + LOG_ERROR("db.query", "CONDITION_QUEST_OBJECTIVE_PROGRESS points to non-existing quest ({}), skipped.", cond->ConditionValue1); return false; } if (cond->ConditionValue2 > 3) { - LOG_ERROR("sql.sql", "CONDITION_QUEST_OBJECTIVE_PROGRESS has out-of-range quest objective index specified ({}), it must be a number between 0 and 3. skipped.", cond->ConditionValue2); + LOG_ERROR("db.query", "CONDITION_QUEST_OBJECTIVE_PROGRESS has out-of-range quest objective index specified ({}), it must be a number between 0 and 3. skipped.", cond->ConditionValue2); return false; } if (quest->RequiredNpcOrGo[cond->ConditionValue2] == 0) { - LOG_ERROR("sql.sql", "CONDITION_QUEST_OBJECTIVE_PROGRESS has quest objective {} for quest {}, but the field RequiredNPCOrGo{} is 0, skipped.", cond->ConditionValue2, cond->ConditionValue1, cond->ConditionValue2); + LOG_ERROR("db.query", "CONDITION_QUEST_OBJECTIVE_PROGRESS has quest objective {} for quest {}, but the field RequiredNPCOrGo{} is 0, skipped.", cond->ConditionValue2, cond->ConditionValue1, cond->ConditionValue2); return false; } if (cond->ConditionValue3 > quest->RequiredNpcOrGoCount[cond->ConditionValue2]) { - LOG_ERROR("sql.sql", "CONDITION_QUEST_OBJECTIVE_PROGRESS has quest objective count {} in value3, but quest {} has a maximum objective count of {} in RequiredNPCOrGOCount{}, skipped.", cond->ConditionValue3, cond->ConditionValue2, quest->RequiredNpcOrGoCount[cond->ConditionValue2], cond->ConditionValue2); + LOG_ERROR("db.query", "CONDITION_QUEST_OBJECTIVE_PROGRESS has quest objective count {} in value3, but quest {} has a maximum objective count of {} in RequiredNPCOrGOCount{}, skipped.", cond->ConditionValue3, cond->ConditionValue2, quest->RequiredNpcOrGoCount[cond->ConditionValue2], cond->ConditionValue2); return false; } break; @@ -2396,7 +2397,7 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) { if (cond->ConditionValue1 == SPELL_AURA_NONE || cond->ConditionValue1 >= TOTAL_AURAS) { - LOG_ERROR("sql.sql", "Has Aura Effect condition has non existing aura ({}), skipped", cond->ConditionValue1); + LOG_ERROR("db.query", "Has Aura Effect condition has non existing aura ({}), skipped", cond->ConditionValue1); return false; } break; @@ -2418,7 +2419,7 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) } if (!valid) { - LOG_ERROR("sql.sql", "CONDITION_STAND_STATE has non-existing stand state ({},{}), skipped.", cond->ConditionValue1, cond->ConditionValue2); + LOG_ERROR("db.query", "CONDITION_STAND_STATE has non-existing stand state ({},{}), skipped.", cond->ConditionValue1, cond->ConditionValue2); return false; } break; @@ -2426,14 +2427,14 @@ bool ConditionMgr::isConditionTypeValid(Condition* cond) case CONDITION_DIFFICULTY_ID: if (cond->ConditionValue1 >= MAX_DIFFICULTY) { - LOG_ERROR("sql.sql", "CONDITION_DIFFICULTY_ID has non existing difficulty in value1 ({}), skipped.", cond->ConditionValue1); + LOG_ERROR("db.query", "CONDITION_DIFFICULTY_ID has non existing difficulty in value1 ({}), skipped.", cond->ConditionValue1); return false; } break; case CONDITION_PET_TYPE: if (cond->ConditionValue1 >= (1 << MAX_PET_TYPE)) { - LOG_ERROR("sql.sql", "CONDITION_PET_TYPE has non-existing pet type {}, skipped.", cond->ConditionValue1); + LOG_ERROR("db.query", "CONDITION_PET_TYPE has non-existing pet type {}, skipped.", cond->ConditionValue1); return false; } break; diff --git a/src/server/game/Conditions/DisableMgr.cpp b/src/server/game/Conditions/DisableMgr.cpp index 1f745391d1e0a2..d7a57af7b3d8ae 100644 --- a/src/server/game/Conditions/DisableMgr.cpp +++ b/src/server/game/Conditions/DisableMgr.cpp @@ -26,6 +26,7 @@ #include "World.h" #include "Tokenize.h" #include "StringConvert.h" +#include "DatabaseEnv.h" namespace DisableMgr { @@ -75,7 +76,7 @@ namespace DisableMgr DisableType type = DisableType(fields[0].Get()); if (type >= MAX_DISABLE_TYPES) { - LOG_ERROR("sql.sql", "Invalid type {} specified in `disables` table, skipped.", type); + LOG_ERROR("db.query", "Invalid type {} specified in `disables` table, skipped.", type); continue; } @@ -92,22 +93,22 @@ namespace DisableMgr case DISABLE_TYPE_GO_LOS: if (!sObjectMgr->GetGameObjectTemplate(entry)) { - LOG_ERROR("sql.sql", "Gameobject entry {} from `disables` doesn't exist in dbc, skipped.", entry); + LOG_ERROR("db.query", "Gameobject entry {} from `disables` doesn't exist in dbc, skipped.", entry); continue; } if (flags) - LOG_ERROR("sql.sql", "Disable flags specified for gameobject {}, useless data.", entry); + LOG_ERROR("db.query", "Disable flags specified for gameobject {}, useless data.", entry); break; case DISABLE_TYPE_SPELL: if (!(sSpellMgr->GetSpellInfo(entry) || flags & SPELL_DISABLE_DEPRECATED_SPELL)) { - LOG_ERROR("sql.sql", "Spell entry {} from `disables` doesn't exist in dbc, skipped.", entry); + LOG_ERROR("db.query", "Spell entry {} from `disables` doesn't exist in dbc, skipped.", entry); continue; } if (!flags || flags > MAX_SPELL_DISABLE_TYPE) { - LOG_ERROR("sql.sql", "Disable flags for spell {} are invalid, skipped.", entry); + LOG_ERROR("db.query", "Disable flags for spell {} are invalid, skipped.", entry); continue; } @@ -118,7 +119,7 @@ namespace DisableMgr if (Optional mapId = Acore::StringTo(mapStr)) data.params[0].insert(*mapId); else - LOG_ERROR("sql.sql", "Disable map '{}' for spell {} is invalid, skipped.", mapStr, entry); + LOG_ERROR("db.query", "Disable map '{}' for spell {} is invalid, skipped.", mapStr, entry); } } @@ -129,7 +130,7 @@ namespace DisableMgr if (Optional areaId = Acore::StringTo(areaStr)) data.params[1].insert(*areaId); else - LOG_ERROR("sql.sql", "Disable area '{}' for spell {} is invalid, skipped.", areaStr, entry); + LOG_ERROR("db.query", "Disable area '{}' for spell {} is invalid, skipped.", areaStr, entry); } } @@ -150,7 +151,7 @@ namespace DisableMgr MapEntry const* mapEntry = sMapStore.LookupEntry(entry); if (!mapEntry) { - LOG_ERROR("sql.sql", "Map entry {} from `disables` doesn't exist in dbc, skipped.", entry); + LOG_ERROR("db.query", "Map entry {} from `disables` doesn't exist in dbc, skipped.", entry); continue; } bool isFlagInvalid = false; @@ -171,12 +172,12 @@ namespace DisableMgr break; case MAP_BATTLEGROUND: case MAP_ARENA: - LOG_ERROR("sql.sql", "Battleground map {} specified to be disabled in map case, skipped.", entry); + LOG_ERROR("db.query", "Battleground map {} specified to be disabled in map case, skipped.", entry); continue; } if (isFlagInvalid) { - LOG_ERROR("sql.sql", "Disable flags for map {} are invalid, skipped.", entry); + LOG_ERROR("db.query", "Disable flags for map {} are invalid, skipped.", entry); continue; } break; @@ -184,36 +185,36 @@ namespace DisableMgr case DISABLE_TYPE_BATTLEGROUND: if (!sBattlemasterListStore.LookupEntry(entry)) { - LOG_ERROR("sql.sql", "Battleground entry {} from `disables` doesn't exist in dbc, skipped.", entry); + LOG_ERROR("db.query", "Battleground entry {} from `disables` doesn't exist in dbc, skipped.", entry); continue; } if (flags) - LOG_ERROR("sql.sql", "Disable flags specified for battleground {}, useless data.", entry); + LOG_ERROR("db.query", "Disable flags specified for battleground {}, useless data.", entry); break; case DISABLE_TYPE_OUTDOORPVP: if (entry > MAX_OUTDOORPVP_TYPES) { - LOG_ERROR("sql.sql", "OutdoorPvPTypes value {} from `disables` is invalid, skipped.", entry); + LOG_ERROR("db.query", "OutdoorPvPTypes value {} from `disables` is invalid, skipped.", entry); continue; } if (flags) - LOG_ERROR("sql.sql", "Disable flags specified for outdoor PvP {}, useless data.", entry); + LOG_ERROR("db.query", "Disable flags specified for outdoor PvP {}, useless data.", entry); break; case DISABLE_TYPE_ACHIEVEMENT_CRITERIA: if (!sAchievementCriteriaStore.LookupEntry(entry)) { - LOG_ERROR("sql.sql", "Achievement Criteria entry {} from `disables` doesn't exist in dbc, skipped.", entry); + LOG_ERROR("db.query", "Achievement Criteria entry {} from `disables` doesn't exist in dbc, skipped.", entry); continue; } if (flags) - LOG_ERROR("sql.sql", "Disable flags specified for Achievement Criteria {}, useless data.", entry); + LOG_ERROR("db.query", "Disable flags specified for Achievement Criteria {}, useless data.", entry); break; case DISABLE_TYPE_VMAP: { MapEntry const* mapEntry = sMapStore.LookupEntry(entry); if (!mapEntry) { - LOG_ERROR("sql.sql", "Map entry {} from `disables` doesn't exist in dbc, skipped.", entry); + LOG_ERROR("db.query", "Map entry {} from `disables` doesn't exist in dbc, skipped.", entry); continue; } switch (mapEntry->map_type) @@ -290,12 +291,12 @@ namespace DisableMgr const uint32 entry = itr->first; if (!sObjectMgr->GetQuestTemplate(entry)) { - LOG_ERROR("sql.sql", "Quest entry {} from `disables` doesn't exist, skipped.", entry); + LOG_ERROR("db.query", "Quest entry {} from `disables` doesn't exist, skipped.", entry); m_DisableMap[DISABLE_TYPE_QUEST].erase(itr++); continue; } if (itr->second.flags) - LOG_ERROR("sql.sql", "Disable flags specified for quest {}, useless data.", entry); + LOG_ERROR("db.query", "Disable flags specified for quest {}, useless data.", entry); ++itr; } diff --git a/src/server/game/DataStores/DBCStores.cpp b/src/server/game/DataStores/DBCStores.cpp index b557ea9ce5ae39..f847e56cec5bf0 100644 --- a/src/server/game/DataStores/DBCStores.cpp +++ b/src/server/game/DataStores/DBCStores.cpp @@ -466,7 +466,7 @@ void LoadDBCStores(const std::string& dataPath) if (spellDiff->SpellID[x] <= 0 || !sSpellStore.LookupEntry(spellDiff->SpellID[x])) { if (spellDiff->SpellID[x] > 0) //don't show error if spell is <= 0, not all modes have spells and there are unknown negative values - LOG_ERROR("sql.sql", "spelldifficulty_dbc: spell {} at field id: {} at spellid {} does not exist in SpellStore (spell.dbc), loaded as 0", spellDiff->SpellID[x], spellDiff->ID, x); + LOG_ERROR("db.query", "spelldifficulty_dbc: spell {} at field id: {} at spellid {} does not exist in SpellStore (spell.dbc), loaded as 0", spellDiff->SpellID[x], spellDiff->ID, x); newEntry.SpellID[x] = 0; // spell was <= 0 or invalid, set to 0 } diff --git a/src/server/game/DungeonFinding/LFGMgr.cpp b/src/server/game/DungeonFinding/LFGMgr.cpp index ae21b5c7646b06..0de4b14100edfd 100644 --- a/src/server/game/DungeonFinding/LFGMgr.cpp +++ b/src/server/game/DungeonFinding/LFGMgr.cpp @@ -38,6 +38,7 @@ #include "SocialMgr.h" #include "SpellAuras.h" #include "WorldSession.h" +#include "DatabaseEnv.h" namespace lfg { @@ -99,7 +100,7 @@ namespace lfg if (!guid.IsGroup()) return; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_LFG_DATA); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_LFG_DATA); stmt->SetData(0, guid.GetCounter()); stmt->SetData(1, GetDungeon(guid)); stmt->SetData(2, GetState(guid)); diff --git a/src/server/game/Entities/Corpse/Corpse.cpp b/src/server/game/Entities/Corpse/Corpse.cpp index b2304cb182ce5d..95202006114792 100644 --- a/src/server/game/Entities/Corpse/Corpse.cpp +++ b/src/server/game/Entities/Corpse/Corpse.cpp @@ -94,7 +94,7 @@ void Corpse::SaveToDB() CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); DeleteFromDB(trans); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CORPSE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CORPSE); stmt->SetData(0, GetOwnerGUID().GetCounter()); // guid stmt->SetData (1, GetPositionX()); // posX stmt->SetData (2, GetPositionY()); // posY @@ -124,7 +124,7 @@ void Corpse::DeleteFromDB(CharacterDatabaseTransaction trans) void Corpse::DeleteFromDB(ObjectGuid const ownerGuid, CharacterDatabaseTransaction trans) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CORPSE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CORPSE); stmt->SetData(0, ownerGuid.GetCounter()); CharacterDatabase.ExecuteOrAppend(trans, stmt); } diff --git a/src/server/game/Entities/Corpse/Corpse.h b/src/server/game/Entities/Corpse/Corpse.h index 6d1dedcf0b7ef6..4e76524ef66468 100644 --- a/src/server/game/Entities/Corpse/Corpse.h +++ b/src/server/game/Entities/Corpse/Corpse.h @@ -18,7 +18,7 @@ #ifndef AZEROTHCORE_CORPSE_H #define AZEROTHCORE_CORPSE_H -#include "DatabaseEnv.h" +#include "DatabaseEnvFwd.h" #include "GridDefines.h" #include "LootMgr.h" #include "Object.h" diff --git a/src/server/game/Entities/Creature/Creature.cpp b/src/server/game/Entities/Creature/Creature.cpp index 3d0c018baef1d8..16d6f6aaca42fe 100644 --- a/src/server/game/Entities/Creature/Creature.cpp +++ b/src/server/game/Entities/Creature/Creature.cpp @@ -387,7 +387,7 @@ bool Creature::InitEntry(uint32 Entry, const CreatureData* data) CreatureTemplate const* normalInfo = sObjectMgr->GetCreatureTemplate(Entry); if (!normalInfo) { - LOG_ERROR("sql.sql", "Creature::InitEntry creature entry {} does not exist.", Entry); + LOG_ERROR("db.query", "Creature::InitEntry creature entry {} does not exist.", Entry); return false; } @@ -426,14 +426,14 @@ bool Creature::InitEntry(uint32 Entry, const CreatureData* data) // Cancel load if no model defined if (!(cinfo->GetFirstValidModelId())) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has no model defined in table `creature_template`, can't load. ", Entry); + LOG_ERROR("db.query", "Creature (Entry: {}) has no model defined in table `creature_template`, can't load. ", Entry); return false; } uint32 displayID = ObjectMgr::ChooseDisplayId(GetCreatureTemplate(), data); if (!sObjectMgr->GetCreatureModelRandomGender(&displayID)) // Cancel load if no model defined { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has no model defined in table `creature_template`, can't load. ", Entry); + LOG_ERROR("db.query", "Creature (Entry: {}) has no model defined in table `creature_template`, can't load. ", Entry); return false; } @@ -1107,7 +1107,7 @@ bool Creature::Create(ObjectGuid::LowType guidlow, Map* map, uint32 phaseMask, u CreatureTemplate const* cinfo = sObjectMgr->GetCreatureTemplate(Entry); if (!cinfo) { - LOG_ERROR("sql.sql", "Creature::Create(): creature template (guidlow: {}, entry: {}) does not exist.", guidlow, Entry); + LOG_ERROR("db.query", "Creature::Create(): creature template (guidlow: {}, entry: {}) does not exist.", guidlow, Entry); return false; } @@ -1445,7 +1445,7 @@ void Creature::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask) // update in DB WorldDatabaseTransaction trans = WorldDatabase.BeginTransaction(); - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_CREATURE); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_CREATURE); stmt->SetData(0, m_spawnId); trans->Append(stmt); @@ -1609,7 +1609,7 @@ bool Creature::CreateFromProto(ObjectGuid::LowType guidlow, uint32 Entry, uint32 CreatureTemplate const* normalInfo = sObjectMgr->GetCreatureTemplate(Entry); if (!normalInfo) { - LOG_ERROR("sql.sql", "Creature::CreateFromProto(): creature template (guidlow: {}, entry: {}) does not exist.", guidlow, Entry); + LOG_ERROR("db.query", "Creature::CreateFromProto(): creature template (guidlow: {}, entry: {}) does not exist.", guidlow, Entry); return false; } @@ -1693,7 +1693,7 @@ bool Creature::LoadCreatureFromDB(ObjectGuid::LowType spawnId, Map* map, bool ad CreatureData const* data = sObjectMgr->GetCreatureData(spawnId); if (!data) { - LOG_ERROR("sql.sql", "Creature (SpawnId: {}) not found in table `creature`, can't load. ", spawnId); + LOG_ERROR("db.query", "Creature (SpawnId: {}) not found in table `creature`, can't load. ", spawnId); return false; } @@ -1831,7 +1831,7 @@ void Creature::DeleteFromDB() WorldDatabaseTransaction trans = WorldDatabase.BeginTransaction(); - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_CREATURE); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_CREATURE); stmt->SetData(0, m_spawnId); trans->Append(stmt); @@ -2691,7 +2691,7 @@ bool Creature::LoadCreaturesAddon(bool reload) SpellInfo const* AdditionalSpellInfo = sSpellMgr->GetSpellInfo(*itr); if (!AdditionalSpellInfo) { - LOG_ERROR("sql.sql", "Creature ({}) has wrong spell {} defined in `auras` field.", GetGUID().ToString(), *itr); + LOG_ERROR("db.query", "Creature ({}) has wrong spell {} defined in `auras` field.", GetGUID().ToString(), *itr); continue; } @@ -2699,7 +2699,7 @@ bool Creature::LoadCreaturesAddon(bool reload) if (HasAura(*itr)) { if (!reload) - LOG_ERROR("sql.sql", "Creature ({}) has duplicate aura (spell {}) in `auras` field.", GetGUID().ToString(), *itr); + LOG_ERROR("db.query", "Creature ({}) has duplicate aura (spell {}) in `auras` field.", GetGUID().ToString(), *itr); continue; } diff --git a/src/server/game/Entities/Creature/Creature.h b/src/server/game/Entities/Creature/Creature.h index 903ae70994e783..cfb429a19f6f3a 100644 --- a/src/server/game/Entities/Creature/Creature.h +++ b/src/server/game/Entities/Creature/Creature.h @@ -21,7 +21,7 @@ #include "Cell.h" #include "Common.h" #include "CreatureData.h" -#include "DatabaseEnv.h" +#include "DatabaseEnvFwd.h" #include "ItemTemplate.h" #include "LootMgr.h" #include "Unit.h" diff --git a/src/server/game/Entities/Creature/CreatureData.h b/src/server/game/Entities/Creature/CreatureData.h index 80e4b3c7b8fa26..c4b7f9807b67d7 100644 --- a/src/server/game/Entities/Creature/CreatureData.h +++ b/src/server/game/Entities/Creature/CreatureData.h @@ -21,7 +21,7 @@ #include "Cell.h" #include "Common.h" #include "DBCEnums.h" -#include "DatabaseEnv.h" +#include "DatabaseEnvFwd.h" #include "ItemTemplate.h" #include "LootMgr.h" #include "Unit.h" diff --git a/src/server/game/Entities/Creature/CreatureGroups.cpp b/src/server/game/Entities/Creature/CreatureGroups.cpp index c24edb79bd2c8e..f1064d0ca03629 100644 --- a/src/server/game/Entities/Creature/CreatureGroups.cpp +++ b/src/server/game/Entities/Creature/CreatureGroups.cpp @@ -21,6 +21,7 @@ #include "Log.h" #include "MoveSplineInit.h" #include "ObjectMgr.h" +#include "DatabaseEnv.h" FormationMgr::~FormationMgr() { @@ -111,13 +112,13 @@ void FormationMgr::LoadCreatureFormations() { if (!group_member.HasGroupFlag(std::underlying_type_t(GroupAIFlags::GROUP_AI_FLAG_SUPPORTED))) { - LOG_ERROR("sql.sql", "creature_formations table leader guid {} and member guid {} has unsupported GroupAI flag value ({}). Skipped", group_member.leaderGUID, memberGUID, group_member.groupAI); + LOG_ERROR("db.query", "creature_formations table leader guid {} and member guid {} has unsupported GroupAI flag value ({}). Skipped", group_member.leaderGUID, memberGUID, group_member.groupAI); continue; } if (!group_member.HasGroupFlag(std::underlying_type_t(GroupAIFlags::GROUP_AI_FLAG_FOLLOW_LEADER)) && (follow_dist > 0.0f || follow_angle > 0.0f)) { - LOG_ERROR("sql.sql", "creature_formations table member guid {} and leader guid {} cannot have follow distance or follow angle because don't have GROUP_AI_FLAG_FOLLOW_LEADER flag. Values are not gonna be used", memberGUID, group_member.leaderGUID); + LOG_ERROR("db.query", "creature_formations table member guid {} and leader guid {} cannot have follow distance or follow angle because don't have GROUP_AI_FLAG_FOLLOW_LEADER flag. Values are not gonna be used", memberGUID, group_member.leaderGUID); group_member.follow_dist = 0.0f; group_member.follow_angle = 0.0f; } @@ -132,7 +133,7 @@ void FormationMgr::LoadCreatureFormations() // Leader can have 0 AI flags - its allowed if (group_member.groupAI && !group_member.HasGroupFlag(std::underlying_type_t(GroupAIFlags::GROUP_AI_FLAG_SUPPORTED))) { - LOG_ERROR("sql.sql", "creature_formations table leader guid {} and member guid {} has unsupported GroupAI flag value ({}). Skipped", group_member.leaderGUID, memberGUID, group_member.groupAI); + LOG_ERROR("db.query", "creature_formations table leader guid {} and member guid {} has unsupported GroupAI flag value ({}). Skipped", group_member.leaderGUID, memberGUID, group_member.groupAI); continue; } @@ -140,19 +141,19 @@ void FormationMgr::LoadCreatureFormations() group_member.follow_angle = 0.0f; if (follow_dist > 0.0f || follow_angle > 0.0f) { - LOG_ERROR("sql.sql", "creature_formations table member guid {} and leader guid {} cannot have follow distance or follow angle. Values are not gonna be used", memberGUID, group_member.leaderGUID); + LOG_ERROR("db.query", "creature_formations table member guid {} and leader guid {} cannot have follow distance or follow angle. Values are not gonna be used", memberGUID, group_member.leaderGUID); } } if (!sObjectMgr->GetCreatureData(group_member.leaderGUID)) { - LOG_ERROR("sql.sql", "creature_formations table leader guid {} incorrect (does not exist). Skipped", group_member.leaderGUID); + LOG_ERROR("db.query", "creature_formations table leader guid {} incorrect (does not exist). Skipped", group_member.leaderGUID); continue; } if (!sObjectMgr->GetCreatureData(memberGUID)) { - LOG_ERROR("sql.sql", "creature_formations table member guid {} incorrect (does not exist). Skipped", memberGUID); + LOG_ERROR("db.query", "creature_formations table member guid {} incorrect (does not exist). Skipped", memberGUID); continue; } diff --git a/src/server/game/Entities/Creature/GossipDef.cpp b/src/server/game/Entities/Creature/GossipDef.cpp index 102cd4d5061d74..20fb20c954f152 100644 --- a/src/server/game/Entities/Creature/GossipDef.cpp +++ b/src/server/game/Entities/Creature/GossipDef.cpp @@ -250,7 +250,7 @@ void PlayerMenu::SendPointOfInterest(uint32 poiId) const PointOfInterest const* poi = sObjectMgr->GetPointOfInterest(poiId); if (!poi) { - LOG_ERROR("sql.sql", "Request to send non-existing POI (Id: {}), ignored.", poiId); + LOG_ERROR("db.query", "Request to send non-existing POI (Id: {}), ignored.", poiId); return; } diff --git a/src/server/game/Entities/GameObject/GameObject.cpp b/src/server/game/Entities/GameObject/GameObject.cpp index 1365834de96b75..16fa016b505222 100644 --- a/src/server/game/Entities/GameObject/GameObject.cpp +++ b/src/server/game/Entities/GameObject/GameObject.cpp @@ -35,6 +35,7 @@ #include "Transport.h" #include "UpdateFieldFlags.h" #include "World.h" +#include "DatabaseEnv.h" #include #include #include @@ -273,7 +274,7 @@ bool GameObject::Create(ObjectGuid::LowType guidlow, uint32 name_id, Map* map, u GameObjectTemplate const* goinfo = sObjectMgr->GetGameObjectTemplate(name_id); if (!goinfo) { - LOG_ERROR("sql.sql", "Gameobject (GUID: {} Entry: {}) not created: non-existing entry in `gameobject_template`. Map: {} (X: {} Y: {} Z: {})", guidlow, name_id, map->GetId(), x, y, z); + LOG_ERROR("db.query", "Gameobject (GUID: {} Entry: {}) not created: non-existing entry in `gameobject_template`. Map: {} (X: {} Y: {} Z: {})", guidlow, name_id, map->GetId(), x, y, z); return false; } @@ -283,7 +284,7 @@ bool GameObject::Create(ObjectGuid::LowType guidlow, uint32 name_id, Map* map, u if (goinfo->type >= MAX_GAMEOBJECT_TYPE) { - LOG_ERROR("sql.sql", "Gameobject (GUID: {} Entry: {}) not created: non-existing GO type '{}' in `gameobject_template`. It will crash client if created.", guidlow, name_id, goinfo->type); + LOG_ERROR("db.query", "Gameobject (GUID: {} Entry: {}) not created: non-existing GO type '{}' in `gameobject_template`. It will crash client if created.", guidlow, name_id, goinfo->type); return false; } @@ -1082,7 +1083,7 @@ void GameObject::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask, bool uint8 index = 0; - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_GAMEOBJECT); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_GAMEOBJECT); stmt->SetData(0, m_spawnId); trans->Append(stmt); @@ -1123,7 +1124,7 @@ bool GameObject::LoadGameObjectFromDB(ObjectGuid::LowType spawnId, Map* map, boo if (!data) { - LOG_ERROR("sql.sql", "Gameobject (GUID: {}) not found in table `gameobject`, can't load. ", spawnId); + LOG_ERROR("db.query", "Gameobject (GUID: {}) not found in table `gameobject`, can't load. ", spawnId); return false; } @@ -1187,7 +1188,7 @@ void GameObject::DeleteFromDB() GetMap()->RemoveGORespawnTime(m_spawnId); sObjectMgr->DeleteGOData(m_spawnId); - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_GAMEOBJECT); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_GAMEOBJECT); stmt->SetData(0, m_spawnId); WorldDatabase.Execute(stmt); @@ -1751,7 +1752,7 @@ void GameObject::Use(Unit* user) //provide error, no fishable zone or area should be 0 if (!zone_skill) - LOG_ERROR("sql.sql", "Fishable areaId {} are not properly defined in `skill_fishing_base_level`.", subzone); + LOG_ERROR("db.query", "Fishable areaId {} are not properly defined in `skill_fishing_base_level`.", subzone); int32 skill = player->GetSkillValue(SKILL_FISHING); @@ -2599,7 +2600,7 @@ void GameObject::SaveInstanceData(uint8 state) uint32 id = GetInstanceId(); uint32 guid = GetSpawnId(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INSERT_INSTANCE_SAVED_DATA); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INSERT_INSTANCE_SAVED_DATA); stmt->SetData(0, id); stmt->SetData(1, guid); stmt->SetData(2, state); @@ -2613,7 +2614,7 @@ void GameObject::UpdateInstanceData(uint8 state) uint32 id = GetInstanceId(); uint32 guid = GetSpawnId(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPDATE_INSTANCE_SAVED_DATA); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPDATE_INSTANCE_SAVED_DATA); stmt->SetData(0, state); stmt->SetData(1, guid); stmt->SetData(2, id); diff --git a/src/server/game/Entities/GameObject/GameObject.h b/src/server/game/Entities/GameObject/GameObject.h index 61962e75dd545c..993cebf8a9424e 100644 --- a/src/server/game/Entities/GameObject/GameObject.h +++ b/src/server/game/Entities/GameObject/GameObject.h @@ -19,7 +19,7 @@ #define AZEROTHCORE_GAMEOBJECT_H #include "Common.h" -#include "DatabaseEnv.h" +#include "DatabaseEnvFwd.h" #include "G3D/Quat.h" #include "LootMgr.h" #include "Object.h" diff --git a/src/server/game/Entities/Item/Item.cpp b/src/server/game/Entities/Item/Item.cpp index bfcb13892e5ff1..79fe4c350c8953 100644 --- a/src/server/game/Entities/Item/Item.cpp +++ b/src/server/game/Entities/Item/Item.cpp @@ -40,7 +40,7 @@ void AddItemsSetItem(Player* player, Item* item) if (!set) { - LOG_ERROR("sql.sql", "Item set {} for item (id {}) not found, mods not applied.", setid, proto->ItemId); + LOG_ERROR("db.query", "Item set {} for item (id {}) not found, mods not applied.", setid, proto->ItemId); return; } @@ -125,7 +125,7 @@ void RemoveItemsSetItem(Player* player, ItemTemplate const* proto) if (!set) { - LOG_ERROR("sql.sql", "Item set #{} for item #{} not found, mods not removed.", setid, proto->ItemId); + LOG_ERROR("db.query", "Item set #{} for item #{} not found, mods not removed.", setid, proto->ItemId); return; } @@ -348,7 +348,7 @@ void Item::SaveToDB(CharacterDatabaseTransaction trans) case ITEM_CHANGED: { uint8 index = 0; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(uState == ITEM_NEW ? CHAR_REP_ITEM_INSTANCE : CHAR_UPD_ITEM_INSTANCE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(uState == ITEM_NEW ? CHAR_REP_ITEM_INSTANCE : CHAR_UPD_ITEM_INSTANCE); stmt->SetData( index, GetEntry()); stmt->SetData(++index, GetOwnerGUID().GetCounter()); stmt->SetData(++index, GetGuidValue(ITEM_FIELD_CREATOR).GetCounter()); @@ -391,7 +391,7 @@ void Item::SaveToDB(CharacterDatabaseTransaction trans) } case ITEM_REMOVED: { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE); stmt->SetData(0, guid); trans->Append(stmt); @@ -505,7 +505,7 @@ bool Item::LoadFromDB(ObjectGuid::LowType guid, ObjectGuid owner_guid, Field* fi if (need_save) // normal item changed state set not work at loading { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ITEM_INSTANCE_ON_LOAD); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ITEM_INSTANCE_ON_LOAD); stmt->SetData(0, GetUInt32Value(ITEM_FIELD_DURATION)); stmt->SetData(1, GetUInt32Value(ITEM_FIELD_FLAGS)); stmt->SetData(2, GetUInt32Value(ITEM_FIELD_DURABILITY)); @@ -520,7 +520,7 @@ bool Item::LoadFromDB(ObjectGuid::LowType guid, ObjectGuid owner_guid, Field* fi void Item::DeleteFromDB(CharacterDatabaseTransaction trans, ObjectGuid::LowType itemGuid) { sScriptMgr->OnGlobalItemDelFromDB(trans, itemGuid); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE); stmt->SetData(0, itemGuid); trans->Append(stmt); } @@ -533,7 +533,7 @@ void Item::DeleteFromDB(CharacterDatabaseTransaction trans) /*static*/ void Item::DeleteFromInventoryDB(CharacterDatabaseTransaction trans, ObjectGuid::LowType itemGuid) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INVENTORY_BY_ITEM); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INVENTORY_BY_ITEM); stmt->SetData(0, itemGuid); trans->Append(stmt); } @@ -635,7 +635,7 @@ int32 Item::GenerateItemRandomPropertyId(uint32 item_id) // item can have not null only one from field values if ((itemProto->RandomProperty) && (itemProto->RandomSuffix)) { - LOG_ERROR("sql.sql", "Item template {} have RandomProperty == {} and RandomSuffix == {}, but must have one from field =0", itemProto->ItemId, itemProto->RandomProperty, itemProto->RandomSuffix); + LOG_ERROR("db.query", "Item template {} have RandomProperty == {} and RandomSuffix == {}, but must have one from field =0", itemProto->ItemId, itemProto->RandomProperty, itemProto->RandomSuffix); return 0; } @@ -646,7 +646,7 @@ int32 Item::GenerateItemRandomPropertyId(uint32 item_id) ItemRandomPropertiesEntry const* random_id = sItemRandomPropertiesStore.LookupEntry(randomPropId); if (!random_id) { - LOG_ERROR("sql.sql", "Enchantment id #{} used but it doesn't have records in 'ItemRandomProperties.dbc'", randomPropId); + LOG_ERROR("db.query", "Enchantment id #{} used but it doesn't have records in 'ItemRandomProperties.dbc'", randomPropId); return 0; } @@ -659,7 +659,7 @@ int32 Item::GenerateItemRandomPropertyId(uint32 item_id) ItemRandomSuffixEntry const* random_id = sItemRandomSuffixStore.LookupEntry(randomPropId); if (!random_id) { - LOG_ERROR("sql.sql", "Enchantment id #{} used but it doesn't have records in sItemRandomSuffixStore.", randomPropId); + LOG_ERROR("db.query", "Enchantment id #{} used but it doesn't have records in sItemRandomSuffixStore.", randomPropId); return 0; } @@ -1175,7 +1175,7 @@ void Item::SaveRefundDataToDB() { CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_REFUND_INSTANCE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_REFUND_INSTANCE); stmt->SetData(0, GetGUID().GetCounter()); trans->Append(stmt); @@ -1193,7 +1193,7 @@ void Item::DeleteRefundDataFromDB(CharacterDatabaseTransaction* trans) { if (trans) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_REFUND_INSTANCE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_REFUND_INSTANCE); stmt->SetData(0, GetGUID().GetCounter()); (*trans)->Append(stmt); } @@ -1271,7 +1271,7 @@ void Item::ClearSoulboundTradeable(Player* currentOwner) allowedGUIDs.clear(); SetState(ITEM_CHANGED, currentOwner); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_BOP_TRADE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_BOP_TRADE); stmt->SetData(0, GetGUID().GetCounter()); CharacterDatabase.Execute(stmt); } diff --git a/src/server/game/Entities/Item/Item.h b/src/server/game/Entities/Item/Item.h index 300e7a6a17983b..5c1702a920eb67 100644 --- a/src/server/game/Entities/Item/Item.h +++ b/src/server/game/Entities/Item/Item.h @@ -19,7 +19,7 @@ #define AZEROTHCORE_ITEM_H #include "Common.h" -#include "DatabaseEnv.h" +#include "DatabaseEnvFwd.h" #include "ItemTemplate.h" #include "LootMgr.h" #include "Object.h" diff --git a/src/server/game/Entities/Item/ItemEnchantmentMgr.cpp b/src/server/game/Entities/Item/ItemEnchantmentMgr.cpp index 6696e66b9818b7..2931d434e33aad 100644 --- a/src/server/game/Entities/Item/ItemEnchantmentMgr.cpp +++ b/src/server/game/Entities/Item/ItemEnchantmentMgr.cpp @@ -89,7 +89,7 @@ uint32 GetItemEnchantMod(int32 entry) EnchantmentStore::const_iterator tab = RandomItemEnch.find(entry); if (tab == RandomItemEnch.end()) { - LOG_ERROR("sql.sql", "Item RandomProperty / RandomSuffix id #{} used in `item_template` but it does not have records in `item_enchantment_template` table.", entry); + LOG_ERROR("db.query", "Item RandomProperty / RandomSuffix id #{} used in `item_template` but it does not have records in `item_enchantment_template` table.", entry); return 0; } diff --git a/src/server/game/Entities/Object/Object.cpp b/src/server/game/Entities/Object/Object.cpp index a4b218b361e737..08d35f1e37500c 100644 --- a/src/server/game/Entities/Object/Object.cpp +++ b/src/server/game/Entities/Object/Object.cpp @@ -2292,7 +2292,7 @@ GameObject* Map::SummonGameObject(uint32 entry, float x, float y, float z, float GameObjectTemplate const* goinfo = sObjectMgr->GetGameObjectTemplate(entry); if (!goinfo) { - LOG_ERROR("sql.sql", "Gameobject template {} not found in database!", entry); + LOG_ERROR("db.query", "Gameobject template {} not found in database!", entry); return nullptr; } @@ -2362,7 +2362,7 @@ GameObject* WorldObject::SummonGameObject(uint32 entry, float x, float y, float GameObjectTemplate const* goinfo = sObjectMgr->GetGameObjectTemplate(entry); if (!goinfo) { - LOG_ERROR("sql.sql", "Gameobject template {} not found in database!", entry); + LOG_ERROR("db.query", "Gameobject template {} not found in database!", entry); return nullptr; } diff --git a/src/server/game/Entities/Pet/Pet.cpp b/src/server/game/Entities/Pet/Pet.cpp index 01b8fb14665f71..88985eee362eb8 100644 --- a/src/server/game/Entities/Pet/Pet.cpp +++ b/src/server/game/Entities/Pet/Pet.cpp @@ -134,28 +134,25 @@ class PetLoadQueryHolder : public CharacterDatabaseQueryHolder MAX }; - PetLoadQueryHolder(ObjectGuid::LowType ownerGuid, uint32 petNumber) + PetLoadQueryHolder(ObjectGuid::LowType ownerGuid, uint32 petNumber) : CharacterDatabaseQueryHolder("PetLoadQueryHolder") { - SetSize(MAX); - - CharacterDatabasePreparedStatement* stmt = nullptr; - + CharacterDatabasePreparedStatement stmt = nullptr; stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PET_DECLINED_NAME); stmt->SetData(0, ownerGuid); stmt->SetData(1, petNumber); - SetPreparedQuery(DECLINED_NAMES, stmt); + AddPreparedQuery(DECLINED_NAMES, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PET_AURA); stmt->SetData(0, petNumber); - SetPreparedQuery(AURAS, stmt); + AddPreparedQuery(AURAS, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PET_SPELL); stmt->SetData(0, petNumber); - SetPreparedQuery(SPELLS, stmt); + AddPreparedQuery(SPELLS, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PET_SPELL_COOLDOWN); stmt->SetData(0, petNumber); - SetPreparedQuery(COOLDOWNS, stmt); + AddPreparedQuery(COOLDOWNS, stmt); } }; @@ -536,7 +533,7 @@ void Pet::SavePetToDB(PetSaveMode mode) trans = CharacterDatabase.BeginTransaction(); // remove current data - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_PET_BY_ID); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_PET_BY_ID); stmt->SetData(0, m_charmInfo->GetPetNumber()); trans->Append(stmt); @@ -592,7 +589,7 @@ void Pet::DeleteFromDB(ObjectGuid::LowType guidlow) { CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_PET_BY_ID); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_PET_BY_ID); stmt->SetData(0, guidlow); trans->Append(stmt); @@ -1486,7 +1483,7 @@ void Pet::_LoadSpellCooldowns(PreparedQueryResult result) void Pet::_SaveSpellCooldowns(CharacterDatabaseTransaction trans) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PET_SPELL_COOLDOWNS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PET_SPELL_COOLDOWNS); stmt->SetData(0, m_charmInfo->GetPetNumber()); trans->Append(stmt); @@ -1541,7 +1538,7 @@ void Pet::_SaveSpells(CharacterDatabaseTransaction trans) if (itr->second.type == PETSPELL_FAMILY) continue; - CharacterDatabasePreparedStatement* stmt; + CharacterDatabasePreparedStatement stmt; switch (itr->second.state) { @@ -1662,7 +1659,7 @@ void Pet::_LoadAuras(PreparedQueryResult result, uint32 timediff) void Pet::_SaveAuras(CharacterDatabaseTransaction trans) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PET_AURAS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PET_AURAS); stmt->SetData(0, m_charmInfo->GetPetNumber()); trans->Append(stmt); @@ -1722,7 +1719,7 @@ void Pet::_SaveAuras(CharacterDatabaseTransaction trans) uint8 index = 0; - CharacterDatabasePreparedStatement* stmt2 = CharacterDatabase.GetPreparedStatement(CHAR_INS_PET_AURA); + CharacterDatabasePreparedStatement stmt2 = CharacterDatabase.GetPreparedStatement(CHAR_INS_PET_AURA); stmt2->SetData(index++, m_charmInfo->GetPetNumber()); stmt2->SetData(index++, casterGUID.GetRawValue()); stmt2->SetData(index++, itr->second->GetId()); @@ -1752,7 +1749,7 @@ bool Pet::addSpell(uint32 spellId, ActiveStates active /*= ACT_DECIDE*/, PetSpel { LOG_ERROR("entities.pet", "Pet::addSpell: Non-existed in SpellStore spell #{} request, deleting for all pets in `pet_spell`.", spellId); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_PET_SPELL); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_PET_SPELL); stmt->SetData(0, spellId); CharacterDatabase.Execute(stmt); } diff --git a/src/server/game/Entities/Player/Player.cpp b/src/server/game/Entities/Player/Player.cpp index 1805c42b2ba2d6..d48875dfa0f30c 100644 --- a/src/server/game/Entities/Player/Player.cpp +++ b/src/server/game/Entities/Player/Player.cpp @@ -3569,7 +3569,7 @@ void Player::_LoadSpellCooldowns(PreparedQueryResult result) void Player::_SaveSpellCooldowns(CharacterDatabaseTransaction trans, bool logout) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SPELL_COOLDOWN); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SPELL_COOLDOWN); stmt->SetData(0, GetGUID().GetCounter()); trans->Append(stmt); @@ -3955,7 +3955,7 @@ void Player::DeleteFromDB(ObjectGuid::LowType lowGuid, uint32 accountId, bool up // Remove signs from petitions (also remove petitions if owner); RemovePetitionsAndSigns(playerGuid, 10); - CharacterDatabasePreparedStatement* stmt = nullptr; + CharacterDatabasePreparedStatement stmt = nullptr; switch (charDelete_method) { @@ -4286,7 +4286,7 @@ void Player::DeleteOldCharacters(uint32 keepDays) LOG_INFO("server.loading", "Player::DeleteOldChars: Deleting all characters which have been deleted {} days before...", keepDays); LOG_INFO("server.loading", " "); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_OLD_CHARS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_OLD_CHARS); stmt->SetData(0, uint32(GameTime::GetGameTime().count() - time_t(keepDays * DAY))); PreparedQueryResult result = CharacterDatabase.Query(stmt); @@ -4491,7 +4491,7 @@ void Player::KillPlayer() void Player::OfflineResurrect(ObjectGuid const guid, CharacterDatabaseTransaction trans) { Corpse::DeleteFromDB(guid, trans); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG); stmt->SetData(0, uint16(AT_LOGIN_RESURRECT)); stmt->SetData(1, guid.GetCounter()); CharacterDatabase.ExecuteOrAppend(trans, stmt); @@ -4602,7 +4602,7 @@ void Player::SpawnCorpseBones(bool triggerSave /*= true*/) CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); // pussywizard: update only ghost flag instead of whole character table entry! data integrity is crucial - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_REMOVE_GHOST); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_REMOVE_GHOST); stmt->SetData(0, GetGUID().GetCounter()); trans->Append(stmt); @@ -6189,7 +6189,7 @@ void Player::ModifyHonorPoints(int32 value, CharacterDatabaseTransaction trans) if (trans) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UDP_CHAR_HONOR_POINTS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UDP_CHAR_HONOR_POINTS); stmt->SetData(0, newValue); stmt->SetData(1, GetGUID().GetCounter()); trans->Append(stmt); @@ -6205,7 +6205,7 @@ void Player::ModifyArenaPoints(int32 value, CharacterDatabaseTransaction trans) if (trans) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UDP_CHAR_ARENA_POINTS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UDP_CHAR_ARENA_POINTS); stmt->SetData(0, newValue); stmt->SetData(1, GetGUID().GetCounter()); trans->Append(stmt); @@ -6214,7 +6214,7 @@ void Player::ModifyArenaPoints(int32 value, CharacterDatabaseTransaction trans) uint32 Player::GetArenaTeamIdFromDB(ObjectGuid guid, uint8 type) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ARENA_TEAM_ID_BY_PLAYER_GUID); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ARENA_TEAM_ID_BY_PLAYER_GUID); stmt->SetData(0, guid.GetCounter()); stmt->SetData(1, type); PreparedQueryResult result = CharacterDatabase.Query(stmt); @@ -6230,7 +6230,7 @@ uint32 Player::GetZoneIdFromDB(ObjectGuid guid) { ObjectGuid::LowType guidLow = guid.GetCounter(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_ZONE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_ZONE); stmt->SetData(0, guidLow); PreparedQueryResult result = CharacterDatabase.Query(stmt); @@ -9007,7 +9007,7 @@ void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent) if (mode == PET_SAVE_NOT_IN_SLOT && m_petStable && m_petStable->CurrentPet) { // Handle removing pet while it is in "temporarily unsummoned" state, for example on mount - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_PET_SLOT_BY_ID); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_PET_SLOT_BY_ID); stmt->SetData(0, PET_SAVE_NOT_IN_SLOT); stmt->SetData(1, GetGUID().GetCounter()); stmt->SetData(2, m_petStable->CurrentPet->PetNumber); @@ -10052,13 +10052,13 @@ void Player::RemovePetitionsAndSigns(ObjectGuid guid, uint32 type) if (type == 10) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ALL_PETITION_SIGNATURES); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ALL_PETITION_SIGNATURES); stmt->SetData(0, guid.GetCounter()); CharacterDatabase.Execute(stmt); } else { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_SIGNATURE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_SIGNATURE); stmt->SetData(0, guid.GetCounter()); stmt->SetData(1, uint8(type)); CharacterDatabase.Execute(stmt); @@ -10067,7 +10067,7 @@ void Player::RemovePetitionsAndSigns(ObjectGuid guid, uint32 type) CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); if (type == 10) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_BY_OWNER); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_BY_OWNER); stmt->SetData(0, guid.GetCounter()); trans->Append(stmt); @@ -10080,7 +10080,7 @@ void Player::RemovePetitionsAndSigns(ObjectGuid guid, uint32 type) } else { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_BY_OWNER_AND_TYPE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_BY_OWNER_AND_TYPE); stmt->SetData(0, guid.GetCounter()); stmt->SetData(1, uint8(type)); trans->Append(stmt); @@ -10099,7 +10099,7 @@ void Player::RemovePetitionsAndSigns(ObjectGuid guid, uint32 type) void Player::LeaveAllArenaTeams(ObjectGuid guid) { // xinef: sync query - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PLAYER_ARENA_TEAMS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PLAYER_ARENA_TEAMS); stmt->SetData(0, guid.GetCounter()); PreparedQueryResult result = CharacterDatabase.Query(stmt); @@ -11251,7 +11251,7 @@ void Player::LeaveBattleground(Battleground* bg) { if (sWorld->getBoolConfig(CONFIG_BATTLEGROUND_TRACK_DESERTERS)) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_DESERTER_TRACK); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_DESERTER_TRACK); stmt->SetData(0, GetGUID().GetCounter()); stmt->SetData(1, BG_DESERTION_TYPE_LEAVE_BG); CharacterDatabase.Execute(stmt); @@ -13623,7 +13623,7 @@ void Player::_LoadSkills(PreparedQueryResult result) { LOG_ERROR("entities.player", "Character {} has skill {} with value 0. Will be deleted.", GetGUID().ToString(), skill); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER_SKILL); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER_SKILL); stmt->SetData(0, GetGUID().GetCounter()); stmt->SetData(1, skill); @@ -14463,7 +14463,7 @@ void Player::_SaveEquipmentSets(CharacterDatabaseTransaction trans) { uint32 index = itr->first; EquipmentSet& eqset = itr->second; - CharacterDatabasePreparedStatement* stmt = nullptr; + CharacterDatabasePreparedStatement stmt = nullptr; uint8 j = 0; switch (eqset.state) { @@ -14515,7 +14515,7 @@ void Player::_SaveEntryPoint(CharacterDatabaseTransaction trans) if (!mEntry) return; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_ENTRY_POINT); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_ENTRY_POINT); stmt->SetData(0, GetGUID().GetCounter()); trans->Append(stmt); @@ -14553,7 +14553,7 @@ void Player::RemoveAtLoginFlag(AtLoginFlags flags, bool persist /*= false*/) if (persist) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_REM_AT_LOGIN_FLAG); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_REM_AT_LOGIN_FLAG); stmt->SetData(0, uint16(flags)); stmt->SetData(1, GetGUID().GetCounter()); @@ -14593,7 +14593,7 @@ void Player::SetMap(Map* map) void Player::_SaveCharacter(bool create, CharacterDatabaseTransaction trans) { - CharacterDatabasePreparedStatement* stmt = nullptr; + CharacterDatabasePreparedStatement stmt = nullptr; uint8 index = 0; auto finiteAlways = [](float f) { return std::isfinite(f) ? f : 0.0f; }; @@ -14895,7 +14895,7 @@ void Player::_SaveGlyphs(CharacterDatabaseTransaction trans) if (!NeedToSaveGlyphs()) return; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_GLYPHS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_GLYPHS); stmt->SetData(0, GetGUID().GetCounter()); trans->Append(stmt); @@ -14939,7 +14939,7 @@ void Player::_LoadTalents(PreparedQueryResult result) void Player::_SaveTalents(CharacterDatabaseTransaction trans) { - CharacterDatabasePreparedStatement* stmt = nullptr; + CharacterDatabasePreparedStatement stmt = nullptr; for (PlayerTalentMap::iterator itr = m_talents.begin(); itr != m_talents.end();) { @@ -15135,7 +15135,7 @@ void Player::ActivateSpec(uint8 spec) // load them asynchronously { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_ACTIONS_SPEC); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_ACTIONS_SPEC); stmt->SetData(0, GetGUID().GetCounter()); stmt->SetData(1, m_activeSpec); @@ -15621,7 +15621,7 @@ void Player::SetRandomWinner(bool isWinner) m_IsBGRandomWinner = isWinner; if (m_IsBGRandomWinner) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_BATTLEGROUND_RANDOM); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_BATTLEGROUND_RANDOM); stmt->SetData(0, GetGUID().GetCounter()); CharacterDatabase.Execute(stmt); } @@ -15720,7 +15720,7 @@ void Player::_LoadBrewOfTheMonth(PreparedQueryResult result) draft.SendMailTo(trans, MailReceiver(this, GetGUID().GetCounter()), sender); // Update Event Id - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_BREW_OF_THE_MONTH); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_BREW_OF_THE_MONTH); stmt->SetData(0, GetGUID().GetCounter()); stmt->SetData(1, uint32(eventId)); trans->Append(stmt); @@ -15786,7 +15786,7 @@ void Player::_SaveInstanceTimeRestrictions(CharacterDatabaseTransaction trans) if (_instanceResetTimes.empty()) return; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ACCOUNT_INSTANCE_LOCK_TIMES); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ACCOUNT_INSTANCE_LOCK_TIMES); stmt->SetData(0, GetSession()->GetAccountId()); trans->Append(stmt); diff --git a/src/server/game/Entities/Player/PlayerGossip.cpp b/src/server/game/Entities/Player/PlayerGossip.cpp index e6fcb518cfc75e..b88104ad42418f 100644 --- a/src/server/game/Entities/Player/PlayerGossip.cpp +++ b/src/server/game/Entities/Player/PlayerGossip.cpp @@ -80,7 +80,7 @@ void Player::PrepareGossipMenu(WorldObject* source, uint32 menuId /*= 0*/, bool VendorItemData const* vendorItems = itr->second.ActionMenuID ? sObjectMgr->GetNpcVendorItemList(itr->second.ActionMenuID) : creature->GetVendorItems(); if (!vendorItems || vendorItems->Empty()) { - LOG_ERROR("sql.sql", "Creature {} have UNIT_NPC_FLAG_VENDOR but have empty trading item list.", creature->GetGUID().ToString()); + LOG_ERROR("db.query", "Creature {} have UNIT_NPC_FLAG_VENDOR but have empty trading item list.", creature->GetGUID().ToString()); canTalk = false; } break; @@ -143,7 +143,7 @@ void Player::PrepareGossipMenu(WorldObject* source, uint32 menuId /*= 0*/, bool canTalk = false; break; default: - LOG_ERROR("sql.sql", "Creature entry {} has unknown OptionType {} for menu {}", creature->GetEntry(), itr->second.OptionType, itr->second.MenuID); + LOG_ERROR("db.query", "Creature entry {} has unknown OptionType {} for menu {}", creature->GetEntry(), itr->second.OptionType, itr->second.MenuID); canTalk = false; break; } diff --git a/src/server/game/Entities/Player/PlayerMisc.cpp b/src/server/game/Entities/Player/PlayerMisc.cpp index 8c32b2cae0f410..f21bb7e4e0c5cf 100644 --- a/src/server/game/Entities/Player/PlayerMisc.cpp +++ b/src/server/game/Entities/Player/PlayerMisc.cpp @@ -21,6 +21,7 @@ #include "Player.h" #include "ScriptMgr.h" #include "WorldSession.h" +#include "DatabaseEnv.h" /*********************************************************/ /*** FLOOD FILTER SYSTEM ***/ @@ -83,7 +84,7 @@ void Player::SendAttackSwingNotInRange() void Player::SavePositionInDB(uint32 mapid, float x, float y, float z, float o, uint32 zone, ObjectGuid guid) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHARACTER_POSITION); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHARACTER_POSITION); stmt->SetData(0, x); stmt->SetData(1, y); @@ -98,7 +99,7 @@ void Player::SavePositionInDB(uint32 mapid, float x, float y, float z, float o, void Player::SavePositionInDB(WorldLocation const& loc, uint16 zoneId, ObjectGuid guid, CharacterDatabaseTransaction trans) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHARACTER_POSITION); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHARACTER_POSITION); stmt->SetData(0, loc.GetPositionX()); stmt->SetData(1, loc.GetPositionY()); @@ -113,7 +114,7 @@ void Player::SavePositionInDB(WorldLocation const& loc, uint16 zoneId, ObjectGui void Player::Customize(CharacterCustomizeInfo const* customizeInfo, CharacterDatabaseTransaction trans) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GENDER_AND_APPEARANCE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GENDER_AND_APPEARANCE); stmt->SetData(0, customizeInfo->Gender); stmt->SetData(1, customizeInfo->Skin); stmt->SetData(2, customizeInfo->Face); diff --git a/src/server/game/Entities/Player/PlayerQuest.cpp b/src/server/game/Entities/Player/PlayerQuest.cpp index 4056534a71e135..df64d2177806de 100644 --- a/src/server/game/Entities/Player/PlayerQuest.cpp +++ b/src/server/game/Entities/Player/PlayerQuest.cpp @@ -30,6 +30,7 @@ #include "SpellAuraEffects.h" #include "SpellMgr.h" #include "WorldSession.h" +#include "DatabaseEnv.h" /*********************************************************/ /*** QUEST SYSTEM ***/ diff --git a/src/server/game/Entities/Player/PlayerSettings.cpp b/src/server/game/Entities/Player/PlayerSettings.cpp index 7e45d03db76e3f..687dbb15e1d605 100644 --- a/src/server/game/Entities/Player/PlayerSettings.cpp +++ b/src/server/game/Entities/Player/PlayerSettings.cpp @@ -18,6 +18,7 @@ #include "Player.h" #include "StringConvert.h" #include "Tokenize.h" +#include "DatabaseEnv.h" /*********************************************************/ /*** PLAYER SETTINGS SYSTEM ***/ @@ -104,7 +105,7 @@ void Player::_SavePlayerSettings(CharacterDatabaseTransaction trans) data << setting.value << ' '; } - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_CHAR_SETTINGS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_CHAR_SETTINGS); stmt->SetData(0, GetGUID().GetCounter()); stmt->SetData(1, itr.first); stmt->SetData(2, data.str()); diff --git a/src/server/game/Entities/Player/PlayerStorage.cpp b/src/server/game/Entities/Player/PlayerStorage.cpp index 3c4feee114e4ba..527af5d31d4818 100644 --- a/src/server/game/Entities/Player/PlayerStorage.cpp +++ b/src/server/game/Entities/Player/PlayerStorage.cpp @@ -2588,7 +2588,7 @@ Item* Player::StoreNewItem(ItemPosCountVec const& dest, uint32 item, bool update for (++itr; itr != allowedLooters.end(); ++itr) ss << ' ' << (*itr).GetCounter(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ITEM_BOP_TRADE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ITEM_BOP_TRADE); stmt->SetData(0, pItem->GetGUID().GetCounter()); stmt->SetData(1, ss.str()); CharacterDatabase.Execute(stmt); @@ -3062,7 +3062,7 @@ void Player::DestroyItem(uint8 bag, uint8 slot, bool update) if (pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_WRAPPED)) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GIFT); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GIFT); stmt->SetData(0, pItem->GetGUID().GetCounter()); CharacterDatabase.Execute(stmt); } @@ -4900,7 +4900,7 @@ void Player::_LoadEntryPointData(PreparedQueryResult result) bool Player::LoadPositionFromDB(uint32& mapid, float& x, float& y, float& z, float& o, bool& in_flight, ObjectGuid::LowType guid) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_POSITION); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_POSITION); stmt->SetData(0, guid); PreparedQueryResult result = CharacterDatabase.Query(stmt); @@ -4926,7 +4926,7 @@ void Player::SetHomebind(WorldLocation const& loc, uint32 areaId) m_homebindAreaId = areaId; // update sql homebind - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_PLAYER_HOMEBIND); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_PLAYER_HOMEBIND); stmt->SetData(0, m_homebindMapId); stmt->SetData(1, m_homebindAreaId); stmt->SetData(2, m_homebindX); @@ -4992,7 +4992,7 @@ bool Player::LoadFromDB(ObjectGuid playerGuid, CharacterDatabaseQueryHolder cons if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS || (AccountMgr::IsPlayerAccount(GetSession()->GetSecurity()) && (sObjectMgr->IsReservedName(m_name) || sObjectMgr->IsProfanityName(m_name)))) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG); stmt->SetData(0, uint16(AT_LOGIN_RENAME)); stmt->SetData(1, guid); CharacterDatabase.Execute(stmt); @@ -5598,7 +5598,10 @@ bool Player::LoadFromDB(ObjectGuid playerGuid, CharacterDatabaseQueryHolder cons if (m_grantableLevels > 0) SetByteValue(PLAYER_FIELD_BYTES, 1, 0x01); - _LoadDeclinedNames(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_DECLINED_NAMES)); + if (sWorld->getBoolConfig(CONFIG_DECLINED_NAMES_USED)) + { + _LoadDeclinedNames(holder.GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_DECLINED_NAMES)); + } //m_achievementMgr->CheckAllAchievementCriteria(); // pussywizard: disabled this @@ -5999,7 +6002,7 @@ Item* Player::_LoadItem(CharacterDatabaseTransaction trans, uint32 zoneId, uint3 item = NewItemOrBag(proto); if (item->LoadFromDB(itemGuid, GetGUID(), fields, itemEntry)) { - CharacterDatabasePreparedStatement* stmt = nullptr; + CharacterDatabasePreparedStatement stmt = nullptr; // Do not allow to have item limited to another map/zone in alive state if (IsAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(), zoneId)) @@ -6137,7 +6140,7 @@ Item* Player::_LoadMailedItem(ObjectGuid const& playerGuid, Player* player, uint CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_MAIL_ITEM); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_MAIL_ITEM); stmt->SetData(0, itemGuid); trans->Append(stmt); @@ -6152,7 +6155,7 @@ Item* Player::_LoadMailedItem(ObjectGuid const& playerGuid, Player* player, uint { LOG_ERROR("entities.player", "Player::_LoadMailedItems: Item (GUID: {}) in mail ({}) doesn't exist, deleted from mail.", itemGuid, mailId); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM); stmt->SetData(0, itemGuid); CharacterDatabase.Execute(stmt); @@ -7033,7 +7036,7 @@ bool Player::_LoadHomeBind(PreparedQueryResult result) ok = true; else { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_HOMEBIND); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_HOMEBIND); stmt->SetData(0, GetGUID().GetCounter()); CharacterDatabase.Execute(stmt); } @@ -7047,7 +7050,7 @@ bool Player::_LoadHomeBind(PreparedQueryResult result) m_homebindY = info->positionY; m_homebindZ = info->positionZ; m_homebindO = info->orientation; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_PLAYER_HOMEBIND); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_PLAYER_HOMEBIND); stmt->SetData(0, GetGUID().GetCounter()); stmt->SetData(1, m_homebindMapId); stmt->SetData(2, m_homebindAreaId); @@ -7146,7 +7149,7 @@ void Player::SaveInventoryAndGoldToDB(CharacterDatabaseTransaction trans) void Player::SaveGoldToDB(CharacterDatabaseTransaction trans) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UDP_CHAR_MONEY); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UDP_CHAR_MONEY); stmt->SetData(0, GetMoney()); stmt->SetData(1, GetGUID().GetCounter()); trans->Append(stmt); @@ -7154,7 +7157,7 @@ void Player::SaveGoldToDB(CharacterDatabaseTransaction trans) void Player::_SaveActions(CharacterDatabaseTransaction trans) { - CharacterDatabasePreparedStatement* stmt = nullptr; + CharacterDatabasePreparedStatement stmt = nullptr; for (ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end();) { @@ -7202,7 +7205,7 @@ void Player::_SaveActions(CharacterDatabaseTransaction trans) void Player::_SaveAuras(CharacterDatabaseTransaction trans, bool logout) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_AURA); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_AURA); stmt->SetData(0, GetGUID().GetCounter()); trans->Append(stmt); @@ -7260,7 +7263,7 @@ void Player::_SaveAuras(CharacterDatabaseTransaction trans, bool logout) void Player::_SaveInventory(CharacterDatabaseTransaction trans) { - CharacterDatabasePreparedStatement* stmt = nullptr; + CharacterDatabasePreparedStatement stmt = nullptr; // force items in buyback slots to new state // and remove those that aren't already for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i) @@ -7403,7 +7406,7 @@ void Player::_SaveMail(CharacterDatabaseTransaction trans) return; } - CharacterDatabasePreparedStatement* stmt = nullptr; + CharacterDatabasePreparedStatement stmt = nullptr; for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr) { @@ -7479,7 +7482,7 @@ void Player::_SaveQuestStatus(CharacterDatabaseTransaction trans) QuestStatusSaveMap::iterator saveItr; QuestStatusMap::iterator statusItr; - CharacterDatabasePreparedStatement* stmt = nullptr; + CharacterDatabasePreparedStatement stmt = nullptr; bool keepAbandoned = !(sWorld->GetCleaningFlags() & CharacterDatabaseCleaner::CLEANING_FLAG_QUESTSTATUS); @@ -7548,7 +7551,7 @@ void Player::_SaveDailyQuestStatus(CharacterDatabaseTransaction trans) // save last daily quest time for all quests: we need only mostly reset time for reset check anyway // we don't need transactions here. - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_DAILY_CHAR); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_DAILY_CHAR); stmt->SetData(0, GetGUID().GetCounter()); trans->Append(stmt); for (uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx) @@ -7582,7 +7585,7 @@ void Player::_SaveWeeklyQuestStatus(CharacterDatabaseTransaction trans) return; // we don't need transactions here. - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_WEEKLY_CHAR); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_WEEKLY_CHAR); stmt->SetData(0, GetGUID().GetCounter()); trans->Append(stmt); @@ -7607,7 +7610,7 @@ void Player::_SaveSeasonalQuestStatus(CharacterDatabaseTransaction trans) } // we don't need transactions here. - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_SEASONAL_CHAR); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_SEASONAL_CHAR); stmt->SetData(0, GetGUID().GetCounter()); trans->Append(stmt); @@ -7639,7 +7642,7 @@ void Player::_SaveMonthlyQuestStatus(CharacterDatabaseTransaction trans) return; // we don't need transactions here. - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_MONTHLY_CHAR); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_MONTHLY_CHAR); stmt->SetData(0, GetGUID().GetCounter()); trans->Append(stmt); @@ -7657,7 +7660,7 @@ void Player::_SaveMonthlyQuestStatus(CharacterDatabaseTransaction trans) void Player::_SaveSkills(CharacterDatabaseTransaction trans) { - CharacterDatabasePreparedStatement* stmt = nullptr; + CharacterDatabasePreparedStatement stmt = nullptr; // we don't need transactions here. for (SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end();) { @@ -7713,7 +7716,7 @@ void Player::_SaveSkills(CharacterDatabaseTransaction trans) void Player::_SaveSpells(CharacterDatabaseTransaction trans) { - CharacterDatabasePreparedStatement* stmt = nullptr; + CharacterDatabasePreparedStatement stmt = nullptr; for (PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end();) { @@ -7764,7 +7767,7 @@ void Player::_SaveStats(CharacterDatabaseTransaction trans) if (!sWorld->getIntConfig(CONFIG_MIN_LEVEL_STAT_SAVE) || GetLevel() < sWorld->getIntConfig(CONFIG_MIN_LEVEL_STAT_SAVE)) return; - CharacterDatabasePreparedStatement* stmt = nullptr; + CharacterDatabasePreparedStatement stmt = nullptr; stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_STATS); stmt->SetData(0, GetGUID().GetCounter()); diff --git a/src/server/game/Entities/Player/PlayerUpdates.cpp b/src/server/game/Entities/Player/PlayerUpdates.cpp index 4e703b43392d63..a9752b3fcfedf1 100644 --- a/src/server/game/Entities/Player/PlayerUpdates.cpp +++ b/src/server/game/Entities/Player/PlayerUpdates.cpp @@ -37,6 +37,7 @@ #include "Vehicle.h" #include "WeatherMgr.h" #include "WorldStatePackets.h" +#include "DatabaseEnv.h" /// @todo: this import is not necessary for compilation and marked as unused by the IDE // however, for some reasons removing it would cause a damn linking issue @@ -127,7 +128,7 @@ void Player::Update(uint32 p_time) if (GetSession()->m_muteTime && GetSession()->m_muteTime < now) { GetSession()->m_muteTime = 0; - LoginDatabasePreparedStatement* stmt = + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_MUTE_TIME); stmt->SetData(0, 0); // Set the mute time to 0 stmt->SetData(1, ""); @@ -434,7 +435,7 @@ void Player::UpdateNextMailTimeAndUnreads() // Update the next delivery time and unread mails time_t cTime = GameTime::GetGameTime().count(); // Get the next delivery time - CharacterDatabasePreparedStatement* stmtNextDeliveryTime = + CharacterDatabasePreparedStatement stmtNextDeliveryTime = CharacterDatabase.GetPreparedStatement(CHAR_SEL_NEXT_MAIL_DELIVERYTIME); stmtNextDeliveryTime->SetData(0, GetGUID().GetCounter()); stmtNextDeliveryTime->SetData(1, uint32(cTime)); @@ -447,7 +448,7 @@ void Player::UpdateNextMailTimeAndUnreads() } // Get unread mails count - CharacterDatabasePreparedStatement* stmtUnreadAmount = + CharacterDatabasePreparedStatement stmtUnreadAmount = CharacterDatabase.GetPreparedStatement( CHAR_SEL_CHARACTER_MAILCOUNT_UNREAD_SYNCH); stmtUnreadAmount->SetData(0, GetGUID().GetCounter()); @@ -2153,7 +2154,7 @@ void Player::UpdateSpecCount(uint8 count) ActivateSpec(0); CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = nullptr; + CharacterDatabasePreparedStatement stmt = nullptr; // Copy spec data if (count > curCount) diff --git a/src/server/game/Entities/Player/SocialMgr.cpp b/src/server/game/Entities/Player/SocialMgr.cpp index 2893c99f75ae43..bd49af7b2dbf93 100644 --- a/src/server/game/Entities/Player/SocialMgr.cpp +++ b/src/server/game/Entities/Player/SocialMgr.cpp @@ -48,7 +48,7 @@ bool PlayerSocial::AddToSocialList(ObjectGuid friendGuid, SocialFlag flag) { itr->second.Flags |= flag; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_CHARACTER_SOCIAL_FLAGS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_CHARACTER_SOCIAL_FLAGS); stmt->SetData(0, itr->second.Flags); stmt->SetData(1, GetPlayerGUID().GetCounter()); @@ -60,7 +60,7 @@ bool PlayerSocial::AddToSocialList(ObjectGuid friendGuid, SocialFlag flag) { m_playerSocialMap[friendGuid].Flags |= flag; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_SOCIAL); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_SOCIAL); stmt->SetData(0, GetPlayerGUID().GetCounter()); stmt->SetData(1, friendGuid.GetCounter()); @@ -81,7 +81,7 @@ void PlayerSocial::RemoveFromSocialList(ObjectGuid friendGuid, SocialFlag flag) if (itr->second.Flags == 0) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER_SOCIAL); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER_SOCIAL); stmt->SetData(0, GetPlayerGUID().GetCounter()); stmt->SetData(1, friendGuid.GetCounter()); @@ -92,7 +92,7 @@ void PlayerSocial::RemoveFromSocialList(ObjectGuid friendGuid, SocialFlag flag) } else { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_REM_CHARACTER_SOCIAL_FLAGS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_REM_CHARACTER_SOCIAL_FLAGS); stmt->SetData(0, flag); stmt->SetData(1, GetPlayerGUID().GetCounter()); @@ -110,7 +110,7 @@ void PlayerSocial::SetFriendNote(ObjectGuid friendGuid, std::string note) utf8truncate(note, 48); // DB and client size limitation - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHARACTER_SOCIAL_NOTE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHARACTER_SOCIAL_NOTE); stmt->SetData(0, note); stmt->SetData(1, GetPlayerGUID().GetCounter()); diff --git a/src/server/game/Entities/Player/SocialMgr.h b/src/server/game/Entities/Player/SocialMgr.h index cf495705d4b615..192e189bd2edc7 100644 --- a/src/server/game/Entities/Player/SocialMgr.h +++ b/src/server/game/Entities/Player/SocialMgr.h @@ -19,7 +19,7 @@ #define __ACORE_SOCIALMGR_H #include "Common.h" -#include "DatabaseEnv.h" +#include "DatabaseEnvFwd.h" #include "ObjectGuid.h" #include diff --git a/src/server/game/Entities/Transport/Transport.cpp b/src/server/game/Entities/Transport/Transport.cpp index c442ff35c698e0..b21110db730991 100644 --- a/src/server/game/Entities/Transport/Transport.cpp +++ b/src/server/game/Entities/Transport/Transport.cpp @@ -702,7 +702,7 @@ bool StaticTransport::Create(ObjectGuid::LowType guidlow, uint32 name_id, Map* m GameObjectTemplate const* goinfo = sObjectMgr->GetGameObjectTemplate(name_id); if (!goinfo) { - LOG_ERROR("sql.sql", "Gameobject (GUID: {} Entry: {}) not created: non-existing entry in `gameobject_template`. Map: {} (X: {} Y: {} Z: {})", guidlow, name_id, map->GetId(), x, y, z); + LOG_ERROR("db.query", "Gameobject (GUID: {} Entry: {}) not created: non-existing entry in `gameobject_template`. Map: {} (X: {} Y: {} Z: {})", guidlow, name_id, map->GetId(), x, y, z); return false; } @@ -712,7 +712,7 @@ bool StaticTransport::Create(ObjectGuid::LowType guidlow, uint32 name_id, Map* m if (goinfo->type >= MAX_GAMEOBJECT_TYPE) { - LOG_ERROR("sql.sql", "Gameobject (GUID: {} Entry: {}) not created: non-existing GO type '{}' in `gameobject_template`. It will crash client if created.", guidlow, name_id, goinfo->type); + LOG_ERROR("db.query", "Gameobject (GUID: {} Entry: {}) not created: non-existing GO type '{}' in `gameobject_template`. It will crash client if created.", guidlow, name_id, goinfo->type); return false; } diff --git a/src/server/game/Entities/Unit/Unit.cpp b/src/server/game/Entities/Unit/Unit.cpp index c9c3127d02aec6..7b540a283151d0 100644 --- a/src/server/game/Entities/Unit/Unit.cpp +++ b/src/server/game/Entities/Unit/Unit.cpp @@ -19831,7 +19831,7 @@ bool Unit::HandleSpellClick(Unit* clicker, int8 seatId) if (!valid) { - LOG_ERROR("sql.sql", "Spell {} specified in npc_spellclick_spells is not a valid vehicle enter aura!", itr->second.spellId); + LOG_ERROR("db.query", "Spell {} specified in npc_spellclick_spells is not a valid vehicle enter aura!", itr->second.spellId); continue; } diff --git a/src/server/game/Events/GameEventMgr.cpp b/src/server/game/Events/GameEventMgr.cpp index 21e40c9e1d68ec..0dc4044b812093 100644 --- a/src/server/game/Events/GameEventMgr.cpp +++ b/src/server/game/Events/GameEventMgr.cpp @@ -33,6 +33,7 @@ #include "Util.h" #include "World.h" #include "WorldStatePackets.h" +#include "DatabaseEnv.h" #include GameEventMgr* GameEventMgr::instance() @@ -221,7 +222,7 @@ void GameEventMgr::StopEvent(uint16 event_id, bool overwrite) itr->second.done = 0; CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ALL_GAME_EVENT_CONDITION_SAVE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ALL_GAME_EVENT_CONDITION_SAVE); stmt->SetData(0, uint8(event_id)); trans->Append(stmt); @@ -259,7 +260,7 @@ void GameEventMgr::LoadFromDB() uint8 event_id = fields[0].Get(); if (event_id == 0) { - LOG_ERROR("sql.sql", "`game_event` game event entry 0 is reserved and can't be used."); + LOG_ERROR("db.query", "`game_event` game event entry 0 is reserved and can't be used."); continue; } @@ -285,7 +286,7 @@ void GameEventMgr::LoadFromDB() if (pGameEvent.length == 0 && pGameEvent.state == GAMEEVENT_NORMAL) // length>0 is validity check { - LOG_ERROR("sql.sql", "`game_event` game event id ({}) isn't a world event and has length = 0, thus it can't be used.", event_id); + LOG_ERROR("db.query", "`game_event` game event id ({}) isn't a world event and has length = 0, thus it can't be used.", event_id); continue; } @@ -293,7 +294,7 @@ void GameEventMgr::LoadFromDB() { if (!sHolidaysStore.LookupEntry(pGameEvent.holiday_id)) { - LOG_ERROR("sql.sql", "`game_event` game event id ({}) have not existed holiday id {}.", event_id, pGameEvent.holiday_id); + LOG_ERROR("db.query", "`game_event` game event id ({}) have not existed holiday id {}.", event_id, pGameEvent.holiday_id); pGameEvent.holiday_id = HOLIDAY_NONE; } @@ -328,7 +329,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEvent.size()) { - LOG_ERROR("sql.sql", "`game_event_save` game event entry ({}) is out of range compared to max event entry in `game_event`", event_id); + LOG_ERROR("db.query", "`game_event_save` game event entry ({}) is out of range compared to max event entry in `game_event`", event_id); continue; } @@ -339,7 +340,7 @@ void GameEventMgr::LoadFromDB() } else { - LOG_ERROR("sql.sql", "game_event_save includes event save for non-worldevent id {}", event_id); + LOG_ERROR("db.query", "game_event_save includes event save for non-worldevent id {}", event_id); continue; } @@ -373,7 +374,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEvent.size()) { - LOG_ERROR("sql.sql", "`game_event_prerequisite` game event id ({}) is out of range compared to max event id in `game_event`", event_id); + LOG_ERROR("db.query", "`game_event_prerequisite` game event id ({}) is out of range compared to max event id in `game_event`", event_id); continue; } @@ -382,14 +383,14 @@ void GameEventMgr::LoadFromDB() uint16 prerequisite_event = fields[1].Get(); if (prerequisite_event >= mGameEvent.size()) { - LOG_ERROR("sql.sql", "`game_event_prerequisite` game event prerequisite id ({}) is out of range compared to max event id in `game_event`", prerequisite_event); + LOG_ERROR("db.query", "`game_event_prerequisite` game event prerequisite id ({}) is out of range compared to max event id in `game_event`", prerequisite_event); continue; } mGameEvent[event_id].prerequisite_events.insert(prerequisite_event); } else { - LOG_ERROR("sql.sql", "game_event_prerequisiste includes event entry for non-worldevent id {}", event_id); + LOG_ERROR("db.query", "game_event_prerequisiste includes event entry for non-worldevent id {}", event_id); continue; } @@ -426,7 +427,7 @@ void GameEventMgr::LoadFromDB() CreatureData const* data = sObjectMgr->GetCreatureData(guid); if (!data) { - LOG_ERROR("sql.sql", "`game_event_creature` contains creature (GUID: {}) not found in `creature` table.", guid); + LOG_ERROR("db.query", "`game_event_creature` contains creature (GUID: {}) not found in `creature` table.", guid); continue; } @@ -434,7 +435,7 @@ void GameEventMgr::LoadFromDB() if (internal_event_id < 0 || internal_event_id >= int32(mGameEventCreatureGuids.size())) { - LOG_ERROR("sql.sql", "`game_event_creature` game event id ({}) is out of range compared to max event id in `game_event`", event_id); + LOG_ERROR("db.query", "`game_event_creature` game event id ({}) is out of range compared to max event id in `game_event`", event_id); continue; } @@ -476,13 +477,13 @@ void GameEventMgr::LoadFromDB() GameObjectData const* data = sObjectMgr->GetGameObjectData(guid); if (!data) { - LOG_ERROR("sql.sql", "`game_event_gameobject` contains gameobject (GUID: {}) not found in `gameobject` table.", guid); + LOG_ERROR("db.query", "`game_event_gameobject` contains gameobject (GUID: {}) not found in `gameobject` table.", guid); continue; } if (internal_event_id < 0 || internal_event_id >= int32(mGameEventGameobjectGuids.size())) { - LOG_ERROR("sql.sql", "`game_event_gameobject` game event id ({}) is out of range compared to max event id in `game_event`", event_id); + LOG_ERROR("db.query", "`game_event_gameobject` game event id ({}) is out of range compared to max event id in `game_event`", event_id); continue; } @@ -525,7 +526,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEventModelEquip.size()) { - LOG_ERROR("sql.sql", "`game_event_model_equip` game event id ({}) is out of range compared to max event id in `game_event`", event_id); + LOG_ERROR("db.query", "`game_event_model_equip` game event id ({}) is out of range compared to max event id in `game_event`", event_id); continue; } @@ -541,7 +542,7 @@ void GameEventMgr::LoadFromDB() int8 equipId = static_cast(newModelEquipSet.equipment_id); if ((!sObjectMgr->GetEquipmentInfo(entry, equipId)) || (entry2 && !sObjectMgr->GetEquipmentInfo(entry2, equipId)) || (entry3 && !sObjectMgr->GetEquipmentInfo(entry3, equipId))) { - LOG_ERROR("sql.sql", "Table `game_event_model_equip` have creature (Guid: {}) with equipment_id {} not found in table `creature_equip_template`, set to no equipment.", + LOG_ERROR("db.query", "Table `game_event_model_equip` have creature (Guid: {}) with equipment_id {} not found in table `creature_equip_template`, set to no equipment.", guid, newModelEquipSet.equipment_id); continue; } @@ -582,7 +583,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEventCreatureQuests.size()) { - LOG_ERROR("sql.sql", "`game_event_creature_quest` game event id ({}) is out of range compared to max event id in `game_event`", event_id); + LOG_ERROR("db.query", "`game_event_creature_quest` game event id ({}) is out of range compared to max event id in `game_event`", event_id); continue; } @@ -622,7 +623,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEventGameObjectQuests.size()) { - LOG_ERROR("sql.sql", "`game_event_gameobject_quest` game event id ({}) is out of range compared to max event id in `game_event`", event_id); + LOG_ERROR("db.query", "`game_event_gameobject_quest` game event id ({}) is out of range compared to max event id in `game_event`", event_id); continue; } @@ -663,7 +664,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEvent.size()) { - LOG_ERROR("sql.sql", "`game_event_quest_condition` game event id ({}) is out of range compared to max event id in `game_event`", event_id); + LOG_ERROR("db.query", "`game_event_quest_condition` game event id ({}) is out of range compared to max event id in `game_event`", event_id); continue; } @@ -703,7 +704,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEvent.size()) { - LOG_ERROR("sql.sql", "`game_event_condition` game event id ({}) is out of range compared to max event id in `game_event`", event_id); + LOG_ERROR("db.query", "`game_event_condition` game event id ({}) is out of range compared to max event id in `game_event`", event_id); continue; } @@ -744,7 +745,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEvent.size()) { - LOG_ERROR("sql.sql", "`game_event_condition_save` game event id ({}) is out of range compared to max event id in `game_event`", event_id); + LOG_ERROR("db.query", "`game_event_condition_save` game event id ({}) is out of range compared to max event id in `game_event`", event_id); continue; } @@ -755,7 +756,7 @@ void GameEventMgr::LoadFromDB() } else { - LOG_ERROR("sql.sql", "game_event_condition_save contains not present condition evt id {} cond id {}", event_id, condition); + LOG_ERROR("db.query", "game_event_condition_save contains not present condition evt id {} cond id {}", event_id, condition); continue; } @@ -792,7 +793,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEvent.size()) { - LOG_ERROR("sql.sql", "`game_event_npcflag` game event id ({}) is out of range compared to max event id in `game_event`", event_id); + LOG_ERROR("db.query", "`game_event_npcflag` game event id ({}) is out of range compared to max event id in `game_event`", event_id); continue; } @@ -832,13 +833,13 @@ void GameEventMgr::LoadFromDB() if (!questTemplate) { - LOG_ERROR("sql.sql", "`game_event_seasonal_questrelation` quest id ({}) does not exist in `quest_template`", questId); + LOG_ERROR("db.query", "`game_event_seasonal_questrelation` quest id ({}) does not exist in `quest_template`", questId); continue; } if (eventEntry >= mGameEvent.size()) { - LOG_ERROR("sql.sql", "`game_event_seasonal_questrelation` event id ({}) is out of range compared to max event in `game_event`", eventEntry); + LOG_ERROR("db.query", "`game_event_seasonal_questrelation` event id ({}) is out of range compared to max event in `game_event`", eventEntry); continue; } @@ -875,7 +876,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEventVendors.size()) { - LOG_ERROR("sql.sql", "`game_event_npc_vendor` game event id ({}) is out of range compared to max event id in `game_event`", event_id); + LOG_ERROR("db.query", "`game_event_npc_vendor` game event id ({}) is out of range compared to max event id in `game_event`", event_id); continue; } @@ -940,7 +941,7 @@ void GameEventMgr::LoadFromDB() if (event_id >= mGameEvent.size()) { - LOG_ERROR("sql.sql", "`game_event_battleground_holiday` game event id ({}) is out of range compared to max event id in `game_event`", event_id); + LOG_ERROR("db.query", "`game_event_battleground_holiday` game event id ({}) is out of range compared to max event id in `game_event`", event_id); continue; } @@ -981,13 +982,13 @@ void GameEventMgr::LoadFromDB() if (internal_event_id < 0 || internal_event_id >= int32(mGameEventPoolIds.size())) { - LOG_ERROR("sql.sql", "`game_event_pool` game event id ({}) is out of range compared to max event id in `game_event`", event_id); + LOG_ERROR("db.query", "`game_event_pool` game event id ({}) is out of range compared to max event id in `game_event`", event_id); continue; } if (!sPoolMgr->CheckPool(entry)) { - LOG_ERROR("sql.sql", "Pool Id ({}) has all creatures or gameobjects with explicit chance sum <>100 and no equal chance defined. The pool system cannot pick one to spawn.", entry); + LOG_ERROR("db.query", "Pool Id ({}) has all creatures or gameobjects with explicit chance sum <>100 and no equal chance defined. The pool system cannot pick one to spawn.", entry); continue; } @@ -1025,14 +1026,14 @@ void GameEventMgr::LoadHolidayDates() HolidaysEntry* entry = const_cast(sHolidaysStore.LookupEntry(holidayId)); if (!entry) { - LOG_ERROR("sql.sql", "holiday_dates entry has invalid holiday id {}.", holidayId); + LOG_ERROR("db.query", "holiday_dates entry has invalid holiday id {}.", holidayId); continue; } uint8 dateId = fields[1].Get(); if (dateId >= MAX_HOLIDAY_DATES) { - LOG_ERROR("sql.sql", "holiday_dates entry has out of range date_id {}.", dateId); + LOG_ERROR("db.query", "holiday_dates entry has out of range date_id {}.", dateId); continue; } entry->Date[dateId] = fields[2].Get(); @@ -1135,7 +1136,7 @@ uint32 GameEventMgr::Update() // return the next e { // must do the activating first, and after that the deactivating // so first queue it - //LOG_ERROR("sql.sql", "Checking event {}", itr); + //LOG_ERROR("db.query", "Checking event {}", itr); sScriptMgr->OnGameEventCheck(itr); @@ -1689,7 +1690,7 @@ void GameEventMgr::HandleQuestComplete(uint32 quest_id) // save the change to db CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GAME_EVENT_CONDITION_SAVE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GAME_EVENT_CONDITION_SAVE); stmt->SetData(0, uint8(event_id)); stmt->SetData(1, condition); trans->Append(stmt); @@ -1734,7 +1735,7 @@ void GameEventMgr::SaveWorldEventStateToDB(uint16 event_id) { CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GAME_EVENT_SAVE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GAME_EVENT_SAVE); stmt->SetData(0, uint8(event_id)); trans->Append(stmt); @@ -1806,7 +1807,7 @@ void GameEventMgr::SetHolidayEventTime(GameEventData& event) if (!holiday->Date[0] || !holiday->Duration[0]) // Invalid definitions { - LOG_ERROR("sql.sql", "Missing date or duration for holiday {}.", event.holiday_id); + LOG_ERROR("db.query", "Missing date or duration for holiday {}.", event.holiday_id); return; } diff --git a/src/server/game/Globals/ObjectMgr.cpp b/src/server/game/Globals/ObjectMgr.cpp index 702f71441bbdcf..4018ec16d451a7 100644 --- a/src/server/game/Globals/ObjectMgr.cpp +++ b/src/server/game/Globals/ObjectMgr.cpp @@ -779,14 +779,14 @@ void ObjectMgr::LoadCreatureTemplateResistances() if (school == SPELL_SCHOOL_NORMAL || school >= MAX_SPELL_SCHOOL) { - LOG_ERROR("sql.sql", "creature_template_resistance has resistance definitions for creature {} but this school {} doesn't exist", creatureID, school); + LOG_ERROR("db.query", "creature_template_resistance has resistance definitions for creature {} but this school {} doesn't exist", creatureID, school); continue; } CreatureTemplateContainer::iterator itr = _creatureTemplateStore.find(creatureID); if (itr == _creatureTemplateStore.end()) { - LOG_ERROR("sql.sql", "creature_template_resistance has resistance definitions for creature {} but this creature doesn't exist", creatureID); + LOG_ERROR("db.query", "creature_template_resistance has resistance definitions for creature {} but this creature doesn't exist", creatureID); continue; } @@ -825,14 +825,14 @@ void ObjectMgr::LoadCreatureTemplateSpells() if (index >= MAX_CREATURE_SPELLS) { - LOG_ERROR("sql.sql", "creature_template_spell has spell definitions for creature {} with a incorrect index {}", creatureID, index); + LOG_ERROR("db.query", "creature_template_spell has spell definitions for creature {} with a incorrect index {}", creatureID, index); continue; } CreatureTemplateContainer::iterator itr = _creatureTemplateStore.find(creatureID); if (itr == _creatureTemplateStore.end()) { - LOG_ERROR("sql.sql", "creature_template_spell has spell definitions for creature {} but this creature doesn't exist", creatureID); + LOG_ERROR("db.query", "creature_template_spell has spell definitions for creature {} but this creature doesn't exist", creatureID); continue; } @@ -869,7 +869,7 @@ void ObjectMgr::LoadCreatureTemplateAddons() if (!sObjectMgr->GetCreatureTemplate(entry)) { - LOG_ERROR("sql.sql", "Creature template (Entry: {}) does not exist but has a record in `creature_template_addon`", entry); + LOG_ERROR("db.query", "Creature template (Entry: {}) does not exist but has a record in `creature_template_addon`", entry); continue; } @@ -893,19 +893,19 @@ void ObjectMgr::LoadCreatureTemplateAddons() if (!spellInfo) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has wrong spell '{}' defined in `auras` field in `creature_template_addon`.", entry, aura); + LOG_ERROR("db.query", "Creature (Entry: {}) has wrong spell '{}' defined in `auras` field in `creature_template_addon`.", entry, aura); continue; } if (std::find(creatureAddon.auras.begin(), creatureAddon.auras.end(), spellInfo->Id) != creatureAddon.auras.end()) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has duplicate aura (spell {}) in `auras` field in `creature_template_addon`.", entry, spellInfo->Id); + LOG_ERROR("db.query", "Creature (Entry: {}) has duplicate aura (spell {}) in `auras` field in `creature_template_addon`.", entry, spellInfo->Id); continue; } if (spellInfo->GetDuration() > 0) { - LOG_DEBUG/*ERROR*/("sql.sql", "Creature (Entry: {}) has temporary aura (spell {}) in `auras` field in `creature_template_addon`.", entry, spellInfo->Id); + LOG_DEBUG/*ERROR*/("db.query", "Creature (Entry: {}) has temporary aura (spell {}) in `auras` field in `creature_template_addon`.", entry, spellInfo->Id); // continue; } @@ -916,20 +916,20 @@ void ObjectMgr::LoadCreatureTemplateAddons() { if (!sCreatureDisplayInfoStore.LookupEntry(creatureAddon.mount)) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has invalid displayInfoId ({}) for mount defined in `creature_template_addon`", entry, creatureAddon.mount); + LOG_ERROR("db.query", "Creature (Entry: {}) has invalid displayInfoId ({}) for mount defined in `creature_template_addon`", entry, creatureAddon.mount); creatureAddon.mount = 0; } } if (!sEmotesStore.LookupEntry(creatureAddon.emote)) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has invalid emote ({}) defined in `creature_addon`.", entry, creatureAddon.emote); + LOG_ERROR("db.query", "Creature (Entry: {}) has invalid emote ({}) defined in `creature_addon`.", entry, creatureAddon.emote); creatureAddon.emote = 0; } if (creatureAddon.visibilityDistanceType >= VisibilityDistanceType::Max) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has invalid visibilityDistanceType ({}) defined in `creature_template_addon`.", entry, AsUnderlyingType(creatureAddon.visibilityDistanceType)); + LOG_ERROR("db.query", "Creature (Entry: {}) has invalid visibilityDistanceType ({}) defined in `creature_template_addon`.", entry, AsUnderlyingType(creatureAddon.visibilityDistanceType)); creatureAddon.visibilityDistanceType = VisibilityDistanceType::Normal; } ++count; @@ -969,7 +969,7 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) CreatureTemplate const* difficultyInfo = GetCreatureTemplate(cInfo->DifficultyEntry[diff]); if (!difficultyInfo) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has `difficulty_entry_{}`={} but creature entry {} does not exist.", + LOG_ERROR("db.query", "Creature (Entry: {}) has `difficulty_entry_{}`={} but creature entry {} does not exist.", cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff], cInfo->DifficultyEntry[diff]); continue; } @@ -980,20 +980,20 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) ok2 = false; if (_difficultyEntries[diff2].find(cInfo->Entry) != _difficultyEntries[diff2].end()) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) is listed as `difficulty_entry_{}` of another creature, but itself lists {} in `difficulty_entry_{}`.", + LOG_ERROR("db.query", "Creature (Entry: {}) is listed as `difficulty_entry_{}` of another creature, but itself lists {} in `difficulty_entry_{}`.", cInfo->Entry, diff2 + 1, cInfo->DifficultyEntry[diff], diff + 1); continue; } if (_difficultyEntries[diff2].find(cInfo->DifficultyEntry[diff]) != _difficultyEntries[diff2].end()) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) already listed as `difficulty_entry_{}` for another entry.", cInfo->DifficultyEntry[diff], diff2 + 1); + LOG_ERROR("db.query", "Creature (Entry: {}) already listed as `difficulty_entry_{}` for another entry.", cInfo->DifficultyEntry[diff], diff2 + 1); continue; } if (_hasDifficultyEntries[diff2].find(cInfo->DifficultyEntry[diff]) != _hasDifficultyEntries[diff2].end()) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has `difficulty_entry_{}`={} but creature entry {} has itself a value in `difficulty_entry_{}`.", + LOG_ERROR("db.query", "Creature (Entry: {}) has `difficulty_entry_{}`={} but creature entry {} has itself a value in `difficulty_entry_{}`.", cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff], cInfo->DifficultyEntry[diff], diff2 + 1); continue; } @@ -1004,87 +1004,87 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) if (cInfo->expansion > difficultyInfo->expansion) { - LOG_ERROR("sql.sql", "Creature (Entry: {}, expansion {}) has different `expansion` in difficulty {} mode (Entry: {}, expansion {}).", + LOG_ERROR("db.query", "Creature (Entry: {}, expansion {}) has different `expansion` in difficulty {} mode (Entry: {}, expansion {}).", cInfo->Entry, cInfo->expansion, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->expansion); } if (cInfo->faction != difficultyInfo->faction) { - LOG_ERROR("sql.sql", "Creature (Entry: {}, faction {}) has different `faction` in difficulty {} mode (Entry: {}, faction {}).", + LOG_ERROR("db.query", "Creature (Entry: {}, faction {}) has different `faction` in difficulty {} mode (Entry: {}, faction {}).", cInfo->Entry, cInfo->faction, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->faction); } if (cInfo->unit_class != difficultyInfo->unit_class) { - LOG_ERROR("sql.sql", "Creature (Entry: {}, class {}) has different `unit_class` in difficulty {} mode (Entry: {}, class {}).", + LOG_ERROR("db.query", "Creature (Entry: {}, class {}) has different `unit_class` in difficulty {} mode (Entry: {}, class {}).", cInfo->Entry, cInfo->unit_class, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->unit_class); continue; } if (cInfo->npcflag != difficultyInfo->npcflag) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has different `npcflag` in difficulty {} mode (Entry: {}).", cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff]); + LOG_ERROR("db.query", "Creature (Entry: {}) has different `npcflag` in difficulty {} mode (Entry: {}).", cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff]); continue; } if (cInfo->family != difficultyInfo->family) { - LOG_ERROR("sql.sql", "Creature (Entry: {}, family {}) has different `family` in difficulty {} mode (Entry: {}, family {}).", + LOG_ERROR("db.query", "Creature (Entry: {}, family {}) has different `family` in difficulty {} mode (Entry: {}, family {}).", cInfo->Entry, cInfo->family, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->family); } if (cInfo->trainer_class != difficultyInfo->trainer_class) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has different `trainer_class` in difficulty {} mode (Entry: {}).", cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff]); + LOG_ERROR("db.query", "Creature (Entry: {}) has different `trainer_class` in difficulty {} mode (Entry: {}).", cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff]); continue; } if (cInfo->trainer_race != difficultyInfo->trainer_race) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has different `trainer_race` in difficulty {} mode (Entry: {}).", cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff]); + LOG_ERROR("db.query", "Creature (Entry: {}) has different `trainer_race` in difficulty {} mode (Entry: {}).", cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff]); continue; } if (cInfo->trainer_type != difficultyInfo->trainer_type) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has different `trainer_type` in difficulty {} mode (Entry: {}).", cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff]); + LOG_ERROR("db.query", "Creature (Entry: {}) has different `trainer_type` in difficulty {} mode (Entry: {}).", cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff]); continue; } if (cInfo->trainer_spell != difficultyInfo->trainer_spell) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has different `trainer_spell` in difficulty {} mode (Entry: {}).", cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff]); + LOG_ERROR("db.query", "Creature (Entry: {}) has different `trainer_spell` in difficulty {} mode (Entry: {}).", cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff]); continue; } if (cInfo->type != difficultyInfo->type) { - LOG_ERROR("sql.sql", "Creature (Entry: {}, type {}) has different `type` in difficulty {} mode (Entry: {}, type {}).", + LOG_ERROR("db.query", "Creature (Entry: {}, type {}) has different `type` in difficulty {} mode (Entry: {}, type {}).", cInfo->Entry, cInfo->type, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->type); } if (!cInfo->VehicleId && difficultyInfo->VehicleId) { - LOG_ERROR("sql.sql", "Creature (Entry: {}, VehicleId {}) has different `VehicleId` in difficulty {} mode (Entry: {}, VehicleId {}).", + LOG_ERROR("db.query", "Creature (Entry: {}, VehicleId {}) has different `VehicleId` in difficulty {} mode (Entry: {}, VehicleId {}).", cInfo->Entry, cInfo->VehicleId, diff + 1, cInfo->DifficultyEntry[diff], difficultyInfo->VehicleId); } // Xinef: check dmg school if (cInfo->dmgschool != difficultyInfo->dmgschool) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has different `dmgschool` in difficulty {} mode (Entry: {})", cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff]); + LOG_ERROR("db.query", "Creature (Entry: {}) has different `dmgschool` in difficulty {} mode (Entry: {})", cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff]); } if (!difficultyInfo->AIName.empty()) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) lists difficulty {} mode entry {} with `AIName` filled in. `AIName` of difficulty 0 mode creature is always used instead.", + LOG_ERROR("db.query", "Creature (Entry: {}) lists difficulty {} mode entry {} with `AIName` filled in. `AIName` of difficulty 0 mode creature is always used instead.", cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff]); continue; } if (difficultyInfo->ScriptID) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) lists difficulty {} mode entry {} with `ScriptName` filled in. `ScriptName` of difficulty 0 mode creature is always used instead.", + LOG_ERROR("db.query", "Creature (Entry: {}) lists difficulty {} mode entry {} with `ScriptName` filled in. `ScriptName` of difficulty 0 mode creature is always used instead.", cInfo->Entry, diff + 1, cInfo->DifficultyEntry[diff]); continue; } @@ -1096,13 +1096,13 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) if (!cInfo->AIName.empty() && !sCreatureAIRegistry->HasItem(cInfo->AIName)) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has non-registered `AIName` '{}' set, removing", cInfo->Entry, cInfo->AIName); + LOG_ERROR("db.query", "Creature (Entry: {}) has non-registered `AIName` '{}' set, removing", cInfo->Entry, cInfo->AIName); const_cast(cInfo)->AIName.clear(); } FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(cInfo->faction); if (!factionTemplate) - LOG_ERROR("sql.sql", "Creature (Entry: {}) has non-existing faction template ({}).", cInfo->Entry, cInfo->faction); + LOG_ERROR("db.query", "Creature (Entry: {}) has non-existing faction template ({}).", cInfo->Entry, cInfo->faction); // used later for scale CreatureDisplayInfoEntry const* displayScaleEntry = nullptr; @@ -1112,7 +1112,7 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->Modelid1); if (!displayEntry) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) lists non-existing Modelid1 id ({}), this can crash the client.", cInfo->Entry, cInfo->Modelid1); + LOG_ERROR("db.query", "Creature (Entry: {}) lists non-existing Modelid1 id ({}), this can crash the client.", cInfo->Entry, cInfo->Modelid1); const_cast(cInfo)->Modelid1 = 0; } else if (!displayScaleEntry) @@ -1120,7 +1120,7 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) CreatureModelInfo const* modelInfo = GetCreatureModelInfo(cInfo->Modelid1); if (!modelInfo) - LOG_ERROR("sql.sql", "No model data exist for `Modelid1` = {} listed by creature (Entry: {}).", cInfo->Modelid1, cInfo->Entry); + LOG_ERROR("db.query", "No model data exist for `Modelid1` = {} listed by creature (Entry: {}).", cInfo->Modelid1, cInfo->Entry); } if (cInfo->Modelid2) @@ -1128,7 +1128,7 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->Modelid2); if (!displayEntry) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) lists non-existing Modelid2 id ({}), this can crash the client.", cInfo->Entry, cInfo->Modelid2); + LOG_ERROR("db.query", "Creature (Entry: {}) lists non-existing Modelid2 id ({}), this can crash the client.", cInfo->Entry, cInfo->Modelid2); const_cast(cInfo)->Modelid2 = 0; } else if (!displayScaleEntry) @@ -1136,7 +1136,7 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) CreatureModelInfo const* modelInfo = GetCreatureModelInfo(cInfo->Modelid2); if (!modelInfo) - LOG_ERROR("sql.sql", "No model data exist for `Modelid2` = {} listed by creature (Entry: {}).", cInfo->Modelid2, cInfo->Entry); + LOG_ERROR("db.query", "No model data exist for `Modelid2` = {} listed by creature (Entry: {}).", cInfo->Modelid2, cInfo->Entry); } if (cInfo->Modelid3) @@ -1144,7 +1144,7 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->Modelid3); if (!displayEntry) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) lists non-existing Modelid3 id ({}), this can crash the client.", cInfo->Entry, cInfo->Modelid3); + LOG_ERROR("db.query", "Creature (Entry: {}) lists non-existing Modelid3 id ({}), this can crash the client.", cInfo->Entry, cInfo->Modelid3); const_cast(cInfo)->Modelid3 = 0; } else if (!displayScaleEntry) @@ -1152,7 +1152,7 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) CreatureModelInfo const* modelInfo = GetCreatureModelInfo(cInfo->Modelid3); if (!modelInfo) - LOG_ERROR("sql.sql", "No model data exist for `Modelid3` = {} listed by creature (Entry: {}).", cInfo->Modelid3, cInfo->Entry); + LOG_ERROR("db.query", "No model data exist for `Modelid3` = {} listed by creature (Entry: {}).", cInfo->Modelid3, cInfo->Entry); } if (cInfo->Modelid4) @@ -1160,7 +1160,7 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) CreatureDisplayInfoEntry const* displayEntry = sCreatureDisplayInfoStore.LookupEntry(cInfo->Modelid4); if (!displayEntry) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) lists non-existing Modelid4 id ({}), this can crash the client.", cInfo->Entry, cInfo->Modelid4); + LOG_ERROR("db.query", "Creature (Entry: {}) lists non-existing Modelid4 id ({}), this can crash the client.", cInfo->Entry, cInfo->Modelid4); const_cast(cInfo)->Modelid4 = 0; } else if (!displayScaleEntry) @@ -1168,11 +1168,11 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) CreatureModelInfo const* modelInfo = GetCreatureModelInfo(cInfo->Modelid4); if (!modelInfo) - LOG_ERROR("sql.sql", "No model data exist for `Modelid4` = {} listed by creature (Entry: {}).", cInfo->Modelid4, cInfo->Entry); + LOG_ERROR("db.query", "No model data exist for `Modelid4` = {} listed by creature (Entry: {}).", cInfo->Modelid4, cInfo->Entry); } if (!displayScaleEntry) - LOG_ERROR("sql.sql", "Creature (Entry: {}) does not have any existing display id in Modelid1/Modelid2/Modelid3/Modelid4.", cInfo->Entry); + LOG_ERROR("db.query", "Creature (Entry: {}) does not have any existing display id in Modelid1/Modelid2/Modelid3/Modelid4.", cInfo->Entry); for (int k = 0; k < MAX_KILL_CREDIT; ++k) { @@ -1180,7 +1180,7 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) { if (!GetCreatureTemplate(cInfo->KillCredit[k])) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) lists non-existing creature entry {} in `KillCredit{}`.", cInfo->Entry, cInfo->KillCredit[k], k + 1); + LOG_ERROR("db.query", "Creature (Entry: {}) lists non-existing creature entry {} in `KillCredit{}`.", cInfo->Entry, cInfo->KillCredit[k], k + 1); const_cast(cInfo)->KillCredit[k] = 0; } } @@ -1188,13 +1188,13 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) if (!cInfo->unit_class || ((1 << (cInfo->unit_class - 1)) & CLASSMASK_ALL_CREATURES) == 0) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has invalid unit_class ({}) in creature_template. Set to 1 (UNIT_CLASS_WARRIOR).", cInfo->Entry, cInfo->unit_class); + LOG_ERROR("db.query", "Creature (Entry: {}) has invalid unit_class ({}) in creature_template. Set to 1 (UNIT_CLASS_WARRIOR).", cInfo->Entry, cInfo->unit_class); const_cast(cInfo)->unit_class = UNIT_CLASS_WARRIOR; } if (cInfo->dmgschool >= MAX_SPELL_SCHOOL) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has invalid spell school value ({}) in `dmgschool`.", cInfo->Entry, cInfo->dmgschool); + LOG_ERROR("db.query", "Creature (Entry: {}) has invalid spell school value ({}) in `dmgschool`.", cInfo->Entry, cInfo->dmgschool); const_cast(cInfo)->dmgschool = SPELL_SCHOOL_NORMAL; } @@ -1205,30 +1205,30 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) const_cast(cInfo)->RangeAttackTime = BASE_ATTACK_TIME; if ((cInfo->npcflag & UNIT_NPC_FLAG_TRAINER) && cInfo->trainer_type >= MAX_TRAINER_TYPE) - LOG_ERROR("sql.sql", "Creature (Entry: {}) has wrong trainer type {}.", cInfo->Entry, cInfo->trainer_type); + LOG_ERROR("db.query", "Creature (Entry: {}) has wrong trainer type {}.", cInfo->Entry, cInfo->trainer_type); if (cInfo->speed_walk == 0.0f) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has wrong value ({}) in speed_walk, set to 1.", cInfo->Entry, cInfo->speed_walk); + LOG_ERROR("db.query", "Creature (Entry: {}) has wrong value ({}) in speed_walk, set to 1.", cInfo->Entry, cInfo->speed_walk); const_cast(cInfo)->speed_walk = 1.0f; } if (cInfo->speed_run == 0.0f) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has wrong value ({}) in speed_run, set to 1.14286.", cInfo->Entry, cInfo->speed_run); + LOG_ERROR("db.query", "Creature (Entry: {}) has wrong value ({}) in speed_run, set to 1.14286.", cInfo->Entry, cInfo->speed_run); const_cast(cInfo)->speed_run = 1.14286f; } if (cInfo->type && !sCreatureTypeStore.LookupEntry(cInfo->type)) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has invalid creature type ({}) in `type`.", cInfo->Entry, cInfo->type); + LOG_ERROR("db.query", "Creature (Entry: {}) has invalid creature type ({}) in `type`.", cInfo->Entry, cInfo->type); const_cast(cInfo)->type = CREATURE_TYPE_HUMANOID; } // must exist or used hidden but used in data horse case if (cInfo->family && !sCreatureFamilyStore.LookupEntry(cInfo->family) && cInfo->family != CREATURE_FAMILY_HORSE_CUSTOM) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has invalid creature family ({}) in `family`.", cInfo->Entry, cInfo->family); + LOG_ERROR("db.query", "Creature (Entry: {}) has invalid creature family ({}) in `family`.", cInfo->Entry, cInfo->family); const_cast(cInfo)->family = 0; } @@ -1236,7 +1236,7 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) if (cInfo->HoverHeight < 0.0f) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has wrong value ({}) in `HoverHeight`", cInfo->Entry, cInfo->HoverHeight); + LOG_ERROR("db.query", "Creature (Entry: {}) has wrong value ({}) in `HoverHeight`", cInfo->Entry, cInfo->HoverHeight); const_cast(cInfo)->HoverHeight = 1.0f; } @@ -1245,7 +1245,7 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) VehicleEntry const* vehId = sVehicleStore.LookupEntry(cInfo->VehicleId); if (!vehId) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has a non-existing VehicleId ({}). This *WILL* cause the client to freeze!", cInfo->Entry, cInfo->VehicleId); + LOG_ERROR("db.query", "Creature (Entry: {}) has a non-existing VehicleId ({}). This *WILL* cause the client to freeze!", cInfo->Entry, cInfo->VehicleId); const_cast(cInfo)->VehicleId = 0; } } @@ -1254,21 +1254,21 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) { CreatureSpellDataEntry const* spellDataId = sCreatureSpellDataStore.LookupEntry(cInfo->PetSpellDataId); if (!spellDataId) - LOG_ERROR("sql.sql", "Creature (Entry: {}) has non-existing PetSpellDataId ({}).", cInfo->Entry, cInfo->PetSpellDataId); + LOG_ERROR("db.query", "Creature (Entry: {}) has non-existing PetSpellDataId ({}).", cInfo->Entry, cInfo->PetSpellDataId); } for (uint8 j = 0; j < MAX_CREATURE_SPELLS; ++j) { if (cInfo->spells[j] && !sSpellMgr->GetSpellInfo(cInfo->spells[j])) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has non-existing Spell{} ({}), set to 0.", cInfo->Entry, j + 1, cInfo->spells[j]); + LOG_ERROR("db.query", "Creature (Entry: {}) has non-existing Spell{} ({}), set to 0.", cInfo->Entry, j + 1, cInfo->spells[j]); const_cast(cInfo)->spells[j] = 0; } } if (cInfo->MovementType >= MAX_DB_MOTION_TYPE) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has wrong movement generator type ({}), ignored and set to IDLE.", cInfo->Entry, cInfo->MovementType); + LOG_ERROR("db.query", "Creature (Entry: {}) has wrong movement generator type ({}), ignored and set to IDLE.", cInfo->Entry, cInfo->MovementType); const_cast(cInfo)->MovementType = IDLE_MOTION_TYPE; } @@ -1283,13 +1283,13 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) if (cInfo->expansion > (MAX_EXPANSIONS - 1)) { - LOG_ERROR("sql.sql", "Table `creature_template` lists creature (Entry: {}) with expansion {}. Ignored and set to 0.", cInfo->Entry, cInfo->expansion); + LOG_ERROR("db.query", "Table `creature_template` lists creature (Entry: {}) with expansion {}. Ignored and set to 0.", cInfo->Entry, cInfo->expansion); const_cast(cInfo)->expansion = 0; } if (uint32 badFlags = (cInfo->flags_extra & ~CREATURE_FLAG_EXTRA_DB_ALLOWED)) { - LOG_ERROR("sql.sql", "Table `creature_template` lists creature (Entry: {}) with disallowed `flags_extra` {}, removing incorrect flag.", cInfo->Entry, badFlags); + LOG_ERROR("db.query", "Table `creature_template` lists creature (Entry: {}) with disallowed `flags_extra` {}, removing incorrect flag.", cInfo->Entry, badFlags); const_cast(cInfo)->flags_extra &= CREATURE_FLAG_EXTRA_DB_ALLOWED; } @@ -1304,11 +1304,11 @@ void ObjectMgr::CheckCreatureTemplate(CreatureTemplate const* cInfo) if ((cInfo->GossipMenuId && !(cInfo->npcflag & UNIT_NPC_FLAG_GOSSIP)) && !(cInfo->flags_extra & CREATURE_FLAG_EXTRA_MODULE)) { - LOG_ERROR("sql.sql", "Creature (Entry: {}) has assigned gossip menu {}, but npcflag does not include UNIT_NPC_FLAG_GOSSIP (1).", cInfo->Entry, cInfo->GossipMenuId); + LOG_ERROR("db.query", "Creature (Entry: {}) has assigned gossip menu {}, but npcflag does not include UNIT_NPC_FLAG_GOSSIP (1).", cInfo->Entry, cInfo->GossipMenuId); } else if ((!cInfo->GossipMenuId && (cInfo->npcflag & UNIT_NPC_FLAG_GOSSIP)) && !(cInfo->flags_extra & CREATURE_FLAG_EXTRA_MODULE)) { - LOG_INFO("sql.sql", "Creature (Entry: {}) has npcflag UNIT_NPC_FLAG_GOSSIP (1), but gossip menu is unassigned.", cInfo->Entry); + LOG_INFO("db.query", "Creature (Entry: {}) has npcflag UNIT_NPC_FLAG_GOSSIP (1), but gossip menu is unassigned.", cInfo->Entry); } } @@ -1316,25 +1316,25 @@ void ObjectMgr::CheckCreatureMovement(char const* table, uint64 id, CreatureMove { if (creatureMovement.Ground >= CreatureGroundMovementType::Max) { - LOG_ERROR("sql.sql", "`{}`.`Ground` wrong value ({}) for Id {}, setting to Run.", table, uint32(creatureMovement.Ground), id); + LOG_ERROR("db.query", "`{}`.`Ground` wrong value ({}) for Id {}, setting to Run.", table, uint32(creatureMovement.Ground), id); creatureMovement.Ground = CreatureGroundMovementType::Run; } if (creatureMovement.Flight >= CreatureFlightMovementType::Max) { - LOG_ERROR("sql.sql", "`{}`.`Flight` wrong value ({}) for Id {}, setting to None.", table, uint32(creatureMovement.Flight), id); + LOG_ERROR("db.query", "`{}`.`Flight` wrong value ({}) for Id {}, setting to None.", table, uint32(creatureMovement.Flight), id); creatureMovement.Flight = CreatureFlightMovementType::None; } if (creatureMovement.Chase >= CreatureChaseMovementType::Max) { - LOG_ERROR("sql.sql", "`{}`.`Chase` wrong value ({}) for Id {}, setting to Run.", table, uint32(creatureMovement.Chase), id); + LOG_ERROR("db.query", "`{}`.`Chase` wrong value ({}) for Id {}, setting to Run.", table, uint32(creatureMovement.Chase), id); creatureMovement.Chase = CreatureChaseMovementType::Run; } if (creatureMovement.Random >= CreatureRandomMovementType::Max) { - LOG_ERROR("sql.sql", "`{}`.`Random` wrong value ({}) for Id {}, setting to Walk.", table, uint32(creatureMovement.Random), id); + LOG_ERROR("db.query", "`{}`.`Random` wrong value ({}) for Id {}, setting to Walk.", table, uint32(creatureMovement.Random), id); creatureMovement.Random = CreatureRandomMovementType::Walk; } } @@ -1363,7 +1363,7 @@ void ObjectMgr::LoadCreatureAddons() CreatureData const* creData = GetCreatureData(guid); if (!creData) { - LOG_ERROR("sql.sql", "Creature (GUID: {}) does not exist but has a record in `creature_addon`", guid); + LOG_ERROR("db.query", "Creature (GUID: {}) does not exist but has a record in `creature_addon`", guid); continue; } @@ -1373,7 +1373,7 @@ void ObjectMgr::LoadCreatureAddons() if (creData->movementType == WAYPOINT_MOTION_TYPE && !creatureAddon.path_id) { const_cast(creData)->movementType = IDLE_MOTION_TYPE; - LOG_ERROR("sql.sql", "Creature (GUID {}) has movement type set to WAYPOINT_MOTION_TYPE but no path assigned", guid); + LOG_ERROR("db.query", "Creature (GUID {}) has movement type set to WAYPOINT_MOTION_TYPE but no path assigned", guid); } creatureAddon.mount = fields[2].Get(); @@ -1393,19 +1393,19 @@ void ObjectMgr::LoadCreatureAddons() if (!spellInfo) { - LOG_ERROR("sql.sql", "Creature (GUID: {}) has wrong spell '{}' defined in `auras` field in `creature_addon`.", guid, aura); + LOG_ERROR("db.query", "Creature (GUID: {}) has wrong spell '{}' defined in `auras` field in `creature_addon`.", guid, aura); continue; } if (std::find(creatureAddon.auras.begin(), creatureAddon.auras.end(), spellInfo->Id) != creatureAddon.auras.end()) { - LOG_ERROR("sql.sql", "Creature (GUID: {}) has duplicate aura (spell {}) in `auras` field in `creature_addon`.", guid, spellInfo->Id); + LOG_ERROR("db.query", "Creature (GUID: {}) has duplicate aura (spell {}) in `auras` field in `creature_addon`.", guid, spellInfo->Id); continue; } if (spellInfo->GetDuration() > 0) { - LOG_DEBUG/*ERROR*/("sql.sql", "Creature (Entry: {}) has temporary aura (spell {}) in `auras` field in `creature_template_addon`.", guid, spellInfo->Id); + LOG_DEBUG/*ERROR*/("db.query", "Creature (Entry: {}) has temporary aura (spell {}) in `auras` field in `creature_template_addon`.", guid, spellInfo->Id); // continue; } @@ -1416,20 +1416,20 @@ void ObjectMgr::LoadCreatureAddons() { if (!sCreatureDisplayInfoStore.LookupEntry(creatureAddon.mount)) { - LOG_ERROR("sql.sql", "Creature (GUID: {}) has invalid displayInfoId ({}) for mount defined in `creature_addon`", guid, creatureAddon.mount); + LOG_ERROR("db.query", "Creature (GUID: {}) has invalid displayInfoId ({}) for mount defined in `creature_addon`", guid, creatureAddon.mount); creatureAddon.mount = 0; } } if (!sEmotesStore.LookupEntry(creatureAddon.emote)) { - LOG_ERROR("sql.sql", "Creature (GUID: {}) has invalid emote ({}) defined in `creature_addon`.", guid, creatureAddon.emote); + LOG_ERROR("db.query", "Creature (GUID: {}) has invalid emote ({}) defined in `creature_addon`.", guid, creatureAddon.emote); creatureAddon.emote = 0; } if (creatureAddon.visibilityDistanceType >= VisibilityDistanceType::Max) { - LOG_ERROR("sql.sql", "Creature (GUID: {}) has invalid visibilityDistanceType ({}) defined in `creature_addon`.", guid, AsUnderlyingType(creatureAddon.visibilityDistanceType)); + LOG_ERROR("db.query", "Creature (GUID: {}) has invalid visibilityDistanceType ({}) defined in `creature_addon`.", guid, AsUnderlyingType(creatureAddon.visibilityDistanceType)); creatureAddon.visibilityDistanceType = VisibilityDistanceType::Normal; } @@ -1464,7 +1464,7 @@ void ObjectMgr::LoadGameObjectAddons() const GameObjectData* goData = GetGameObjectData(guid); if (!goData) { - LOG_ERROR("sql.sql", "GameObject (GUID: {}) does not exist but has a record in `gameobject_addon`", guid); + LOG_ERROR("db.query", "GameObject (GUID: {}) does not exist but has a record in `gameobject_addon`", guid); continue; } @@ -1474,14 +1474,14 @@ void ObjectMgr::LoadGameObjectAddons() if (gameObjectAddon.invisibilityType >= TOTAL_INVISIBILITY_TYPES) { - LOG_ERROR("sql.sql", "GameObject (GUID: {}) has invalid InvisibilityType in `gameobject_addon`", guid); + LOG_ERROR("db.query", "GameObject (GUID: {}) has invalid InvisibilityType in `gameobject_addon`", guid); gameObjectAddon.invisibilityType = INVISIBILITY_GENERAL; gameObjectAddon.InvisibilityValue = 0; } if (gameObjectAddon.invisibilityType && !gameObjectAddon.InvisibilityValue) { - LOG_ERROR("sql.sql", "GameObject (GUID: {}) has InvisibilityType set but has no InvisibilityValue in `gameobject_addon`, set to 1", guid); + LOG_ERROR("db.query", "GameObject (GUID: {}) has InvisibilityType set but has no InvisibilityValue in `gameobject_addon`, set to 1", guid); gameObjectAddon.InvisibilityValue = 1; } @@ -1573,14 +1573,14 @@ void ObjectMgr::LoadEquipmentTemplates() if (!sObjectMgr->GetCreatureTemplate(entry)) { - LOG_ERROR("sql.sql", "Creature template (CreatureID: {}) does not exist but has a record in `creature_equip_template`", entry); + LOG_ERROR("db.query", "Creature template (CreatureID: {}) does not exist but has a record in `creature_equip_template`", entry); continue; } uint8 id = fields[1].Get(); if (!id) { - LOG_ERROR("sql.sql", "Creature equipment template with id 0 found for creature {}, skipped.", entry); + LOG_ERROR("db.query", "Creature equipment template with id 0 found for creature {}, skipped.", entry); continue; } @@ -1599,7 +1599,7 @@ void ObjectMgr::LoadEquipmentTemplates() if (!dbcItem) { - LOG_ERROR("sql.sql", "Unknown item (ID={}) in creature_equip_template.ItemID{} for CreatureID = {} and ID = {}, forced to 0.", + LOG_ERROR("db.query", "Unknown item (ID={}) in creature_equip_template.ItemID{} for CreatureID = {} and ID = {}, forced to 0.", equipmentInfo.ItemEntry[i], i + 1, entry, id); equipmentInfo.ItemEntry[i] = 0; continue; @@ -1615,7 +1615,7 @@ void ObjectMgr::LoadEquipmentTemplates() dbcItem->InventoryType != INVTYPE_THROWN && dbcItem->InventoryType != INVTYPE_RANGEDRIGHT) { - LOG_ERROR("sql.sql", "Item (ID={}) in creature_equip_template.ItemID{} for CreatureID = {} and ID = {} is not equipable in a hand, forced to 0.", + LOG_ERROR("db.query", "Item (ID={}) in creature_equip_template.ItemID{} for CreatureID = {} and ID = {} is not equipable in a hand, forced to 0.", equipmentInfo.ItemEntry[i], i + 1, entry, id); equipmentInfo.ItemEntry[i] = 0; } @@ -1658,7 +1658,7 @@ void ObjectMgr::LoadCreatureMovementOverrides() ObjectGuid::LowType spawnId = fields[0].Get(); if (!GetCreatureData(spawnId)) { - LOG_ERROR("sql.sql", "Creature (GUID: {}) does not exist but has a record in `creature_movement_override`", spawnId); + LOG_ERROR("db.query", "Creature (GUID: {}) does not exist but has a record in `creature_movement_override`", spawnId); continue; } @@ -1753,7 +1753,7 @@ CreatureModelInfo const* ObjectMgr::GetCreatureModelRandomGender(uint32* display { CreatureModelInfo const* minfo_tmp = GetCreatureModelInfo(modelInfo->modelid_other_gender); if (!minfo_tmp) - LOG_ERROR("sql.sql", "Model (Entry: {}) has modelid_other_gender {} not found in table `creature_model_info`. ", *displayID, modelInfo->modelid_other_gender); + LOG_ERROR("db.query", "Model (Entry: {}) has modelid_other_gender {} not found in table `creature_model_info`. ", *displayID, modelInfo->modelid_other_gender); else { // Model ID changed @@ -1798,17 +1798,17 @@ void ObjectMgr::LoadCreatureModelInfo() // Checks if (!sCreatureDisplayInfoStore.LookupEntry(modelId)) - LOG_ERROR("sql.sql", "Table `creature_model_info` has model for not existed display id ({}).", modelId); + LOG_ERROR("db.query", "Table `creature_model_info` has model for not existed display id ({}).", modelId); if (modelInfo.gender > GENDER_NONE) { - LOG_ERROR("sql.sql", "Table `creature_model_info` has wrong gender ({}) for display id ({}).", uint32(modelInfo.gender), modelId); + LOG_ERROR("db.query", "Table `creature_model_info` has wrong gender ({}) for display id ({}).", uint32(modelInfo.gender), modelId); modelInfo.gender = GENDER_MALE; } if (modelInfo.modelid_other_gender && !sCreatureDisplayInfoStore.LookupEntry(modelInfo.modelid_other_gender)) { - LOG_ERROR("sql.sql", "Table `creature_model_info` has not existed alt.gender model ({}) for existed display id ({}).", modelInfo.modelid_other_gender, modelId); + LOG_ERROR("db.query", "Table `creature_model_info` has not existed alt.gender model ({}) for existed display id ({}).", modelInfo.modelid_other_gender, modelId); modelInfo.modelid_other_gender = 0; } @@ -1854,7 +1854,7 @@ void ObjectMgr::LoadLinkedRespawn() const CreatureData* slave = GetCreatureData(guidLow); if (!slave) { - LOG_ERROR("sql.sql", "LinkedRespawn: Creature (guid) {} not found in creature table", guidLow); + LOG_ERROR("db.query", "LinkedRespawn: Creature (guid) {} not found in creature table", guidLow); error = true; break; } @@ -1862,7 +1862,7 @@ void ObjectMgr::LoadLinkedRespawn() const CreatureData* master = GetCreatureData(linkedGuidLow); if (!master) { - LOG_ERROR("sql.sql", "LinkedRespawn: Creature (linkedGuid) {} not found in creature table", linkedGuidLow); + LOG_ERROR("db.query", "LinkedRespawn: Creature (linkedGuid) {} not found in creature table", linkedGuidLow); error = true; break; } @@ -1870,14 +1870,14 @@ void ObjectMgr::LoadLinkedRespawn() MapEntry const* const map = sMapStore.LookupEntry(master->mapid); if (!map || !map->Instanceable() || (master->mapid != slave->mapid)) { - LOG_ERROR("sql.sql", "LinkedRespawn: Creature '{}' linking to Creature '{}' on an unpermitted map.", guidLow, linkedGuidLow); + LOG_ERROR("db.query", "LinkedRespawn: Creature '{}' linking to Creature '{}' on an unpermitted map.", guidLow, linkedGuidLow); error = true; break; } if (!(master->spawnMask & slave->spawnMask)) // they must have a possibility to meet (normal/heroic difficulty) { - LOG_ERROR("sql.sql", "LinkedRespawn: Creature '{}' linking to Creature '{}' with not corresponding spawnMask", guidLow, linkedGuidLow); + LOG_ERROR("db.query", "LinkedRespawn: Creature '{}' linking to Creature '{}' with not corresponding spawnMask", guidLow, linkedGuidLow); error = true; break; } @@ -1891,7 +1891,7 @@ void ObjectMgr::LoadLinkedRespawn() const CreatureData* slave = GetCreatureData(guidLow); if (!slave) { - LOG_ERROR("sql.sql", "LinkedRespawn: Creature (guid) {} not found in creature table", guidLow); + LOG_ERROR("db.query", "LinkedRespawn: Creature (guid) {} not found in creature table", guidLow); error = true; break; } @@ -1899,7 +1899,7 @@ void ObjectMgr::LoadLinkedRespawn() const GameObjectData* master = GetGameObjectData(linkedGuidLow); if (!master) { - LOG_ERROR("sql.sql", "LinkedRespawn: Gameobject (linkedGuid) {} not found in gameobject table", linkedGuidLow); + LOG_ERROR("db.query", "LinkedRespawn: Gameobject (linkedGuid) {} not found in gameobject table", linkedGuidLow); error = true; break; } @@ -1907,14 +1907,14 @@ void ObjectMgr::LoadLinkedRespawn() MapEntry const* const map = sMapStore.LookupEntry(master->mapid); if (!map || !map->Instanceable() || (master->mapid != slave->mapid)) { - LOG_ERROR("sql.sql", "LinkedRespawn: Creature '{}' linking to Gameobject '{}' on an unpermitted map.", guidLow, linkedGuidLow); + LOG_ERROR("db.query", "LinkedRespawn: Creature '{}' linking to Gameobject '{}' on an unpermitted map.", guidLow, linkedGuidLow); error = true; break; } if (!(master->spawnMask & slave->spawnMask)) // they must have a possibility to meet (normal/heroic difficulty) { - LOG_ERROR("sql.sql", "LinkedRespawn: Creature '{}' linking to Gameobject '{}' with not corresponding spawnMask", guidLow, linkedGuidLow); + LOG_ERROR("db.query", "LinkedRespawn: Creature '{}' linking to Gameobject '{}' with not corresponding spawnMask", guidLow, linkedGuidLow); error = true; break; } @@ -1928,7 +1928,7 @@ void ObjectMgr::LoadLinkedRespawn() const GameObjectData* slave = GetGameObjectData(guidLow); if (!slave) { - LOG_ERROR("sql.sql", "LinkedRespawn: Gameobject (guid) {} not found in gameobject table", guidLow); + LOG_ERROR("db.query", "LinkedRespawn: Gameobject (guid) {} not found in gameobject table", guidLow); error = true; break; } @@ -1936,7 +1936,7 @@ void ObjectMgr::LoadLinkedRespawn() const GameObjectData* master = GetGameObjectData(linkedGuidLow); if (!master) { - LOG_ERROR("sql.sql", "LinkedRespawn: Gameobject (linkedGuid) {} not found in gameobject table", linkedGuidLow); + LOG_ERROR("db.query", "LinkedRespawn: Gameobject (linkedGuid) {} not found in gameobject table", linkedGuidLow); error = true; break; } @@ -1944,14 +1944,14 @@ void ObjectMgr::LoadLinkedRespawn() MapEntry const* const map = sMapStore.LookupEntry(master->mapid); if (!map || !map->Instanceable() || (master->mapid != slave->mapid)) { - LOG_ERROR("sql.sql", "LinkedRespawn: Gameobject '{}' linking to Gameobject '{}' on an unpermitted map.", guidLow, linkedGuidLow); + LOG_ERROR("db.query", "LinkedRespawn: Gameobject '{}' linking to Gameobject '{}' on an unpermitted map.", guidLow, linkedGuidLow); error = true; break; } if (!(master->spawnMask & slave->spawnMask)) // they must have a possibility to meet (normal/heroic difficulty) { - LOG_ERROR("sql.sql", "LinkedRespawn: Gameobject '{}' linking to Gameobject '{}' with not corresponding spawnMask", guidLow, linkedGuidLow); + LOG_ERROR("db.query", "LinkedRespawn: Gameobject '{}' linking to Gameobject '{}' with not corresponding spawnMask", guidLow, linkedGuidLow); error = true; break; } @@ -1965,7 +1965,7 @@ void ObjectMgr::LoadLinkedRespawn() const GameObjectData* slave = GetGameObjectData(guidLow); if (!slave) { - LOG_ERROR("sql.sql", "LinkedRespawn: Gameobject (guid) {} not found in gameobject table", guidLow); + LOG_ERROR("db.query", "LinkedRespawn: Gameobject (guid) {} not found in gameobject table", guidLow); error = true; break; } @@ -1973,7 +1973,7 @@ void ObjectMgr::LoadLinkedRespawn() const CreatureData* master = GetCreatureData(linkedGuidLow); if (!master) { - LOG_ERROR("sql.sql", "LinkedRespawn: Creature (linkedGuid) {} not found in creature table", linkedGuidLow); + LOG_ERROR("db.query", "LinkedRespawn: Creature (linkedGuid) {} not found in creature table", linkedGuidLow); error = true; break; } @@ -1981,14 +1981,14 @@ void ObjectMgr::LoadLinkedRespawn() MapEntry const* const map = sMapStore.LookupEntry(master->mapid); if (!map || !map->Instanceable() || (master->mapid != slave->mapid)) { - LOG_ERROR("sql.sql", "LinkedRespawn: Gameobject '{}' linking to Creature '{}' on an unpermitted map.", guidLow, linkedGuidLow); + LOG_ERROR("db.query", "LinkedRespawn: Gameobject '{}' linking to Creature '{}' on an unpermitted map.", guidLow, linkedGuidLow); error = true; break; } if (!(master->spawnMask & slave->spawnMask)) // they must have a possibility to meet (normal/heroic difficulty) { - LOG_ERROR("sql.sql", "LinkedRespawn: Gameobject '{}' linking to Creature '{}' with not corresponding spawnMask", guidLow, linkedGuidLow); + LOG_ERROR("db.query", "LinkedRespawn: Gameobject '{}' linking to Creature '{}' with not corresponding spawnMask", guidLow, linkedGuidLow); error = true; break; } @@ -2018,7 +2018,7 @@ bool ObjectMgr::SetCreatureLinkedRespawn(ObjectGuid::LowType guidLow, ObjectGuid if (!linkedGuidLow) // we're removing the linking { _linkedRespawnStore.erase(guid); - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_CRELINKED_RESPAWN); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_CRELINKED_RESPAWN); stmt->SetData(0, guidLow); WorldDatabase.Execute(stmt); return true; @@ -2027,27 +2027,27 @@ bool ObjectMgr::SetCreatureLinkedRespawn(ObjectGuid::LowType guidLow, ObjectGuid CreatureData const* slave = GetCreatureData(linkedGuidLow); if (!slave) { - LOG_ERROR("sql.sql", "Creature '{}' linking to non-existent creature '{}'.", guidLow, linkedGuidLow); + LOG_ERROR("db.query", "Creature '{}' linking to non-existent creature '{}'.", guidLow, linkedGuidLow); return false; } MapEntry const* map = sMapStore.LookupEntry(master->mapid); if (!map || !map->Instanceable() || (master->mapid != slave->mapid)) { - LOG_ERROR("sql.sql", "Creature '{}' linking to '{}' on an unpermitted map.", guidLow, linkedGuidLow); + LOG_ERROR("db.query", "Creature '{}' linking to '{}' on an unpermitted map.", guidLow, linkedGuidLow); return false; } if (!(master->spawnMask & slave->spawnMask)) // they must have a possibility to meet (normal/heroic difficulty) { - LOG_ERROR("sql.sql", "LinkedRespawn: Creature '{}' linking to '{}' with not corresponding spawnMask", guidLow, linkedGuidLow); + LOG_ERROR("db.query", "LinkedRespawn: Creature '{}' linking to '{}' with not corresponding spawnMask", guidLow, linkedGuidLow); return false; } ObjectGuid linkedGuid = ObjectGuid::Create(slave->id1, linkedGuidLow); _linkedRespawnStore[guid] = linkedGuid; - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_REP_CREATURE_LINKED_RESPAWN); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_REP_CREATURE_LINKED_RESPAWN); stmt->SetData(0, guidLow); stmt->SetData(1, linkedGuidLow); WorldDatabase.Execute(stmt); @@ -2081,26 +2081,26 @@ void ObjectMgr::LoadTempSummons() case SUMMONER_TYPE_CREATURE: if (!GetCreatureTemplate(summonerId)) { - LOG_ERROR("sql.sql", "Table `creature_summon_groups` has summoner with non existing entry {} for creature summoner type, skipped.", summonerId); + LOG_ERROR("db.query", "Table `creature_summon_groups` has summoner with non existing entry {} for creature summoner type, skipped.", summonerId); continue; } break; case SUMMONER_TYPE_GAMEOBJECT: if (!GetGameObjectTemplate(summonerId)) { - LOG_ERROR("sql.sql", "Table `creature_summon_groups` has summoner with non existing entry {} for gameobject summoner type, skipped.", summonerId); + LOG_ERROR("db.query", "Table `creature_summon_groups` has summoner with non existing entry {} for gameobject summoner type, skipped.", summonerId); continue; } break; case SUMMONER_TYPE_MAP: if (!sMapStore.LookupEntry(summonerId)) { - LOG_ERROR("sql.sql", "Table `creature_summon_groups` has summoner with non existing entry {} for map summoner type, skipped.", summonerId); + LOG_ERROR("db.query", "Table `creature_summon_groups` has summoner with non existing entry {} for map summoner type, skipped.", summonerId); continue; } break; default: - LOG_ERROR("sql.sql", "Table `creature_summon_groups` has unhandled summoner type {} for summoner {}, skipped.", summonerType, summonerId); + LOG_ERROR("db.query", "Table `creature_summon_groups` has unhandled summoner type {} for summoner {}, skipped.", summonerType, summonerId); continue; } @@ -2109,7 +2109,7 @@ void ObjectMgr::LoadTempSummons() if (!GetCreatureTemplate(data.entry)) { - LOG_ERROR("sql.sql", "Table `creature_summon_groups` has creature in group [Summoner ID: {}, Summoner Type: {}, Group ID: {}] with non existing creature entry {}, skipped.", summonerId, summonerType, group, data.entry); + LOG_ERROR("db.query", "Table `creature_summon_groups` has creature in group [Summoner ID: {}, Summoner Type: {}, Group ID: {}] with non existing creature entry {}, skipped.", summonerId, summonerType, group, data.entry); continue; } @@ -2124,7 +2124,7 @@ void ObjectMgr::LoadTempSummons() if (data.type > TEMPSUMMON_MANUAL_DESPAWN) { - LOG_ERROR("sql.sql", "Table `creature_summon_groups` has unhandled temp summon type {} in group [Summoner ID: {}, Summoner Type: {}, Group ID: {}] for creature entry {}, skipped.", data.type, summonerId, summonerType, group, data.entry); + LOG_ERROR("db.query", "Table `creature_summon_groups` has unhandled temp summon type {} in group [Summoner ID: {}, Summoner Type: {}, Group ID: {}] for creature entry {}, skipped.", data.type, summonerId, summonerType, group, data.entry); continue; } @@ -2183,24 +2183,24 @@ void ObjectMgr::LoadCreatures() CreatureTemplate const* cInfo = GetCreatureTemplate(id1); if (!cInfo) { - LOG_ERROR("sql.sql", "Table `creature` has creature (SpawnId: {}) with non existing creature entry {} in id1 field, skipped.", spawnId, id1); + LOG_ERROR("db.query", "Table `creature` has creature (SpawnId: {}) with non existing creature entry {} in id1 field, skipped.", spawnId, id1); continue; } CreatureTemplate const* cInfo2 = GetCreatureTemplate(id2); if (!cInfo2 && id2) { - LOG_ERROR("sql.sql", "Table `creature` has creature (SpawnId: {}) with non existing creature entry {} in id2 field, skipped.", spawnId, id2); + LOG_ERROR("db.query", "Table `creature` has creature (SpawnId: {}) with non existing creature entry {} in id2 field, skipped.", spawnId, id2); continue; } CreatureTemplate const* cInfo3 = GetCreatureTemplate(id3); if (!cInfo3 && id3) { - LOG_ERROR("sql.sql", "Table `creature` has creature (SpawnId: {}) with non existing creature entry {} in id3 field, skipped.", spawnId, id3); + LOG_ERROR("db.query", "Table `creature` has creature (SpawnId: {}) with non existing creature entry {} in id3 field, skipped.", spawnId, id3); continue; } if (!id2 && id3) { - LOG_ERROR("sql.sql", "Table `creature` has creature (SpawnId: {}) with creature entry {} in id3 field but no entry in id2 field, skipped.", spawnId, id3); + LOG_ERROR("db.query", "Table `creature` has creature (SpawnId: {}) with creature entry {} in id3 field but no entry in id2 field, skipped.", spawnId, id3); continue; } CreatureData& data = _creatureDataStore[spawnId]; @@ -2234,7 +2234,7 @@ void ObjectMgr::LoadCreatures() MapEntry const* mapEntry = sMapStore.LookupEntry(data.mapid); if (!mapEntry) { - LOG_ERROR("sql.sql", "Table `creature` have creature (SpawnId: {}) that spawned at not existed map (Id: {}), skipped.", spawnId, data.mapid); + LOG_ERROR("db.query", "Table `creature` have creature (SpawnId: {}) that spawned at not existed map (Id: {}), skipped.", spawnId, data.mapid); continue; } @@ -2244,7 +2244,7 @@ void ObjectMgr::LoadCreatures() // Skip spawnMask check for transport maps if (!_transportMaps.count(data.mapid) && data.spawnMask & ~spawnMasks[data.mapid]) - LOG_ERROR("sql.sql", "Table `creature` have creature (SpawnId: {}) that have wrong spawn mask {} including not supported difficulty modes for map (Id: {}).", + LOG_ERROR("db.query", "Table `creature` have creature (SpawnId: {}) that have wrong spawn mask {} including not supported difficulty modes for map (Id: {}).", spawnId, data.spawnMask, data.mapid); bool ok = true; @@ -2252,7 +2252,7 @@ void ObjectMgr::LoadCreatures() { if ((_difficultyEntries[diff].find(data.id1) != _difficultyEntries[diff].end()) || (_difficultyEntries[diff].find(data.id2) != _difficultyEntries[diff].end()) || (_difficultyEntries[diff].find(data.id3) != _difficultyEntries[diff].end())) { - LOG_ERROR("sql.sql", "Table `creature` have creature (SpawnId: {}) that listed as difficulty {} template (Entries: {}, {}, {}) in `creature_template`, skipped.", + LOG_ERROR("db.query", "Table `creature` have creature (SpawnId: {}) that listed as difficulty {} template (Entries: {}, {}, {}) in `creature_template`, skipped.", spawnId, diff + 1, data.id1, data.id2, data.id3); ok = false; } @@ -2265,7 +2265,7 @@ void ObjectMgr::LoadCreatures() { if ((!GetEquipmentInfo(data.id1, data.equipmentId)) || (data.id2 && !GetEquipmentInfo(data.id2, data.equipmentId)) || (data.id3 && !GetEquipmentInfo(data.id3, data.equipmentId))) { - LOG_ERROR("sql.sql", "Table `creature` have creature (Entries: {}, {}, {}) one or more with equipment_id {} not found in table `creature_equip_template`, set to no equipment.", + LOG_ERROR("db.query", "Table `creature` have creature (Entries: {}, {}, {}) one or more with equipment_id {} not found in table `creature_equip_template`, set to no equipment.", data.id1, data.id2, data.id3, data.equipmentId); data.equipmentId = 0; } @@ -2273,24 +2273,24 @@ void ObjectMgr::LoadCreatures() if ((cInfo->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND) || (data.id2 && cInfo2->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND) || (data.id3 && cInfo3->flags_extra & CREATURE_FLAG_EXTRA_INSTANCE_BIND)) { if (!mapEntry->IsDungeon()) - LOG_ERROR("sql.sql", "Table `creature` have creature (SpawnId: {} Entries: {}, {}, {}) with a `creature_template`.`flags_extra` in one or more entries including CREATURE_FLAG_EXTRA_INSTANCE_BIND but creature are not in instance.", + LOG_ERROR("db.query", "Table `creature` have creature (SpawnId: {} Entries: {}, {}, {}) with a `creature_template`.`flags_extra` in one or more entries including CREATURE_FLAG_EXTRA_INSTANCE_BIND but creature are not in instance.", spawnId, data.id1, data.id2, data.id3); } if (data.movementType >= MAX_DB_MOTION_TYPE) { - LOG_ERROR("sql.sql", "Table `creature` has creature (SpawnId: {} Entries: {}, {}, {}) with wrong movement generator type ({}), ignored and set to IDLE.", spawnId, data.id1, data.id2, data.id3, data.movementType); + LOG_ERROR("db.query", "Table `creature` has creature (SpawnId: {} Entries: {}, {}, {}) with wrong movement generator type ({}), ignored and set to IDLE.", spawnId, data.id1, data.id2, data.id3, data.movementType); data.movementType = IDLE_MOTION_TYPE; } if (data.wander_distance < 0.0f) { - LOG_ERROR("sql.sql", "Table `creature` have creature (SpawnId: {} Entries: {}, {}, {}) with `wander_distance`< 0, set to 0.", spawnId, data.id1, data.id2, data.id3); + LOG_ERROR("db.query", "Table `creature` have creature (SpawnId: {} Entries: {}, {}, {}) with `wander_distance`< 0, set to 0.", spawnId, data.id1, data.id2, data.id3); data.wander_distance = 0.0f; } else if (data.movementType == RANDOM_MOTION_TYPE) { if (data.wander_distance == 0.0f) { - LOG_ERROR("sql.sql", "Table `creature` have creature (SpawnId: {} Entries: {}, {}, {}) with `MovementType`=1 (random movement) but with `wander_distance`=0, replace by idle movement type (0).", + LOG_ERROR("db.query", "Table `creature` have creature (SpawnId: {} Entries: {}, {}, {}) with `MovementType`=1 (random movement) but with `wander_distance`=0, replace by idle movement type (0).", spawnId, data.id1, data.id2, data.id3); data.movementType = IDLE_MOTION_TYPE; } @@ -2299,14 +2299,14 @@ void ObjectMgr::LoadCreatures() { if (data.wander_distance != 0.0f) { - LOG_ERROR("sql.sql", "Table `creature` have creature (SpawnId: {} Entries: {}, {}, {}) with `MovementType`=0 (idle) have `wander_distance`<>0, set to 0.", spawnId, data.id1, data.id2, data.id3); + LOG_ERROR("db.query", "Table `creature` have creature (SpawnId: {} Entries: {}, {}, {}) with `MovementType`=0 (idle) have `wander_distance`<>0, set to 0.", spawnId, data.id1, data.id2, data.id3); data.wander_distance = 0.0f; } } if (data.phaseMask == 0) { - LOG_ERROR("sql.sql", "Table `creature` have creature (SpawnId: {} Entries: {}, {}, {}) with `phaseMask`=0 (not visible for anyone), set to 1.", spawnId, data.id1, data.id2, data.id3); + LOG_ERROR("db.query", "Table `creature` have creature (SpawnId: {} Entries: {}, {}, {}) with `phaseMask`=0 (not visible for anyone), set to 1.", spawnId, data.id1, data.id2, data.id3); data.phaseMask = 1; } @@ -2315,7 +2315,7 @@ void ObjectMgr::LoadCreatures() uint32 zoneId = sMapMgr->GetZoneId(data.phaseMask, data.mapid, data.posX, data.posY, data.posZ); uint32 areaId = sMapMgr->GetAreaId(data.phaseMask, data.mapid, data.posX, data.posY, data.posZ); - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_ZONE_AREA_DATA); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_ZONE_AREA_DATA); stmt->SetData(0, zoneId); stmt->SetData(1, areaId); @@ -2403,7 +2403,7 @@ uint32 ObjectMgr::AddGOData(uint32 entry, uint32 mapId, float x, float y, float GameObject* go = sObjectMgr->IsGameObjectStaticTransport(data.id) ? new StaticTransport() : new GameObject(); if (!go->LoadGameObjectFromDB(spawnId, map)) { - LOG_ERROR("sql.sql", "AddGOData: cannot add gameobject entry {} to map", entry); + LOG_ERROR("db.query", "AddGOData: cannot add gameobject entry {} to map", entry); delete go; return 0; } @@ -2460,7 +2460,7 @@ uint32 ObjectMgr::AddCreData(uint32 entry, uint32 mapId, float x, float y, float Creature* creature = new Creature(); if (!creature->LoadCreatureFromDB(spawnId, map, true, false, true)) { - LOG_ERROR("sql.sql", "AddCreature: Cannot add creature entry {} to map", entry); + LOG_ERROR("db.query", "AddCreature: Cannot add creature entry {} to map", entry); delete creature; return 0; } @@ -2510,7 +2510,7 @@ void ObjectMgr::LoadGameobjects() GameObjectTemplate const* gInfo = GetGameObjectTemplate(entry); if (!gInfo) { - LOG_ERROR("sql.sql", "Table `gameobject` has gameobject (GUID: {}) with non existing gameobject entry {}, skipped.", guid, entry); + LOG_ERROR("db.query", "Table `gameobject` has gameobject (GUID: {}) with non existing gameobject entry {}, skipped.", guid, entry); continue; } @@ -2522,14 +2522,14 @@ void ObjectMgr::LoadGameobjects() case GAMEOBJECT_TYPE_SPELL_FOCUS: break; default: - LOG_ERROR("sql.sql", "Gameobject (GUID: {} Entry {} GoType: {}) doesn't have a displayId ({}), not loaded.", guid, entry, gInfo->type, gInfo->displayId); + LOG_ERROR("db.query", "Gameobject (GUID: {} Entry {} GoType: {}) doesn't have a displayId ({}), not loaded.", guid, entry, gInfo->type, gInfo->displayId); break; } } if (gInfo->displayId && !sGameObjectDisplayInfoStore.LookupEntry(gInfo->displayId)) { - LOG_ERROR("sql.sql", "Gameobject (GUID: {} Entry {} GoType: {}) has an invalid displayId ({}), not loaded.", guid, entry, gInfo->type, gInfo->displayId); + LOG_ERROR("db.query", "Gameobject (GUID: {} Entry {} GoType: {}) has an invalid displayId ({}), not loaded.", guid, entry, gInfo->type, gInfo->displayId); continue; } @@ -2553,13 +2553,13 @@ void ObjectMgr::LoadGameobjects() MapEntry const* mapEntry = sMapStore.LookupEntry(data.mapid); if (!mapEntry) { - LOG_ERROR("sql.sql", "Table `gameobject` has gameobject (GUID: {} Entry: {}) spawned on a non-existed map (Id: {}), skip", guid, data.id, data.mapid); + LOG_ERROR("db.query", "Table `gameobject` has gameobject (GUID: {} Entry: {}) spawned on a non-existed map (Id: {}), skip", guid, data.id, data.mapid); continue; } if (data.spawntimesecs == 0 && gInfo->IsDespawnAtAction()) { - LOG_ERROR("sql.sql", "Table `gameobject` has gameobject (GUID: {} Entry: {}) with `spawntimesecs` (0) value, but the gameobejct is marked as despawnable at action.", guid, data.id); + LOG_ERROR("db.query", "Table `gameobject` has gameobject (GUID: {} Entry: {}) with `spawntimesecs` (0) value, but the gameobejct is marked as despawnable at action.", guid, data.id); } data.animprogress = fields[12].Get(); @@ -2568,7 +2568,7 @@ void ObjectMgr::LoadGameobjects() uint32 go_state = fields[13].Get(); if (go_state >= MAX_GO_STATE) { - LOG_ERROR("sql.sql", "Table `gameobject` has gameobject (GUID: {} Entry: {}) with invalid `state` ({}) value, skip", guid, data.id, go_state); + LOG_ERROR("db.query", "Table `gameobject` has gameobject (GUID: {} Entry: {}) with invalid `state` ({}) value, skip", guid, data.id, go_state); continue; } data.go_state = GOState(go_state); @@ -2576,7 +2576,7 @@ void ObjectMgr::LoadGameobjects() data.spawnMask = fields[14].Get(); if (!_transportMaps.count(data.mapid) && data.spawnMask & ~spawnMasks[data.mapid]) - LOG_ERROR("sql.sql", "Table `gameobject` has gameobject (GUID: {} Entry: {}) that has wrong spawn mask {} including not supported difficulty modes for map (Id: {}), skip", guid, data.id, data.spawnMask, data.mapid); + LOG_ERROR("db.query", "Table `gameobject` has gameobject (GUID: {} Entry: {}) that has wrong spawn mask {} including not supported difficulty modes for map (Id: {}), skip", guid, data.id, data.spawnMask, data.mapid); data.phaseMask = fields[15].Get(); int16 gameEvent = fields[16].Get(); @@ -2584,37 +2584,37 @@ void ObjectMgr::LoadGameobjects() if (data.rotation.x < -1.0f || data.rotation.x > 1.0f) { - LOG_ERROR("sql.sql", "Table `gameobject` has gameobject (GUID: {} Entry: {}) with invalid rotationX ({}) value, skip", guid, data.id, data.rotation.x); + LOG_ERROR("db.query", "Table `gameobject` has gameobject (GUID: {} Entry: {}) with invalid rotationX ({}) value, skip", guid, data.id, data.rotation.x); continue; } if (data.rotation.y < -1.0f || data.rotation.y > 1.0f) { - LOG_ERROR("sql.sql", "Table `gameobject` has gameobject (GUID: {} Entry: {}) with invalid rotationY ({}) value, skip", guid, data.id, data.rotation.y); + LOG_ERROR("db.query", "Table `gameobject` has gameobject (GUID: {} Entry: {}) with invalid rotationY ({}) value, skip", guid, data.id, data.rotation.y); continue; } if (data.rotation.z < -1.0f || data.rotation.z > 1.0f) { - LOG_ERROR("sql.sql", "Table `gameobject` has gameobject (GUID: {} Entry: {}) with invalid rotationZ ({}) value, skip", guid, data.id, data.rotation.z); + LOG_ERROR("db.query", "Table `gameobject` has gameobject (GUID: {} Entry: {}) with invalid rotationZ ({}) value, skip", guid, data.id, data.rotation.z); continue; } if (data.rotation.w < -1.0f || data.rotation.w > 1.0f) { - LOG_ERROR("sql.sql", "Table `gameobject` has gameobject (GUID: {} Entry: {}) with invalid rotationW ({}) value, skip", guid, data.id, data.rotation.w); + LOG_ERROR("db.query", "Table `gameobject` has gameobject (GUID: {} Entry: {}) with invalid rotationW ({}) value, skip", guid, data.id, data.rotation.w); continue; } if (!MapMgr::IsValidMapCoord(data.mapid, data.posX, data.posY, data.posZ, data.orientation)) { - LOG_ERROR("sql.sql", "Table `gameobject` has gameobject (GUID: {} Entry: {}) with invalid coordinates, skip", guid, data.id); + LOG_ERROR("db.query", "Table `gameobject` has gameobject (GUID: {} Entry: {}) with invalid coordinates, skip", guid, data.id); continue; } if (data.phaseMask == 0) { - LOG_ERROR("sql.sql", "Table `gameobject` has gameobject (GUID: {} Entry: {}) with `phaseMask`=0 (not visible for anyone), set to 1.", guid, data.id); + LOG_ERROR("db.query", "Table `gameobject` has gameobject (GUID: {} Entry: {}) with `phaseMask`=0 (not visible for anyone), set to 1.", guid, data.id); data.phaseMask = 1; } @@ -2623,7 +2623,7 @@ void ObjectMgr::LoadGameobjects() uint32 zoneId = sMapMgr->GetZoneId(data.phaseMask, data.mapid, data.posX, data.posY, data.posZ); uint32 areaId = sMapMgr->GetAreaId(data.phaseMask, data.mapid, data.posX, data.posY, data.posZ); - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_GAMEOBJECT_ZONE_AREA_DATA); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_GAMEOBJECT_ZONE_AREA_DATA); stmt->SetData(0, zoneId); stmt->SetData(1, areaId); @@ -2867,53 +2867,53 @@ void ObjectMgr::LoadItemTemplates() { if (itemTemplate.Class != dbcitem->ClassID) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong Class value ({}), must be ({}).", entry, itemTemplate.Class, dbcitem->ClassID); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong Class value ({}), must be ({}).", entry, itemTemplate.Class, dbcitem->ClassID); if (enforceDBCAttributes) itemTemplate.Class = dbcitem->ClassID; } if (itemTemplate.SubClass != dbcitem->SubclassID) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong Subclass value ({}) for class {}, must be ({}).", entry, itemTemplate.SubClass, itemTemplate.Class, dbcitem->SubclassID); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong Subclass value ({}) for class {}, must be ({}).", entry, itemTemplate.SubClass, itemTemplate.Class, dbcitem->SubclassID); if (enforceDBCAttributes) itemTemplate.SubClass = dbcitem->SubclassID; } if (itemTemplate.SoundOverrideSubclass != dbcitem->SoundOverrideSubclassID) { - LOG_ERROR("sql.sql", "Item (Entry: {}) does not have a correct SoundOverrideSubclass ({}), must be {}.", entry, itemTemplate.SoundOverrideSubclass); + LOG_ERROR("db.query", "Item (Entry: {}) does not have a correct SoundOverrideSubclass ({}), must be {}.", entry, itemTemplate.SoundOverrideSubclass); if (enforceDBCAttributes) itemTemplate.SoundOverrideSubclass = dbcitem->SoundOverrideSubclassID; } if (itemTemplate.Material != dbcitem->Material) { - LOG_ERROR("sql.sql", "Item (Entry: {}) does not have a correct material ({}), must be {}.", entry, itemTemplate.Material, dbcitem->Material); + LOG_ERROR("db.query", "Item (Entry: {}) does not have a correct material ({}), must be {}.", entry, itemTemplate.Material, dbcitem->Material); if (enforceDBCAttributes) itemTemplate.Material = dbcitem->Material; } if (itemTemplate.InventoryType != dbcitem->InventoryType) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong InventoryType value ({}), must be {}.", entry, itemTemplate.InventoryType, dbcitem->InventoryType); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong InventoryType value ({}), must be {}.", entry, itemTemplate.InventoryType, dbcitem->InventoryType); if (enforceDBCAttributes) itemTemplate.InventoryType = dbcitem->InventoryType; } if (itemTemplate.DisplayInfoID != dbcitem->DisplayInfoID) { - LOG_ERROR("sql.sql", "Item (Entry: {}) does not have a correct display id ({}), must be {}.", entry, itemTemplate.DisplayInfoID, dbcitem->DisplayInfoID); + LOG_ERROR("db.query", "Item (Entry: {}) does not have a correct display id ({}), must be {}.", entry, itemTemplate.DisplayInfoID, dbcitem->DisplayInfoID); if (enforceDBCAttributes) itemTemplate.DisplayInfoID = dbcitem->DisplayInfoID; } if (itemTemplate.Sheath != dbcitem->SheatheType) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong Sheath ({}), must be {}.", entry, itemTemplate.Sheath, dbcitem->SheatheType); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong Sheath ({}), must be {}.", entry, itemTemplate.Sheath, dbcitem->SheatheType); if (enforceDBCAttributes) itemTemplate.Sheath = dbcitem->SheatheType; } } else - LOG_ERROR("sql.sql", "Item (Entry: {}) does not exist in item.dbc! (not correct id?).", entry); + LOG_ERROR("db.query", "Item (Entry: {}) does not exist in item.dbc! (not correct id?).", entry); if (itemTemplate.Quality >= MAX_ITEM_QUALITY) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong Quality value ({})", entry, itemTemplate.Quality); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong Quality value ({})", entry, itemTemplate.Quality); itemTemplate.Quality = ITEM_QUALITY_NORMAL; } @@ -2921,30 +2921,30 @@ void ObjectMgr::LoadItemTemplates() { if (FactionEntry const* faction = sFactionStore.LookupEntry(HORDE)) if ((itemTemplate.AllowableRace & faction->BaseRepRaceMask[0]) == 0) - LOG_ERROR("sql.sql", "Item (Entry: {}) has value ({}) in `AllowableRace` races, not compatible with ITEM_FLAGS_EXTRA_HORDE_ONLY ({}) in Flags field, item cannot be equipped or used by these races.", + LOG_ERROR("db.query", "Item (Entry: {}) has value ({}) in `AllowableRace` races, not compatible with ITEM_FLAGS_EXTRA_HORDE_ONLY ({}) in Flags field, item cannot be equipped or used by these races.", entry, itemTemplate.AllowableRace, ITEM_FLAGS_EXTRA_HORDE_ONLY); if (itemTemplate.Flags2 & ITEM_FLAGS_EXTRA_ALLIANCE_ONLY) - LOG_ERROR("sql.sql", "Item (Entry: {}) has value ({}) in `Flags2` flags (ITEM_FLAGS_EXTRA_ALLIANCE_ONLY) and ITEM_FLAGS_EXTRA_HORDE_ONLY ({}) in Flags field, this is a wrong combination.", + LOG_ERROR("db.query", "Item (Entry: {}) has value ({}) in `Flags2` flags (ITEM_FLAGS_EXTRA_ALLIANCE_ONLY) and ITEM_FLAGS_EXTRA_HORDE_ONLY ({}) in Flags field, this is a wrong combination.", entry, ITEM_FLAGS_EXTRA_ALLIANCE_ONLY, ITEM_FLAGS_EXTRA_HORDE_ONLY); } else if (itemTemplate.Flags2 & ITEM_FLAGS_EXTRA_ALLIANCE_ONLY) { if (FactionEntry const* faction = sFactionStore.LookupEntry(ALLIANCE)) if ((itemTemplate.AllowableRace & faction->BaseRepRaceMask[0]) == 0) - LOG_ERROR("sql.sql", "Item (Entry: {}) has value ({}) in `AllowableRace` races, not compatible with ITEM_FLAGS_EXTRA_ALLIANCE_ONLY ({}) in Flags field, item cannot be equipped or used by these races.", + LOG_ERROR("db.query", "Item (Entry: {}) has value ({}) in `AllowableRace` races, not compatible with ITEM_FLAGS_EXTRA_ALLIANCE_ONLY ({}) in Flags field, item cannot be equipped or used by these races.", entry, itemTemplate.AllowableRace, ITEM_FLAGS_EXTRA_ALLIANCE_ONLY); } if (itemTemplate.BuyCount <= 0) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong BuyCount value ({}), set to default(1).", entry, itemTemplate.BuyCount); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong BuyCount value ({}), set to default(1).", entry, itemTemplate.BuyCount); itemTemplate.BuyCount = 1; } if (itemTemplate.RequiredSkill >= MAX_SKILL_TYPE) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong RequiredSkill value ({})", entry, itemTemplate.RequiredSkill); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong RequiredSkill value ({})", entry, itemTemplate.RequiredSkill); itemTemplate.RequiredSkill = 0; } @@ -2964,60 +2964,60 @@ void ObjectMgr::LoadItemTemplates() if (req) { if (!(itemTemplate.AllowableClass & CLASSMASK_ALL_PLAYABLE)) - LOG_ERROR("sql.sql", "Item (Entry: {}) does not have any playable classes ({}) in `AllowableClass` and can't be equipped or used.", entry, itemTemplate.AllowableClass); + LOG_ERROR("db.query", "Item (Entry: {}) does not have any playable classes ({}) in `AllowableClass` and can't be equipped or used.", entry, itemTemplate.AllowableClass); if (!(itemTemplate.AllowableRace & RACEMASK_ALL_PLAYABLE)) - LOG_ERROR("sql.sql", "Item (Entry: {}) does not have any playable races ({}) in `AllowableRace` and can't be equipped or used.", entry, itemTemplate.AllowableRace); + LOG_ERROR("db.query", "Item (Entry: {}) does not have any playable races ({}) in `AllowableRace` and can't be equipped or used.", entry, itemTemplate.AllowableRace); } } if (itemTemplate.RequiredSpell && !sSpellMgr->GetSpellInfo(itemTemplate.RequiredSpell)) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has a wrong (non-existing) spell in RequiredSpell ({})", entry, itemTemplate.RequiredSpell); + LOG_ERROR("db.query", "Item (Entry: {}) has a wrong (non-existing) spell in RequiredSpell ({})", entry, itemTemplate.RequiredSpell); itemTemplate.RequiredSpell = 0; } if (itemTemplate.RequiredReputationRank >= MAX_REPUTATION_RANK) - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong reputation rank in RequiredReputationRank ({}), item can't be used.", entry, itemTemplate.RequiredReputationRank); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong reputation rank in RequiredReputationRank ({}), item can't be used.", entry, itemTemplate.RequiredReputationRank); if (itemTemplate.RequiredReputationFaction) { if (!sFactionStore.LookupEntry(itemTemplate.RequiredReputationFaction)) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong (not existing) faction in RequiredReputationFaction ({})", entry, itemTemplate.RequiredReputationFaction); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong (not existing) faction in RequiredReputationFaction ({})", entry, itemTemplate.RequiredReputationFaction); itemTemplate.RequiredReputationFaction = 0; } if (itemTemplate.RequiredReputationRank == MIN_REPUTATION_RANK) - LOG_ERROR("sql.sql", "Item (Entry: {}) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.", entry); + LOG_ERROR("db.query", "Item (Entry: {}) has min. reputation rank in RequiredReputationRank (0) but RequiredReputationFaction > 0, faction setting is useless.", entry); } if (itemTemplate.MaxCount < -1) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has too large negative in maxcount ({}), replace by value (-1) no storing limits.", entry, itemTemplate.MaxCount); + LOG_ERROR("db.query", "Item (Entry: {}) has too large negative in maxcount ({}), replace by value (-1) no storing limits.", entry, itemTemplate.MaxCount); itemTemplate.MaxCount = -1; } if (itemTemplate.Stackable == 0) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong value in stackable ({}), replace by default 1.", entry, itemTemplate.Stackable); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong value in stackable ({}), replace by default 1.", entry, itemTemplate.Stackable); itemTemplate.Stackable = 1; } else if (itemTemplate.Stackable < -1) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has too large negative in stackable ({}), replace by value (-1) no stacking limits.", entry, itemTemplate.Stackable); + LOG_ERROR("db.query", "Item (Entry: {}) has too large negative in stackable ({}), replace by value (-1) no stacking limits.", entry, itemTemplate.Stackable); itemTemplate.Stackable = -1; } if (itemTemplate.ContainerSlots > MAX_BAG_SIZE) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has too large value in ContainerSlots ({}), replace by hardcoded limit ({}).", entry, itemTemplate.ContainerSlots, MAX_BAG_SIZE); + LOG_ERROR("db.query", "Item (Entry: {}) has too large value in ContainerSlots ({}), replace by hardcoded limit ({}).", entry, itemTemplate.ContainerSlots, MAX_BAG_SIZE); itemTemplate.ContainerSlots = MAX_BAG_SIZE; } if (itemTemplate.StatsCount > MAX_ITEM_PROTO_STATS) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has too large value in statscount ({}), replace by hardcoded limit ({}).", entry, itemTemplate.StatsCount, MAX_ITEM_PROTO_STATS); + LOG_ERROR("db.query", "Item (Entry: {}) has too large value in statscount ({}), replace by hardcoded limit ({}).", entry, itemTemplate.StatsCount, MAX_ITEM_PROTO_STATS); itemTemplate.StatsCount = MAX_ITEM_PROTO_STATS; } @@ -3026,7 +3026,7 @@ void ObjectMgr::LoadItemTemplates() // for ItemStatValue != 0 if (itemTemplate.ItemStat[j].ItemStatValue && itemTemplate.ItemStat[j].ItemStatType >= MAX_ITEM_MOD) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong (non-existing?) stat_type{} ({})", entry, j + 1, itemTemplate.ItemStat[j].ItemStatType); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong (non-existing?) stat_type{} ({})", entry, j + 1, itemTemplate.ItemStat[j].ItemStatType); itemTemplate.ItemStat[j].ItemStatType = 0; } @@ -3034,7 +3034,7 @@ void ObjectMgr::LoadItemTemplates() { case ITEM_MOD_SPELL_HEALING_DONE: case ITEM_MOD_SPELL_DAMAGE_DONE: - LOG_ERROR("sql.sql", "Item (Entry: {}) has deprecated stat_type{} ({})", entry, j + 1, itemTemplate.ItemStat[j].ItemStatType); + LOG_ERROR("db.query", "Item (Entry: {}) has deprecated stat_type{} ({})", entry, j + 1, itemTemplate.ItemStat[j].ItemStatType); break; default: break; @@ -3045,7 +3045,7 @@ void ObjectMgr::LoadItemTemplates() { if (itemTemplate.Damage[j].DamageType >= MAX_SPELL_SCHOOL) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong dmg_type{} ({})", entry, j + 1, itemTemplate.Damage[j].DamageType); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong dmg_type{} ({})", entry, j + 1, itemTemplate.Damage[j].DamageType); itemTemplate.Damage[j].DamageType = 0; } } @@ -3056,7 +3056,7 @@ void ObjectMgr::LoadItemTemplates() // spell_1 if (itemTemplate.Spells[0].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong item spell trigger value in spelltrigger_{} ({}) for special learning format", entry, 0 + 1, itemTemplate.Spells[0].SpellTrigger); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong item spell trigger value in spelltrigger_{} ({}) for special learning format", entry, 0 + 1, itemTemplate.Spells[0].SpellTrigger); itemTemplate.Spells[0].SpellId = 0; itemTemplate.Spells[0].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE; itemTemplate.Spells[1].SpellId = 0; @@ -3066,14 +3066,14 @@ void ObjectMgr::LoadItemTemplates() // spell_2 have learning spell if (itemTemplate.Spells[1].SpellTrigger != ITEM_SPELLTRIGGER_LEARN_SPELL_ID) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong item spell trigger value in spelltrigger_{} ({}) for special learning format.", entry, 1 + 1, itemTemplate.Spells[1].SpellTrigger); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong item spell trigger value in spelltrigger_{} ({}) for special learning format.", entry, 1 + 1, itemTemplate.Spells[1].SpellTrigger); itemTemplate.Spells[0].SpellId = 0; itemTemplate.Spells[1].SpellId = 0; itemTemplate.Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE; } else if (!itemTemplate.Spells[1].SpellId) { - LOG_ERROR("sql.sql", "Item (Entry: {}) does not have an expected spell in spellid_{} in special learning format.", entry, 1 + 1); + LOG_ERROR("db.query", "Item (Entry: {}) does not have an expected spell in spellid_{} in special learning format.", entry, 1 + 1); itemTemplate.Spells[0].SpellId = 0; itemTemplate.Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE; } @@ -3082,7 +3082,7 @@ void ObjectMgr::LoadItemTemplates() SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itemTemplate.Spells[1].SpellId); if (!spellInfo && !DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, itemTemplate.Spells[1].SpellId, nullptr)) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong (not existing) spell in spellid_{} ({})", entry, 1 + 1, itemTemplate.Spells[1].SpellId); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong (not existing) spell in spellid_{} ({})", entry, 1 + 1, itemTemplate.Spells[1].SpellId); itemTemplate.Spells[0].SpellId = 0; itemTemplate.Spells[1].SpellId = 0; itemTemplate.Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE; @@ -3090,7 +3090,7 @@ void ObjectMgr::LoadItemTemplates() // allowed only in special format else if ((itemTemplate.Spells[1].SpellId == 483) || (itemTemplate.Spells[1].SpellId == 55884)) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has broken spell in spellid_{} ({})", entry, 1 + 1, itemTemplate.Spells[1].SpellId); + LOG_ERROR("db.query", "Item (Entry: {}) has broken spell in spellid_{} ({})", entry, 1 + 1, itemTemplate.Spells[1].SpellId); itemTemplate.Spells[0].SpellId = 0; itemTemplate.Spells[1].SpellId = 0; itemTemplate.Spells[1].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE; @@ -3102,13 +3102,13 @@ void ObjectMgr::LoadItemTemplates() { if (itemTemplate.Spells[j].SpellTrigger != ITEM_SPELLTRIGGER_ON_USE) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong item spell trigger value in spelltrigger_{} ({})", entry, j + 1, itemTemplate.Spells[j].SpellTrigger); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong item spell trigger value in spelltrigger_{} ({})", entry, j + 1, itemTemplate.Spells[j].SpellTrigger); itemTemplate.Spells[j].SpellId = 0; itemTemplate.Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE; } else if (itemTemplate.Spells[j].SpellId != 0) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong spell in spellid_{} ({}) for learning special format", entry, j + 1, itemTemplate.Spells[j].SpellId); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong spell in spellid_{} ({}) for learning special format", entry, j + 1, itemTemplate.Spells[j].SpellId); itemTemplate.Spells[j].SpellId = 0; } } @@ -3120,7 +3120,7 @@ void ObjectMgr::LoadItemTemplates() { if (itemTemplate.Spells[j].SpellTrigger >= MAX_ITEM_SPELLTRIGGER || itemTemplate.Spells[j].SpellTrigger == ITEM_SPELLTRIGGER_LEARN_SPELL_ID) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong item spell trigger value in spelltrigger_{} ({})", entry, j + 1, itemTemplate.Spells[j].SpellTrigger); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong item spell trigger value in spelltrigger_{} ({})", entry, j + 1, itemTemplate.Spells[j].SpellTrigger); itemTemplate.Spells[j].SpellId = 0; itemTemplate.Spells[j].SpellTrigger = ITEM_SPELLTRIGGER_ON_USE; } @@ -3130,13 +3130,13 @@ void ObjectMgr::LoadItemTemplates() SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(itemTemplate.Spells[j].SpellId); if (!spellInfo && !DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, itemTemplate.Spells[j].SpellId, nullptr)) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong (not existing) spell in spellid_{} ({})", entry, j + 1, itemTemplate.Spells[j].SpellId); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong (not existing) spell in spellid_{} ({})", entry, j + 1, itemTemplate.Spells[j].SpellId); itemTemplate.Spells[j].SpellId = 0; } // allowed only in special format else if ((itemTemplate.Spells[j].SpellId == 483) || (itemTemplate.Spells[j].SpellId == 55884)) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has broken spell in spellid_{} ({})", entry, j + 1, itemTemplate.Spells[j].SpellId); + LOG_ERROR("db.query", "Item (Entry: {}) has broken spell in spellid_{} ({})", entry, j + 1, itemTemplate.Spells[j].SpellId); itemTemplate.Spells[j].SpellId = 0; } } @@ -3144,13 +3144,13 @@ void ObjectMgr::LoadItemTemplates() } if (itemTemplate.Bonding >= MAX_BIND_TYPE) - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong Bonding value ({})", entry, itemTemplate.Bonding); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong Bonding value ({})", entry, itemTemplate.Bonding); if (itemTemplate.PageText && !GetPageText(itemTemplate.PageText)) - LOG_ERROR("sql.sql", "Item (Entry: {}) has non existing first page (Id:{})", entry, itemTemplate.PageText); + LOG_ERROR("db.query", "Item (Entry: {}) has non existing first page (Id:{})", entry, itemTemplate.PageText); if (itemTemplate.LockID && !sLockStore.LookupEntry(itemTemplate.LockID)) - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong LockID ({})", entry, itemTemplate.LockID); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong LockID ({})", entry, itemTemplate.LockID); if (itemTemplate.RandomProperty) { @@ -3160,28 +3160,28 @@ void ObjectMgr::LoadItemTemplates() else if (!sItemRandomPropertiesStore.LookupEntry(GetItemEnchantMod(itemTemplate.RandomProperty))) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty ({})", entry, itemTemplate.RandomProperty); + LOG_ERROR("db.query", "Item (Entry: {}) has unknown (wrong or not listed in `item_enchantment_template`) RandomProperty ({})", entry, itemTemplate.RandomProperty); itemTemplate.RandomProperty = 0; } } if (itemTemplate.RandomSuffix && !sItemRandomSuffixStore.LookupEntry(GetItemEnchantMod(itemTemplate.RandomSuffix))) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong RandomSuffix ({})", entry, itemTemplate.RandomSuffix); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong RandomSuffix ({})", entry, itemTemplate.RandomSuffix); itemTemplate.RandomSuffix = 0; } if (itemTemplate.ItemSet && !sItemSetStore.LookupEntry(itemTemplate.ItemSet)) { - LOG_ERROR("sql.sql", "Item (Entry: {}) have wrong ItemSet ({})", entry, itemTemplate.ItemSet); + LOG_ERROR("db.query", "Item (Entry: {}) have wrong ItemSet ({})", entry, itemTemplate.ItemSet); itemTemplate.ItemSet = 0; } if (itemTemplate.Area && !sAreaTableStore.LookupEntry(itemTemplate.Area)) - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong Area ({})", entry, itemTemplate.Area); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong Area ({})", entry, itemTemplate.Area); if (itemTemplate.Map && !sMapStore.LookupEntry(itemTemplate.Map)) - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong Map ({})", entry, itemTemplate.Map); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong Map ({})", entry, itemTemplate.Map); if (itemTemplate.BagFamily) { @@ -3195,7 +3195,7 @@ void ObjectMgr::LoadItemTemplates() ItemBagFamilyEntry const* bf = sItemBagFamilyStore.LookupEntry(j + 1); if (!bf) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has bag family bit set not listed in ItemBagFamily.dbc, remove bit", entry); + LOG_ERROR("db.query", "Item (Entry: {}) has bag family bit set not listed in ItemBagFamily.dbc, remove bit", entry); itemTemplate.BagFamily &= ~mask; continue; } @@ -3205,7 +3205,7 @@ void ObjectMgr::LoadItemTemplates() CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemTemplate.ItemId); if (!ctEntry) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has currency bag family bit set in BagFamily but not listed in CurrencyTypes.dbc, remove bit", entry); + LOG_ERROR("db.query", "Item (Entry: {}) has currency bag family bit set in BagFamily but not listed in CurrencyTypes.dbc, remove bit", entry); itemTemplate.BagFamily &= ~mask; } } @@ -3213,41 +3213,41 @@ void ObjectMgr::LoadItemTemplates() } if (itemTemplate.TotemCategory && !sTotemCategoryStore.LookupEntry(itemTemplate.TotemCategory)) - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong TotemCategory ({})", entry, itemTemplate.TotemCategory); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong TotemCategory ({})", entry, itemTemplate.TotemCategory); for (uint8 j = 0; j < MAX_ITEM_PROTO_SOCKETS; ++j) { if (itemTemplate.Socket[j].Color && (itemTemplate.Socket[j].Color & SOCKET_COLOR_ALL) != itemTemplate.Socket[j].Color) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong socketColor_{} ({})", entry, j + 1, itemTemplate.Socket[j].Color); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong socketColor_{} ({})", entry, j + 1, itemTemplate.Socket[j].Color); itemTemplate.Socket[j].Color = 0; } } if (itemTemplate.GemProperties && !sGemPropertiesStore.LookupEntry(itemTemplate.GemProperties)) - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong GemProperties ({})", entry, itemTemplate.GemProperties); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong GemProperties ({})", entry, itemTemplate.GemProperties); if (itemTemplate.FoodType >= MAX_PET_DIET) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong FoodType value ({})", entry, itemTemplate.FoodType); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong FoodType value ({})", entry, itemTemplate.FoodType); itemTemplate.FoodType = 0; } if (itemTemplate.ItemLimitCategory && !sItemLimitCategoryStore.LookupEntry(itemTemplate.ItemLimitCategory)) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong LimitCategory value ({})", entry, itemTemplate.ItemLimitCategory); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong LimitCategory value ({})", entry, itemTemplate.ItemLimitCategory); itemTemplate.ItemLimitCategory = 0; } if (itemTemplate.HolidayId && !sHolidaysStore.LookupEntry(itemTemplate.HolidayId)) { - LOG_ERROR("sql.sql", "Item (Entry: {}) has wrong HolidayId value ({})", entry, itemTemplate.HolidayId); + LOG_ERROR("db.query", "Item (Entry: {}) has wrong HolidayId value ({})", entry, itemTemplate.HolidayId); itemTemplate.HolidayId = 0; } if (itemTemplate.FlagsCu & ITEM_FLAGS_CU_DURATION_REAL_TIME && !itemTemplate.Duration) { - LOG_ERROR("sql.sql", "Item (Entry {}) has flag ITEM_FLAGS_CU_DURATION_REAL_TIME but it does not have duration limit", entry); + LOG_ERROR("db.query", "Item (Entry {}) has flag ITEM_FLAGS_CU_DURATION_REAL_TIME but it does not have duration limit", entry); itemTemplate.FlagsCu &= ~ITEM_FLAGS_CU_DURATION_REAL_TIME; } @@ -3306,7 +3306,7 @@ void ObjectMgr::LoadItemTemplates() } for (std::set::const_iterator itr = notFoundOutfit.begin(); itr != notFoundOutfit.end(); ++itr) - LOG_ERROR("sql.sql", "Item (Entry: {}) does not exist in `item_template` but is referenced in `CharStartOutfit.dbc`", *itr); + LOG_ERROR("db.query", "Item (Entry: {}) does not exist in `item_template` but is referenced in `CharStartOutfit.dbc`", *itr); LOG_INFO("server.loading", ">> Loaded {} Item Templates in {} ms", count, GetMSTimeDiffToNow(oldMSTime)); LOG_INFO("server.loading", " "); @@ -3385,7 +3385,7 @@ void ObjectMgr::LoadItemSetNames() uint32 entry = fields[0].Get(); if (itemSetItems.find(entry) == itemSetItems.end()) { - LOG_ERROR("sql.sql", "Item set name (Entry: {}) not found in ItemSet.dbc, data useless.", entry); + LOG_ERROR("db.query", "Item set name (Entry: {}) not found in ItemSet.dbc, data useless.", entry); continue; } @@ -3395,7 +3395,7 @@ void ObjectMgr::LoadItemSetNames() uint32 invType = fields[2].Get(); if (invType >= MAX_INVTYPE) { - LOG_ERROR("sql.sql", "Item set name (Entry: {}) has wrong InventoryType value ({})", entry, invType); + LOG_ERROR("db.query", "Item set name (Entry: {}) has wrong InventoryType value ({})", entry, invType); invType = INVTYPE_NON_EQUIP; } @@ -3414,14 +3414,14 @@ void ObjectMgr::LoadItemSetNames() pProto = sObjectMgr->GetItemTemplate(entry); if (pProto) { - LOG_ERROR("sql.sql", "Item set part (Entry: {}) does not have entry in `item_set_names`, adding data from `item_template`.", entry); + LOG_ERROR("db.query", "Item set part (Entry: {}) does not have entry in `item_set_names`, adding data from `item_template`.", entry); ItemSetNameEntry& data = _itemSetNameStore[entry]; data.name = pProto->Name1; data.InventoryType = pProto->InventoryType; ++count; } else - LOG_ERROR("sql.sql", "Item set part (Entry: {}) does not have entry in `item_set_names`, set will not display properly.", entry); + LOG_ERROR("db.query", "Item set part (Entry: {}) does not have entry in `item_set_names`, set will not display properly.", entry); } } @@ -3460,19 +3460,19 @@ void ObjectMgr::LoadVehicleTemplateAccessories() if (!sObjectMgr->GetCreatureTemplate(uiEntry)) { - LOG_ERROR("sql.sql", "Table `vehicle_template_accessory`: creature template entry {} does not exist.", uiEntry); + LOG_ERROR("db.query", "Table `vehicle_template_accessory`: creature template entry {} does not exist.", uiEntry); continue; } if (!sObjectMgr->GetCreatureTemplate(uiAccessory)) { - LOG_ERROR("sql.sql", "Table `vehicle_template_accessory`: Accessory {} does not exist.", uiAccessory); + LOG_ERROR("db.query", "Table `vehicle_template_accessory`: Accessory {} does not exist.", uiAccessory); continue; } if (_spellClickInfoStore.find(uiEntry) == _spellClickInfoStore.end()) { - LOG_ERROR("sql.sql", "Table `vehicle_template_accessory`: creature template entry {} has no data in npc_spellclick_spells", uiEntry); + LOG_ERROR("db.query", "Table `vehicle_template_accessory`: creature template entry {} has no data in npc_spellclick_spells", uiEntry); continue; } @@ -3516,7 +3516,7 @@ void ObjectMgr::LoadVehicleAccessories() if (!sObjectMgr->GetCreatureTemplate(uiAccessory)) { - LOG_ERROR("sql.sql", "Table `vehicle_accessory`: Accessory {} does not exist.", uiAccessory); + LOG_ERROR("db.query", "Table `vehicle_accessory`: Accessory {} does not exist.", uiAccessory); continue; } @@ -3552,7 +3552,7 @@ void ObjectMgr::LoadPetLevelInfo() uint32 creature_id = fields[0].Get(); if (!sObjectMgr->GetCreatureTemplate(creature_id)) { - LOG_ERROR("sql.sql", "Wrong creature id {} in `pet_levelstats` table, ignoring.", creature_id); + LOG_ERROR("db.query", "Wrong creature id {} in `pet_levelstats` table, ignoring.", creature_id); continue; } @@ -3560,17 +3560,17 @@ void ObjectMgr::LoadPetLevelInfo() if (current_level > sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)) { if (current_level > STRONG_MAX_LEVEL) // hardcoded level maximum - LOG_ERROR("sql.sql", "Wrong (> {}) level {} in `pet_levelstats` table, ignoring.", STRONG_MAX_LEVEL, current_level); + LOG_ERROR("db.query", "Wrong (> {}) level {} in `pet_levelstats` table, ignoring.", STRONG_MAX_LEVEL, current_level); else { - LOG_DEBUG("sql.sql", "Unused (> MaxPlayerLevel in worldserver.conf) level {} in `pet_levelstats` table, ignoring.", current_level); + LOG_DEBUG("db.query", "Unused (> MaxPlayerLevel in worldserver.conf) level {} in `pet_levelstats` table, ignoring.", current_level); ++count; // make result loading percent "expected" correct in case disabled detail mode for example. } continue; } else if (current_level < 1) { - LOG_ERROR("sql.sql", "Wrong (<1) level {} in `pet_levelstats` table, ignoring.", current_level); + LOG_ERROR("db.query", "Wrong (<1) level {} in `pet_levelstats` table, ignoring.", current_level); continue; } @@ -3603,7 +3603,7 @@ void ObjectMgr::LoadPetLevelInfo() // fatal error if no level 1 data if (!pInfo || pInfo[0].health == 0) { - LOG_ERROR("sql.sql", "Creature {} does not have pet stats data for Level 1!", itr->first); + LOG_ERROR("db.query", "Creature {} does not have pet stats data for Level 1!", itr->first); exit(1); } @@ -3612,7 +3612,7 @@ void ObjectMgr::LoadPetLevelInfo() { if (pInfo[level].health == 0) { - LOG_ERROR("sql.sql", "Creature {} has no data for Level {} pet stats data, using data of Level {}.", itr->first, level + 1, level); + LOG_ERROR("db.query", "Creature {} has no data for Level {} pet stats data, using data of Level {}.", itr->first, level + 1, level); pInfo[level] = pInfo[level - 1]; } } @@ -3644,7 +3644,7 @@ void ObjectMgr::PlayerCreateInfoAddItemHelper(uint32 race_, uint32 class_, uint3 else { if (count < -1) - LOG_ERROR("sql.sql", "Invalid count {} specified on item {} be removed from original player create info (use -1)!", count, itemId); + LOG_ERROR("db.query", "Invalid count {} specified on item {} be removed from original player create info (use -1)!", count, itemId); for (uint32 gender = 0; gender < GENDER_NONE; ++gender) { @@ -3662,7 +3662,7 @@ void ObjectMgr::PlayerCreateInfoAddItemHelper(uint32 race_, uint32 class_, uint3 } if (!found) - LOG_ERROR("sql.sql", "Item {} specified to be removed from original create info not found in dbc!", itemId); + LOG_ERROR("db.query", "Item {} specified to be removed from original create info not found in dbc!", itemId); } } } @@ -3701,39 +3701,39 @@ void ObjectMgr::LoadPlayerInfo() if (current_race >= MAX_RACES) { - LOG_ERROR("sql.sql", "Wrong race {} in `playercreateinfo` table, ignoring.", current_race); + LOG_ERROR("db.query", "Wrong race {} in `playercreateinfo` table, ignoring.", current_race); continue; } ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(current_race); if (!rEntry) { - LOG_ERROR("sql.sql", "Wrong race {} in `playercreateinfo` table, ignoring.", current_race); + LOG_ERROR("db.query", "Wrong race {} in `playercreateinfo` table, ignoring.", current_race); continue; } if (current_class >= MAX_CLASSES) { - LOG_ERROR("sql.sql", "Wrong class {} in `playercreateinfo` table, ignoring.", current_class); + LOG_ERROR("db.query", "Wrong class {} in `playercreateinfo` table, ignoring.", current_class); continue; } if (!sChrClassesStore.LookupEntry(current_class)) { - LOG_ERROR("sql.sql", "Wrong class {} in `playercreateinfo` table, ignoring.", current_class); + LOG_ERROR("db.query", "Wrong class {} in `playercreateinfo` table, ignoring.", current_class); continue; } // accept DB data only for valid position (and non instanceable) if (!MapMgr::IsValidMapCoord(mapId, positionX, positionY, positionZ, orientation)) { - LOG_ERROR("sql.sql", "Wrong home position for class {} race {} pair in `playercreateinfo` table, ignoring.", current_class, current_race); + LOG_ERROR("db.query", "Wrong home position for class {} race {} pair in `playercreateinfo` table, ignoring.", current_class, current_race); continue; } if (sMapStore.LookupEntry(mapId)->Instanceable()) { - LOG_ERROR("sql.sql", "Home position in instanceable map for class {} race {} pair in `playercreateinfo` table, ignoring.", current_class, current_race); + LOG_ERROR("db.query", "Home position in instanceable map for class {} race {} pair in `playercreateinfo` table, ignoring.", current_class, current_race); continue; } @@ -3779,14 +3779,14 @@ void ObjectMgr::LoadPlayerInfo() uint32 current_race = fields[0].Get(); if (current_race >= MAX_RACES) { - LOG_ERROR("sql.sql", "Wrong race {} in `playercreateinfo_item` table, ignoring.", current_race); + LOG_ERROR("db.query", "Wrong race {} in `playercreateinfo_item` table, ignoring.", current_race); continue; } uint32 current_class = fields[1].Get(); if (current_class >= MAX_CLASSES) { - LOG_ERROR("sql.sql", "Wrong class {} in `playercreateinfo_item` table, ignoring.", current_class); + LOG_ERROR("db.query", "Wrong class {} in `playercreateinfo_item` table, ignoring.", current_class); continue; } @@ -3794,7 +3794,7 @@ void ObjectMgr::LoadPlayerInfo() if (!GetItemTemplate(item_id)) { - LOG_ERROR("sql.sql", "Item id {} (race {} class {}) in `playercreateinfo_item` table but not listed in `item_template`, ignoring.", item_id, current_race, current_class); + LOG_ERROR("db.query", "Item id {} (race {} class {}) in `playercreateinfo_item` table but not listed in `item_template`, ignoring.", item_id, current_race, current_class); continue; } @@ -3802,7 +3802,7 @@ void ObjectMgr::LoadPlayerInfo() if (!amount) { - LOG_ERROR("sql.sql", "Item id {} (class {} race {}) have amount == 0 in `playercreateinfo_item` table, ignoring.", item_id, current_race, current_class); + LOG_ERROR("db.query", "Item id {} (class {} race {}) have amount == 0 in `playercreateinfo_item` table, ignoring.", item_id, current_race, current_class); continue; } @@ -3853,25 +3853,25 @@ void ObjectMgr::LoadPlayerInfo() if (skill.Rank >= MAX_SKILL_STEP) { - LOG_ERROR("sql.sql", "Skill rank value {} set for skill {} raceMask {} classMask {} is too high, max allowed value is {}", skill.Rank, skill.SkillId, raceMask, classMask, MAX_SKILL_STEP); + LOG_ERROR("db.query", "Skill rank value {} set for skill {} raceMask {} classMask {} is too high, max allowed value is {}", skill.Rank, skill.SkillId, raceMask, classMask, MAX_SKILL_STEP); continue; } if (raceMask != 0 && !(raceMask & RACEMASK_ALL_PLAYABLE)) { - LOG_ERROR("sql.sql", "Wrong race mask {} in `playercreateinfo_skills` table, ignoring.", raceMask); + LOG_ERROR("db.query", "Wrong race mask {} in `playercreateinfo_skills` table, ignoring.", raceMask); continue; } if (classMask != 0 && !(classMask & CLASSMASK_ALL_PLAYABLE)) { - LOG_ERROR("sql.sql", "Wrong class mask {} in `playercreateinfo_skills` table, ignoring.", classMask); + LOG_ERROR("db.query", "Wrong class mask {} in `playercreateinfo_skills` table, ignoring.", classMask); continue; } if (!sSkillLineStore.LookupEntry(skill.SkillId)) { - LOG_ERROR("sql.sql", "Wrong skill id {} in `playercreateinfo_skills` table, ignoring.", skill.SkillId); + LOG_ERROR("db.query", "Wrong skill id {} in `playercreateinfo_skills` table, ignoring.", skill.SkillId); continue; } @@ -3926,13 +3926,13 @@ void ObjectMgr::LoadPlayerInfo() if (raceMask != 0 && !(raceMask & RACEMASK_ALL_PLAYABLE)) { - LOG_ERROR("sql.sql", "Wrong race mask {} in `playercreateinfo_spell_custom` table, ignoring.", raceMask); + LOG_ERROR("db.query", "Wrong race mask {} in `playercreateinfo_spell_custom` table, ignoring.", raceMask); continue; } if (classMask != 0 && !(classMask & CLASSMASK_ALL_PLAYABLE)) { - LOG_ERROR("sql.sql", "Wrong class mask {} in `playercreateinfo_spell_custom` table, ignoring.", classMask); + LOG_ERROR("db.query", "Wrong class mask {} in `playercreateinfo_spell_custom` table, ignoring.", classMask); continue; } @@ -3984,13 +3984,13 @@ void ObjectMgr::LoadPlayerInfo() if (raceMask != 0 && !(raceMask & RACEMASK_ALL_PLAYABLE)) { - LOG_ERROR("sql.sql", "Wrong race mask {} in `playercreateinfo_cast_spell` table, ignoring.", raceMask); + LOG_ERROR("db.query", "Wrong race mask {} in `playercreateinfo_cast_spell` table, ignoring.", raceMask); continue; } if (classMask != 0 && !(classMask & CLASSMASK_ALL_PLAYABLE)) { - LOG_ERROR("sql.sql", "Wrong class mask {} in `playercreateinfo_cast_spell` table, ignoring.", classMask); + LOG_ERROR("db.query", "Wrong class mask {} in `playercreateinfo_cast_spell` table, ignoring.", classMask); continue; } @@ -4042,14 +4042,14 @@ void ObjectMgr::LoadPlayerInfo() uint32 current_race = fields[0].Get(); if (current_race >= MAX_RACES) { - LOG_ERROR("sql.sql", "Wrong race {} in `playercreateinfo_action` table, ignoring.", current_race); + LOG_ERROR("db.query", "Wrong race {} in `playercreateinfo_action` table, ignoring.", current_race); continue; } uint32 current_class = fields[1].Get(); if (current_class >= MAX_CLASSES) { - LOG_ERROR("sql.sql", "Wrong class {} in `playercreateinfo_action` table, ignoring.", current_class); + LOG_ERROR("db.query", "Wrong class {} in `playercreateinfo_action` table, ignoring.", current_class); continue; } @@ -4087,14 +4087,14 @@ void ObjectMgr::LoadPlayerInfo() uint32 current_class = fields[0].Get(); if (current_class >= MAX_CLASSES) { - LOG_ERROR("sql.sql", "Wrong class {} in `player_classlevelstats` table, ignoring.", current_class); + LOG_ERROR("db.query", "Wrong class {} in `player_classlevelstats` table, ignoring.", current_class); continue; } uint8 current_level = fields[1].Get(); // Can't be > than STRONG_MAX_LEVEL (hardcoded level maximum) due to var type if (current_level > sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)) { - LOG_INFO("sql.sql", "Unused (> MaxPlayerLevel in worldserver.conf) level {} in `player_classlevelstats` table, ignoring.", current_level); + LOG_INFO("db.query", "Unused (> MaxPlayerLevel in worldserver.conf) level {} in `player_classlevelstats` table, ignoring.", current_level); ++count; // make result loading percent "expected" correct in case disabled detail mode for example. continue; } @@ -4127,7 +4127,7 @@ void ObjectMgr::LoadPlayerInfo() // fatal error if no initial level data if (!pClassInfo->levelInfo || (pClassInfo->levelInfo[sWorld->getIntConfig(CONFIG_START_PLAYER_LEVEL) - 1].basehealth == 0 && class_ != CLASS_DEATH_KNIGHT) || (pClassInfo->levelInfo[sWorld->getIntConfig(CONFIG_START_HEROIC_PLAYER_LEVEL) - 1].basehealth == 0 && class_ == CLASS_DEATH_KNIGHT)) { - LOG_ERROR("sql.sql", "Class {} initial level does not have health/mana data!", class_); + LOG_ERROR("db.query", "Class {} initial level does not have health/mana data!", class_); exit(1); } @@ -4136,7 +4136,7 @@ void ObjectMgr::LoadPlayerInfo() { if ((pClassInfo->levelInfo[level].basehealth == 0 && class_ != CLASS_DEATH_KNIGHT) || (level >= sWorld->getIntConfig(CONFIG_START_HEROIC_PLAYER_LEVEL) && pClassInfo->levelInfo[level].basehealth == 0 && class_ == CLASS_DEATH_KNIGHT)) { - LOG_ERROR("sql.sql", "Class {} level {} does not have health/mana data. Using stats data of level {}.", class_, level + 1, level); + LOG_ERROR("db.query", "Class {} level {} does not have health/mana data. Using stats data of level {}.", class_, level + 1, level); pClassInfo->levelInfo[level] = pClassInfo->levelInfo[level - 1]; } } @@ -4175,7 +4175,7 @@ void ObjectMgr::LoadPlayerInfo() uint32 current_race = fields[0].Get(); if (current_race >= MAX_RACES) { - LOG_ERROR("sql.sql", "Wrong race {} in `player_race_stats` table, ignoring.", current_race); + LOG_ERROR("db.query", "Wrong race {} in `player_race_stats` table, ignoring.", current_race); continue; } @@ -4202,7 +4202,7 @@ void ObjectMgr::LoadPlayerInfo() uint32 current_class = fields[0].Get(); if (current_class >= MAX_CLASSES) { - LOG_ERROR("sql.sql", "Wrong class {} in `player_class_stats` table, ignoring.", current_class); + LOG_ERROR("db.query", "Wrong class {} in `player_class_stats` table, ignoring.", current_class); continue; } @@ -4210,9 +4210,9 @@ void ObjectMgr::LoadPlayerInfo() if (current_level > sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)) { if (current_level > STRONG_MAX_LEVEL) // hardcoded level maximum - LOG_ERROR("sql.sql", "Wrong (> {}) level {} in `player_class_stats` table, ignoring.", STRONG_MAX_LEVEL, current_level); + LOG_ERROR("db.query", "Wrong (> {}) level {} in `player_class_stats` table, ignoring.", STRONG_MAX_LEVEL, current_level); else - LOG_DEBUG("sql.sql", "Unused (> MaxPlayerLevel in worldserver.conf) level {} in `player_class_stats` table, ignoring.", current_level); + LOG_DEBUG("db.query", "Unused (> MaxPlayerLevel in worldserver.conf) level {} in `player_class_stats` table, ignoring.", current_level); continue; } @@ -4261,7 +4261,7 @@ void ObjectMgr::LoadPlayerInfo() // fatal error if no initial level data if (!info->levelInfo || (info->levelInfo[sWorld->getIntConfig(CONFIG_START_PLAYER_LEVEL) - 1].stats[0] == 0 && class_ != CLASS_DEATH_KNIGHT) || (info->levelInfo[sWorld->getIntConfig(CONFIG_START_HEROIC_PLAYER_LEVEL) - 1].stats[0] == 0 && class_ == CLASS_DEATH_KNIGHT)) { - LOG_ERROR("sql.sql", "Race {} class {} initial level does not have stats data!", race, class_); + LOG_ERROR("db.query", "Race {} class {} initial level does not have stats data!", race, class_); exit(1); } @@ -4270,7 +4270,7 @@ void ObjectMgr::LoadPlayerInfo() { if ((info->levelInfo[level].stats[0] == 0 && class_ != CLASS_DEATH_KNIGHT) || (level >= sWorld->getIntConfig(CONFIG_START_HEROIC_PLAYER_LEVEL) && info->levelInfo[level].stats[0] == 0 && class_ == CLASS_DEATH_KNIGHT)) { - LOG_ERROR("sql.sql", "Race {} class {} level {} does not have stats data. Using stats data of level {}.", race, class_, level + 1, level); + LOG_ERROR("db.query", "Race {} class {} level {} does not have stats data. Using stats data of level {}.", race, class_, level + 1, level); info->levelInfo[level] = info->levelInfo[level - 1]; } } @@ -4312,10 +4312,10 @@ void ObjectMgr::LoadPlayerInfo() if (current_level >= sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)) { if (current_level > STRONG_MAX_LEVEL) // hardcoded level maximum - LOG_ERROR("sql.sql", "Wrong (> {}) level {} in `player_xp_for_level` table, ignoring.", STRONG_MAX_LEVEL, current_level); + LOG_ERROR("db.query", "Wrong (> {}) level {} in `player_xp_for_level` table, ignoring.", STRONG_MAX_LEVEL, current_level); else { - LOG_DEBUG("sql.sql", "Unused (> MaxPlayerLevel in worldserver.conf) level {} in `player_xp_for_levels` table, ignoring.", current_level); + LOG_DEBUG("db.query", "Unused (> MaxPlayerLevel in worldserver.conf) level {} in `player_xp_for_levels` table, ignoring.", current_level); ++count; // make result loading percent "expected" correct in case disabled detail mode for example. } continue; @@ -4330,7 +4330,7 @@ void ObjectMgr::LoadPlayerInfo() { if (_playerXPperLevel[level] == 0) { - LOG_ERROR("sql.sql", "Level {} does not have XP for level data. Using data of level [{}] + 100.", level + 1, level); + LOG_ERROR("db.query", "Level {} does not have XP for level data. Using data of level [{}] + 100.", level + 1, level); _playerXPperLevel[level] = _playerXPperLevel[level - 1] + 100; } } @@ -4540,7 +4540,7 @@ void ObjectMgr::LoadQuests() if (itr != _questTemplates.end()) itr->second->LoadQuestDetails(fields); else - LOG_ERROR("sql.sql", "Table `quest_details` has data for quest {} but such quest does not exist", questId); + LOG_ERROR("db.query", "Table `quest_details` has data for quest {} but such quest does not exist", questId); } while (result->NextRow()); } @@ -4563,7 +4563,7 @@ void ObjectMgr::LoadQuests() if (itr != _questTemplates.end()) itr->second->LoadQuestRequestItems(fields); else - LOG_ERROR("sql.sql", "Table `quest_request_items` has data for quest {} but such quest does not exist", questId); + LOG_ERROR("db.query", "Table `quest_request_items` has data for quest {} but such quest does not exist", questId); } while (result->NextRow()); } @@ -4586,7 +4586,7 @@ void ObjectMgr::LoadQuests() if (itr != _questTemplates.end()) itr->second->LoadQuestOfferReward(fields); else - LOG_ERROR("sql.sql", "Table `quest_offer_reward` has data for quest {} but such quest does not exist", questId); + LOG_ERROR("db.query", "Table `quest_offer_reward` has data for quest {} but such quest does not exist", questId); } while (result->NextRow()); } @@ -4611,7 +4611,7 @@ void ObjectMgr::LoadQuests() if (itr != _questTemplates.end()) itr->second->LoadQuestTemplateAddon(fields); else - LOG_ERROR("sql.sql", "Table `quest_template_addon` has data for quest {} but such quest does not exist", questId); + LOG_ERROR("db.query", "Table `quest_template_addon` has data for quest {} but such quest does not exist", questId); } while (result->NextRow()); } @@ -4627,18 +4627,18 @@ void ObjectMgr::LoadQuests() // additional quest integrity checks (GO, creature_template and item_template must be loaded already) if (qinfo->GetQuestMethod() >= 3) - LOG_ERROR("sql.sql", "Quest {} has `Method` = {}, expected values are 0, 1 or 2.", qinfo->GetQuestId(), qinfo->GetQuestMethod()); + LOG_ERROR("db.query", "Quest {} has `Method` = {}, expected values are 0, 1 or 2.", qinfo->GetQuestId(), qinfo->GetQuestMethod()); if (qinfo->SpecialFlags & ~QUEST_SPECIAL_FLAGS_DB_ALLOWED) { - LOG_ERROR("sql.sql", "Quest {} has `SpecialFlags` = {} > max allowed value. Correct `SpecialFlags` to value <= {}", + LOG_ERROR("db.query", "Quest {} has `SpecialFlags` = {} > max allowed value. Correct `SpecialFlags` to value <= {}", qinfo->GetQuestId(), qinfo->SpecialFlags, QUEST_SPECIAL_FLAGS_DB_ALLOWED); qinfo->SpecialFlags &= QUEST_SPECIAL_FLAGS_DB_ALLOWED; } if (qinfo->Flags & QUEST_FLAGS_DAILY && qinfo->Flags & QUEST_FLAGS_WEEKLY) { - LOG_ERROR("sql.sql", "Weekly Quest {} is marked as daily quest in `Flags`, removed daily flag.", qinfo->GetQuestId()); + LOG_ERROR("db.query", "Weekly Quest {} is marked as daily quest in `Flags`, removed daily flag.", qinfo->GetQuestId()); qinfo->Flags &= ~QUEST_FLAGS_DAILY; } @@ -4646,7 +4646,7 @@ void ObjectMgr::LoadQuests() { if (!(qinfo->SpecialFlags & QUEST_SPECIAL_FLAGS_REPEATABLE)) { - LOG_ERROR("sql.sql", "Daily Quest {} not marked as repeatable in `SpecialFlags`, added.", qinfo->GetQuestId()); + LOG_ERROR("db.query", "Daily Quest {} not marked as repeatable in `SpecialFlags`, added.", qinfo->GetQuestId()); qinfo->SpecialFlags |= QUEST_SPECIAL_FLAGS_REPEATABLE; } } @@ -4655,7 +4655,7 @@ void ObjectMgr::LoadQuests() { if (!(qinfo->SpecialFlags & QUEST_SPECIAL_FLAGS_REPEATABLE)) { - LOG_ERROR("sql.sql", "Weekly Quest {} not marked as repeatable in `SpecialFlags`, added.", qinfo->GetQuestId()); + LOG_ERROR("db.query", "Weekly Quest {} not marked as repeatable in `SpecialFlags`, added.", qinfo->GetQuestId()); qinfo->SpecialFlags |= QUEST_SPECIAL_FLAGS_REPEATABLE; } } @@ -4664,7 +4664,7 @@ void ObjectMgr::LoadQuests() { if (!(qinfo->SpecialFlags & QUEST_SPECIAL_FLAGS_REPEATABLE)) { - LOG_ERROR("sql.sql", "Monthly quest {} not marked as repeatable in `SpecialFlags`, added.", qinfo->GetQuestId()); + LOG_ERROR("db.query", "Monthly quest {} not marked as repeatable in `SpecialFlags`, added.", qinfo->GetQuestId()); qinfo->SpecialFlags |= QUEST_SPECIAL_FLAGS_REPEATABLE; } } @@ -4676,7 +4676,7 @@ void ObjectMgr::LoadQuests() { if (uint32 id = qinfo->RewardChoiceItemId[j]) { - LOG_ERROR("sql.sql", "Quest {} has `RewardChoiceItemId{}` = {} but item from `RewardChoiceItemId{}` can't be rewarded with quest flag QUEST_FLAGS_TRACKING.", + LOG_ERROR("db.query", "Quest {} has `RewardChoiceItemId{}` = {} but item from `RewardChoiceItemId{}` can't be rewarded with quest flag QUEST_FLAGS_TRACKING.", qinfo->GetQuestId(), j + 1, id, j + 1); // no changes, quest ignore this data } @@ -4688,7 +4688,7 @@ void ObjectMgr::LoadQuests() { if (!sAreaTableStore.LookupEntry(qinfo->ZoneOrSort)) { - LOG_ERROR("sql.sql", "Quest {} has `ZoneOrSort` = {} (zone case) but zone with this id does not exist.", + LOG_ERROR("db.query", "Quest {} has `ZoneOrSort` = {} (zone case) but zone with this id does not exist.", qinfo->GetQuestId(), qinfo->ZoneOrSort); // no changes, quest not dependent from this value but can have problems at client } @@ -4699,7 +4699,7 @@ void ObjectMgr::LoadQuests() QuestSortEntry const* qSort = sQuestSortStore.LookupEntry(-int32(qinfo->ZoneOrSort)); if (!qSort) { - LOG_ERROR("sql.sql", "Quest {} has `ZoneOrSort` = {} (sort case) but quest sort with this id does not exist.", + LOG_ERROR("db.query", "Quest {} has `ZoneOrSort` = {} (sort case) but quest sort with this id does not exist.", qinfo->GetQuestId(), qinfo->ZoneOrSort); // no changes, quest not dependent from this value but can have problems at client (note some may be 0, we must allow this so no check) } @@ -4708,7 +4708,7 @@ void ObjectMgr::LoadQuests() { if (qinfo->RequiredSkillId != skill_id) { - LOG_ERROR("sql.sql", "Quest {} has `ZoneOrSort` = {} but `RequiredSkillId` does not have a corresponding value ({}).", + LOG_ERROR("db.query", "Quest {} has `ZoneOrSort` = {} but `RequiredSkillId` does not have a corresponding value ({}).", qinfo->GetQuestId(), qinfo->ZoneOrSort, skill_id); //override, and force proper value here? } @@ -4720,7 +4720,7 @@ void ObjectMgr::LoadQuests() { if (!(qinfo->RequiredClasses & CLASSMASK_ALL_PLAYABLE)) { - LOG_ERROR("sql.sql", "Quest {} does not contain any playable classes in `RequiredClasses` ({}), value set to 0 (all classes).", qinfo->GetQuestId(), qinfo->RequiredClasses); + LOG_ERROR("db.query", "Quest {} does not contain any playable classes in `RequiredClasses` ({}), value set to 0 (all classes).", qinfo->GetQuestId(), qinfo->RequiredClasses); qinfo->RequiredClasses = 0; } } @@ -4729,7 +4729,7 @@ void ObjectMgr::LoadQuests() { if (!(qinfo->AllowableRaces & RACEMASK_ALL_PLAYABLE)) { - LOG_ERROR("sql.sql", "Quest {} does not contain any playable races in `AllowableRaces` ({}), value set to 0 (all races).", qinfo->GetQuestId(), qinfo->AllowableRaces); + LOG_ERROR("db.query", "Quest {} does not contain any playable races in `AllowableRaces` ({}), value set to 0 (all races).", qinfo->GetQuestId(), qinfo->AllowableRaces); qinfo->AllowableRaces = 0; } } @@ -4738,7 +4738,7 @@ void ObjectMgr::LoadQuests() { if (!sSkillLineStore.LookupEntry(qinfo->RequiredSkillId)) { - LOG_ERROR("sql.sql", "Quest {} has `RequiredSkillId` = {} but this skill does not exist", + LOG_ERROR("db.query", "Quest {} has `RequiredSkillId` = {} but this skill does not exist", qinfo->GetQuestId(), qinfo->RequiredSkillId); } } @@ -4747,7 +4747,7 @@ void ObjectMgr::LoadQuests() { if (qinfo->RequiredSkillPoints > sWorld->GetConfigMaxSkillValue()) { - LOG_ERROR("sql.sql", "Quest {} has `RequiredSkillPoints` = {} but max possible skill is {}, quest can't be done.", + LOG_ERROR("db.query", "Quest {} has `RequiredSkillPoints` = {} but max possible skill is {}, quest can't be done.", qinfo->GetQuestId(), qinfo->RequiredSkillPoints, sWorld->GetConfigMaxSkillValue()); // no changes, quest can't be done for this requirement } @@ -4756,77 +4756,77 @@ void ObjectMgr::LoadQuests() if (qinfo->RequiredFactionId2 && !sFactionStore.LookupEntry(qinfo->RequiredFactionId2)) { - LOG_ERROR("sql.sql", "Quest {} has `RequiredFactionId2` = {} but faction template {} does not exist, quest can't be done.", + LOG_ERROR("db.query", "Quest {} has `RequiredFactionId2` = {} but faction template {} does not exist, quest can't be done.", qinfo->GetQuestId(), qinfo->RequiredFactionId2, qinfo->RequiredFactionId2); // no changes, quest can't be done for this requirement } if (qinfo->RequiredFactionId1 && !sFactionStore.LookupEntry(qinfo->RequiredFactionId1)) { - LOG_ERROR("sql.sql", "Quest {} has `RequiredFactionId1` = {} but faction template {} does not exist, quest can't be done.", + LOG_ERROR("db.query", "Quest {} has `RequiredFactionId1` = {} but faction template {} does not exist, quest can't be done.", qinfo->GetQuestId(), qinfo->RequiredFactionId1, qinfo->RequiredFactionId1); // no changes, quest can't be done for this requirement } if (qinfo->RequiredMinRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMinRepFaction)) { - LOG_ERROR("sql.sql", "Quest {} has `RequiredMinRepFaction` = {} but faction template {} does not exist, quest can't be done.", + LOG_ERROR("db.query", "Quest {} has `RequiredMinRepFaction` = {} but faction template {} does not exist, quest can't be done.", qinfo->GetQuestId(), qinfo->RequiredMinRepFaction, qinfo->RequiredMinRepFaction); // no changes, quest can't be done for this requirement } if (qinfo->RequiredMaxRepFaction && !sFactionStore.LookupEntry(qinfo->RequiredMaxRepFaction)) { - LOG_ERROR("sql.sql", "Quest {} has `RequiredMaxRepFaction` = {} but faction template {} does not exist, quest can't be done.", + LOG_ERROR("db.query", "Quest {} has `RequiredMaxRepFaction` = {} but faction template {} does not exist, quest can't be done.", qinfo->GetQuestId(), qinfo->RequiredMaxRepFaction, qinfo->RequiredMaxRepFaction); // no changes, quest can't be done for this requirement } if (qinfo->RequiredMinRepValue && qinfo->RequiredMinRepValue > ReputationMgr::Reputation_Cap) { - LOG_ERROR("sql.sql", "Quest {} has `RequiredMinRepValue` = {} but max reputation is {}, quest can't be done.", + LOG_ERROR("db.query", "Quest {} has `RequiredMinRepValue` = {} but max reputation is {}, quest can't be done.", qinfo->GetQuestId(), qinfo->RequiredMinRepValue, ReputationMgr::Reputation_Cap); // no changes, quest can't be done for this requirement } if (qinfo->RequiredMinRepValue && qinfo->RequiredMaxRepValue && qinfo->RequiredMaxRepValue <= qinfo->RequiredMinRepValue) { - LOG_ERROR("sql.sql", "Quest {} has `RequiredMaxRepValue` = {} and `RequiredMinRepValue` = {}, quest can't be done.", + LOG_ERROR("db.query", "Quest {} has `RequiredMaxRepValue` = {} and `RequiredMinRepValue` = {}, quest can't be done.", qinfo->GetQuestId(), qinfo->RequiredMaxRepValue, qinfo->RequiredMinRepValue); // no changes, quest can't be done for this requirement } if (!qinfo->RequiredFactionId1 && qinfo->RequiredFactionValue1 != 0) { - LOG_ERROR("sql.sql", "Quest {} has `RequiredFactionValue1` = {} but `RequiredFactionId1` is 0, value has no effect", + LOG_ERROR("db.query", "Quest {} has `RequiredFactionValue1` = {} but `RequiredFactionId1` is 0, value has no effect", qinfo->GetQuestId(), qinfo->RequiredFactionValue1); // warning } if (!qinfo->RequiredFactionId2 && qinfo->RequiredFactionValue2 != 0) { - LOG_ERROR("sql.sql", "Quest {} has `RequiredFactionValue2` = {} but `RequiredFactionId2` is 0, value has no effect", + LOG_ERROR("db.query", "Quest {} has `RequiredFactionValue2` = {} but `RequiredFactionId2` is 0, value has no effect", qinfo->GetQuestId(), qinfo->RequiredFactionValue2); // warning } if (!qinfo->RequiredMinRepFaction && qinfo->RequiredMinRepValue != 0) { - LOG_ERROR("sql.sql", "Quest {} has `RequiredMinRepValue` = {} but `RequiredMinRepFaction` is 0, value has no effect", + LOG_ERROR("db.query", "Quest {} has `RequiredMinRepValue` = {} but `RequiredMinRepFaction` is 0, value has no effect", qinfo->GetQuestId(), qinfo->RequiredMinRepValue); // warning } if (!qinfo->RequiredMaxRepFaction && qinfo->RequiredMaxRepValue != 0) { - LOG_ERROR("sql.sql", "Quest {} has `RequiredMaxRepValue` = {} but `RequiredMaxRepFaction` is 0, value has no effect", + LOG_ERROR("db.query", "Quest {} has `RequiredMaxRepValue` = {} but `RequiredMaxRepFaction` is 0, value has no effect", qinfo->GetQuestId(), qinfo->RequiredMaxRepValue); // warning } if (qinfo->RewardTitleId && !sCharTitlesStore.LookupEntry(qinfo->RewardTitleId)) { - LOG_ERROR("sql.sql", "Quest {} has `RewardTitleId` = {} but CharTitle Id {} does not exist, quest can't be rewarded with title.", + LOG_ERROR("db.query", "Quest {} has `RewardTitleId` = {} but CharTitle Id {} does not exist, quest can't be rewarded with title.", qinfo->GetQuestId(), qinfo->GetCharTitleId(), qinfo->GetCharTitleId()); qinfo->RewardTitleId = 0; // quest can't reward this title @@ -4836,20 +4836,20 @@ void ObjectMgr::LoadQuests() { if (!sObjectMgr->GetItemTemplate(qinfo->StartItem)) { - LOG_ERROR("sql.sql", "Quest {} has `StartItem` = {} but item with entry {} does not exist, quest can't be done.", + LOG_ERROR("db.query", "Quest {} has `StartItem` = {} but item with entry {} does not exist, quest can't be done.", qinfo->GetQuestId(), qinfo->StartItem, qinfo->StartItem); qinfo->StartItem = 0; // quest can't be done for this requirement } else if (qinfo->StartItemCount == 0) { - LOG_ERROR("sql.sql", "Quest {} has `StartItem` = {} but `StartItemCount` = 0, set to 1 but need fix in DB.", + LOG_ERROR("db.query", "Quest {} has `StartItem` = {} but `StartItemCount` = 0, set to 1 but need fix in DB.", qinfo->GetQuestId(), qinfo->StartItem); qinfo->StartItemCount = 1; // update to 1 for allow quest work for backward compatibility with DB } } else if (qinfo->StartItemCount > 0) { - LOG_ERROR("sql.sql", "Quest {} has `StartItem` = 0 but `StartItemCount` = {}, useless value.", + LOG_ERROR("db.query", "Quest {} has `StartItem` = 0 but `StartItemCount` = {}, useless value.", qinfo->GetQuestId(), qinfo->StartItemCount); qinfo->StartItemCount = 0; // no quest work changes in fact } @@ -4859,13 +4859,13 @@ void ObjectMgr::LoadQuests() SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(qinfo->SourceSpellid); if (!spellInfo) { - LOG_ERROR("sql.sql", "Quest {} has `SourceSpellid` = {} but spell {} doesn't exist, quest can't be done.", + LOG_ERROR("db.query", "Quest {} has `SourceSpellid` = {} but spell {} doesn't exist, quest can't be done.", qinfo->GetQuestId(), qinfo->SourceSpellid, qinfo->SourceSpellid); qinfo->SourceSpellid = 0; // quest can't be done for this requirement } else if (!SpellMgr::ComputeIsSpellValid(spellInfo)) { - LOG_ERROR("sql.sql", "Quest {} has `SourceSpellid` = {} but spell {} is broken, quest can't be done.", + LOG_ERROR("db.query", "Quest {} has `SourceSpellid` = {} but spell {} is broken, quest can't be done.", qinfo->GetQuestId(), qinfo->SourceSpellid, qinfo->SourceSpellid); qinfo->SourceSpellid = 0; // quest can't be done for this requirement } @@ -4878,7 +4878,7 @@ void ObjectMgr::LoadQuests() { if (qinfo->RequiredItemCount[j] == 0) { - LOG_ERROR("sql.sql", "Quest {} has `RequiredItemId{}` = {} but `RequiredItemCount{}` = 0, quest can't be done.", + LOG_ERROR("db.query", "Quest {} has `RequiredItemId{}` = {} but `RequiredItemCount{}` = 0, quest can't be done.", qinfo->GetQuestId(), j + 1, id, j + 1); // no changes, quest can't be done for this requirement } @@ -4887,14 +4887,14 @@ void ObjectMgr::LoadQuests() if (!sObjectMgr->GetItemTemplate(id)) { - LOG_ERROR("sql.sql", "Quest {} has `RequiredItemId{}` = {} but item with entry {} does not exist, quest can't be done.", + LOG_ERROR("db.query", "Quest {} has `RequiredItemId{}` = {} but item with entry {} does not exist, quest can't be done.", qinfo->GetQuestId(), j + 1, id, id); qinfo->RequiredItemCount[j] = 0; // prevent incorrect work of quest } } else if (qinfo->RequiredItemCount[j] > 0) { - LOG_ERROR("sql.sql", "Quest {} has `RequiredItemId{}` = 0 but `RequiredItemCount{}` = {}, quest can't be done.", + LOG_ERROR("db.query", "Quest {} has `RequiredItemId{}` = 0 but `RequiredItemCount{}` = {}, quest can't be done.", qinfo->GetQuestId(), j + 1, j + 1, qinfo->RequiredItemCount[j]); qinfo->RequiredItemCount[j] = 0; // prevent incorrect work of quest } @@ -4907,7 +4907,7 @@ void ObjectMgr::LoadQuests() { if (!sObjectMgr->GetItemTemplate(id)) { - LOG_ERROR("sql.sql", "Quest {} has `ItemDrop{}` = {} but item with entry {} does not exist, quest can't be done.", + LOG_ERROR("db.query", "Quest {} has `ItemDrop{}` = {} but item with entry {} does not exist, quest can't be done.", qinfo->GetQuestId(), j + 1, id, id); // no changes, quest can't be done for this requirement } @@ -4916,7 +4916,7 @@ void ObjectMgr::LoadQuests() { if (qinfo->ItemDropQuantity[j] > 0) { - LOG_ERROR("sql.sql", "Quest {} has `ItemDrop{}` = 0 but `ItemDropQuantity{}` = {}.", + LOG_ERROR("db.query", "Quest {} has `ItemDrop{}` = 0 but `ItemDropQuantity{}` = {}.", qinfo->GetQuestId(), j + 1, j + 1, qinfo->ItemDropQuantity[j]); // no changes, quest ignore this data } @@ -4928,14 +4928,14 @@ void ObjectMgr::LoadQuests() int32 id = qinfo->RequiredNpcOrGo[j]; if (id < 0 && !sObjectMgr->GetGameObjectTemplate(-id)) { - LOG_ERROR("sql.sql", "Quest {} has `RequiredNpcOrGo{}` = {} but gameobject {} does not exist, quest can't be done.", + LOG_ERROR("db.query", "Quest {} has `RequiredNpcOrGo{}` = {} but gameobject {} does not exist, quest can't be done.", qinfo->GetQuestId(), j + 1, id, uint32(-id)); qinfo->RequiredNpcOrGo[j] = 0; // quest can't be done for this requirement } if (id > 0 && !sObjectMgr->GetCreatureTemplate(id)) { - LOG_ERROR("sql.sql", "Quest {} has `RequiredNpcOrGo{}` = {} but creature with entry {} does not exist, quest can't be done.", + LOG_ERROR("db.query", "Quest {} has `RequiredNpcOrGo{}` = {} but creature with entry {} does not exist, quest can't be done.", qinfo->GetQuestId(), j + 1, id, uint32(id)); qinfo->RequiredNpcOrGo[j] = 0; // quest can't be done for this requirement } @@ -4948,14 +4948,14 @@ void ObjectMgr::LoadQuests() if (!qinfo->RequiredNpcOrGoCount[j]) { - LOG_ERROR("sql.sql", "Quest {} has `RequiredNpcOrGo{}` = {} but `RequiredNpcOrGoCount{}` = 0, quest can't be done.", + LOG_ERROR("db.query", "Quest {} has `RequiredNpcOrGo{}` = {} but `RequiredNpcOrGoCount{}` = 0, quest can't be done.", qinfo->GetQuestId(), j + 1, id, j + 1); // no changes, quest can be incorrectly done, but we already report this } } else if (qinfo->RequiredNpcOrGoCount[j] > 0) { - LOG_ERROR("sql.sql", "Quest {} has `RequiredNpcOrGo{}` = 0 but `RequiredNpcOrGoCount{}` = {}.", + LOG_ERROR("db.query", "Quest {} has `RequiredNpcOrGo{}` = 0 but `RequiredNpcOrGoCount{}` = {}.", qinfo->GetQuestId(), j + 1, j + 1, qinfo->RequiredNpcOrGoCount[j]); // no changes, quest ignore this data } @@ -4968,21 +4968,21 @@ void ObjectMgr::LoadQuests() { if (!sObjectMgr->GetItemTemplate(id)) { - LOG_ERROR("sql.sql", "Quest {} has `RewardChoiceItemId{}` = {} but item with entry {} does not exist, quest will not reward this item.", + LOG_ERROR("db.query", "Quest {} has `RewardChoiceItemId{}` = {} but item with entry {} does not exist, quest will not reward this item.", qinfo->GetQuestId(), j + 1, id, id); qinfo->RewardChoiceItemId[j] = 0; // no changes, quest will not reward this } if (!qinfo->RewardChoiceItemCount[j]) { - LOG_ERROR("sql.sql", "Quest {} has `RewardChoiceItemId{}` = {} but `RewardChoiceItemCount{}` = 0, quest can't be done.", + LOG_ERROR("db.query", "Quest {} has `RewardChoiceItemId{}` = {} but `RewardChoiceItemCount{}` = 0, quest can't be done.", qinfo->GetQuestId(), j + 1, id, j + 1); // no changes, quest can't be done } } else if (qinfo->RewardChoiceItemCount[j] > 0) { - LOG_ERROR("sql.sql", "Quest {} has `RewardChoiceItemId{}` = 0 but `RewardChoiceItemCount{}` = {}.", + LOG_ERROR("db.query", "Quest {} has `RewardChoiceItemId{}` = 0 but `RewardChoiceItemCount{}` = {}.", qinfo->GetQuestId(), j + 1, j + 1, qinfo->RewardChoiceItemCount[j]); // no changes, quest ignore this data } @@ -4995,21 +4995,21 @@ void ObjectMgr::LoadQuests() { if (!sObjectMgr->GetItemTemplate(id)) { - LOG_ERROR("sql.sql", "Quest {} has `RewardItemId{}` = {} but item with entry {} does not exist, quest will not reward this item.", + LOG_ERROR("db.query", "Quest {} has `RewardItemId{}` = {} but item with entry {} does not exist, quest will not reward this item.", qinfo->GetQuestId(), j + 1, id, id); qinfo->RewardItemId[j] = 0; // no changes, quest will not reward this item } if (!qinfo->RewardItemIdCount[j]) { - LOG_ERROR("sql.sql", "Quest {} has `RewardItemId{}` = {} but `RewardItemIdCount{}` = 0, quest will not reward this item.", + LOG_ERROR("db.query", "Quest {} has `RewardItemId{}` = {} but `RewardItemIdCount{}` = 0, quest will not reward this item.", qinfo->GetQuestId(), j + 1, id, j + 1); // no changes } } else if (qinfo->RewardItemIdCount[j] > 0) { - LOG_ERROR("sql.sql", "Quest {} has `RewardItemId{}` = 0 but `RewardItemIdCount{}` = {}.", + LOG_ERROR("db.query", "Quest {} has `RewardItemId{}` = 0 but `RewardItemIdCount{}` = {}.", qinfo->GetQuestId(), j + 1, j + 1, qinfo->RewardItemIdCount[j]); // no changes, quest ignore this data } @@ -5021,18 +5021,18 @@ void ObjectMgr::LoadQuests() { if (std::abs(qinfo->RewardFactionValueId[j]) > 9) { - LOG_ERROR("sql.sql", "Quest {} has RewardFactionValueId{} = {}. That is outside the range of valid values (-9 to 9).", qinfo->GetQuestId(), j + 1, qinfo->RewardFactionValueId[j]); + LOG_ERROR("db.query", "Quest {} has RewardFactionValueId{} = {}. That is outside the range of valid values (-9 to 9).", qinfo->GetQuestId(), j + 1, qinfo->RewardFactionValueId[j]); } if (!sFactionStore.LookupEntry(qinfo->RewardFactionId[j])) { - LOG_ERROR("sql.sql", "Quest {} has `RewardFactionId{}` = {} but raw faction (faction.dbc) {} does not exist, quest will not reward reputation for this faction.", qinfo->GetQuestId(), j + 1, qinfo->RewardFactionId[j], qinfo->RewardFactionId[j]); + LOG_ERROR("db.query", "Quest {} has `RewardFactionId{}` = {} but raw faction (faction.dbc) {} does not exist, quest will not reward reputation for this faction.", qinfo->GetQuestId(), j + 1, qinfo->RewardFactionId[j], qinfo->RewardFactionId[j]); qinfo->RewardFactionId[j] = 0; // quest will not reward this } } else if (qinfo->RewardFactionValueIdOverride[j] != 0) { - LOG_ERROR("sql.sql", "Quest {} has `RewardFactionId{}` = 0 but `RewardFactionValueIdOverride{}` = {}.", + LOG_ERROR("db.query", "Quest {} has `RewardFactionId{}` = 0 but `RewardFactionValueIdOverride{}` = {}.", qinfo->GetQuestId(), j + 1, j + 1, qinfo->RewardFactionValueIdOverride[j]); // no changes, quest ignore this data } @@ -5044,21 +5044,21 @@ void ObjectMgr::LoadQuests() if (!spellInfo) { - LOG_ERROR("sql.sql", "Quest {} has `RewardDisplaySpell` = {} but spell {} does not exist, spell removed as display reward.", + LOG_ERROR("db.query", "Quest {} has `RewardDisplaySpell` = {} but spell {} does not exist, spell removed as display reward.", qinfo->GetQuestId(), qinfo->RewardDisplaySpell, qinfo->RewardDisplaySpell); qinfo->RewardDisplaySpell = 0; // no spell reward will display for this quest } else if (!SpellMgr::ComputeIsSpellValid(spellInfo)) { - LOG_ERROR("sql.sql", "Quest {} has `RewardDisplaySpell` = {} but spell {} is broken, quest will not have a spell reward.", + LOG_ERROR("db.query", "Quest {} has `RewardDisplaySpell` = {} but spell {} is broken, quest will not have a spell reward.", qinfo->GetQuestId(), qinfo->RewardDisplaySpell, qinfo->RewardDisplaySpell); qinfo->RewardDisplaySpell = 0; // no spell reward will display for this quest } else if (GetTalentSpellCost(qinfo->RewardDisplaySpell)) { - LOG_ERROR("sql.sql", "Quest {} has `RewardDisplaySpell` = {} but spell {} is talent, quest will not have a spell reward.", + LOG_ERROR("db.query", "Quest {} has `RewardDisplaySpell` = {} but spell {} is talent, quest will not have a spell reward.", qinfo->GetQuestId(), qinfo->RewardDisplaySpell, qinfo->RewardDisplaySpell); qinfo->RewardDisplaySpell = 0; // no spell reward will display for this quest } @@ -5070,21 +5070,21 @@ void ObjectMgr::LoadQuests() if (!spellInfo) { - LOG_ERROR("sql.sql", "Quest {} has `RewardSpell` = {} but spell {} does not exist, quest will not have a spell reward.", + LOG_ERROR("db.query", "Quest {} has `RewardSpell` = {} but spell {} does not exist, quest will not have a spell reward.", qinfo->GetQuestId(), qinfo->RewardSpell, qinfo->RewardSpell); qinfo->RewardSpell = 0; // no spell will be casted on player } else if (!SpellMgr::ComputeIsSpellValid(spellInfo)) { - LOG_ERROR("sql.sql", "Quest {} has `RewardSpell` = {} but spell {} is broken, quest will not have a spell reward.", + LOG_ERROR("db.query", "Quest {} has `RewardSpell` = {} but spell {} is broken, quest will not have a spell reward.", qinfo->GetQuestId(), qinfo->RewardSpell, qinfo->RewardSpell); qinfo->RewardSpell = 0; // no spell will be casted on player } else if (GetTalentSpellCost(qinfo->RewardSpell)) { - LOG_ERROR("sql.sql", "Quest {} has `RewardDisplaySpell` = {} but spell {} is talent, quest will not have a spell reward.", + LOG_ERROR("db.query", "Quest {} has `RewardDisplaySpell` = {} but spell {} is talent, quest will not have a spell reward.", qinfo->GetQuestId(), qinfo->RewardSpell, qinfo->RewardSpell); qinfo->RewardSpell = 0; // no spell will be casted on player } @@ -5094,7 +5094,7 @@ void ObjectMgr::LoadQuests() { if (!sMailTemplateStore.LookupEntry(qinfo->RewardMailTemplateId)) { - LOG_ERROR("sql.sql", "Quest {} has `RewardMailTemplateId` = {} but mail template {} does not exist, quest will not have a mail reward.", + LOG_ERROR("db.query", "Quest {} has `RewardMailTemplateId` = {} but mail template {} does not exist, quest will not have a mail reward.", qinfo->GetQuestId(), qinfo->RewardMailTemplateId, qinfo->RewardMailTemplateId); qinfo->RewardMailTemplateId = 0; // no mail will send to player qinfo->RewardMailDelay = 0; // no mail will send to player @@ -5103,7 +5103,7 @@ void ObjectMgr::LoadQuests() else if (usedMailTemplates.find(qinfo->RewardMailTemplateId) != usedMailTemplates.end()) { std::map::const_iterator used_mt_itr = usedMailTemplates.find(qinfo->RewardMailTemplateId); - LOG_ERROR("sql.sql", "Quest {} has `RewardMailTemplateId` = {} but mail template {} already used for quest {}, quest will not have a mail reward.", + LOG_ERROR("db.query", "Quest {} has `RewardMailTemplateId` = {} but mail template {} already used for quest {}, quest will not have a mail reward.", qinfo->GetQuestId(), qinfo->RewardMailTemplateId, qinfo->RewardMailTemplateId, used_mt_itr->second); qinfo->RewardMailTemplateId = 0; // no mail will send to player qinfo->RewardMailDelay = 0; // no mail will send to player @@ -5118,7 +5118,7 @@ void ObjectMgr::LoadQuests() QuestMap::iterator qNextItr = _questTemplates.find(qinfo->RewardNextQuest); if (qNextItr == _questTemplates.end()) { - LOG_ERROR("sql.sql", "Quest {} has `RewardNextQuest` = {} but quest {} does not exist, quest chain will not work.", + LOG_ERROR("db.query", "Quest {} has `RewardNextQuest` = {} but quest {} does not exist, quest chain will not work.", qinfo->GetQuestId(), qinfo->RewardNextQuest, qinfo->RewardNextQuest); qinfo->RewardNextQuest = 0; } @@ -5131,7 +5131,7 @@ void ObjectMgr::LoadQuests() { if (_questTemplates.find(std::abs(qinfo->GetPrevQuestId())) == _questTemplates.end()) { - LOG_ERROR("sql.sql", "Quest {} has PrevQuestId {}, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId()); + LOG_ERROR("db.query", "Quest {} has PrevQuestId {}, but no such quest", qinfo->GetQuestId(), qinfo->GetPrevQuestId()); } else { @@ -5144,7 +5144,7 @@ void ObjectMgr::LoadQuests() QuestMap::iterator qNextItr = _questTemplates.find(qinfo->GetNextQuestId()); if (qNextItr == _questTemplates.end()) { - LOG_ERROR("sql.sql", "Quest {} has NextQuestId {}, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId()); + LOG_ERROR("db.query", "Quest {} has NextQuestId {}, but no such quest", qinfo->GetQuestId(), qinfo->GetNextQuestId()); } else qNextItr->second->prevQuests.push_back(static_cast(qinfo->GetQuestId())); @@ -5180,7 +5180,7 @@ void ObjectMgr::LoadQuests() if (!quest->HasSpecialFlag(QUEST_SPECIAL_FLAGS_EXPLORATION_OR_EVENT)) { - LOG_ERROR("sql.sql", "Spell (id: {}) have SPELL_EFFECT_QUEST_COMPLETE for quest {}, but quest not have specialflag QUEST_SPECIAL_FLAGS_EXPLORATION_OR_EVENT. Quest flags must be fixed, quest modified to enable objective.", spellInfo->Id, quest_id); + LOG_ERROR("db.query", "Spell (id: {}) have SPELL_EFFECT_QUEST_COMPLETE for quest {}, but quest not have specialflag QUEST_SPECIAL_FLAGS_EXPLORATION_OR_EVENT. Quest flags must be fixed, quest modified to enable objective.", spellInfo->Id, quest_id); // this will prevent quest completing without objective // xinef: remove this, leave error but do not break the quest @@ -5286,13 +5286,13 @@ void ObjectMgr::LoadScripts(ScriptsType type) { if (tmp.Talk.ChatType > CHAT_TYPE_WHISPER && tmp.Talk.ChatType != CHAT_MSG_RAID_BOSS_WHISPER) { - LOG_ERROR("sql.sql", "Table `{}` has invalid talk type (datalong = {}) in SCRIPT_COMMAND_TALK for script id {}", + LOG_ERROR("db.query", "Table `{}` has invalid talk type (datalong = {}) in SCRIPT_COMMAND_TALK for script id {}", tableName, tmp.Talk.ChatType, tmp.id); continue; } if (!GetBroadcastText(uint32(tmp.Talk.TextID))) { - LOG_ERROR("sql.sql", "Table `{}` has invalid talk text id (dataint = {}) in SCRIPT_COMMAND_TALK for script id {}", + LOG_ERROR("db.query", "Table `{}` has invalid talk text id (dataint = {}) in SCRIPT_COMMAND_TALK for script id {}", tableName, tmp.Talk.TextID, tmp.id); continue; } @@ -5303,7 +5303,7 @@ void ObjectMgr::LoadScripts(ScriptsType type) { if (!sEmotesStore.LookupEntry(tmp.Emote.EmoteID)) { - LOG_ERROR("sql.sql", "Table `{}` has invalid emote id (datalong = {}) in SCRIPT_COMMAND_EMOTE for script id {}", + LOG_ERROR("db.query", "Table `{}` has invalid emote id (datalong = {}) in SCRIPT_COMMAND_EMOTE for script id {}", tableName, tmp.Emote.EmoteID, tmp.id); continue; } @@ -5314,14 +5314,14 @@ void ObjectMgr::LoadScripts(ScriptsType type) { if (!sMapStore.LookupEntry(tmp.TeleportTo.MapID)) { - LOG_ERROR("sql.sql", "Table `{}` has invalid map (Id: {}) in SCRIPT_COMMAND_TELEPORT_TO for script id {}", + LOG_ERROR("db.query", "Table `{}` has invalid map (Id: {}) in SCRIPT_COMMAND_TELEPORT_TO for script id {}", tableName, tmp.TeleportTo.MapID, tmp.id); continue; } if (!Acore::IsValidMapCoord(tmp.TeleportTo.DestX, tmp.TeleportTo.DestY, tmp.TeleportTo.DestZ, tmp.TeleportTo.Orientation)) { - LOG_ERROR("sql.sql", "Table `{}` has invalid coordinates (X: {} Y: {} Z: {} O: {}) in SCRIPT_COMMAND_TELEPORT_TO for script id {}", + LOG_ERROR("db.query", "Table `{}` has invalid coordinates (X: {} Y: {} Z: {} O: {}) in SCRIPT_COMMAND_TELEPORT_TO for script id {}", tableName, tmp.TeleportTo.DestX, tmp.TeleportTo.DestY, tmp.TeleportTo.DestZ, tmp.TeleportTo.Orientation, tmp.id); continue; } @@ -5333,14 +5333,14 @@ void ObjectMgr::LoadScripts(ScriptsType type) Quest const* quest = GetQuestTemplate(tmp.QuestExplored.QuestID); if (!quest) { - LOG_ERROR("sql.sql", "Table `{}` has invalid quest (ID: {}) in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id {}", + LOG_ERROR("db.query", "Table `{}` has invalid quest (ID: {}) in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id {}", tableName, tmp.QuestExplored.QuestID, tmp.id); continue; } if (!quest->HasSpecialFlag(QUEST_SPECIAL_FLAGS_EXPLORATION_OR_EVENT)) { - LOG_ERROR("sql.sql", "Table `{}` has quest (ID: {}) in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id {}, but quest not have specialflag QUEST_SPECIAL_FLAGS_EXPLORATION_OR_EVENT in quest flags. Script command or quest flags wrong. Quest modified to require objective.", + LOG_ERROR("db.query", "Table `{}` has quest (ID: {}) in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id {}, but quest not have specialflag QUEST_SPECIAL_FLAGS_EXPLORATION_OR_EVENT in quest flags. Script command or quest flags wrong. Quest modified to require objective.", tableName, tmp.QuestExplored.QuestID, tmp.id); // this will prevent quest completing without objective @@ -5351,21 +5351,21 @@ void ObjectMgr::LoadScripts(ScriptsType type) if (float(tmp.QuestExplored.Distance) > DEFAULT_VISIBILITY_DISTANCE) { - LOG_ERROR("sql.sql", "Table `{}` has too large distance ({}) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id {}", + LOG_ERROR("db.query", "Table `{}` has too large distance ({}) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id {}", tableName, tmp.QuestExplored.Distance, tmp.id); continue; } if (tmp.QuestExplored.Distance && float(tmp.QuestExplored.Distance) > DEFAULT_VISIBILITY_DISTANCE) { - LOG_ERROR("sql.sql", "Table `{}` has too large distance ({}) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id {}, max distance is {} or 0 for disable distance check", + LOG_ERROR("db.query", "Table `{}` has too large distance ({}) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id {}, max distance is {} or 0 for disable distance check", tableName, tmp.QuestExplored.Distance, tmp.id, DEFAULT_VISIBILITY_DISTANCE); continue; } if (tmp.QuestExplored.Distance && float(tmp.QuestExplored.Distance) < INTERACTION_DISTANCE) { - LOG_ERROR("sql.sql", "Table `{}` has too small distance ({}) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id {}, min distance is {} or 0 for disable distance check", + LOG_ERROR("db.query", "Table `{}` has too small distance ({}) for exploring objective complete in `datalong2` in SCRIPT_COMMAND_QUEST_EXPLORED in `datalong` for script id {}, min distance is {} or 0 for disable distance check", tableName, tmp.QuestExplored.Distance, tmp.id, INTERACTION_DISTANCE); continue; } @@ -5377,7 +5377,7 @@ void ObjectMgr::LoadScripts(ScriptsType type) { if (!GetCreatureTemplate(tmp.KillCredit.CreatureEntry)) { - LOG_ERROR("sql.sql", "Table `{}` has invalid creature (Entry: {}) in SCRIPT_COMMAND_KILL_CREDIT for script id {}", + LOG_ERROR("db.query", "Table `{}` has invalid creature (Entry: {}) in SCRIPT_COMMAND_KILL_CREDIT for script id {}", tableName, tmp.KillCredit.CreatureEntry, tmp.id); continue; } @@ -5389,7 +5389,7 @@ void ObjectMgr::LoadScripts(ScriptsType type) GameObjectData const* data = GetGameObjectData(tmp.RespawnGameobject.GOGuid); if (!data) { - LOG_ERROR("sql.sql", "Table `{}` has invalid gameobject (GUID: {}) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id {}", + LOG_ERROR("db.query", "Table `{}` has invalid gameobject (GUID: {}) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id {}", tableName, tmp.RespawnGameobject.GOGuid, tmp.id); continue; } @@ -5397,7 +5397,7 @@ void ObjectMgr::LoadScripts(ScriptsType type) GameObjectTemplate const* info = GetGameObjectTemplate(data->id); if (!info) { - LOG_ERROR("sql.sql", "Table `{}` has gameobject with invalid entry (GUID: {} Entry: {}) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id {}", + LOG_ERROR("db.query", "Table `{}` has gameobject with invalid entry (GUID: {} Entry: {}) in SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id {}", tableName, tmp.RespawnGameobject.GOGuid, data->id, tmp.id); continue; } @@ -5408,7 +5408,7 @@ void ObjectMgr::LoadScripts(ScriptsType type) info->type == GAMEOBJECT_TYPE_BUTTON || info->type == GAMEOBJECT_TYPE_TRAP) { - LOG_ERROR("sql.sql", "Table `{}` have gameobject type ({}) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id {}", + LOG_ERROR("db.query", "Table `{}` have gameobject type ({}) unsupported by command SCRIPT_COMMAND_RESPAWN_GAMEOBJECT for script id {}", tableName, info->entry, tmp.id); continue; } @@ -5419,7 +5419,7 @@ void ObjectMgr::LoadScripts(ScriptsType type) { if (!Acore::IsValidMapCoord(tmp.TempSummonCreature.PosX, tmp.TempSummonCreature.PosY, tmp.TempSummonCreature.PosZ, tmp.TempSummonCreature.Orientation)) { - LOG_ERROR("sql.sql", "Table `{}` has invalid coordinates (X: {} Y: {} Z: {} O: {}) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id {}", + LOG_ERROR("db.query", "Table `{}` has invalid coordinates (X: {} Y: {} Z: {} O: {}) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id {}", tableName, tmp.TempSummonCreature.PosX, tmp.TempSummonCreature.PosY, tmp.TempSummonCreature.PosZ, tmp.TempSummonCreature.Orientation, tmp.id); continue; } @@ -5427,7 +5427,7 @@ void ObjectMgr::LoadScripts(ScriptsType type) uint32 entry = tmp.TempSummonCreature.CreatureEntry; if (!GetCreatureTemplate(entry)) { - LOG_ERROR("sql.sql", "Table `{}` has invalid creature (Entry: {}) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id {}", + LOG_ERROR("db.query", "Table `{}` has invalid creature (Entry: {}) in SCRIPT_COMMAND_TEMP_SUMMON_CREATURE for script id {}", tableName, tmp.TempSummonCreature.CreatureEntry, tmp.id); continue; } @@ -5440,7 +5440,7 @@ void ObjectMgr::LoadScripts(ScriptsType type) GameObjectData const* data = GetGameObjectData(tmp.ToggleDoor.GOGuid); if (!data) { - LOG_ERROR("sql.sql", "Table `{}` has invalid gameobject (GUID: {}) in {} for script id {}", + LOG_ERROR("db.query", "Table `{}` has invalid gameobject (GUID: {}) in {} for script id {}", tableName, tmp.ToggleDoor.GOGuid, GetScriptCommandName(tmp.command), tmp.id); continue; } @@ -5448,14 +5448,14 @@ void ObjectMgr::LoadScripts(ScriptsType type) GameObjectTemplate const* info = GetGameObjectTemplate(data->id); if (!info) { - LOG_ERROR("sql.sql", "Table `{}` has gameobject with invalid entry (GUID: {} Entry: {}) in {} for script id {}", + LOG_ERROR("db.query", "Table `{}` has gameobject with invalid entry (GUID: {} Entry: {}) in {} for script id {}", tableName, tmp.ToggleDoor.GOGuid, data->id, GetScriptCommandName(tmp.command), tmp.id); continue; } if (info->type != GAMEOBJECT_TYPE_DOOR) { - LOG_ERROR("sql.sql", "Table `{}` has gameobject type ({}) non supported by command {} for script id {}", + LOG_ERROR("db.query", "Table `{}` has gameobject type ({}) non supported by command {} for script id {}", tableName, info->entry, GetScriptCommandName(tmp.command), tmp.id); continue; } @@ -5467,13 +5467,13 @@ void ObjectMgr::LoadScripts(ScriptsType type) { if (!sSpellMgr->GetSpellInfo(tmp.RemoveAura.SpellID)) { - LOG_ERROR("sql.sql", "Table `{}` using non-existent spell (id: {}) in SCRIPT_COMMAND_REMOVE_AURA for script id {}", + LOG_ERROR("db.query", "Table `{}` using non-existent spell (id: {}) in SCRIPT_COMMAND_REMOVE_AURA for script id {}", tableName, tmp.RemoveAura.SpellID, tmp.id); continue; } if (tmp.RemoveAura.Flags & ~0x1) // 1 bits (0, 1) { - LOG_ERROR("sql.sql", "Table `{}` using unknown flags in datalong2 ({}) in SCRIPT_COMMAND_REMOVE_AURA for script id {}", + LOG_ERROR("db.query", "Table `{}` using unknown flags in datalong2 ({}) in SCRIPT_COMMAND_REMOVE_AURA for script id {}", tableName, tmp.RemoveAura.Flags, tmp.id); continue; } @@ -5484,25 +5484,25 @@ void ObjectMgr::LoadScripts(ScriptsType type) { if (!sSpellMgr->GetSpellInfo(tmp.CastSpell.SpellID)) { - LOG_ERROR("sql.sql", "Table `{}` using non-existent spell (id: {}) in SCRIPT_COMMAND_CAST_SPELL for script id {}", + LOG_ERROR("db.query", "Table `{}` using non-existent spell (id: {}) in SCRIPT_COMMAND_CAST_SPELL for script id {}", tableName, tmp.CastSpell.SpellID, tmp.id); continue; } if (tmp.CastSpell.Flags > 4) // targeting type { - LOG_ERROR("sql.sql", "Table `{}` using unknown target in datalong2 ({}) in SCRIPT_COMMAND_CAST_SPELL for script id {}", + LOG_ERROR("db.query", "Table `{}` using unknown target in datalong2 ({}) in SCRIPT_COMMAND_CAST_SPELL for script id {}", tableName, tmp.CastSpell.Flags, tmp.id); continue; } if (tmp.CastSpell.Flags != 4 && tmp.CastSpell.CreatureEntry & ~0x1) // 1 bit (0, 1) { - LOG_ERROR("sql.sql", "Table `{}` using unknown flags in dataint ({}) in SCRIPT_COMMAND_CAST_SPELL for script id {}", + LOG_ERROR("db.query", "Table `{}` using unknown flags in dataint ({}) in SCRIPT_COMMAND_CAST_SPELL for script id {}", tableName, tmp.CastSpell.CreatureEntry, tmp.id); continue; } else if (tmp.CastSpell.Flags == 4 && !GetCreatureTemplate(tmp.CastSpell.CreatureEntry)) { - LOG_ERROR("sql.sql", "Table `{}` using invalid creature entry in dataint ({}) in SCRIPT_COMMAND_CAST_SPELL for script id {}", + LOG_ERROR("db.query", "Table `{}` using invalid creature entry in dataint ({}) in SCRIPT_COMMAND_CAST_SPELL for script id {}", tableName, tmp.CastSpell.CreatureEntry, tmp.id); continue; } @@ -5513,13 +5513,13 @@ void ObjectMgr::LoadScripts(ScriptsType type) { if (!GetItemTemplate(tmp.CreateItem.ItemEntry)) { - LOG_ERROR("sql.sql", "Table `{}` has nonexistent item (entry: {}) in SCRIPT_COMMAND_CREATE_ITEM for script id {}", + LOG_ERROR("db.query", "Table `{}` has nonexistent item (entry: {}) in SCRIPT_COMMAND_CREATE_ITEM for script id {}", tableName, tmp.CreateItem.ItemEntry, tmp.id); continue; } if (!tmp.CreateItem.Amount) { - LOG_ERROR("sql.sql", "Table `{}` SCRIPT_COMMAND_CREATE_ITEM but amount is {} for script id {}", + LOG_ERROR("db.query", "Table `{}` SCRIPT_COMMAND_CREATE_ITEM but amount is {} for script id {}", tableName, tmp.CreateItem.Amount, tmp.id); continue; } @@ -5555,19 +5555,19 @@ void ObjectMgr::LoadSpellScripts() if (!spellInfo) { - LOG_ERROR("sql.sql", "Table `spell_scripts` has not existing spell (Id: {}) as script id", spellId); + LOG_ERROR("db.query", "Table `spell_scripts` has not existing spell (Id: {}) as script id", spellId); continue; } SpellEffIndex i = SpellEffIndex((uint32(itr->first) >> 24) & 0x000000FF); if (uint32(i) >= MAX_SPELL_EFFECTS) { - LOG_ERROR("sql.sql", "Table `spell_scripts` has too high effect index {} for spell (Id: {}) as script id", uint32(i), spellId); + LOG_ERROR("db.query", "Table `spell_scripts` has too high effect index {} for spell (Id: {}) as script id", uint32(i), spellId); } //check for correct spellEffect if (!spellInfo->Effects[i].Effect || (spellInfo->Effects[i].Effect != SPELL_EFFECT_SCRIPT_EFFECT && spellInfo->Effects[i].Effect != SPELL_EFFECT_DUMMY)) - LOG_ERROR("sql.sql", "Table `spell_scripts` - spell {} effect {} is not SPELL_EFFECT_SCRIPT_EFFECT or SPELL_EFFECT_DUMMY", spellId, uint32(i)); + LOG_ERROR("db.query", "Table `spell_scripts` - spell {} effect {} is not SPELL_EFFECT_SCRIPT_EFFECT or SPELL_EFFECT_DUMMY", spellId, uint32(i)); } } @@ -5609,7 +5609,7 @@ void ObjectMgr::LoadEventScripts() { std::set::const_iterator itr2 = evt_scripts.find(itr->first); if (itr2 == evt_scripts.end()) - LOG_ERROR("sql.sql", "Table `event_scripts` has script (Id: {}) not referring to any gameobject_template type 10 data2 field, type 3 data6 field, type 13 data 2 field or any spell effect {}", + LOG_ERROR("db.query", "Table `event_scripts` has script (Id: {}) not referring to any gameobject_template type 10 data2 field, type 3 data6 field, type 13 data 2 field or any spell effect {}", itr->first, SPELL_EFFECT_SEND_EVENT); } } @@ -5624,7 +5624,7 @@ void ObjectMgr::LoadWaypointScripts() for (ScriptMapMap::const_iterator itr = sWaypointScripts.begin(); itr != sWaypointScripts.end(); ++itr) actionSet.insert(itr->first); - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_ACTION); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_ACTION); PreparedQueryResult result = WorldDatabase.Query(stmt); if (result) @@ -5639,7 +5639,7 @@ void ObjectMgr::LoadWaypointScripts() } for (std::set::iterator itr = actionSet.begin(); itr != actionSet.end(); ++itr) - LOG_ERROR("sql.sql", "There is no waypoint which links to the waypoint script {}", *itr); + LOG_ERROR("db.query", "There is no waypoint which links to the waypoint script {}", *itr); } void ObjectMgr::LoadSpellScriptNames() @@ -5676,7 +5676,7 @@ void ObjectMgr::LoadSpellScriptNames() SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId); if (!spellInfo) { - LOG_ERROR("sql.sql", "Scriptname: `{}` spell (spell_id:{}) does not exist in `Spell.dbc`.", scriptName, fields[0].Get()); + LOG_ERROR("db.query", "Scriptname: `{}` spell (spell_id:{}) does not exist in `Spell.dbc`.", scriptName, fields[0].Get()); continue; } @@ -5684,7 +5684,7 @@ void ObjectMgr::LoadSpellScriptNames() { if (sSpellMgr->GetFirstSpellInChain(spellId) != uint32(spellId)) { - LOG_ERROR("sql.sql", "Scriptname: `{}` spell (spell_id:{}) is not first rank of spell.", scriptName, fields[0].Get()); + LOG_ERROR("db.query", "Scriptname: `{}` spell (spell_id:{}) is not first rank of spell.", scriptName, fields[0].Get()); continue; } while (spellInfo) @@ -5729,7 +5729,7 @@ void ObjectMgr::ValidateSpellScripts() bool valid = true; if (!spellScript && !auraScript) { - LOG_ERROR("sql.sql", "Functions GetSpellScript() and GetAuraScript() of script `{}` do not return objects - script skipped", GetScriptName(sitr->second->second)); + LOG_ERROR("db.query", "Functions GetSpellScript() and GetAuraScript() of script `{}` do not return objects - script skipped", GetScriptName(sitr->second->second)); valid = false; } if (spellScript) @@ -5805,7 +5805,7 @@ void ObjectMgr::LoadPageTexts() { PageTextContainer::const_iterator itr2 = _pageTextStore.find(itr->second.NextPage); if (itr2 == _pageTextStore.end()) - LOG_ERROR("sql.sql", "Page text (Id: {}) has not existing next page (Id: {})", itr->first, itr->second.NextPage); + LOG_ERROR("db.query", "Page text (Id: {}) has not existing next page (Id: {})", itr->first, itr->second.NextPage); } } @@ -5874,7 +5874,7 @@ void ObjectMgr::LoadInstanceTemplate() if (!MapMgr::IsValidMAP(mapID, true)) { - LOG_ERROR("sql.sql", "ObjectMgr::LoadInstanceTemplate: bad mapid {} for template!", mapID); + LOG_ERROR("db.query", "ObjectMgr::LoadInstanceTemplate: bad mapid {} for template!", mapID); continue; } @@ -5927,13 +5927,13 @@ void ObjectMgr::LoadInstanceEncounters() DungeonEncounterEntry const* dungeonEncounter = sDungeonEncounterStore.LookupEntry(entry); if (!dungeonEncounter) { - LOG_ERROR("sql.sql", "Table `instance_encounters` has an invalid encounter id {}, skipped!", entry); + LOG_ERROR("db.query", "Table `instance_encounters` has an invalid encounter id {}, skipped!", entry); continue; } if (lastEncounterDungeon && !sLFGMgr->GetLFGDungeonEntry(lastEncounterDungeon)) { - LOG_ERROR("sql.sql", "Table `instance_encounters` has an encounter {} ({}) marked as final for invalid dungeon id {}, skipped!", entry, dungeonEncounter->encounterName[0], lastEncounterDungeon); + LOG_ERROR("db.query", "Table `instance_encounters` has an encounter {} ({}) marked as final for invalid dungeon id {}, skipped!", entry, dungeonEncounter->encounterName[0], lastEncounterDungeon); continue; } @@ -5942,7 +5942,7 @@ void ObjectMgr::LoadInstanceEncounters() { if (itr != dungeonLastBosses.end()) { - LOG_ERROR("sql.sql", "Table `instance_encounters` specified encounter {} ({}) as last encounter but {} ({}) is already marked as one, skipped!", entry, dungeonEncounter->encounterName[0], itr->second->id, itr->second->encounterName[0]); + LOG_ERROR("db.query", "Table `instance_encounters` specified encounter {} ({}) as last encounter but {} ({}) is already marked as one, skipped!", entry, dungeonEncounter->encounterName[0], itr->second->id, itr->second->encounterName[0]); continue; } @@ -5956,7 +5956,7 @@ void ObjectMgr::LoadInstanceEncounters() CreatureTemplate const* creatureInfo = GetCreatureTemplate(creditEntry); if (!creatureInfo) { - LOG_ERROR("sql.sql", "Table `instance_encounters` has an invalid creature (entry {}) linked to the encounter {} ({}), skipped!", creditEntry, entry, dungeonEncounter->encounterName[0]); + LOG_ERROR("db.query", "Table `instance_encounters` has an invalid creature (entry {}) linked to the encounter {} ({}), skipped!", creditEntry, entry, dungeonEncounter->encounterName[0]); continue; } const_cast(creatureInfo)->flags_extra |= CREATURE_FLAG_EXTRA_DUNGEON_BOSS; @@ -5967,14 +5967,14 @@ void ObjectMgr::LoadInstanceEncounters() SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(creditEntry); if (!spellInfo) { - LOG_ERROR("sql.sql", "Table `instance_encounters` has an invalid spell (entry {}) linked to the encounter {} ({}), skipped!", creditEntry, entry, dungeonEncounter->encounterName[0]); + LOG_ERROR("db.query", "Table `instance_encounters` has an invalid spell (entry {}) linked to the encounter {} ({}), skipped!", creditEntry, entry, dungeonEncounter->encounterName[0]); continue; } const_cast(spellInfo)->AttributesCu |= SPELL_ATTR0_CU_ENCOUNTER_REWARD; break; } default: - LOG_ERROR("sql.sql", "Table `instance_encounters` has an invalid credit type ({}) for encounter {} ({}), skipped!", creditType, entry, dungeonEncounter->encounterName[0]); + LOG_ERROR("db.query", "Table `instance_encounters` has an invalid credit type ({}) for encounter {} ({}), skipped!", creditType, entry, dungeonEncounter->encounterName[0]); continue; } @@ -6031,7 +6031,7 @@ void ObjectMgr::LoadGossipText() uint32 id = fields[cic++].Get(); if (!id) { - LOG_ERROR("sql.sql", "Table `npc_text` has record wit reserved id 0, ignore."); + LOG_ERROR("db.query", "Table `npc_text` has record wit reserved id 0, ignore."); continue; } @@ -6058,7 +6058,7 @@ void ObjectMgr::LoadGossipText() { if (!GetBroadcastText(gText.Options[i].BroadcastTextID)) { - LOG_ERROR("sql.sql", "GossipText (Id: {}) in table `npc_text` has non-existing or incompatible BroadcastTextID{} {}.", id, i, gText.Options[i].BroadcastTextID); + LOG_ERROR("db.query", "GossipText (Id: {}) in table `npc_text` has non-existing or incompatible BroadcastTextID{} {}.", id, i, gText.Options[i].BroadcastTextID); gText.Options[i].BroadcastTextID = 0; } } @@ -6112,7 +6112,7 @@ void ObjectMgr::ReturnOrDeleteOldMails(bool serverUp) time_t curTime = GameTime::GetGameTime().count(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_EXPIRED_MAIL); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_EXPIRED_MAIL); stmt->SetData(0, uint32(curTime)); PreparedQueryResult result = CharacterDatabase.Query(stmt); if (!result) @@ -6258,7 +6258,7 @@ void ObjectMgr::LoadQuestAreaTriggers() AreaTrigger const* atEntry = GetAreaTrigger(trigger_ID); if (!atEntry) { - LOG_ERROR("sql.sql", "Area trigger (ID:{}) does not exist in `AreaTrigger.dbc`.", trigger_ID); + LOG_ERROR("db.query", "Area trigger (ID:{}) does not exist in `AreaTrigger.dbc`.", trigger_ID); continue; } @@ -6266,13 +6266,13 @@ void ObjectMgr::LoadQuestAreaTriggers() if (!quest) { - LOG_ERROR("sql.sql", "Table `areatrigger_involvedrelation` has record (id: {}) for not existing quest {}", trigger_ID, quest_ID); + LOG_ERROR("db.query", "Table `areatrigger_involvedrelation` has record (id: {}) for not existing quest {}", trigger_ID, quest_ID); continue; } if (!quest->HasSpecialFlag(QUEST_SPECIAL_FLAGS_EXPLORATION_OR_EVENT)) { - LOG_ERROR("sql.sql", "Table `areatrigger_involvedrelation` has record (id: {}) for not quest {}, but quest not have specialflag QUEST_SPECIAL_FLAGS_EXPLORATION_OR_EVENT. Trigger or quest flags must be fixed, quest modified to require objective.", trigger_ID, quest_ID); + LOG_ERROR("db.query", "Table `areatrigger_involvedrelation` has record (id: {}) for not quest {}, but quest not have specialflag QUEST_SPECIAL_FLAGS_EXPLORATION_OR_EVENT. Trigger or quest flags must be fixed, quest modified to require objective.", trigger_ID, quest_ID); // this will prevent quest completing without objective const_cast(quest)->SetSpecialFlag(QUEST_SPECIAL_FLAGS_EXPLORATION_OR_EVENT); @@ -6328,14 +6328,14 @@ void ObjectMgr::LoadQuestGreetings() case 0: // Creature if (!sObjectMgr->GetCreatureTemplate(id)) { - LOG_ERROR("sql.sql", "Table `quest_greeting`: creature template entry {} does not exist.", id); + LOG_ERROR("db.query", "Table `quest_greeting`: creature template entry {} does not exist.", id); continue; } break; case 1: // GameObject if (!sObjectMgr->GetGameObjectTemplate(id)) { - LOG_ERROR("sql.sql", "Table `quest_greeting`: gameobject template entry {} does not exist.", id); + LOG_ERROR("db.query", "Table `quest_greeting`: gameobject template entry {} does not exist.", id); continue; } break; @@ -6384,14 +6384,14 @@ void ObjectMgr::LoadQuestGreetingsLocales() case 0: // Creature if (!sObjectMgr->GetCreatureTemplate(id)) { - LOG_ERROR("sql.sql", "Table `quest_greeting_locale`: creature template entry {} does not exist.", id); + LOG_ERROR("db.query", "Table `quest_greeting_locale`: creature template entry {} does not exist.", id); continue; } break; case 1: // GameObject if (!sObjectMgr->GetGameObjectTemplate(id)) { - LOG_ERROR("sql.sql", "Table `quest_greeting_locale`: gameobject template entry {} does not exist.", id); + LOG_ERROR("db.query", "Table `quest_greeting_locale`: gameobject template entry {} does not exist.", id); continue; } break; @@ -6501,7 +6501,7 @@ void ObjectMgr::LoadTavernAreaTriggers() AreaTrigger const* atEntry = GetAreaTrigger(Trigger_ID); if (!atEntry) { - LOG_ERROR("sql.sql", "Area trigger (ID:{}) does not exist in `AreaTrigger.dbc`.", Trigger_ID); + LOG_ERROR("db.query", "Area trigger (ID:{}) does not exist in `AreaTrigger.dbc`.", Trigger_ID); continue; } @@ -6542,7 +6542,7 @@ void ObjectMgr::LoadAreaTriggerScripts() AreaTrigger const* atEntry = GetAreaTrigger(Trigger_ID); if (!atEntry) { - LOG_ERROR("sql.sql", "Area trigger (ID:{}) does not exist in `AreaTrigger.dbc`.", Trigger_ID); + LOG_ERROR("db.query", "Area trigger (ID:{}) does not exist in `AreaTrigger.dbc`.", Trigger_ID); continue; } _areaTriggerScriptStore[Trigger_ID] = GetScriptId(scriptName); @@ -6642,7 +6642,7 @@ uint32 ObjectMgr::GetTaxiMountDisplayId(uint32 id, TeamId teamId, bool allowed_a mount_id = mount_info->GetRandomValidModelId(); if (!mount_id) { - LOG_ERROR("sql.sql", "No displayid found for the taxi mount with the entry {}! Can't load it!", mount_entry); + LOG_ERROR("db.query", "No displayid found for the taxi mount with the entry {}! Can't load it!", mount_entry); return 0; } } @@ -6693,7 +6693,7 @@ void ObjectMgr::LoadAreaTriggers() MapEntry const* mapEntry = sMapStore.LookupEntry(at.map); if (!mapEntry) { - LOG_ERROR("sql.sql", "Area trigger (ID:{}) map (ID: {}) does not exist in `Map.dbc`.", at.entry, at.map); + LOG_ERROR("db.query", "Area trigger (ID:{}) map (ID: {}) does not exist in `Map.dbc`.", at.entry, at.map); continue; } @@ -6741,20 +6741,20 @@ void ObjectMgr::LoadAreaTriggerTeleports() AreaTrigger const* atEntry = GetAreaTrigger(Trigger_ID); if (!atEntry) { - LOG_ERROR("sql.sql", "Area trigger (ID:{}) does not exist in `AreaTrigger.dbc`.", Trigger_ID); + LOG_ERROR("db.query", "Area trigger (ID:{}) does not exist in `AreaTrigger.dbc`.", Trigger_ID); continue; } MapEntry const* mapEntry = sMapStore.LookupEntry(at.target_mapId); if (!mapEntry) { - LOG_ERROR("sql.sql", "Area trigger (ID:{}) target map (ID: {}) does not exist in `Map.dbc`.", Trigger_ID, at.target_mapId); + LOG_ERROR("db.query", "Area trigger (ID:{}) target map (ID: {}) does not exist in `Map.dbc`.", Trigger_ID, at.target_mapId); continue; } if (at.target_X == 0 && at.target_Y == 0 && at.target_Z == 0) { - LOG_ERROR("sql.sql", "Area trigger (ID:{}) target coordinates not provided.", Trigger_ID); + LOG_ERROR("db.query", "Area trigger (ID:{}) target coordinates not provided.", Trigger_ID); continue; } @@ -6855,7 +6855,7 @@ void ObjectMgr::LoadAccessRequirements() //Achievement if (!sAchievementStore.LookupEntry(progression_requirement->id)) { - LOG_ERROR("sql.sql", "Required achievement {} for faction {} does not exist for map {} difficulty {}, remove or fix this achievement requirement.", progression_requirement->id, requirement_faction, mapid, difficulty); + LOG_ERROR("db.query", "Required achievement {} for faction {} does not exist for map {} difficulty {}, remove or fix this achievement requirement.", progression_requirement->id, requirement_faction, mapid, difficulty); break; } @@ -6867,7 +6867,7 @@ void ObjectMgr::LoadAccessRequirements() //Quest if (!GetQuestTemplate(progression_requirement->id)) { - LOG_ERROR("sql.sql", "Required quest {} for faction {} does not exist for map {} difficulty {}, remove or fix this quest requirement.", progression_requirement->id, requirement_faction, mapid, difficulty); + LOG_ERROR("db.query", "Required quest {} for faction {} does not exist for map {} difficulty {}, remove or fix this quest requirement.", progression_requirement->id, requirement_faction, mapid, difficulty); break; } @@ -6880,7 +6880,7 @@ void ObjectMgr::LoadAccessRequirements() ItemTemplate const* pProto = GetItemTemplate(progression_requirement->id); if (!pProto) { - LOG_ERROR("sql.sql", "Required item {} for faction {} does not exist for map {} difficulty {}, remove or fix this item requirement.", progression_requirement->id, requirement_faction, mapid, difficulty); + LOG_ERROR("db.query", "Required item {} for faction {} does not exist for map {} difficulty {}, remove or fix this item requirement.", progression_requirement->id, requirement_faction, mapid, difficulty); break; } @@ -6888,7 +6888,7 @@ void ObjectMgr::LoadAccessRequirements() break; } default: - LOG_ERROR("sql.sql", "requirement_type of {} is not valid for map {} difficulty {}. Please use 0 for achievements, 1 for quest, 2 for items or remove this entry from the db.", requirement_type, mapid, difficulty); + LOG_ERROR("db.query", "requirement_type of {} is not valid for map {} difficulty {}. Please use 0 for achievements, 1 for quest, 2 for items or remove this entry from the db.", requirement_type, mapid, difficulty); break; } @@ -7119,7 +7119,7 @@ inline void CheckGOLockId(GameObjectTemplate const* goInfo, uint32 dataN, uint32 if (sLockStore.LookupEntry(dataN)) return; - LOG_ERROR("sql.sql", "Gameobject (Entry: {} GoType: {}) have data{}={} but lock (Id: {}) not found.", + LOG_ERROR("db.query", "Gameobject (Entry: {} GoType: {}) have data{}={} but lock (Id: {}) not found.", goInfo->entry, goInfo->type, N, goInfo->door.lockId, goInfo->door.lockId); } @@ -7128,7 +7128,7 @@ inline void CheckGOLinkedTrapId(GameObjectTemplate const* goInfo, uint32 dataN, if (GameObjectTemplate const* trapInfo = sObjectMgr->GetGameObjectTemplate(dataN)) { if (trapInfo->type != GAMEOBJECT_TYPE_TRAP) - LOG_ERROR("sql.sql", "Gameobject (Entry: {} GoType: {}) have data{}={} but GO (Entry {}) have not GAMEOBJECT_TYPE_TRAP ({}) type.", + LOG_ERROR("db.query", "Gameobject (Entry: {} GoType: {}) have data{}={} but GO (Entry {}) have not GAMEOBJECT_TYPE_TRAP ({}) type.", goInfo->entry, goInfo->type, N, dataN, dataN, GAMEOBJECT_TYPE_TRAP); } } @@ -7138,7 +7138,7 @@ inline void CheckGOSpellId(GameObjectTemplate const* goInfo, uint32 dataN, uint3 if (sSpellMgr->GetSpellInfo(dataN)) return; - LOG_ERROR("sql.sql", "Gameobject (Entry: {} GoType: {}) have data{}={} but Spell (Entry {}) not exist.", + LOG_ERROR("db.query", "Gameobject (Entry: {} GoType: {}) have data{}={} but Spell (Entry {}) not exist.", goInfo->entry, goInfo->type, N, dataN, dataN); } @@ -7147,7 +7147,7 @@ inline void CheckAndFixGOChairHeightId(GameObjectTemplate const* goInfo, uint32 if (dataN <= (UNIT_STAND_STATE_SIT_HIGH_CHAIR - UNIT_STAND_STATE_SIT_LOW_CHAIR)) return; - LOG_ERROR("sql.sql", "Gameobject (Entry: {} GoType: {}) have data{}={} but correct chair height in range 0..{}.", + LOG_ERROR("db.query", "Gameobject (Entry: {} GoType: {}) have data{}={} but correct chair height in range 0..{}.", goInfo->entry, goInfo->type, N, dataN, UNIT_STAND_STATE_SIT_HIGH_CHAIR - UNIT_STAND_STATE_SIT_LOW_CHAIR); // prevent client and server unexpected work @@ -7160,7 +7160,7 @@ inline void CheckGONoDamageImmuneId(GameObjectTemplate* goTemplate, uint32 dataN if (dataN <= 1) return; - LOG_ERROR("sql.sql", "Gameobject (Entry: {} GoType: {}) have data{}={} but expected boolean (0/1) noDamageImmune field value.", goTemplate->entry, goTemplate->type, N, dataN); + LOG_ERROR("db.query", "Gameobject (Entry: {} GoType: {}) have data{}={} but expected boolean (0/1) noDamageImmune field value.", goTemplate->entry, goTemplate->type, N, dataN); } inline void CheckGOConsumable(GameObjectTemplate const* goInfo, uint32 dataN, uint32 N) @@ -7169,7 +7169,7 @@ inline void CheckGOConsumable(GameObjectTemplate const* goInfo, uint32 dataN, ui if (dataN <= 1) return; - LOG_ERROR("sql.sql", "Gameobject (Entry: {} GoType: {}) have data{}={} but expected boolean (0/1) consumable field value.", + LOG_ERROR("db.query", "Gameobject (Entry: {} GoType: {}) have data{}={} but expected boolean (0/1) consumable field value.", goInfo->entry, goInfo->type, N, dataN); } @@ -7221,7 +7221,7 @@ void ObjectMgr::LoadGameObjectTemplate() // Checks if (!got.AIName.empty() && !sGameObjectAIRegistry->HasItem(got.AIName)) { - LOG_ERROR("sql.sql", "GameObject (Entry: {}) has non-registered `AIName` '{}' set, removing", got.entry, got.AIName); + LOG_ERROR("db.query", "GameObject (Entry: {}) has non-registered `AIName` '{}' set, removing", got.entry, got.AIName); } switch (got.type) @@ -7272,7 +7272,7 @@ void ObjectMgr::LoadGameObjectTemplate() if (got.spellFocus.focusId) { if (!sSpellFocusObjectStore.LookupEntry(got.spellFocus.focusId)) - LOG_ERROR("sql.sql", "GameObject (Entry: {} GoType: {}) have data0={} but SpellFocus (Id: {}) not exist.", + LOG_ERROR("db.query", "GameObject (Entry: {} GoType: {}) have data0={} but SpellFocus (Id: {}) not exist.", entry, got.type, got.spellFocus.focusId, got.spellFocus.focusId); } @@ -7290,7 +7290,7 @@ void ObjectMgr::LoadGameObjectTemplate() if (got.goober.pageId) // pageId { if (!GetPageText(got.goober.pageId)) - LOG_ERROR("sql.sql", "GameObject (Entry: {} GoType: {}) have data7={} but PageText (Entry {}) not exist.", + LOG_ERROR("db.query", "GameObject (Entry: {} GoType: {}) have data7={} but PageText (Entry {}) not exist.", entry, got.type, got.goober.pageId, got.goober.pageId); } CheckGONoDamageImmuneId(&got, got.goober.noDamageImmune, 11); @@ -7315,7 +7315,7 @@ void ObjectMgr::LoadGameObjectTemplate() if (got.moTransport.taxiPathId) { if (got.moTransport.taxiPathId >= sTaxiPathNodesByPath.size() || sTaxiPathNodesByPath[got.moTransport.taxiPathId].empty()) - LOG_ERROR("sql.sql", "GameObject (Entry: {} GoType: {}) have data0={} but TaxiPath (Id: {}) not exist.", + LOG_ERROR("db.query", "GameObject (Entry: {} GoType: {}) have data0={} but TaxiPath (Id: {}) not exist.", entry, got.type, got.moTransport.taxiPathId, got.moTransport.taxiPathId); } if (uint32 transportMap = got.moTransport.mapID) @@ -7386,7 +7386,7 @@ void ObjectMgr::LoadGameObjectTemplateAddons() GameObjectTemplate const* got = sObjectMgr->GetGameObjectTemplate(entry); if (!got) { - LOG_ERROR("sql.sql", + LOG_ERROR("db.query", "GameObject template (Entry: {}) does not exist but has a record in `gameobject_template_addon`", entry); continue; @@ -7406,7 +7406,7 @@ void ObjectMgr::LoadGameObjectTemplateAddons() if (!sGameObjectArtKitStore.LookupEntry(artKitID)) { - LOG_ERROR("sql.sql", "GameObject (Entry: {}) has invalid `artkit{}` {} defined, set to zero instead.", entry, i, artKitID); + LOG_ERROR("db.query", "GameObject (Entry: {}) has invalid `artkit{}` {} defined, set to zero instead.", entry, i, artKitID); continue; } @@ -7415,7 +7415,7 @@ void ObjectMgr::LoadGameObjectTemplateAddons() // checks if (gameObjectAddon.faction && !sFactionTemplateStore.LookupEntry(gameObjectAddon.faction)) - LOG_ERROR("sql.sql", + LOG_ERROR("db.query", "GameObject (Entry: {}) has invalid faction ({}) defined in `gameobject_template_addon`.", entry, gameObjectAddon.faction); @@ -7427,7 +7427,7 @@ void ObjectMgr::LoadGameObjectTemplateAddons() case GAMEOBJECT_TYPE_FISHINGHOLE: break; default: - LOG_ERROR("sql.sql", + LOG_ERROR("db.query", "GameObject (Entry {} GoType: {}) cannot be looted but has maxgold set in `gameobject_template_addon`.", entry, got->type); break; @@ -7598,49 +7598,49 @@ void ObjectMgr::LoadReputationRewardRate() FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionId); if (!factionEntry) { - LOG_ERROR("sql.sql", "Faction (faction.dbc) {} does not exist but is used in `reputation_reward_rate`", factionId); + LOG_ERROR("db.query", "Faction (faction.dbc) {} does not exist but is used in `reputation_reward_rate`", factionId); continue; } if (repRate.questRate < 0.0f) { - LOG_ERROR("sql.sql", "Table reputation_reward_rate has quest_rate with invalid rate {}, skipping data for faction {}", repRate.questRate, factionId); + LOG_ERROR("db.query", "Table reputation_reward_rate has quest_rate with invalid rate {}, skipping data for faction {}", repRate.questRate, factionId); continue; } if (repRate.questDailyRate < 0.0f) { - LOG_ERROR("sql.sql", "Table reputation_reward_rate has quest_daily_rate with invalid rate {}, skipping data for faction {}", repRate.questDailyRate, factionId); + LOG_ERROR("db.query", "Table reputation_reward_rate has quest_daily_rate with invalid rate {}, skipping data for faction {}", repRate.questDailyRate, factionId); continue; } if (repRate.questWeeklyRate < 0.0f) { - LOG_ERROR("sql.sql", "Table reputation_reward_rate has quest_weekly_rate with invalid rate {}, skipping data for faction {}", repRate.questWeeklyRate, factionId); + LOG_ERROR("db.query", "Table reputation_reward_rate has quest_weekly_rate with invalid rate {}, skipping data for faction {}", repRate.questWeeklyRate, factionId); continue; } if (repRate.questMonthlyRate < 0.0f) { - LOG_ERROR("sql.sql", "Table reputation_reward_rate has quest_monthly_rate with invalid rate {}, skipping data for faction {}", repRate.questMonthlyRate, factionId); + LOG_ERROR("db.query", "Table reputation_reward_rate has quest_monthly_rate with invalid rate {}, skipping data for faction {}", repRate.questMonthlyRate, factionId); continue; } if (repRate.questRepeatableRate < 0.0f) { - LOG_ERROR("sql.sql", "Table reputation_reward_rate has quest_repeatable_rate with invalid rate {}, skipping data for faction {}", repRate.questRepeatableRate, factionId); + LOG_ERROR("db.query", "Table reputation_reward_rate has quest_repeatable_rate with invalid rate {}, skipping data for faction {}", repRate.questRepeatableRate, factionId); continue; } if (repRate.creatureRate < 0.0f) { - LOG_ERROR("sql.sql", "Table reputation_reward_rate has creature_rate with invalid rate {}, skipping data for faction {}", repRate.creatureRate, factionId); + LOG_ERROR("db.query", "Table reputation_reward_rate has creature_rate with invalid rate {}, skipping data for faction {}", repRate.creatureRate, factionId); continue; } if (repRate.spellRate < 0.0f) { - LOG_ERROR("sql.sql", "Table reputation_reward_rate has spell_rate with invalid rate {}, skipping data for faction {}", repRate.spellRate, factionId); + LOG_ERROR("db.query", "Table reputation_reward_rate has spell_rate with invalid rate {}, skipping data for faction {}", repRate.spellRate, factionId); continue; } @@ -7694,7 +7694,7 @@ void ObjectMgr::LoadReputationOnKill() if (!GetCreatureTemplate(creature_id)) { - LOG_ERROR("sql.sql", "Table `creature_onkill_reputation` have data for not existed creature entry ({}), skipped", creature_id); + LOG_ERROR("db.query", "Table `creature_onkill_reputation` have data for not existed creature entry ({}), skipped", creature_id); continue; } @@ -7703,7 +7703,7 @@ void ObjectMgr::LoadReputationOnKill() FactionEntry const* factionEntry1 = sFactionStore.LookupEntry(repOnKill.RepFaction1); if (!factionEntry1) { - LOG_ERROR("sql.sql", "Faction (faction.dbc) {} does not exist but is used in `creature_onkill_reputation`", repOnKill.RepFaction1); + LOG_ERROR("db.query", "Faction (faction.dbc) {} does not exist but is used in `creature_onkill_reputation`", repOnKill.RepFaction1); continue; } } @@ -7713,7 +7713,7 @@ void ObjectMgr::LoadReputationOnKill() FactionEntry const* factionEntry2 = sFactionStore.LookupEntry(repOnKill.RepFaction2); if (!factionEntry2) { - LOG_ERROR("sql.sql", "Faction (faction.dbc) {} does not exist but is used in `creature_onkill_reputation`", repOnKill.RepFaction2); + LOG_ERROR("db.query", "Faction (faction.dbc) {} does not exist but is used in `creature_onkill_reputation`", repOnKill.RepFaction2); continue; } } @@ -7768,13 +7768,13 @@ void ObjectMgr::LoadReputationSpilloverTemplate() if (!factionEntry) { - LOG_ERROR("sql.sql", "Faction (faction.dbc) {} does not exist but is used in `reputation_spillover_template`", factionId); + LOG_ERROR("db.query", "Faction (faction.dbc) {} does not exist but is used in `reputation_spillover_template`", factionId); continue; } if (factionEntry->team == 0) { - LOG_ERROR("sql.sql", "Faction (faction.dbc) {} in `reputation_spillover_template` does not belong to any team, skipping", factionId); + LOG_ERROR("db.query", "Faction (faction.dbc) {} in `reputation_spillover_template` does not belong to any team, skipping", factionId); continue; } @@ -7786,19 +7786,19 @@ void ObjectMgr::LoadReputationSpilloverTemplate() if (!factionSpillover) { - LOG_ERROR("sql.sql", "Spillover faction (faction.dbc) {} does not exist but is used in `reputation_spillover_template` for faction {}, skipping", repTemplate.faction[i], factionId); + LOG_ERROR("db.query", "Spillover faction (faction.dbc) {} does not exist but is used in `reputation_spillover_template` for faction {}, skipping", repTemplate.faction[i], factionId); continue; } if (factionSpillover->reputationListID < 0) { - LOG_ERROR("sql.sql", "Spillover faction (faction.dbc) {} for faction {} in `reputation_spillover_template` can not be listed for client, and then useless, skipping", repTemplate.faction[i], factionId); + LOG_ERROR("db.query", "Spillover faction (faction.dbc) {} for faction {} in `reputation_spillover_template` can not be listed for client, and then useless, skipping", repTemplate.faction[i], factionId); continue; } if (repTemplate.faction_rank[i] >= MAX_REPUTATION_RANK) { - LOG_ERROR("sql.sql", "Rank {} used in `reputation_spillover_template` for spillover faction {} is not valid, skipping", repTemplate.faction_rank[i], repTemplate.faction[i]); + LOG_ERROR("db.query", "Rank {} used in `reputation_spillover_template` for spillover faction {} is not valid, skipping", repTemplate.faction_rank[i], repTemplate.faction[i]); continue; } } @@ -7807,25 +7807,25 @@ void ObjectMgr::LoadReputationSpilloverTemplate() FactionEntry const* factionEntry0 = sFactionStore.LookupEntry(repTemplate.faction[0]); if (repTemplate.faction[0] && !factionEntry0) { - LOG_ERROR("sql.sql", "Faction (faction.dbc) {} does not exist but is used in `reputation_spillover_template`", repTemplate.faction[0]); + LOG_ERROR("db.query", "Faction (faction.dbc) {} does not exist but is used in `reputation_spillover_template`", repTemplate.faction[0]); continue; } FactionEntry const* factionEntry1 = sFactionStore.LookupEntry(repTemplate.faction[1]); if (repTemplate.faction[1] && !factionEntry1) { - LOG_ERROR("sql.sql", "Faction (faction.dbc) {} does not exist but is used in `reputation_spillover_template`", repTemplate.faction[1]); + LOG_ERROR("db.query", "Faction (faction.dbc) {} does not exist but is used in `reputation_spillover_template`", repTemplate.faction[1]); continue; } FactionEntry const* factionEntry2 = sFactionStore.LookupEntry(repTemplate.faction[2]); if (repTemplate.faction[2] && !factionEntry2) { - LOG_ERROR("sql.sql", "Faction (faction.dbc) {} does not exist but is used in `reputation_spillover_template`", repTemplate.faction[2]); + LOG_ERROR("db.query", "Faction (faction.dbc) {} does not exist but is used in `reputation_spillover_template`", repTemplate.faction[2]); continue; } FactionEntry const* factionEntry3 = sFactionStore.LookupEntry(repTemplate.faction[3]); if (repTemplate.faction[3] && !factionEntry3) { - LOG_ERROR("sql.sql", "Faction (faction.dbc) {} does not exist but is used in `reputation_spillover_template`", repTemplate.faction[3]); + LOG_ERROR("db.query", "Faction (faction.dbc) {} does not exist but is used in `reputation_spillover_template`", repTemplate.faction[3]); continue; } @@ -7873,7 +7873,7 @@ void ObjectMgr::LoadPointsOfInterest() if (!Acore::IsValidMapCoord(POI.PositionX, POI.PositionY)) { - LOG_ERROR("sql.sql", "Table `points_of_interest` (ID: {}) have invalid coordinates (X: {} Y: {}), ignored.", point_id, POI.PositionX, POI.PositionY); + LOG_ERROR("db.query", "Table `points_of_interest` (ID: {}) have invalid coordinates (X: {} Y: {}), ignored.", point_id, POI.PositionX, POI.PositionY); continue; } @@ -7960,7 +7960,7 @@ void ObjectMgr::LoadQuestPOI() _questPOIStore[questId].push_back(POI); } else - LOG_ERROR("sql.sql", "Table quest_poi references unknown quest points for quest {} POI id {}", questId, id); + LOG_ERROR("db.query", "Table quest_poi references unknown quest points for quest {} POI id {}", questId, id); ++count; } while (result->NextRow()); @@ -7994,7 +7994,7 @@ void ObjectMgr::LoadNPCSpellClickSpells() CreatureTemplate const* cInfo = GetCreatureTemplate(npc_entry); if (!cInfo) { - LOG_ERROR("sql.sql", "Table npc_spellclick_spells references unknown creature_template {}. Skipping entry.", npc_entry); + LOG_ERROR("db.query", "Table npc_spellclick_spells references unknown creature_template {}. Skipping entry.", npc_entry); continue; } @@ -8002,13 +8002,13 @@ void ObjectMgr::LoadNPCSpellClickSpells() SpellInfo const* spellinfo = sSpellMgr->GetSpellInfo(spellid); if (!spellinfo) { - LOG_ERROR("sql.sql", "Table npc_spellclick_spells references unknown spellid {}. Skipping entry.", spellid); + LOG_ERROR("db.query", "Table npc_spellclick_spells references unknown spellid {}. Skipping entry.", spellid); continue; } uint8 userType = fields[3].Get(); if (userType >= SPELL_CLICK_USER_MAX) - LOG_ERROR("sql.sql", "Table npc_spellclick_spells references unknown user type {}. Skipping entry.", uint32(userType)); + LOG_ERROR("db.query", "Table npc_spellclick_spells references unknown user type {}. Skipping entry.", uint32(userType)); uint8 castFlags = fields[2].Get(); SpellClickInfo info; @@ -8027,7 +8027,7 @@ void ObjectMgr::LoadNPCSpellClickSpells() { if ((itr->second.npcflag & UNIT_NPC_FLAG_SPELLCLICK) && _spellClickInfoStore.find(itr->second.Entry) == _spellClickInfoStore.end()) { - LOG_ERROR("sql.sql", "npc_spellclick_spells: Creature template {} has UNIT_NPC_FLAG_SPELLCLICK but no data in spellclick table! Removing flag", itr->second.Entry); + LOG_ERROR("db.query", "npc_spellclick_spells: Creature template {} has UNIT_NPC_FLAG_SPELLCLICK but no data in spellclick table! Removing flag", itr->second.Entry); const_cast(&itr->second)->npcflag &= ~UNIT_NPC_FLAG_SPELLCLICK; } } @@ -8085,7 +8085,7 @@ void ObjectMgr::LoadQuestRelationsHelper(QuestRelations& map, std::string const& if (_questTemplates.find(quest) == _questTemplates.end()) { - LOG_ERROR("sql.sql", "Table `{}`: Quest {} listed for entry {} does not exist.", table, quest, id); + LOG_ERROR("db.query", "Table `{}`: Quest {} listed for entry {} does not exist.", table, quest, id); continue; } @@ -8109,9 +8109,9 @@ void ObjectMgr::LoadGameobjectQuestStarters() { GameObjectTemplate const* goInfo = GetGameObjectTemplate(itr->first); if (!goInfo) - LOG_ERROR("sql.sql", "Table `gameobject_queststarter` have data for not existed gameobject entry ({}) and existed quest {}", itr->first, itr->second); + LOG_ERROR("db.query", "Table `gameobject_queststarter` have data for not existed gameobject entry ({}) and existed quest {}", itr->first, itr->second); else if (goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER) - LOG_ERROR("sql.sql", "Table `gameobject_queststarter` have data gameobject entry ({}) for quest {}, but GO is not GAMEOBJECT_TYPE_QUESTGIVER", itr->first, itr->second); + LOG_ERROR("db.query", "Table `gameobject_queststarter` have data gameobject entry ({}) for quest {}, but GO is not GAMEOBJECT_TYPE_QUESTGIVER", itr->first, itr->second); } } @@ -8123,9 +8123,9 @@ void ObjectMgr::LoadGameobjectQuestEnders() { GameObjectTemplate const* goInfo = GetGameObjectTemplate(itr->first); if (!goInfo) - LOG_ERROR("sql.sql", "Table `gameobject_questender` have data for not existed gameobject entry ({}) and existed quest {}", itr->first, itr->second); + LOG_ERROR("db.query", "Table `gameobject_questender` have data for not existed gameobject entry ({}) and existed quest {}", itr->first, itr->second); else if (goInfo->type != GAMEOBJECT_TYPE_QUESTGIVER) - LOG_ERROR("sql.sql", "Table `gameobject_questender` have data gameobject entry ({}) for quest {}, but GO is not GAMEOBJECT_TYPE_QUESTGIVER", itr->first, itr->second); + LOG_ERROR("db.query", "Table `gameobject_questender` have data gameobject entry ({}) for quest {}, but GO is not GAMEOBJECT_TYPE_QUESTGIVER", itr->first, itr->second); } } @@ -8137,9 +8137,9 @@ void ObjectMgr::LoadCreatureQuestStarters() { CreatureTemplate const* cInfo = GetCreatureTemplate(itr->first); if (!cInfo) - LOG_ERROR("sql.sql", "Table `creature_queststarter` have data for not existed creature entry ({}) and existed quest {}", itr->first, itr->second); + LOG_ERROR("db.query", "Table `creature_queststarter` have data for not existed creature entry ({}) and existed quest {}", itr->first, itr->second); else if (!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER)) - LOG_ERROR("sql.sql", "Table `creature_queststarter` has creature entry ({}) for quest {}, but npcflag does not include UNIT_NPC_FLAG_QUESTGIVER", itr->first, itr->second); + LOG_ERROR("db.query", "Table `creature_queststarter` has creature entry ({}) for quest {}, but npcflag does not include UNIT_NPC_FLAG_QUESTGIVER", itr->first, itr->second); } } @@ -8151,9 +8151,9 @@ void ObjectMgr::LoadCreatureQuestEnders() { CreatureTemplate const* cInfo = GetCreatureTemplate(itr->first); if (!cInfo) - LOG_ERROR("sql.sql", "Table `creature_questender` have data for not existed creature entry ({}) and existed quest {}", itr->first, itr->second); + LOG_ERROR("db.query", "Table `creature_questender` have data for not existed creature entry ({}) and existed quest {}", itr->first, itr->second); else if (!(cInfo->npcflag & UNIT_NPC_FLAG_QUESTGIVER)) - LOG_ERROR("sql.sql", "Table `creature_questender` has creature entry ({}) for quest {}, but npcflag does not include UNIT_NPC_FLAG_QUESTGIVER", itr->first, itr->second); + LOG_ERROR("db.query", "Table `creature_questender` has creature entry ({}) for quest {}, but npcflag does not include UNIT_NPC_FLAG_QUESTGIVER", itr->first, itr->second); } } @@ -8183,7 +8183,7 @@ void ObjectMgr::LoadReservedPlayersNames() std::wstring wstr; if (!Utf8toWStr (name, wstr)) { - LOG_ERROR("sql.sql", "Table `reserved_name` have invalid name: {}", name); + LOG_ERROR("db.query", "Table `reserved_name` have invalid name: {}", name); continue; } @@ -8226,7 +8226,7 @@ void ObjectMgr::AddReservedPlayerName(std::string const& name) _reservedNamesStore.insert(wstr); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_RESERVED_PLAYER_NAME); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_RESERVED_PLAYER_NAME); stmt->SetData(0, name); CharacterDatabase.Execute(stmt); } @@ -8258,7 +8258,7 @@ void ObjectMgr::LoadProfanityPlayersNames() std::wstring wstr; if (!Utf8toWStr (name, wstr)) { - LOG_ERROR("sql.sql", "Table `profanity_name` have invalid name: {}", name); + LOG_ERROR("db.query", "Table `profanity_name` have invalid name: {}", name); continue; } @@ -8301,7 +8301,7 @@ void ObjectMgr::AddProfanityPlayerName(std::string const& name) _profanityNamesStore.insert(wstr); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_PROFANITY_PLAYER_NAME); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_PROFANITY_PLAYER_NAME); stmt->SetData(0, name); CharacterDatabase.Execute(stmt); } @@ -8644,7 +8644,7 @@ char const* ObjectMgr::GetAcoreString(uint32 entry, LocaleConstant locale) const return ts->Content[DEFAULT_LOCALE].c_str(); } - LOG_ERROR("sql.sql", "Acore string entry {} not found in DB.", entry); + LOG_ERROR("db.query", "Acore string entry {} not found in DB.", entry); return ""; } @@ -8675,7 +8675,7 @@ void ObjectMgr::LoadFishingBaseSkillLevel() AreaTableEntry const* fArea = sAreaTableStore.LookupEntry(entry); if (!fArea) { - LOG_ERROR("sql.sql", "AreaId {} defined in `skill_fishing_base_level` does not exist", entry); + LOG_ERROR("db.query", "AreaId {} defined in `skill_fishing_base_level` does not exist", entry); continue; } @@ -8692,7 +8692,7 @@ void ObjectMgr::ChangeFishingBaseSkillLevel(uint32 entry, int32 skill) AreaTableEntry const* fArea = sAreaTableStore.LookupEntry(entry); if (!fArea) { - LOG_ERROR("sql.sql", "AreaId {} defined in `skill_fishing_base_level` does not exist", entry); + LOG_ERROR("db.query", "AreaId {} defined in `skill_fishing_base_level` does not exist", entry); return; } @@ -8824,13 +8824,13 @@ void ObjectMgr::LoadGameTele() if (!MapMgr::IsValidMapCoord(gt.mapId, gt.position_x, gt.position_y, gt.position_z, gt.orientation)) { - LOG_ERROR("sql.sql", "Wrong position for id {} (name: {}) in `game_tele` table, ignoring.", id, gt.name); + LOG_ERROR("db.query", "Wrong position for id {} (name: {}) in `game_tele` table, ignoring.", id, gt.name); continue; } if (!Utf8toWStr(gt.name, gt.wnameLow)) { - LOG_ERROR("sql.sql", "Wrong UTF8 name for id {} in `game_tele` table, ignoring.", id); + LOG_ERROR("db.query", "Wrong UTF8 name for id {} in `game_tele` table, ignoring.", id); continue; } @@ -8886,7 +8886,7 @@ bool ObjectMgr::AddGameTele(GameTele& tele) _gameTeleStore[new_id] = tele; - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_INS_GAME_TELE); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_INS_GAME_TELE); stmt->SetData(0, new_id); stmt->SetData(1, tele.position_x); @@ -8915,7 +8915,7 @@ bool ObjectMgr::DeleteGameTele(std::string_view name) { if (itr->second.wnameLow == wname) { - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_GAME_TELE); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_GAME_TELE); stmt->SetData(0, itr->second.name); @@ -8958,25 +8958,25 @@ void ObjectMgr::LoadMailLevelRewards() if (level > MAX_LEVEL) { - LOG_ERROR("sql.sql", "Table `mail_level_reward` have data for level {} that more supported by client ({}), ignoring.", level, MAX_LEVEL); + LOG_ERROR("db.query", "Table `mail_level_reward` have data for level {} that more supported by client ({}), ignoring.", level, MAX_LEVEL); continue; } if (!(raceMask & RACEMASK_ALL_PLAYABLE)) { - LOG_ERROR("sql.sql", "Table `mail_level_reward` have raceMask ({}) for level {} that not include any player races, ignoring.", raceMask, level); + LOG_ERROR("db.query", "Table `mail_level_reward` have raceMask ({}) for level {} that not include any player races, ignoring.", raceMask, level); continue; } if (!sMailTemplateStore.LookupEntry(mailTemplateId)) { - LOG_ERROR("sql.sql", "Table `mail_level_reward` have invalid mailTemplateId ({}) for level {} that invalid not include any player races, ignoring.", mailTemplateId, level); + LOG_ERROR("db.query", "Table `mail_level_reward` have invalid mailTemplateId ({}) for level {} that invalid not include any player races, ignoring.", mailTemplateId, level); continue; } if (!GetCreatureTemplate(senderEntry)) { - LOG_ERROR("sql.sql", "Table `mail_level_reward` have not existed sender creature entry ({}) for level {} that invalid not include any player races, ignoring.", senderEntry, level); + LOG_ERROR("db.query", "Table `mail_level_reward` have not existed sender creature entry ({}) for level {} that invalid not include any player races, ignoring.", senderEntry, level); continue; } @@ -8997,38 +8997,38 @@ void ObjectMgr::AddSpellToTrainer(uint32 entry, uint32 spell, uint32 spellCost, CreatureTemplate const* cInfo = GetCreatureTemplate(entry); if (!cInfo) { - LOG_ERROR("sql.sql", "Table `npc_trainer` contains an entry for a non-existing creature template (Entry: {}), ignoring", entry); + LOG_ERROR("db.query", "Table `npc_trainer` contains an entry for a non-existing creature template (Entry: {}), ignoring", entry); return; } if (!(cInfo->npcflag & UNIT_NPC_FLAG_TRAINER)) { - LOG_ERROR("sql.sql", "Table `npc_trainer` contains an entry for a creature template (Entry: {}) without trainer flag, ignoring", entry); + LOG_ERROR("db.query", "Table `npc_trainer` contains an entry for a creature template (Entry: {}) without trainer flag, ignoring", entry); return; } SpellInfo const* spellinfo = sSpellMgr->GetSpellInfo(spell); if (!spellinfo) { - LOG_ERROR("sql.sql", "Table `npc_trainer` contains an entry (Entry: {}) for a non-existing spell (Spell: {}), ignoring", entry, spell); + LOG_ERROR("db.query", "Table `npc_trainer` contains an entry (Entry: {}) for a non-existing spell (Spell: {}), ignoring", entry, spell); return; } if (!SpellMgr::ComputeIsSpellValid(spellinfo)) { - LOG_ERROR("sql.sql", "Table `npc_trainer` contains an entry (Entry: {}) for a broken spell (Spell: {}), ignoring", entry, spell); + LOG_ERROR("db.query", "Table `npc_trainer` contains an entry (Entry: {}) for a broken spell (Spell: {}), ignoring", entry, spell); return; } if (GetTalentSpellCost(spell)) { - LOG_ERROR("sql.sql", "Table `npc_trainer` contains an entry (Entry: {}) for a non-existing spell (Spell: {}) which is a talent, ignoring", entry, spell); + LOG_ERROR("db.query", "Table `npc_trainer` contains an entry (Entry: {}) for a non-existing spell (Spell: {}) which is a talent, ignoring", entry, spell); return; } if (reqSpell && !sSpellMgr->GetSpellInfo(reqSpell)) { - LOG_ERROR("sql.sql", "Table `npc_trainer` contains an entry (Entry: {}) for a non-existing reqSpell (Spell: {}), ignoring", entry, reqSpell); + LOG_ERROR("db.query", "Table `npc_trainer` contains an entry (Entry: {}) for a non-existing reqSpell (Spell: {}), ignoring", entry, reqSpell); return; } @@ -9057,7 +9057,7 @@ void ObjectMgr::AddSpellToTrainer(uint32 entry, uint32 spell, uint32 spellCost, if (spellinfo->Effects[i].TargetA.GetTarget() != 0 && spellinfo->Effects[i].TargetA.GetTarget() != TARGET_UNIT_TARGET_ALLY && spellinfo->Effects[i].TargetA.GetTarget() != TARGET_UNIT_TARGET_ANY && spellinfo->Effects[i].TargetA.GetTarget() != TARGET_UNIT_CASTER) { - LOG_ERROR("sql.sql", "Table `npc_trainer` has spell {} for trainer entry {} with learn effect which has incorrect target type, ignoring learn effect!", spell, entry); + LOG_ERROR("db.query", "Table `npc_trainer` has spell {} for trainer entry {} with learn effect which has incorrect target type, ignoring learn effect!", spell, entry); continue; } @@ -9118,7 +9118,7 @@ void ObjectMgr::LoadTrainerSpell() int ObjectMgr::LoadReferenceVendor(int32 vendor, int32 item, std::set* skip_vendors) { // find all items from the reference vendor - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_NPC_VENDOR_REF); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_NPC_VENDOR_REF); stmt->SetData(0, uint32(item)); PreparedQueryResult result = WorldDatabase.Query(stmt); @@ -9231,7 +9231,7 @@ void ObjectMgr::LoadGossipMenu() if (!GetGossipText(gMenu.TextID)) { - LOG_ERROR("sql.sql", "Table gossip_menu entry {} are using non-existing TextID {}", gMenu.MenuID, gMenu.TextID); + LOG_ERROR("db.query", "Table gossip_menu entry {} are using non-existing TextID {}", gMenu.MenuID, gMenu.TextID); continue; } @@ -9282,28 +9282,28 @@ void ObjectMgr::LoadGossipMenuItems() if (gMenuItem.OptionIcon >= GOSSIP_ICON_MAX) { - LOG_ERROR("sql.sql", "Table `gossip_menu_option` for menu {}, id {} has unknown icon id {}. Replacing with GOSSIP_ICON_CHAT", gMenuItem.MenuID, gMenuItem.OptionID, gMenuItem.OptionIcon); + LOG_ERROR("db.query", "Table `gossip_menu_option` for menu {}, id {} has unknown icon id {}. Replacing with GOSSIP_ICON_CHAT", gMenuItem.MenuID, gMenuItem.OptionID, gMenuItem.OptionIcon); gMenuItem.OptionIcon = GOSSIP_ICON_CHAT; } if (gMenuItem.OptionBroadcastTextID && !GetBroadcastText(gMenuItem.OptionBroadcastTextID)) { - LOG_ERROR("sql.sql", "Table `gossip_menu_option` for menu {}, id {} has non-existing or incompatible OptionBroadcastTextID {}, ignoring.", gMenuItem.MenuID, gMenuItem.OptionID, gMenuItem.OptionBroadcastTextID); + LOG_ERROR("db.query", "Table `gossip_menu_option` for menu {}, id {} has non-existing or incompatible OptionBroadcastTextID {}, ignoring.", gMenuItem.MenuID, gMenuItem.OptionID, gMenuItem.OptionBroadcastTextID); gMenuItem.OptionBroadcastTextID = 0; } if (gMenuItem.OptionType >= GOSSIP_OPTION_MAX) - LOG_ERROR("sql.sql", "Table `gossip_menu_option` for menu {}, id {} has unknown option id {}. Option will not be used", gMenuItem.MenuID, gMenuItem.OptionID, gMenuItem.OptionType); + LOG_ERROR("db.query", "Table `gossip_menu_option` for menu {}, id {} has unknown option id {}. Option will not be used", gMenuItem.MenuID, gMenuItem.OptionID, gMenuItem.OptionType); if (gMenuItem.ActionPoiID && !GetPointOfInterest(gMenuItem.ActionPoiID)) { - LOG_ERROR("sql.sql", "Table `gossip_menu_option` for menu {}, id {} use non-existing ActionPoiID {}, ignoring", gMenuItem.MenuID, gMenuItem.OptionID, gMenuItem.ActionPoiID); + LOG_ERROR("db.query", "Table `gossip_menu_option` for menu {}, id {} use non-existing ActionPoiID {}, ignoring", gMenuItem.MenuID, gMenuItem.OptionID, gMenuItem.ActionPoiID); gMenuItem.ActionPoiID = 0; } if (gMenuItem.BoxBroadcastTextID && !GetBroadcastText(gMenuItem.BoxBroadcastTextID)) { - LOG_ERROR("sql.sql", "Table `gossip_menu_option` for menu {}, id {} has non-existing or incompatible BoxBroadcastTextID {}, ignoring.", gMenuItem.MenuID, gMenuItem.OptionID, gMenuItem.BoxBroadcastTextID); + LOG_ERROR("db.query", "Table `gossip_menu_option` for menu {}, id {} has non-existing or incompatible BoxBroadcastTextID {}, ignoring.", gMenuItem.MenuID, gMenuItem.OptionID, gMenuItem.BoxBroadcastTextID); gMenuItem.BoxBroadcastTextID = 0; } @@ -9321,7 +9321,7 @@ void ObjectMgr::AddVendorItem(uint32 entry, uint32 item, int32 maxcount, uint32 if (persist) { - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_INS_NPC_VENDOR); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_INS_NPC_VENDOR); stmt->SetData(0, entry); stmt->SetData(1, item); @@ -9344,7 +9344,7 @@ bool ObjectMgr::RemoveVendorItem(uint32 entry, uint32 item, bool persist /*= tru if (persist) { - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_NPC_VENDOR); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_NPC_VENDOR); stmt->SetData(0, entry); stmt->SetData(1, item); @@ -9364,7 +9364,7 @@ bool ObjectMgr::IsVendorItemValid(uint32 vendor_entry, uint32 item_id, int32 max if (player) ChatHandler(player->GetSession()).SendSysMessage(LANG_COMMAND_VENDORSELECTION); else - LOG_ERROR("sql.sql", "Table `(game_event_)npc_vendor` have data for not existed creature template (Entry: {}), ignore", vendor_entry); + LOG_ERROR("db.query", "Table `(game_event_)npc_vendor` have data for not existed creature template (Entry: {}), ignore", vendor_entry); return false; } @@ -9375,7 +9375,7 @@ bool ObjectMgr::IsVendorItemValid(uint32 vendor_entry, uint32 item_id, int32 max if (player) ChatHandler(player->GetSession()).SendSysMessage(LANG_COMMAND_VENDORSELECTION); else - LOG_ERROR("sql.sql", "Table `(game_event_)npc_vendor` have data for not creature template (Entry: {}) without vendor flag, ignore", vendor_entry); + LOG_ERROR("db.query", "Table `(game_event_)npc_vendor` have data for not creature template (Entry: {}) without vendor flag, ignore", vendor_entry); if (skip_vendors) skip_vendors->insert(vendor_entry); @@ -9389,7 +9389,7 @@ bool ObjectMgr::IsVendorItemValid(uint32 vendor_entry, uint32 item_id, int32 max if (player) ChatHandler(player->GetSession()).PSendSysMessage(LANG_ITEM_NOT_FOUND, item_id); else - LOG_ERROR("sql.sql", "Table `(game_event_)npc_vendor` for Vendor (Entry: {}) have in item list non-existed item ({}), ignore", vendor_entry, item_id); + LOG_ERROR("db.query", "Table `(game_event_)npc_vendor` for Vendor (Entry: {}) have in item list non-existed item ({}), ignore", vendor_entry, item_id); return false; } @@ -9398,7 +9398,7 @@ bool ObjectMgr::IsVendorItemValid(uint32 vendor_entry, uint32 item_id, int32 max if (player) ChatHandler(player->GetSession()).PSendSysMessage(LANG_EXTENDED_COST_NOT_EXIST, ExtendedCost); else - LOG_ERROR("sql.sql", "Table `(game_event_)npc_vendor` have Item (Entry: {}) with wrong ExtendedCost ({}) for vendor ({}), ignore", item_id, ExtendedCost, vendor_entry); + LOG_ERROR("db.query", "Table `(game_event_)npc_vendor` have Item (Entry: {}) with wrong ExtendedCost ({}) for vendor ({}), ignore", item_id, ExtendedCost, vendor_entry); return false; } @@ -9407,7 +9407,7 @@ bool ObjectMgr::IsVendorItemValid(uint32 vendor_entry, uint32 item_id, int32 max if (player) ChatHandler(player->GetSession()).PSendSysMessage("MaxCount != 0 (%u) but IncrTime == 0", maxcount); else - LOG_ERROR("sql.sql", "Table `(game_event_)npc_vendor` has `maxcount` ({}) for item {} of vendor (Entry: {}) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry); + LOG_ERROR("db.query", "Table `(game_event_)npc_vendor` has `maxcount` ({}) for item {} of vendor (Entry: {}) but `incrtime`=0, ignore", maxcount, item_id, vendor_entry); return false; } else if (maxcount == 0 && incrtime > 0) @@ -9415,7 +9415,7 @@ bool ObjectMgr::IsVendorItemValid(uint32 vendor_entry, uint32 item_id, int32 max if (player) ChatHandler(player->GetSession()).PSendSysMessage("MaxCount == 0 but IncrTime<>= 0"); else - LOG_ERROR("sql.sql", "Table `(game_event_)npc_vendor` has `maxcount`=0 for item {} of vendor (Entry: {}) but `incrtime`<>0, ignore", item_id, vendor_entry); + LOG_ERROR("db.query", "Table `(game_event_)npc_vendor` has `maxcount`=0 for item {} of vendor (Entry: {}) but `incrtime`<>0, ignore", item_id, vendor_entry); return false; } @@ -9428,7 +9428,7 @@ bool ObjectMgr::IsVendorItemValid(uint32 vendor_entry, uint32 item_id, int32 max if (player) ChatHandler(player->GetSession()).PSendSysMessage(LANG_ITEM_ALREADY_IN_LIST, item_id, ExtendedCost); else - LOG_ERROR("sql.sql", "Table `npc_vendor` has duplicate items {} (with extended cost {}) for vendor (Entry: {}), ignoring", item_id, ExtendedCost, vendor_entry); + LOG_ERROR("db.query", "Table `npc_vendor` has duplicate items {} (with extended cost {}) for vendor (Entry: {}), ignoring", item_id, ExtendedCost, vendor_entry); return false; } @@ -9475,7 +9475,7 @@ void ObjectMgr::LoadScriptNames() if (!result) { LOG_INFO("server.loading", " "); - LOG_ERROR("sql.sql", ">> Loaded empty set of Script Names!"); + LOG_ERROR("db.query", ">> Loaded empty set of Script Names!"); return; } @@ -9620,7 +9620,7 @@ void ObjectMgr::LoadBroadcastTextLocales() BroadcastTextContainer::iterator bct = _broadcastTextStore.find(id); if (bct == _broadcastTextStore.end()) { - LOG_ERROR("sql.sql", "BroadcastText (Id: {}) found in table `broadcast_text_locale` but does not exist in `broadcast_text`. Skipped!", id); + LOG_ERROR("db.query", "BroadcastText (Id: {}) found in table `broadcast_text_locale` but does not exist in `broadcast_text`. Skipped!", id); continue; } @@ -9685,7 +9685,7 @@ void ObjectMgr::LoadCreatureClassLevelStats() uint8 Class = fields[1].Get(); if (!Class || ((1 << (Class - 1)) & CLASSMASK_ALL_CREATURES) == 0) - LOG_ERROR("sql.sql", "Creature base stats for level {} has invalid class {}", Level, Class); + LOG_ERROR("db.query", "Creature base stats for level {} has invalid class {}", Level, Class); CreatureBaseStats stats; @@ -9695,7 +9695,7 @@ void ObjectMgr::LoadCreatureClassLevelStats() if (stats.BaseHealth[i] == 0) { - LOG_ERROR("sql.sql", "Creature base stats for class {}, level {} has invalid zero base HP[{}] - set to 1", Class, Level, i); + LOG_ERROR("db.query", "Creature base stats for class {}, level {} has invalid zero base HP[{}] - set to 1", Class, Level, i); stats.BaseHealth[i] = 1; } @@ -9716,7 +9716,7 @@ void ObjectMgr::LoadCreatureClassLevelStats() stats.BaseDamage[i] = fields[9 + i].Get(); if (stats.BaseDamage[i] < 0.0f) { - LOG_ERROR("sql.sql", "Creature base stats for class {}, level {} has invalid negative base damage[{}] - set to 0.0", Class, Level, i); + LOG_ERROR("db.query", "Creature base stats for class {}, level {} has invalid negative base damage[{}] - set to 0.0", Class, Level, i); stats.BaseDamage[i] = 0.0f; } } @@ -9738,7 +9738,7 @@ void ObjectMgr::LoadCreatureClassLevelStats() for (uint16 lvl = itr->second.minlevel; lvl <= itr->second.maxlevel; ++lvl) { if (_creatureBaseStatsStore.find(MAKE_PAIR16(lvl, itr->second.unit_class)) == _creatureBaseStatsStore.end()) - LOG_ERROR("sql.sql", "Missing base stats for creature class {} level {}", itr->second.unit_class, lvl); + LOG_ERROR("db.query", "Missing base stats for creature class {} level {}", itr->second.unit_class, lvl); } } @@ -9769,9 +9769,9 @@ void ObjectMgr::LoadFactionChangeAchievements() uint32 horde = fields[1].Get(); if (!sAchievementStore.LookupEntry(alliance)) - LOG_ERROR("sql.sql", "Achievement {} (alliance_id) referenced in `player_factionchange_achievement` does not exist, pair skipped!", alliance); + LOG_ERROR("db.query", "Achievement {} (alliance_id) referenced in `player_factionchange_achievement` does not exist, pair skipped!", alliance); else if (!sAchievementStore.LookupEntry(horde)) - LOG_ERROR("sql.sql", "Achievement {} (horde_id) referenced in `player_factionchange_achievement` does not exist, pair skipped!", horde); + LOG_ERROR("db.query", "Achievement {} (horde_id) referenced in `player_factionchange_achievement` does not exist, pair skipped!", horde); else FactionChangeAchievements[alliance] = horde; @@ -9805,9 +9805,9 @@ void ObjectMgr::LoadFactionChangeItems() uint32 horde = fields[1].Get(); if (!GetItemTemplate(alliance)) - LOG_ERROR("sql.sql", "Item {} (alliance_id) referenced in `player_factionchange_items` does not exist, pair skipped!", alliance); + LOG_ERROR("db.query", "Item {} (alliance_id) referenced in `player_factionchange_items` does not exist, pair skipped!", alliance); else if (!GetItemTemplate(horde)) - LOG_ERROR("sql.sql", "Item {} (horde_id) referenced in `player_factionchange_items` does not exist, pair skipped!", horde); + LOG_ERROR("db.query", "Item {} (horde_id) referenced in `player_factionchange_items` does not exist, pair skipped!", horde); else FactionChangeItems[alliance] = horde; @@ -9841,9 +9841,9 @@ void ObjectMgr::LoadFactionChangeQuests() uint32 horde = fields[1].Get(); if (!sObjectMgr->GetQuestTemplate(alliance)) - LOG_ERROR("sql.sql", "Quest {} (alliance_id) referenced in `player_factionchange_quests` does not exist, pair skipped!", alliance); + LOG_ERROR("db.query", "Quest {} (alliance_id) referenced in `player_factionchange_quests` does not exist, pair skipped!", alliance); else if (!sObjectMgr->GetQuestTemplate(horde)) - LOG_ERROR("sql.sql", "Quest {} (horde_id) referenced in `player_factionchange_quests` does not exist, pair skipped!", horde); + LOG_ERROR("db.query", "Quest {} (horde_id) referenced in `player_factionchange_quests` does not exist, pair skipped!", horde); else FactionChangeQuests[alliance] = horde; @@ -9877,9 +9877,9 @@ void ObjectMgr::LoadFactionChangeReputations() uint32 horde = fields[1].Get(); if (!sFactionStore.LookupEntry(alliance)) - LOG_ERROR("sql.sql", "Reputation {} (alliance_id) referenced in `player_factionchange_reputations` does not exist, pair skipped!", alliance); + LOG_ERROR("db.query", "Reputation {} (alliance_id) referenced in `player_factionchange_reputations` does not exist, pair skipped!", alliance); else if (!sFactionStore.LookupEntry(horde)) - LOG_ERROR("sql.sql", "Reputation {} (horde_id) referenced in `player_factionchange_reputations` does not exist, pair skipped!", horde); + LOG_ERROR("db.query", "Reputation {} (horde_id) referenced in `player_factionchange_reputations` does not exist, pair skipped!", horde); else FactionChangeReputation[alliance] = horde; @@ -9913,9 +9913,9 @@ void ObjectMgr::LoadFactionChangeSpells() uint32 horde = fields[1].Get(); if (!sSpellMgr->GetSpellInfo(alliance)) - LOG_ERROR("sql.sql", "Spell {} (alliance_id) referenced in `player_factionchange_spells` does not exist, pair skipped!", alliance); + LOG_ERROR("db.query", "Spell {} (alliance_id) referenced in `player_factionchange_spells` does not exist, pair skipped!", alliance); else if (!sSpellMgr->GetSpellInfo(horde)) - LOG_ERROR("sql.sql", "Spell {} (horde_id) referenced in `player_factionchange_spells` does not exist, pair skipped!", horde); + LOG_ERROR("db.query", "Spell {} (horde_id) referenced in `player_factionchange_spells` does not exist, pair skipped!", horde); else FactionChangeSpells[alliance] = horde; @@ -9948,9 +9948,9 @@ void ObjectMgr::LoadFactionChangeTitles() uint32 horde = fields[1].Get(); if (!sCharTitlesStore.LookupEntry(alliance)) - LOG_ERROR("sql.sql", "Title {} (alliance_id) referenced in `player_factionchange_title` does not exist, pair skipped!", alliance); + LOG_ERROR("db.query", "Title {} (alliance_id) referenced in `player_factionchange_title` does not exist, pair skipped!", alliance); else if (!sCharTitlesStore.LookupEntry(horde)) - LOG_ERROR("sql.sql", "Title {} (horde_id) referenced in `player_factionchange_title` does not exist, pair skipped!", horde); + LOG_ERROR("db.query", "Title {} (horde_id) referenced in `player_factionchange_title` does not exist, pair skipped!", horde); else FactionChangeTitles[alliance] = horde; @@ -10044,14 +10044,14 @@ void ObjectMgr::LoadGameObjectQuestItems() GameObjectTemplate const* goInfo = GetGameObjectTemplate(entry); if (!goInfo) { - LOG_ERROR("sql.sql", "Table `gameobject_questitem` has data for nonexistent gameobject (entry: {}, idx: {}), skipped", entry, idx); + LOG_ERROR("db.query", "Table `gameobject_questitem` has data for nonexistent gameobject (entry: {}, idx: {}), skipped", entry, idx); continue; }; ItemEntry const* dbcData = sItemStore.LookupEntry(item); if (!dbcData) { - LOG_ERROR("sql.sql", "Table `gameobject_questitem` has nonexistent item (ID: {}) in gameobject (entry: {}, idx: {}), skipped", item, entry, idx); + LOG_ERROR("db.query", "Table `gameobject_questitem` has nonexistent item (ID: {}) in gameobject (entry: {}, idx: {}), skipped", item, entry, idx); continue; }; @@ -10089,14 +10089,14 @@ void ObjectMgr::LoadCreatureQuestItems() CreatureTemplate const* creatureInfo = GetCreatureTemplate(entry); if (!creatureInfo) { - LOG_ERROR("sql.sql", "Table `creature_questitem` has data for nonexistent creature (entry: {}, idx: {}), skipped", entry, idx); + LOG_ERROR("db.query", "Table `creature_questitem` has data for nonexistent creature (entry: {}, idx: {}), skipped", entry, idx); continue; }; ItemEntry const* dbcData = sItemStore.LookupEntry(item); if (!dbcData) { - LOG_ERROR("sql.sql", "Table `creature_questitem` has nonexistent item (ID: {}) in creature (entry: {}, idx: {}), skipped", item, entry, idx); + LOG_ERROR("db.query", "Table `creature_questitem` has nonexistent item (ID: {}) in creature (entry: {}, idx: {}), skipped", item, entry, idx); continue; }; @@ -10161,13 +10161,13 @@ void ObjectMgr::LoadInstanceSavedGameobjectStateData() { uint32 oldMSTime = getMSTime(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SELECT_INSTANCE_SAVED_DATA); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SELECT_INSTANCE_SAVED_DATA); PreparedQueryResult result = CharacterDatabase.Query(stmt); if (!result) { // There's no gameobject with this GUID saved on the DB - LOG_INFO("sql.sql", ">> Loaded 0 Instance saved gameobject state data. DB table `instance_saved_go_state_data` is empty."); + LOG_INFO("db.query", ">> Loaded 0 Instance saved gameobject state data. DB table `instance_saved_go_state_data` is empty."); return; } @@ -10248,7 +10248,7 @@ void ObjectMgr::SendServerMail(Player* player, uint32 id, uint32 reqLevel, uint3 draft.SendMailTo(trans, MailReceiver(player), sender); CharacterDatabase.CommitTransaction(trans); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_MAIL_SERVER_CHARACTER); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_MAIL_SERVER_CHARACTER); stmt->SetData(0, player->GetGUID().GetCounter()); stmt->SetData(1, id); CharacterDatabase.Execute(stmt); @@ -10267,7 +10267,7 @@ void ObjectMgr::LoadMailServerTemplates() QueryResult result = CharacterDatabase.Query("SELECT `id`, `reqLevel`, `reqPlayTime`, `moneyA`, `moneyH`, `itemA`, `itemCountA`, `itemH`,`itemCountH`, `subject`, `body`, `active` FROM `mail_server_template`"); if (!result) { - LOG_INFO("sql.sql", ">> Loaded 0 server mail rewards. DB table `mail_server_template` is empty."); + LOG_INFO("db.query", ">> Loaded 0 server mail rewards. DB table `mail_server_template` is empty."); LOG_INFO("server.loading", " "); return; } @@ -10297,37 +10297,37 @@ void ObjectMgr::LoadMailServerTemplates() if (servMail.reqLevel > sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL)) { - LOG_ERROR("sql.sql", "Table `mail_server_template` has reqLevel {} but max level is {} for id {}, skipped.", servMail.reqLevel, sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL), servMail.id); + LOG_ERROR("db.query", "Table `mail_server_template` has reqLevel {} but max level is {} for id {}, skipped.", servMail.reqLevel, sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL), servMail.id); return; } if (servMail.moneyA > MAX_MONEY_AMOUNT || servMail.moneyH > MAX_MONEY_AMOUNT) { - LOG_ERROR("sql.sql", "Table `mail_server_template` has moneyA {} or moneyH {} larger than MAX_MONEY_AMOUNT {} for id {}, skipped.", servMail.moneyA, servMail.moneyH, MAX_MONEY_AMOUNT, servMail.id); + LOG_ERROR("db.query", "Table `mail_server_template` has moneyA {} or moneyH {} larger than MAX_MONEY_AMOUNT {} for id {}, skipped.", servMail.moneyA, servMail.moneyH, MAX_MONEY_AMOUNT, servMail.id); return; } ItemTemplate const* itemTemplateA = sObjectMgr->GetItemTemplate(servMail.itemA); if (!itemTemplateA && servMail.itemA) { - LOG_ERROR("sql.sql", "Table `mail_server_template` has invalid item in itemA {} for id {}, skipped.", servMail.itemA, servMail.id); + LOG_ERROR("db.query", "Table `mail_server_template` has invalid item in itemA {} for id {}, skipped.", servMail.itemA, servMail.id); return; } ItemTemplate const* itemTemplateH = sObjectMgr->GetItemTemplate(servMail.itemH); if (!itemTemplateH && servMail.itemH) { - LOG_ERROR("sql.sql", "Table `mail_server_template` has invalid item in itemH {} for id {}, skipped.", servMail.itemH, servMail.id); + LOG_ERROR("db.query", "Table `mail_server_template` has invalid item in itemH {} for id {}, skipped.", servMail.itemH, servMail.id); return; } if (!servMail.itemA && servMail.itemCountA) { - LOG_ERROR("sql.sql", "Table `mail_server_template` has itemCountA {} with no ItemA, set to 0", servMail.itemCountA); + LOG_ERROR("db.query", "Table `mail_server_template` has itemCountA {} with no ItemA, set to 0", servMail.itemCountA); servMail.itemCountA = 0; } if (!servMail.itemH && servMail.itemCountH) { - LOG_ERROR("sql.sql", "Table `mail_server_template` has itemCountH {} with no ItemH, set to 0", servMail.itemCountH); + LOG_ERROR("db.query", "Table `mail_server_template` has itemCountH {} with no ItemH, set to 0", servMail.itemCountH); servMail.itemCountH = 0; } } while (result->NextRow()); diff --git a/src/server/game/Globals/ObjectMgr.h b/src/server/game/Globals/ObjectMgr.h index 999ad14f0a5a12..f5801ae0ebb3c5 100644 --- a/src/server/game/Globals/ObjectMgr.h +++ b/src/server/game/Globals/ObjectMgr.h @@ -22,7 +22,7 @@ #include "ConditionMgr.h" #include "Corpse.h" #include "Creature.h" -#include "DatabaseEnv.h" +#include "DatabaseEnvFwd.h" #include "DynamicObject.h" #include "GameObject.h" #include "ItemTemplate.h" diff --git a/src/server/game/Groups/Group.cpp b/src/server/game/Groups/Group.cpp index e2208fa849a7e7..a8c1356addc003 100644 --- a/src/server/game/Groups/Group.cpp +++ b/src/server/game/Groups/Group.cpp @@ -137,7 +137,7 @@ bool Group::Create(Player* leader) m_raidDifficulty = leader->GetRaidDifficulty(); // Store group in database - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GROUP); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GROUP); uint8 index = 0; @@ -182,7 +182,7 @@ bool Group::LoadGroupFromDB(Field* fields) if (!sCharacterCache->GetCharacterNameByGuid(m_leaderGuid, m_leaderName)) { CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GROUP); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GROUP); stmt->SetData(0, groupLowGuid); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GROUP_MEMBER_ALL); @@ -234,7 +234,7 @@ void Group::LoadMemberFromDB(ObjectGuid::LowType guidLow, uint8 memberFlags, uin // skip non-existed member if (!sCharacterCache->GetCharacterNameByGuid(member.guid, member.name)) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GROUP_MEMBER); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GROUP_MEMBER); stmt->SetData(0, guidLow); stmt->SetData(1, GetGUID().GetCounter()); CharacterDatabase.Execute(stmt); @@ -268,7 +268,7 @@ void Group::ConvertToLFG(bool restricted /*= true*/) if (!isBGGroup() && !isBFGroup()) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GROUP_TYPE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GROUP_TYPE); stmt->SetData(0, uint8(m_groupType)); stmt->SetData(1, GetGUID().GetCounter()); @@ -297,7 +297,7 @@ void Group::ConvertToRaid() if (!isBGGroup() && !isBFGroup()) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GROUP_TYPE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GROUP_TYPE); stmt->SetData(0, uint8(m_groupType)); stmt->SetData(1, GetGUID().GetCounter()); @@ -447,7 +447,7 @@ bool Group::AddMember(Player* player) if (!isBGGroup() && !isBFGroup()) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_GROUP_MEMBER); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_GROUP_MEMBER); stmt->SetData(0, GetGUID().GetCounter()); stmt->SetData(1, member.guid.GetCounter()); stmt->SetData(2, member.flags); @@ -593,7 +593,7 @@ bool Group::RemoveMember(ObjectGuid guid, const RemoveMethod& method /*= GROUP_R // Remove player from group in DB if (!isBGGroup() && !isBFGroup()) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GROUP_MEMBER); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GROUP_MEMBER); stmt->SetData(0, guid.GetCounter()); stmt->SetData(1, GetGUID().GetCounter()); CharacterDatabase.Execute(stmt); @@ -726,7 +726,7 @@ void Group::ChangeLeader(ObjectGuid newLeaderGuid) { CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); // Update the group leader - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GROUP_LEADER); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GROUP_LEADER); stmt->SetData(0, newLeader->GetGUID().GetCounter()); stmt->SetData(1, GetGUID().GetCounter()); trans->Append(stmt); @@ -824,7 +824,7 @@ void Group::Disband(bool hideDestroy /* = false */) { CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GROUP); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GROUP); stmt->SetData(0, GetGUID().GetCounter()); trans->Append(stmt); @@ -1801,7 +1801,7 @@ void Group::ChangeMembersGroup(ObjectGuid guid, uint8 group) // Preserve new sub group in database for non-raid groups if (!isBGGroup() && !isBFGroup()) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GROUP_MEMBER_SUBGROUP); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GROUP_MEMBER_SUBGROUP); stmt->SetData(0, group); stmt->SetData(1, guid.GetCounter()); @@ -2014,7 +2014,7 @@ void Group::SetDungeonDifficulty(Difficulty difficulty) m_dungeonDifficulty = difficulty; if (!isBGGroup() && !isBFGroup()) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GROUP_DIFFICULTY); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GROUP_DIFFICULTY); stmt->SetData(0, uint8(m_dungeonDifficulty)); stmt->SetData(1, GetGUID().GetCounter()); @@ -2035,7 +2035,7 @@ void Group::SetRaidDifficulty(Difficulty difficulty) m_raidDifficulty = difficulty; if (!isBGGroup() && !isBFGroup()) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GROUP_RAID_DIFFICULTY); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GROUP_RAID_DIFFICULTY); stmt->SetData(0, uint8(m_raidDifficulty)); stmt->SetData(1, GetGUID().GetCounter()); @@ -2368,7 +2368,7 @@ void Group::SetGroupMemberFlag(ObjectGuid guid, bool apply, GroupMemberFlags fla ToggleGroupMemberFlag(slot, flag, apply); // Preserve the new setting in the db - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GROUP_MEMBER_FLAG); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GROUP_MEMBER_FLAG); stmt->SetData(0, slot->flags); stmt->SetData(1, guid.GetCounter()); diff --git a/src/server/game/Groups/GroupMgr.cpp b/src/server/game/Groups/GroupMgr.cpp index 58eabc93b3b928..6cd5bdae5bd479 100644 --- a/src/server/game/Groups/GroupMgr.cpp +++ b/src/server/game/Groups/GroupMgr.cpp @@ -17,10 +17,10 @@ #include "GroupMgr.h" #include "Common.h" -#include "DBCStores.h" #include "InstanceSaveMgr.h" #include "Log.h" #include "World.h" +#include "DatabaseEnv.h" GroupMgr::GroupMgr() { diff --git a/src/server/game/Guilds/Guild.cpp b/src/server/game/Guilds/Guild.cpp index 85344f670ad354..a1bce6dbb20c0a 100644 --- a/src/server/game/Guilds/Guild.cpp +++ b/src/server/game/Guilds/Guild.cpp @@ -179,7 +179,7 @@ Guild::LogEntry::LogEntry(uint32 guildId, ObjectGuid::LowType guid) : // EventLogEntry void Guild::EventLogEntry::SaveToDB(CharacterDatabaseTransaction trans) const { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_EVENTLOG); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_EVENTLOG); stmt->SetData(0, m_guildId); stmt->SetData(1, m_guid); CharacterDatabase.ExecuteOrAppend(trans, stmt); @@ -215,7 +215,7 @@ void Guild::BankEventLogEntry::SaveToDB(CharacterDatabaseTransaction trans) cons { uint8 index = 0; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_EVENTLOG); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_EVENTLOG); stmt->SetData( index, m_guildId); stmt->SetData(++index, m_guid); stmt->SetData (++index, m_bankTabId); @@ -275,7 +275,7 @@ void Guild::RankInfo::LoadFromDB(Field* fields) void Guild::RankInfo::SaveToDB(CharacterDatabaseTransaction trans) const { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_RANK); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_RANK); stmt->SetData(0, m_guildId); stmt->SetData (1, m_rankId); stmt->SetData(2, m_name); @@ -299,7 +299,7 @@ void Guild::RankInfo::CreateMissingTabsIfNeeded(uint8 tabs, CharacterDatabaseTra if (logOnCreate) LOG_ERROR("guild", "Guild {} has broken Tab {} for rank {}. Created default tab.", m_guildId, i, m_rankId); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_BANK_RIGHT); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_BANK_RIGHT); stmt->SetData(0, m_guildId); stmt->SetData(1, i); stmt->SetData(2, m_rankId); @@ -316,7 +316,7 @@ void Guild::RankInfo::SetName(std::string_view name) m_name = name; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_RANK_NAME); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_RANK_NAME); stmt->SetData(0, m_name); stmt->SetData (1, m_rankId); stmt->SetData(2, m_guildId); @@ -333,7 +333,7 @@ void Guild::RankInfo::SetRights(uint32 rights) m_rights = rights; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_RANK_RIGHTS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_RANK_RIGHTS); stmt->SetData(0, m_rights); stmt->SetData (1, m_rankId); stmt->SetData(2, m_guildId); @@ -350,7 +350,7 @@ void Guild::RankInfo::SetBankMoneyPerDay(uint32 money) m_bankMoneyPerDay = money; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_RANK_BANK_MONEY); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_RANK_BANK_MONEY); stmt->SetData(0, money); stmt->SetData (1, m_rankId); stmt->SetData(2, m_guildId); @@ -367,7 +367,7 @@ void Guild::RankInfo::SetBankTabSlotsAndRights(GuildBankRightsAndSlots rightsAnd if (saveToDB) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_BANK_RIGHT); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_BANK_RIGHT); stmt->SetData(0, m_guildId); stmt->SetData (1, guildBR.GetTabId()); stmt->SetData (2, m_rankId); @@ -408,7 +408,7 @@ bool Guild::BankTab::LoadItemFromDB(Field* fields) { LOG_ERROR("guild", "Item (GUID {}, id: {}) not found in item_instance, deleting from guild bank!", itemGuid, itemEntry); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_NONEXISTENT_GUILD_BANK_ITEM); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_NONEXISTENT_GUILD_BANK_ITEM); stmt->SetData(0, m_guildId); stmt->SetData (1, m_tabId); stmt->SetData (2, slotId); @@ -445,7 +445,7 @@ void Guild::BankTab::SetInfo(std::string_view name, std::string_view icon) m_name = name; m_icon = icon; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_BANK_TAB_INFO); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_BANK_TAB_INFO); stmt->SetData(0, m_name); stmt->SetData(1, m_icon); stmt->SetData(2, m_guildId); @@ -461,7 +461,7 @@ void Guild::BankTab::SetText(std::string_view text) m_text = text; utf8truncate(m_text, MAX_GUILD_BANK_TAB_TEXT_LEN); // DB and client size limitation - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_BANK_TAB_TEXT); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_BANK_TAB_TEXT); stmt->SetData(0, m_text); stmt->SetData(1, m_guildId); stmt->SetData (2, m_tabId); @@ -477,7 +477,7 @@ bool Guild::BankTab::SetItem(CharacterDatabaseTransaction trans, uint8 slotId, I m_items[slotId] = item; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_ITEM); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_ITEM); stmt->SetData(0, m_guildId); stmt->SetData (1, m_tabId); stmt->SetData (2, slotId); @@ -547,7 +547,7 @@ void Guild::Member::SetPublicNote(std::string_view publicNote) m_publicNote = publicNote; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_MEMBER_PNOTE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_MEMBER_PNOTE); stmt->SetData(0, m_publicNote); stmt->SetData(1, m_guid.GetCounter()); CharacterDatabase.Execute(stmt); @@ -560,7 +560,7 @@ void Guild::Member::SetOfficerNote(std::string_view officerNote) m_officerNote = officerNote; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_MEMBER_OFFNOTE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_MEMBER_OFFNOTE); stmt->SetData(0, m_officerNote); stmt->SetData(1, m_guid.GetCounter()); CharacterDatabase.Execute(stmt); @@ -574,7 +574,7 @@ void Guild::Member::ChangeRank(uint8 newRank) if (Player* player = FindPlayer()) player->SetRank(newRank); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_MEMBER_RANK); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_MEMBER_RANK); stmt->SetData (0, newRank); stmt->SetData(1, m_guid.GetCounter()); CharacterDatabase.Execute(stmt); @@ -587,7 +587,7 @@ void Guild::Member::UpdateLogoutTime() void Guild::Member::SaveToDB(CharacterDatabaseTransaction trans) const { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_MEMBER); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_MEMBER); stmt->SetData(0, m_guildId); stmt->SetData(1, m_guid.GetCounter()); stmt->SetData (2, m_rankId); @@ -651,7 +651,7 @@ void Guild::Member::UpdateBankWithdrawValue(CharacterDatabaseTransaction trans, { m_bankWithdraw[tabId] += amount; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_MEMBER_WITHDRAW); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_MEMBER_WITHDRAW); stmt->SetData(0, m_guid.GetCounter()); for (uint8 i = 0; i <= GUILD_BANK_MAX_TABS;) { @@ -701,7 +701,7 @@ void EmblemInfo::LoadFromDB(Field* fields) void EmblemInfo::SaveToDB(uint32 guildId) const { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_EMBLEM_INFO); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_EMBLEM_INFO); stmt->SetData(0, m_style); stmt->SetData(1, m_color); stmt->SetData(2, m_borderStyle); @@ -1066,7 +1066,7 @@ bool Guild::Create(Player* pLeader, std::string_view name) CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_MEMBERS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_MEMBERS); stmt->SetData(0, m_id); trans->Append(stmt); @@ -1117,7 +1117,7 @@ void Guild::Disband() CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD); stmt->SetData(0, m_id); trans->Append(stmt); @@ -1190,7 +1190,7 @@ bool Guild::SetName(std::string_view const& name) } m_name = name; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_NAME); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_NAME); stmt->SetData(0, m_name); stmt->SetData(1, GetId()); CharacterDatabase.Execute(stmt); @@ -1280,7 +1280,7 @@ void Guild::HandleSetMOTD(WorldSession* session, std::string_view motd) sScriptMgr->OnGuildMOTDChanged(this, m_motd); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_MOTD); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_MOTD); stmt->SetData(0, m_motd); stmt->SetData(1, m_id); CharacterDatabase.Execute(stmt); @@ -1301,7 +1301,7 @@ void Guild::HandleSetInfo(WorldSession* session, std::string_view info) sScriptMgr->OnGuildInfoChanged(this, m_info); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_INFO); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_INFO); stmt->SetData(0, m_info); stmt->SetData(1, m_id); CharacterDatabase.Execute(stmt); @@ -1631,7 +1631,7 @@ void Guild::HandleRemoveRank(WorldSession* session, uint8 rankId) return; // Delete bank rights for rank - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_RIGHTS_FOR_RANK); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_RIGHTS_FOR_RANK); stmt->SetData(0, m_id); stmt->SetData(1, rankId); CharacterDatabase.Execute(stmt); @@ -2205,7 +2205,7 @@ bool Guild::AddMember(ObjectGuid guid, uint8 rankId) bool ok = false; // xinef: sync query // Player must exist - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_DATA_FOR_GUILD); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_DATA_FOR_GUILD); stmt->SetData(0, guid.GetCounter()); if (PreparedQueryResult result = CharacterDatabase.Query(stmt)) { @@ -2314,7 +2314,7 @@ bool Guild::ChangeMemberRank(ObjectGuid guid, uint8 newRank) { m_leaderGuid = guid; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_LEADER); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_LEADER); stmt->SetData(0, m_leaderGuid.GetCounter()); stmt->SetData(1, m_id); CharacterDatabase.Execute(stmt); @@ -2371,7 +2371,7 @@ void Guild::_CreateNewBankTab() CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_TAB); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_TAB); stmt->SetData(0, m_id); stmt->SetData (1, tabId); trans->Append(stmt); @@ -2390,7 +2390,7 @@ void Guild::_CreateNewBankTab() void Guild::_CreateDefaultGuildRanks(LocaleConstant loc) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_RANKS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_RANKS); stmt->SetData(0, m_id); CharacterDatabase.Execute(stmt); @@ -2468,7 +2468,7 @@ bool Guild::_ModifyBankMoney(CharacterDatabaseTransaction trans, uint64 amount, m_bankMoney -= amount; } - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_BANK_MONEY); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_BANK_MONEY); stmt->SetData(0, m_bankMoney); stmt->SetData(1, m_id); trans->Append(stmt); @@ -2480,7 +2480,7 @@ void Guild::_SetLeaderGUID(Member& pLeader) m_leaderGuid = pLeader.GetGUID(); pLeader.ChangeRank(GR_GUILDMASTER); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_LEADER); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GUILD_LEADER); stmt->SetData(0, m_leaderGuid.GetCounter()); stmt->SetData(1, m_id); CharacterDatabase.Execute(stmt); @@ -2919,3 +2919,10 @@ void Guild::ResetTimes() _BroadcastEvent(GE_BANK_TAB_AND_MONEY_UPDATED, ObjectGuid::Empty); } + +void Guild::_DeleteMemberFromDB(ObjectGuid::LowType lowguid) +{ + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_MEMBER); + stmt->SetData(0, lowguid); + CharacterDatabase.Execute(stmt); +} diff --git a/src/server/game/Guilds/Guild.h b/src/server/game/Guilds/Guild.h index 3ed7e10ccbef56..cd625563315fd1 100644 --- a/src/server/game/Guilds/Guild.h +++ b/src/server/game/Guilds/Guild.h @@ -820,12 +820,7 @@ class Guild inline BankTab* GetBankTab(uint8 tabId) { return tabId < m_bankTabs.size() ? &m_bankTabs[tabId] : nullptr; } inline BankTab const* GetBankTab(uint8 tabId) const { return tabId < m_bankTabs.size() ? &m_bankTabs[tabId] : nullptr; } - inline void _DeleteMemberFromDB(ObjectGuid::LowType lowguid) const - { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_MEMBER); - stmt->SetData(0, lowguid); - CharacterDatabase.Execute(stmt); - } + static void _DeleteMemberFromDB(ObjectGuid::LowType lowguid) ; // Tries to create new bank tab void _CreateNewBankTab(); diff --git a/src/server/game/Guilds/GuildMgr.cpp b/src/server/game/Guilds/GuildMgr.cpp index 3df4968def2599..bfc783ed49c376 100644 --- a/src/server/game/Guilds/GuildMgr.cpp +++ b/src/server/game/Guilds/GuildMgr.cpp @@ -17,6 +17,7 @@ #include "GuildMgr.h" #include "Common.h" +#include "DatabaseEnv.h" GuildMgr::GuildMgr() : NextGuildId(1) { } diff --git a/src/server/game/Handlers/AuctionHouseHandler.cpp b/src/server/game/Handlers/AuctionHouseHandler.cpp index 9f8856792a33ab..4987420439cfc3 100644 --- a/src/server/game/Handlers/AuctionHouseHandler.cpp +++ b/src/server/game/Handlers/AuctionHouseHandler.cpp @@ -29,6 +29,7 @@ #include "World.h" #include "WorldPacket.h" #include "WorldSession.h" +#include "DatabaseEnv.h" //void called when player click on auctioneer npc void WorldSession::HandleAuctionHelloOpcode(WorldPacket& recvData) @@ -485,7 +486,7 @@ void WorldSession::HandleAuctionPlaceBid(WorldPacket& recvData) auction->bid = price; GetPlayer()->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID, price); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_AUCTION_BID); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_AUCTION_BID); stmt->SetData(0, auction->bidder.GetCounter()); stmt->SetData(1, auction->bid); stmt->SetData(2, auction->Id); diff --git a/src/server/game/Handlers/BattleGroundHandler.cpp b/src/server/game/Handlers/BattleGroundHandler.cpp index 4ab0894726ba54..8cd25cace153db 100644 --- a/src/server/game/Handlers/BattleGroundHandler.cpp +++ b/src/server/game/Handlers/BattleGroundHandler.cpp @@ -23,13 +23,13 @@ #include "DisableMgr.h" #include "GameTime.h" #include "Group.h" -#include "Language.h" #include "ObjectAccessor.h" #include "Opcodes.h" #include "Player.h" #include "ScriptMgr.h" #include "WorldPacket.h" #include "WorldSession.h" +#include "DatabaseEnv.h" void WorldSession::HandleBattlemasterHelloOpcode(WorldPacket& recvData) { @@ -571,7 +571,7 @@ void WorldSession::HandleBattleFieldPortOpcode(WorldPacket& recvData) { if (sWorld->getBoolConfig(CONFIG_BATTLEGROUND_TRACK_DESERTERS)) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_DESERTER_TRACK); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_DESERTER_TRACK); stmt->SetData(0, _player->GetGUID().GetCounter()); stmt->SetData(1, BG_DESERTION_TYPE_LEAVE_QUEUE); CharacterDatabase.Execute(stmt); diff --git a/src/server/game/Handlers/CalendarHandler.cpp b/src/server/game/Handlers/CalendarHandler.cpp index 9f72af9c069cda..b2750b72d4a14d 100644 --- a/src/server/game/Handlers/CalendarHandler.cpp +++ b/src/server/game/Handlers/CalendarHandler.cpp @@ -804,7 +804,7 @@ void WorldSession::HandleSetSavedInstanceExtend(WorldPacket& recvData) instanceBind->extended = (bool)toggleExtendOn; // update in db - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_INSTANCE_EXTENDED); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_INSTANCE_EXTENDED); stmt->SetData(0, toggleExtendOn ? 1 : 0); stmt->SetData(1, GetPlayer()->GetGUID().GetCounter()); stmt->SetData(2, instanceBind->save->GetInstanceId()); diff --git a/src/server/game/Handlers/CharacterHandler.cpp b/src/server/game/Handlers/CharacterHandler.cpp index 0e4a43a8186380..685a056c8d2f4d 100644 --- a/src/server/game/Handlers/CharacterHandler.cpp +++ b/src/server/game/Handlers/CharacterHandler.cpp @@ -65,8 +65,8 @@ class LoginQueryHolder : public CharacterDatabaseQueryHolder uint32 m_accountId; ObjectGuid m_guid; public: - LoginQueryHolder(uint32 accountId, ObjectGuid guid) - : m_accountId(accountId), m_guid(guid) { } + LoginQueryHolder(uint32 accountId, ObjectGuid guid) : + CharacterDatabaseQueryHolder("LoginQueryHolder"), m_accountId(accountId), m_guid(guid) { } ObjectGuid GetGuid() const { return m_guid; } uint32 GetAccountId() const { return m_accountId; } @@ -75,146 +75,144 @@ class LoginQueryHolder : public CharacterDatabaseQueryHolder bool LoginQueryHolder::Initialize() { - SetSize(MAX_PLAYER_LOGIN_QUERY); - bool res = true; ObjectGuid::LowType lowGuid = m_guid.GetCounter(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_FROM, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_FROM, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_AURAS); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_AURAS, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_AURAS, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_SPELL); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SPELLS, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SPELLS, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_QUESTSTATUS); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_QUEST_STATUS, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_QUEST_STATUS, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_DAILYQUESTSTATUS); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_DAILY_QUEST_STATUS, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_DAILY_QUEST_STATUS, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_WEEKLYQUESTSTATUS); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_WEEKLY_QUEST_STATUS, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_WEEKLY_QUEST_STATUS, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_MONTHLYQUESTSTATUS); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_MONTHLY_QUEST_STATUS, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_MONTHLY_QUEST_STATUS, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_SEASONALQUESTSTATUS); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SEASONAL_QUEST_STATUS, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SEASONAL_QUEST_STATUS, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_REPUTATION); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_REPUTATION, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_REPUTATION, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_INVENTORY); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_INVENTORY, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_INVENTORY, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_ACTIONS); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_ACTIONS, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_ACTIONS, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_MAIL); stmt->SetData(0, lowGuid); stmt->SetData(1, uint32(GameTime::GetGameTime().count())); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_MAILS, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_MAILS, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_MAILITEMS); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_MAIL_ITEMS, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_MAIL_ITEMS, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_SOCIALLIST); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SOCIAL_LIST, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SOCIAL_LIST, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_HOMEBIND); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_HOME_BIND, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_HOME_BIND, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_SPELLCOOLDOWNS); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SPELL_COOLDOWNS, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SPELL_COOLDOWNS, stmt); if (sWorld->getBoolConfig(CONFIG_DECLINED_NAMES_USED)) { stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_DECLINEDNAMES); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_DECLINED_NAMES, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_DECLINED_NAMES, stmt); } stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_ACHIEVEMENTS); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_ACHIEVEMENTS, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_ACHIEVEMENTS, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_CRITERIAPROGRESS); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_CRITERIA_PROGRESS, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_CRITERIA_PROGRESS, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_EQUIPMENTSETS); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_EQUIPMENT_SETS, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_EQUIPMENT_SETS, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_ENTRY_POINT); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_ENTRY_POINT, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_ENTRY_POINT, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_GLYPHS); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_GLYPHS, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_GLYPHS, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_TALENTS); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_TALENTS, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_TALENTS, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PLAYER_ACCOUNT_DATA); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_ACCOUNT_DATA, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_ACCOUNT_DATA, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_SKILLS); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SKILLS, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_SKILLS, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_RANDOMBG); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_RANDOM_BG, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_RANDOM_BG, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_BANNED); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_BANNED, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_BANNED, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_QUESTSTATUSREW); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_QUEST_STATUS_REW, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_QUEST_STATUS_REW, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_BREW_OF_THE_MONTH); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_BREW_OF_THE_MONTH, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_BREW_OF_THE_MONTH, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ACCOUNT_INSTANCELOCKTIMES); stmt->SetData(0, m_accountId); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_INSTANCE_LOCK_TIMES, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_INSTANCE_LOCK_TIMES, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CORPSE_LOCATION); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_CORPSE_LOCATION, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_CORPSE_LOCATION, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_SETTINGS); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_CHARACTER_SETTINGS, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_CHARACTER_SETTINGS, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_PETS); stmt->SetData(0, lowGuid); - res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_PET_SLOTS, stmt); + res &= AddPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_PET_SLOTS, stmt); return res; } @@ -249,7 +247,7 @@ void WorldSession::HandleCharEnum(PreparedQueryResult result) void WorldSession::HandleCharEnumOpcode(WorldPacket& /*recvData*/) { - CharacterDatabasePreparedStatement* stmt = nullptr; + CharacterDatabasePreparedStatement stmt = nullptr; /// get all the data necessary for loading all characters (along with their pets) on the account @@ -372,7 +370,7 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket& recvData) return; } - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHECK_NAME); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHECK_NAME); stmt->SetData(0, createInfo->Name); _queryProcessor.AddCallback(CharacterDatabase.AsyncQuery(stmt) @@ -384,7 +382,7 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket& recvData) return; } - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_SUM_REALM_CHARACTERS); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_SUM_REALM_CHARACTERS); stmt->SetData(0, GetAccountId()); queryCallback.SetNextQuery(LoginDatabase.AsyncQuery(stmt)); }) @@ -403,7 +401,7 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket& recvData) return; } - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_SUM_CHARS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_SUM_CHARS); stmt->SetData(0, GetAccountId()); queryCallback.SetNextQuery(CharacterDatabase.AsyncQuery(stmt)); }) @@ -561,7 +559,7 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket& recvData) newChar->SaveToDB(characterTransaction, true, false); createInfo->CharCount++; - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_REP_REALM_CHARACTERS); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_REP_REALM_CHARACTERS); stmt->SetData(0, createInfo->CharCount); stmt->SetData(1, GetAccountId()); stmt->SetData(2, realm.Id.Realm); @@ -589,7 +587,7 @@ void WorldSession::HandleCharCreateOpcode(WorldPacket& recvData) return; } - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_CREATE_INFO); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_CREATE_INFO); stmt->SetData(0, GetAccountId()); stmt->SetData(1, (skipCinematics == 1 || createInfo->Class == CLASS_DEATH_KNIGHT) ? 10 : 1); queryCallback.WithPreparedCallback(std::move(finalizeCharacterCreation)).SetNextQuery(CharacterDatabase.AsyncQuery(stmt)); @@ -893,11 +891,11 @@ void WorldSession::HandlePlayerLoginFromDB(LoginQueryHolder const& holder) pCurrChar->SendInitialPacketsAfterAddToMap(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_ONLINE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_ONLINE); stmt->SetData(0, pCurrChar->GetGUID().GetCounter()); CharacterDatabase.Execute(stmt); - LoginDatabasePreparedStatement* loginStmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_ONLINE); + LoginDatabasePreparedStatement loginStmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_ONLINE); loginStmt->SetData(0, realm.Id.Realm); loginStmt->SetData(1, GetAccountId()); LoginDatabase.Execute(loginStmt); @@ -1347,7 +1345,7 @@ void WorldSession::HandleCharRenameOpcode(WorldPacket& recvData) // Ensure that the character belongs to the current account, that rename at login is enabled // and that there is no character with the desired new name - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_FREE_NAME); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_FREE_NAME); stmt->SetData(0, renameInfo->Guid.GetCounter()); stmt->SetData(1, GetAccountId()); @@ -1387,7 +1385,7 @@ void WorldSession::HandleCharRenameCallBack(std::shared_ptr } // Update name and at_login flag in the db - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_NAME_AT_LOGIN); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_NAME_AT_LOGIN); stmt->SetData(0, renameInfo->Name); stmt->SetData(1, atLoginFlags); stmt->SetData(2, guidLow); @@ -1471,7 +1469,7 @@ void WorldSession::HandleSetPlayerDeclinedNames(WorldPacket& recvData) CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_DECLINED_NAME); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_DECLINED_NAME); stmt->SetData(0, guid.GetCounter()); trans->Append(stmt); @@ -1633,7 +1631,7 @@ void WorldSession::HandleCharCustomize(WorldPacket& recvData) >> customizeInfo->FacialHair >> customizeInfo->Face; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_CUSTOMIZE_INFO); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_CUSTOMIZE_INFO); stmt->SetData(0, customizeInfo->Guid.GetCounter()); _queryProcessor.AddCallback(CharacterDatabase.AsyncQuery(stmt) @@ -1695,7 +1693,7 @@ void WorldSession::HandleCharCustomizeCallback(std::shared_ptrGuid.GetCounter(); @@ -1917,7 +1915,7 @@ void WorldSession::HandleCharFactionOrRaceChange(WorldPacket& recvData) factionChangeInfo->FactionChange = (recvData.GetOpcode() == CMSG_CHAR_FACTION_CHANGE); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_RACE_OR_FACTION_CHANGE_INFOS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_RACE_OR_FACTION_CHANGE_INFOS); stmt->SetData(0, factionChangeInfo->Guid.GetCounter()); _queryProcessor.AddCallback(CharacterDatabase.AsyncQuery(stmt) @@ -2073,7 +2071,7 @@ void WorldSession::HandleCharFactionOrRaceChangeCallback(std::shared_ptrgetBoolConfig(CONFIG_ITEMDELETE_VENDOR)) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_RECOVERY_ITEM); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_RECOVERY_ITEM); stmt->SetData(0, _player->GetGUID().GetCounter()); stmt->SetData(1, pItem->GetEntry()); stmt->SetData(2, pItem->GetCount()); @@ -1352,7 +1353,7 @@ void WorldSession::HandleWrapItemOpcode(WorldPacket& recvData) CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_GIFT); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_GIFT); stmt->SetData(0, item->GetOwnerGUID().GetCounter()); stmt->SetData(1, item->GetGUID().GetCounter()); stmt->SetData(2, item->GetEntry()); @@ -1688,7 +1689,7 @@ bool WorldSession::recoveryItem(Item* pItem) && pItem->GetTemplate()->Quality >= sWorld->getIntConfig(CONFIG_ITEMDELETE_QUALITY) && pItem->GetTemplate()->ItemLevel >= sWorld->getIntConfig(CONFIG_ITEMDELETE_ITEM_LEVEL)) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_RECOVERY_ITEM); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_RECOVERY_ITEM); stmt->SetData(0, pItem->GetOwnerGUID().GetCounter()); stmt->SetData(1, pItem->GetTemplate()->ItemId); diff --git a/src/server/game/Handlers/MailHandler.cpp b/src/server/game/Handlers/MailHandler.cpp index 6269919671fed0..57f11e35f38cd9 100644 --- a/src/server/game/Handlers/MailHandler.cpp +++ b/src/server/game/Handlers/MailHandler.cpp @@ -438,7 +438,7 @@ void WorldSession::HandleMailReturnToSender(WorldPacket& recvData) //so firstly delete the old one CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_BY_ID); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_BY_ID); stmt->SetData(0, mailId); trans->Append(stmt); diff --git a/src/server/game/Handlers/MiscHandler.cpp b/src/server/game/Handlers/MiscHandler.cpp index 5149e6a49fce9d..981e3580badfc3 100644 --- a/src/server/game/Handlers/MiscHandler.cpp +++ b/src/server/game/Handlers/MiscHandler.cpp @@ -632,7 +632,7 @@ void WorldSession::HandleBugOpcode(WorldPacket& recv_data) LOG_DEBUG("network", "{}", type); LOG_DEBUG("network", "{}", content); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_BUG_REPORT); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_BUG_REPORT); stmt->SetData(0, type); stmt->SetData(1, content); @@ -1179,7 +1179,7 @@ void WorldSession::HandleWhoisOpcode(WorldPacket& recv_data) uint32 accid = player->GetSession()->GetAccountId(); - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_WHOIS); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_WHOIS); stmt->SetData(0, accid); diff --git a/src/server/game/Handlers/NPCHandler.cpp b/src/server/game/Handlers/NPCHandler.cpp index 9794ca8d982e0b..5824d21e2d33b5 100644 --- a/src/server/game/Handlers/NPCHandler.cpp +++ b/src/server/game/Handlers/NPCHandler.cpp @@ -600,7 +600,7 @@ void WorldSession::HandleStablePet(WorldPacket& recvData) return; } - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_PET_SLOT_BY_ID); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_PET_SLOT_BY_ID); stmt->SetData(0, PetSaveMode(PET_SAVE_FIRST_STABLE_SLOT + freeSlot)); stmt->SetData(1, _player->GetGUID().GetCounter()); stmt->SetData(2, petStable->UnslottedPets[0].PetNumber); @@ -686,7 +686,7 @@ void WorldSession::HandleUnstablePet(WorldPacket& recvData) return; } - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_PET_SLOT_BY_ID); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_PET_SLOT_BY_ID); stmt->SetData(0, PetSaveMode(PET_SAVE_FIRST_STABLE_SLOT + std::distance(petStable->StabledPets.begin(), stabledPet))); stmt->SetData(1, _player->GetGUID().GetCounter()); stmt->SetData(2, petStable->UnslottedPets[0].PetNumber); @@ -711,7 +711,7 @@ void WorldSession::HandleUnstablePet(WorldPacket& recvData) petStable->CurrentPet.reset(); // update current pet slot in db immediately to maintain slot consistency, dismissed pet was already saved - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_PET_SLOT_BY_ID); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_PET_SLOT_BY_ID); stmt->SetData(0, PET_SAVE_NOT_IN_SLOT); stmt->SetData(1, _player->GetGUID().GetCounter()); stmt->SetData(2, petnumber); @@ -722,7 +722,7 @@ void WorldSession::HandleUnstablePet(WorldPacket& recvData) else { // update current pet slot in db immediately to maintain slot consistency, dismissed pet was already saved - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_PET_SLOT_BY_ID); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_PET_SLOT_BY_ID); stmt->SetData(0, PET_SAVE_AS_CURRENT); stmt->SetData(1, _player->GetGUID().GetCounter()); stmt->SetData(2, petnumber); @@ -838,7 +838,7 @@ void WorldSession::HandleStableSwapPet(WorldPacket& recvData) return; } - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_PET_SLOT_BY_ID); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_PET_SLOT_BY_ID); stmt->SetData(0, PetSaveMode(PET_SAVE_FIRST_STABLE_SLOT + std::distance(petStable->StabledPets.begin(), stabledPet))); stmt->SetData(1, _player->GetGUID().GetCounter()); stmt->SetData(2, petStable->UnslottedPets[0].PetNumber); @@ -865,7 +865,7 @@ void WorldSession::HandleStableSwapPet(WorldPacket& recvData) petStable->CurrentPet.reset(); // update current pet slot in db immediately to maintain slot consistency, dismissed pet was already saved - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_PET_SLOT_BY_ID); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_PET_SLOT_BY_ID); stmt->SetData(0, PET_SAVE_NOT_IN_SLOT); stmt->SetData(1, _player->GetGUID().GetCounter()); stmt->SetData(2, petId); @@ -874,7 +874,7 @@ void WorldSession::HandleStableSwapPet(WorldPacket& recvData) else { // update current pet slot in db immediately to maintain slot consistency, dismissed pet was already saved - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_PET_SLOT_BY_ID); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_PET_SLOT_BY_ID); stmt->SetData(0, PET_SAVE_AS_CURRENT); stmt->SetData(1, _player->GetGUID().GetCounter()); stmt->SetData(2, petId); diff --git a/src/server/game/Handlers/PetHandler.cpp b/src/server/game/Handlers/PetHandler.cpp index f4b42136912b6a..21536157cb9c2a 100644 --- a/src/server/game/Handlers/PetHandler.cpp +++ b/src/server/game/Handlers/PetHandler.cpp @@ -35,6 +35,7 @@ #include "World.h" #include "WorldPacket.h" #include "WorldSession.h" +#include "DatabaseEnv.h" void WorldSession::HandleDismissCritter(WorldPackets::Pet::DismissCritter& packet) { @@ -899,7 +900,7 @@ void WorldSession::HandlePetRename(WorldPacket& recvData) { if (sWorld->getBoolConfig(CONFIG_DECLINED_NAMES_USED)) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_PET_DECLINEDNAME); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_PET_DECLINEDNAME); stmt->SetData(0, pet->GetCharmInfo()->GetPetNumber()); trans->Append(stmt); @@ -913,7 +914,7 @@ void WorldSession::HandlePetRename(WorldPacket& recvData) } } - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_PET_NAME); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_PET_NAME); stmt->SetData(0, name); stmt->SetData(1, _player->GetGUID().GetCounter()); stmt->SetData(2, pet->GetCharmInfo()->GetPetNumber()); diff --git a/src/server/game/Handlers/PetitionsHandler.cpp b/src/server/game/Handlers/PetitionsHandler.cpp index 0f159d1fe9b463..05c3b545c14dd6 100644 --- a/src/server/game/Handlers/PetitionsHandler.cpp +++ b/src/server/game/Handlers/PetitionsHandler.cpp @@ -19,7 +19,6 @@ #include "ArenaTeamMgr.h" #include "Guild.h" #include "GuildMgr.h" -#include "Language.h" #include "Log.h" #include "ObjectMgr.h" #include "Opcodes.h" @@ -29,6 +28,7 @@ #include "World.h" #include "WorldPacket.h" #include "WorldSession.h" +#include "DatabaseEnv.h" void WorldSession::HandlePetitionBuyOpcode(WorldPacket& recvData) { @@ -211,7 +211,7 @@ void WorldSession::HandlePetitionBuyOpcode(WorldPacket& recvData) // xinef: petition pointer is invalid from now on - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_PETITION); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_PETITION); stmt->SetData(0, _player->GetGUID().GetCounter()); stmt->SetData(1, charter->GetGUID().GetCounter()); stmt->SetData(2, name); @@ -371,7 +371,7 @@ void WorldSession::HandlePetitionRenameOpcode(WorldPacket& recvData) } } - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_PETITION_NAME); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_PETITION_NAME); stmt->SetData(0, newName); stmt->SetData(1, petitionGuid.GetCounter()); @@ -493,7 +493,7 @@ void WorldSession::HandlePetitionSignOpcode(WorldPacket& recvData) return; } - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_PETITION_SIGNATURE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_PETITION_SIGNATURE); stmt->SetData(0, petition->ownerGuid.GetCounter()); stmt->SetData(1, petitionGuid.GetCounter()); @@ -786,7 +786,7 @@ void WorldSession::HandleTurnInPetitionOpcode(WorldPacket& recvData) CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_BY_GUID); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_BY_GUID); stmt->SetData(0, petitionGuid.GetCounter()); trans->Append(stmt); diff --git a/src/server/game/Handlers/QuestHandler.cpp b/src/server/game/Handlers/QuestHandler.cpp index 5f29273038bdfc..9538386a97f65e 100644 --- a/src/server/game/Handlers/QuestHandler.cpp +++ b/src/server/game/Handlers/QuestHandler.cpp @@ -30,6 +30,7 @@ #include "World.h" #include "WorldPacket.h" #include "WorldSession.h" +#include "DatabaseEnv.h" void WorldSession::HandleQuestgiverStatusQueryOpcode(WorldPacket& recvData) { diff --git a/src/server/game/Handlers/SpellHandler.cpp b/src/server/game/Handlers/SpellHandler.cpp index c8947b7f130c41..71703617e960a8 100644 --- a/src/server/game/Handlers/SpellHandler.cpp +++ b/src/server/game/Handlers/SpellHandler.cpp @@ -32,6 +32,7 @@ #include "Vehicle.h" #include "WorldPacket.h" #include "WorldSession.h" +#include "DatabaseEnv.h" void WorldSession::HandleClientCastFlags(WorldPacket& recvPacket, uint8 castFlags, SpellCastTargets& targets) { @@ -237,7 +238,7 @@ void WorldSession::HandleOpenItemOpcode(WorldPacket& recvPacket) { if (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_WRAPPED))// wrapped? { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_GIFT_BY_ITEM); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_GIFT_BY_ITEM); stmt->SetData(0, item->GetGUID().GetCounter()); _queryProcessor.AddCallback(CharacterDatabase.AsyncQuery(stmt) .WithPreparedCallback(std::bind(&WorldSession::HandleOpenWrappedItemCallback, this, bagIndex, slot, item->GetGUID().GetCounter(), std::placeholders::_1))); @@ -282,7 +283,7 @@ void WorldSession::HandleOpenWrappedItemCallback(uint8 bagIndex, uint8 slot, Obj item->SetState(ITEM_CHANGED, GetPlayer()); GetPlayer()->SaveInventoryAndGoldToDB(trans); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GIFT); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GIFT); stmt->SetData(0, item->GetGUID().GetCounter()); trans->Append(stmt); diff --git a/src/server/game/Handlers/TicketHandler.cpp b/src/server/game/Handlers/TicketHandler.cpp index 9a445efe40138f..f817bb411244ac 100644 --- a/src/server/game/Handlers/TicketHandler.cpp +++ b/src/server/game/Handlers/TicketHandler.cpp @@ -25,6 +25,7 @@ #include "World.h" #include "WorldPacket.h" #include "WorldSession.h" +#include "DatabaseEnv.h" #include void WorldSession::HandleGMTicketCreateOpcode(WorldPacket& recvData) @@ -226,7 +227,7 @@ void WorldSession::HandleGMSurveySubmit(WorldPacket& recv_data) if (!surveyIds.insert(subSurveyId).second) continue; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GM_SUBSURVEY); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GM_SUBSURVEY); stmt->SetData(0, nextSurveyID); stmt->SetData(1, subSurveyId); stmt->SetData(2, rank); @@ -242,7 +243,7 @@ void WorldSession::HandleGMSurveySubmit(WorldPacket& recv_data) return; } - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GM_SURVEY); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GM_SURVEY); stmt->SetData(0, GetPlayer()->GetGUID().GetCounter()); stmt->SetData(1, nextSurveyID); stmt->SetData(2, mainSurvey); @@ -265,7 +266,7 @@ void WorldSession::HandleReportLag(WorldPacket& recv_data) recv_data >> y; recv_data >> z; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_LAG_REPORT); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_LAG_REPORT); stmt->SetData(0, GetPlayer()->GetGUID().GetCounter()); stmt->SetData (1, lagType); stmt->SetData(2, mapId); diff --git a/src/server/game/Handlers/TradeHandler.cpp b/src/server/game/Handlers/TradeHandler.cpp index a4e64b9e70f46a..21d5323cb07629 100644 --- a/src/server/game/Handlers/TradeHandler.cpp +++ b/src/server/game/Handlers/TradeHandler.cpp @@ -28,6 +28,7 @@ #include "World.h" #include "WorldPacket.h" #include "WorldSession.h" +#include "DatabaseEnv.h" void WorldSession::SendTradeStatus(TradeStatus status) { diff --git a/src/server/game/Instances/InstanceSaveMgr.cpp b/src/server/game/Instances/InstanceSaveMgr.cpp index 5cb7d3f596b5a8..3b015d2366494f 100644 --- a/src/server/game/Instances/InstanceSaveMgr.cpp +++ b/src/server/game/Instances/InstanceSaveMgr.cpp @@ -33,6 +33,7 @@ #include "Timer.h" #include "Transport.h" #include "World.h" +#include "DatabaseEnv.h" uint16 InstanceSaveMgr::ResetTimeDelay[] = {3600, 900, 300, 60, 0}; PlayerBindStorage InstanceSaveMgr::playerBindStorage; @@ -129,7 +130,7 @@ bool InstanceSaveMgr::DeleteInstanceSaveIfNeeded(InstanceSave* save, bool skipMa // delete save from db: // character_instance is deleted when unbinding a certain player - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INSTANCE_BY_INSTANCE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INSTANCE_BY_INSTANCE); stmt->SetData(0, save->GetInstanceId()); CharacterDatabase.Execute(stmt); DeleteInstanceSavedData(save->GetInstanceId()); @@ -182,7 +183,7 @@ void InstanceSave::InsertToDB() } } - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_INSTANCE_SAVE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_INSTANCE_SAVE); stmt->SetData(0, m_instanceid); stmt->SetData(1, GetMapId()); stmt->SetData(2, uint32(GetResetTimeForDB())); @@ -243,7 +244,7 @@ bool InstanceSave::RemovePlayer(ObjectGuid guid, InstanceSaveMgr* ism) void InstanceSaveMgr::SanitizeInstanceSavedData() { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SANITIZE_INSTANCE_SAVED_DATA); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SANITIZE_INSTANCE_SAVED_DATA); CharacterDatabase.Execute(stmt); } @@ -251,7 +252,7 @@ void InstanceSaveMgr::DeleteInstanceSavedData(uint32 instanceId) { if (instanceId) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DELETE_INSTANCE_SAVED_DATA); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DELETE_INSTANCE_SAVED_DATA); stmt->SetData(0, instanceId); CharacterDatabase.Execute(stmt); } @@ -426,7 +427,7 @@ void InstanceSaveMgr::LoadCharacterBinds() { if (bind.perm) // already loaded perm -> delete currently checked one from db { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID); stmt->SetData(0, guid.GetCounter()); stmt->SetData(1, instanceId); CharacterDatabase.Execute(stmt); @@ -434,7 +435,7 @@ void InstanceSaveMgr::LoadCharacterBinds() } else // override temp bind by newest one { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID); stmt->SetData(0, guid.GetCounter()); stmt->SetData(1, bind.save->GetInstanceId()); CharacterDatabase.Execute(stmt); @@ -519,7 +520,7 @@ void InstanceSaveMgr::_ResetSave(InstanceSaveHashMap::iterator& itr) if (pList.empty()) { // delete character_instance per id, delete instance per id - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE); stmt->SetData(0, itr->second->GetInstanceId()); CharacterDatabase.Execute(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INSTANCE_BY_INSTANCE); @@ -540,7 +541,7 @@ void InstanceSaveMgr::_ResetSave(InstanceSaveHashMap::iterator& itr) { // delete character_instance per id where extended = 0, transtaction with set extended = 0, transaction is used to avoid mysql thread races CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_NOT_EXTENDED); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_NOT_EXTENDED); stmt->SetData(0, itr->second->GetInstanceId()); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_INSTANCE_SET_NOT_EXTENDED); @@ -587,7 +588,7 @@ void InstanceSaveMgr::_ResetOrWarnAll(uint32 mapid, Difficulty difficulty, bool ScheduleReset(time_t(next_reset - 3600), InstResetEvent(1, mapid, difficulty)); // update it in the DB - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GLOBAL_INSTANCE_RESETTIME); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GLOBAL_INSTANCE_RESETTIME); stmt->SetData(0, next_reset); stmt->SetData(1, uint16(mapid)); stmt->SetData(2, uint8(difficulty)); @@ -643,7 +644,7 @@ InstancePlayerBind* InstanceSaveMgr::PlayerBindToInstance(ObjectGuid guid, Insta { bind.extended = false; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_INSTANCE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_INSTANCE); stmt->SetData(0, save->GetInstanceId()); stmt->SetData(1, permanent); stmt->SetData(2, guid.GetCounter()); @@ -659,7 +660,7 @@ InstancePlayerBind* InstanceSaveMgr::PlayerBindToInstance(ObjectGuid guid, Insta // if delete by new id is executed before update, then we end up with in db /*CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); // ensure any for that map+difficulty is deleted! - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_GUID_MAP_DIFF); // DELETE ci FROM character_instance ci JOIN instance i ON ci.instance = i.id WHERE ci.guid = ? AND i.map = ? AND i.difficulty = ? + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_GUID_MAP_DIFF); // DELETE ci FROM character_instance ci JOIN instance i ON ci.instance = i.id WHERE ci.guid = ? AND i.map = ? AND i.difficulty = ? stmt->SetData(0, guidLow); stmt->SetData(1, uint16(save->GetMapId())); stmt->SetData(2, uint8(save->GetDifficulty())); @@ -671,7 +672,7 @@ InstancePlayerBind* InstanceSaveMgr::PlayerBindToInstance(ObjectGuid guid, Insta trans->Append(stmt); CharacterDatabase.CommitTransaction(trans);*/ - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_INSTANCE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_INSTANCE); stmt->SetData(0, guid.GetCounter()); stmt->SetData(1, save->GetInstanceId()); stmt->SetData(2, permanent); @@ -709,7 +710,7 @@ void InstanceSaveMgr::PlayerUnbindInstance(ObjectGuid guid, uint32 mapid, Diffic { if (deleteFromDB) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID); stmt->SetData(0, guid.GetCounter()); stmt->SetData(1, itr->second.save->GetInstanceId()); CharacterDatabase.Execute(stmt); diff --git a/src/server/game/Instances/InstanceSaveMgr.h b/src/server/game/Instances/InstanceSaveMgr.h index 7c6f18371e739d..fb84cc89e4a5ba 100644 --- a/src/server/game/Instances/InstanceSaveMgr.h +++ b/src/server/game/Instances/InstanceSaveMgr.h @@ -19,7 +19,7 @@ #define _INSTANCESAVEMGR_H #include "DBCEnums.h" -#include "DatabaseEnv.h" +#include "DatabaseEnvFwd.h" #include "Define.h" #include "ObjectDefines.h" #include "ObjectGuid.h" diff --git a/src/server/game/Instances/InstanceScript.cpp b/src/server/game/Instances/InstanceScript.cpp index 993d7e9056ff4e..36e1cca04547e3 100644 --- a/src/server/game/Instances/InstanceScript.cpp +++ b/src/server/game/Instances/InstanceScript.cpp @@ -49,7 +49,7 @@ void InstanceScript::SaveToDB() if (save) save->SetInstanceData(data); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_INSTANCE_SAVE_DATA); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_INSTANCE_SAVE_DATA); stmt->SetData(0, data); stmt->SetData(1, instance->GetInstanceId()); CharacterDatabase.Execute(stmt); @@ -687,7 +687,7 @@ void InstanceScript::SetCompletedEncountersMask(uint32 newMask, bool save) if (iSave) iSave->SetCompletedEncounterMask(completedEncounters); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_INSTANCE_SAVE_ENCOUNTERMASK); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_INSTANCE_SAVE_ENCOUNTERMASK); stmt->SetData(0, completedEncounters); stmt->SetData(1, instance->GetInstanceId()); CharacterDatabase.Execute(stmt); diff --git a/src/server/game/Loot/LootItemStorage.cpp b/src/server/game/Loot/LootItemStorage.cpp index 1c490f13ad5fed..4fa197839b1f30 100644 --- a/src/server/game/Loot/LootItemStorage.cpp +++ b/src/server/game/Loot/LootItemStorage.cpp @@ -39,7 +39,7 @@ void LootItemStorage::LoadStorageFromDB() uint32 oldMSTime = getMSTime(); lootItemStore.clear(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ITEMCONTAINER_ITEMS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ITEMCONTAINER_ITEMS); PreparedQueryResult result = CharacterDatabase.Query(stmt); if (!result) { @@ -68,7 +68,7 @@ void LootItemStorage::RemoveEntryFromDB(ObjectGuid containerGUID, uint32 itemid, { CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_SINGLE_ITEM); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_SINGLE_ITEM); stmt->SetData(0, containerGUID.GetCounter()); stmt->SetData(1, itemid); stmt->SetData(2, count); @@ -87,7 +87,7 @@ void LootItemStorage::AddNewStoredLoot(Loot* loot, Player* /*player*/) } CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = nullptr; + CharacterDatabasePreparedStatement stmt = nullptr; StoredLootItemList& itemList = lootItemStore[loot->containerGUID]; @@ -279,7 +279,7 @@ void LootItemStorage::RemoveStoredLoot(ObjectGuid containerGUID) CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_CONTAINER); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_CONTAINER); stmt->SetData(0, containerGUID.GetCounter()); trans->Append(stmt); diff --git a/src/server/game/Loot/LootMgr.cpp b/src/server/game/Loot/LootMgr.cpp index 68ef554d4fb8a6..b78a250c40cfa0 100644 --- a/src/server/game/Loot/LootMgr.cpp +++ b/src/server/game/Loot/LootMgr.cpp @@ -28,6 +28,7 @@ #include "SpellMgr.h" #include "Util.h" #include "World.h" +#include "DatabaseEnv.h" static Rates const qualityToRate[MAX_ITEM_QUALITY] = { @@ -170,13 +171,13 @@ uint32 LootStore::LoadLootTable() if (maxcount > std::numeric_limits::max()) { - LOG_ERROR("sql.sql", "Table '{}' Entry {} Item {}: MaxCount value ({}) to large. must be less {} - skipped", GetName(), entry, item, maxcount, std::numeric_limits::max()); + LOG_ERROR("db.query", "Table '{}' Entry {} Item {}: MaxCount value ({}) to large. must be less {} - skipped", GetName(), entry, item, maxcount, std::numeric_limits::max()); continue; // error already printed to log/console. } if (lootmode == 0) { - LOG_ERROR("sql.sql", "Table '{}' Entry {} Item {}: LootMode is equal to 0, item will never drop - setting mode 1", GetName(), entry, item); + LOG_ERROR("db.query", "Table '{}' Entry {} Item {}: LootMode is equal to 0, item will never drop - setting mode 1", GetName(), entry, item); lootmode = 1; } @@ -283,17 +284,17 @@ void LootStore::ReportUnusedIds(LootIdSet const& lootIdSet) const { // all still listed ids isn't referenced for (LootIdSet::const_iterator itr = lootIdSet.begin(); itr != lootIdSet.end(); ++itr) - LOG_ERROR("sql.sql", "Table '{}' Entry {} isn't {} and not referenced from loot, and thus useless.", GetName(), *itr, GetEntryName()); + LOG_ERROR("db.query", "Table '{}' Entry {} isn't {} and not referenced from loot, and thus useless.", GetName(), *itr, GetEntryName()); } void LootStore::ReportNonExistingId(uint32 lootId) const { - LOG_ERROR("sql.sql", "Table '{}' Entry {} does not exist", GetName(), lootId); + LOG_ERROR("db.query", "Table '{}' Entry {} does not exist", GetName(), lootId); } void LootStore::ReportNonExistingId(uint32 lootId, const char* ownerType, uint32 ownerId) const { - LOG_ERROR("sql.sql", "Table '{}' Entry {} does not exist but it is used by {} {}", GetName(), lootId, ownerType, ownerId); + LOG_ERROR("db.query", "Table '{}' Entry {} does not exist but it is used by {} {}", GetName(), lootId, ownerType, ownerId); } // @@ -327,13 +328,13 @@ bool LootStoreItem::IsValid(LootStore const& store, uint32 entry) const { if (groupid >= 1 << 7) // it stored in 7 bit field { - LOG_ERROR("sql.sql", "Table '{}' Entry {} Item {}: GroupId ({}) must be less {} - skipped", store.GetName(), entry, itemid, groupid, 1 << 7); + LOG_ERROR("db.query", "Table '{}' Entry {} Item {}: GroupId ({}) must be less {} - skipped", store.GetName(), entry, itemid, groupid, 1 << 7); return false; } if (mincount == 0) { - LOG_ERROR("sql.sql", "Table '{}' Entry {} Item {}: wrong MinCount ({}) - skipped", store.GetName(), entry, itemid, mincount); + LOG_ERROR("db.query", "Table '{}' Entry {} Item {}: wrong MinCount ({}) - skipped", store.GetName(), entry, itemid, mincount); return false; } @@ -342,36 +343,36 @@ bool LootStoreItem::IsValid(LootStore const& store, uint32 entry) const ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemid); if (!proto) { - LOG_ERROR("sql.sql", "Table '{}' Entry {} Item {}: item entry not listed in `item_template` - skipped", store.GetName(), entry, itemid); + LOG_ERROR("db.query", "Table '{}' Entry {} Item {}: item entry not listed in `item_template` - skipped", store.GetName(), entry, itemid); return false; } if (chance == 0 && groupid == 0) // Zero chance is allowed for grouped entries only { - LOG_ERROR("sql.sql", "Table '{}' Entry {} Item {}: equal-chanced grouped entry, but group not defined - skipped", store.GetName(), entry, itemid); + LOG_ERROR("db.query", "Table '{}' Entry {} Item {}: equal-chanced grouped entry, but group not defined - skipped", store.GetName(), entry, itemid); return false; } if (chance != 0 && chance < 0.000001f) // loot with low chance { - LOG_ERROR("sql.sql", "Table '{}' Entry {} Item {}: low chance ({}) - skipped", + LOG_ERROR("db.query", "Table '{}' Entry {} Item {}: low chance ({}) - skipped", store.GetName(), entry, itemid, chance); return false; } if (maxcount < mincount) // wrong max count { - LOG_ERROR("sql.sql", "Table '{}' Entry {} Item {}: MaxCount ({}) less that MinCount ({}) - skipped", store.GetName(), entry, itemid, int32(maxcount), mincount); + LOG_ERROR("db.query", "Table '{}' Entry {} Item {}: MaxCount ({}) less that MinCount ({}) - skipped", store.GetName(), entry, itemid, int32(maxcount), mincount); return false; } } else // if reference loot { if (needs_quest) - LOG_ERROR("sql.sql", "Table '{}' Entry {} Item {}: quest required will be ignored", store.GetName(), entry, itemid); + LOG_ERROR("db.query", "Table '{}' Entry {} Item {}: quest required will be ignored", store.GetName(), entry, itemid); else if (chance == 0) // no chance for the reference { - LOG_ERROR("sql.sql", "Table '{}' Entry {} Item {}: zero chance is specified for a reference, skipped", store.GetName(), entry, itemid); + LOG_ERROR("db.query", "Table '{}' Entry {} Item {}: zero chance is specified for a reference, skipped", store.GetName(), entry, itemid); return false; } } @@ -563,7 +564,7 @@ bool Loot::FillLoot(uint32 lootId, LootStore const& store, Player* lootOwner, bo if (!tab) { if (!noEmptyError) - LOG_ERROR("sql.sql", "Table '{}' loot id #{} used but it doesn't have records.", store.GetName(), lootId); + LOG_ERROR("db.query", "Table '{}' loot id #{} used but it doesn't have records.", store.GetName(), lootId); return false; } @@ -1479,12 +1480,12 @@ void LootTemplate::LootGroup::Verify(LootStore const& lootstore, uint32 id, uint float chance = RawTotalChance(); if (chance > 101.0f) /// @todo: replace with 100% when DBs will be ready { - LOG_ERROR("sql.sql", "Table '{}' entry {} group {} has total chance > 100% ({})", lootstore.GetName(), id, group_id, chance); + LOG_ERROR("db.query", "Table '{}' entry {} group {} has total chance > 100% ({})", lootstore.GetName(), id, group_id, chance); } if (chance >= 100.0f && !EqualChanced.empty()) { - LOG_ERROR("sql.sql", "Table '{}' entry {} group {} has items with chance=0% but group total chance >= 100% ({})", lootstore.GetName(), id, group_id, chance); + LOG_ERROR("db.query", "Table '{}' entry {} group {} has items with chance=0% but group total chance >= 100% ({})", lootstore.GetName(), id, group_id, chance); } } diff --git a/src/server/game/Mails/Mail.cpp b/src/server/game/Mails/Mail.cpp index e33755a53036fb..49cd28b4c65e9a 100644 --- a/src/server/game/Mails/Mail.cpp +++ b/src/server/game/Mails/Mail.cpp @@ -138,7 +138,7 @@ void MailDraft::deleteIncludedItems(CharacterDatabaseTransaction trans, bool inD if (inDB) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE); stmt->SetData(0, item->GetGUID().GetCounter()); trans->Append(stmt); } @@ -170,7 +170,7 @@ void MailDraft::SendReturnToSender(uint32 /*sender_acc*/, ObjectGuid::LowType se Item* item = mailItemIter->second; item->SaveToDB(trans); // item not in inventory and can be save standalone // owner in data will set at mail receive and item extracting - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ITEM_OWNER); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ITEM_OWNER); stmt->SetData(0, receiver_guid); stmt->SetData(1, item->GetGUID().GetCounter()); trans->Append(stmt); @@ -226,7 +226,7 @@ void MailDraft::SendMailTo(CharacterDatabaseTransaction trans, MailReceiver cons // Add to DB uint8 index = 0; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_MAIL); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_MAIL); stmt->SetData( index, mailId); stmt->SetData(++index, uint8(sender.GetMailMessageType())); stmt->SetData(++index, int8(sender.GetStationery())); diff --git a/src/server/game/Maps/Map.cpp b/src/server/game/Maps/Map.cpp index 26c35ffdfed0c5..f63268028a86e3 100644 --- a/src/server/game/Maps/Map.cpp +++ b/src/server/game/Maps/Map.cpp @@ -42,6 +42,7 @@ #include "VMapMgr2.h" #include "Vehicle.h" #include "Weather.h" +#include "DatabaseEnv.h" union u_map_magic { @@ -3351,7 +3352,7 @@ void Map::SaveCreatureRespawnTime(ObjectGuid::LowType spawnId, time_t& respawnTi _creatureRespawnTimes[spawnId] = respawnTime; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_CREATURE_RESPAWN); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_CREATURE_RESPAWN); stmt->SetData(0, spawnId); stmt->SetData(1, uint32(respawnTime)); stmt->SetData(2, GetId()); @@ -3363,7 +3364,7 @@ void Map::RemoveCreatureRespawnTime(ObjectGuid::LowType spawnId) { _creatureRespawnTimes.erase(spawnId); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CREATURE_RESPAWN); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CREATURE_RESPAWN); stmt->SetData(0, spawnId); stmt->SetData(1, GetId()); stmt->SetData(2, GetInstanceId()); @@ -3385,7 +3386,7 @@ void Map::SaveGORespawnTime(ObjectGuid::LowType spawnId, time_t& respawnTime) _goRespawnTimes[spawnId] = respawnTime; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_GO_RESPAWN); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_GO_RESPAWN); stmt->SetData(0, spawnId); stmt->SetData(1, uint32(respawnTime)); stmt->SetData(2, GetId()); @@ -3397,7 +3398,7 @@ void Map::RemoveGORespawnTime(ObjectGuid::LowType spawnId) { _goRespawnTimes.erase(spawnId); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GO_RESPAWN); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GO_RESPAWN); stmt->SetData(0, spawnId); stmt->SetData(1, GetId()); stmt->SetData(2, GetInstanceId()); @@ -3406,7 +3407,7 @@ void Map::RemoveGORespawnTime(ObjectGuid::LowType spawnId) void Map::LoadRespawnTimes() { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CREATURE_RESPAWNS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CREATURE_RESPAWNS); stmt->SetData(0, GetId()); stmt->SetData(1, GetInstanceId()); if (PreparedQueryResult result = CharacterDatabase.Query(stmt)) @@ -3447,7 +3448,7 @@ void Map::DeleteRespawnTimes() void Map::DeleteRespawnTimesInDB(uint16 mapId, uint32 instanceId) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CREATURE_RESPAWN_BY_INSTANCE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CREATURE_RESPAWN_BY_INSTANCE); stmt->SetData(0, mapId); stmt->SetData(1, instanceId); CharacterDatabase.Execute(stmt); @@ -3992,7 +3993,7 @@ bool Map::CheckCollisionAndGetValidCoords(WorldObject const* source, float start void Map::LoadCorpseData() { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CORPSES); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CORPSES); stmt->SetData(0, GetId()); stmt->SetData(1, GetInstanceId()); @@ -4030,7 +4031,7 @@ void Map::LoadCorpseData() void Map::DeleteCorpseData() { // DELETE FROM corpse WHERE mapId = ? AND instanceId = ? - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CORPSES_FROM_MAP); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CORPSES_FROM_MAP); stmt->SetData(0, GetId()); stmt->SetData(1, GetInstanceId()); CharacterDatabase.Execute(stmt); diff --git a/src/server/game/Maps/TransportMgr.cpp b/src/server/game/Maps/TransportMgr.cpp index e6ad171d38ee9a..c2c69fd4b3c026 100644 --- a/src/server/game/Maps/TransportMgr.cpp +++ b/src/server/game/Maps/TransportMgr.cpp @@ -20,6 +20,7 @@ #include "MapMgr.h" #include "MoveSpline.h" #include "Transport.h" +#include "DatabaseEnv.h" TransportTemplate::~TransportTemplate() { diff --git a/src/server/game/Misc/BanMgr.cpp b/src/server/game/Misc/BanMgr.cpp index e55d4e276d1d2a..3281b348c8e72c 100644 --- a/src/server/game/Misc/BanMgr.cpp +++ b/src/server/game/Misc/BanMgr.cpp @@ -48,7 +48,7 @@ BanReturn BanMgr::BanAccount(std::string const& AccountName, std::string const& LoginDatabaseTransaction trans = LoginDatabase.BeginTransaction(); // pussywizard: check existing ban to prevent overriding by a shorter one! >_> - LoginDatabasePreparedStatement* stmtAccountBanned = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_BANNED); + LoginDatabasePreparedStatement stmtAccountBanned = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_BANNED); stmtAccountBanned->SetData(0, AccountID); PreparedQueryResult banresult = LoginDatabase.Query(stmtAccountBanned); @@ -56,7 +56,7 @@ BanReturn BanMgr::BanAccount(std::string const& AccountName, std::string const& return BAN_LONGER_EXISTS; // make sure there is only one active ban - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_NOT_BANNED); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_NOT_BANNED); stmt->SetData(0, AccountID); trans->Append(stmt); @@ -110,7 +110,7 @@ BanReturn BanMgr::BanAccountByPlayerName(std::string const& CharacterName, std:: LoginDatabaseTransaction trans = LoginDatabase.BeginTransaction(); // pussywizard: check existing ban to prevent overriding by a shorter one! >_> - LoginDatabasePreparedStatement* stmtAccountBanned = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_BANNED); + LoginDatabasePreparedStatement stmtAccountBanned = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_BANNED); stmtAccountBanned->SetData(0, AccountID); PreparedQueryResult banresult = LoginDatabase.Query(stmtAccountBanned); @@ -118,7 +118,7 @@ BanReturn BanMgr::BanAccountByPlayerName(std::string const& CharacterName, std:: return BAN_LONGER_EXISTS; // make sure there is only one active ban - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_NOT_BANNED); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_NOT_BANNED); stmt->SetData(0, AccountID); trans->Append(stmt); @@ -169,7 +169,7 @@ BanReturn BanMgr::BanIP(std::string const& IP, std::string const& Duration, std: uint32 DurationSecs = TimeStringToSecs(Duration); // No SQL injection with prepared statements - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_BY_IP); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_BY_IP); stmt->SetData(0, IP); PreparedQueryResult resultAccounts = LoginDatabase.Query(stmt); @@ -236,7 +236,7 @@ BanReturn BanMgr::BanCharacter(std::string const& CharacterName, std::string con TargetGUID = target->GetGUID(); // make sure there is only one active ban - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHARACTER_BAN); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHARACTER_BAN); stmt->SetData(0, TargetGUID.GetCounter()); CharacterDatabase.Execute(stmt); @@ -274,7 +274,7 @@ bool BanMgr::RemoveBanAccount(std::string const& AccountName) return false; // NO SQL injection as account is uint32 - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_NOT_BANNED); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_NOT_BANNED); stmt->SetData(0, AccountID); LoginDatabase.Execute(stmt); @@ -289,7 +289,7 @@ bool BanMgr::RemoveBanAccountByPlayerName(std::string const& CharacterName) return false; // NO SQL injection as account is uint32 - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_NOT_BANNED); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_NOT_BANNED); stmt->SetData(0, AccountID); LoginDatabase.Execute(stmt); @@ -299,7 +299,7 @@ bool BanMgr::RemoveBanAccountByPlayerName(std::string const& CharacterName) /// Remove a ban from an account bool BanMgr::RemoveBanIP(std::string const& IP) { - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_IP_NOT_BANNED); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_IP_NOT_BANNED); stmt->SetData(0, IP); LoginDatabase.Execute(stmt); @@ -321,7 +321,7 @@ bool BanMgr::RemoveBanCharacter(std::string const& CharacterName) if (!guid) return false; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHARACTER_BAN); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHARACTER_BAN); stmt->SetData(0, guid.GetCounter()); CharacterDatabase.Execute(stmt); return true; diff --git a/src/server/game/Misc/GameGraveyard.cpp b/src/server/game/Misc/GameGraveyard.cpp index 5552a05fd4424d..a9ec60a71e7d7e 100644 --- a/src/server/game/Misc/GameGraveyard.cpp +++ b/src/server/game/Misc/GameGraveyard.cpp @@ -59,7 +59,7 @@ void Graveyard::LoadGraveyardFromDB() if (!Utf8toWStr(Graveyard.name, Graveyard.wnameLow)) { - LOG_ERROR("sql.sql", "Wrong UTF8 name for id {} in `game_graveyard` table, ignoring.", ID); + LOG_ERROR("db.query", "Wrong UTF8 name for id {} in `game_graveyard` table, ignoring.", ID); continue; } @@ -123,7 +123,7 @@ GraveyardStruct const* Graveyard::GetClosestGraveyard(Player* player, TeamId tea { if (z > -500) { - LOG_ERROR("sql.sql", "GetClosestGraveyard: unable to find zoneId and areaId for map {} coords ({}, {}, {})", mapId, x, y, z); + LOG_ERROR("db.query", "GetClosestGraveyard: unable to find zoneId and areaId for map {} coords ({}, {}, {})", mapId, x, y, z); return GetDefaultGraveyard(teamId); } } @@ -160,7 +160,7 @@ GraveyardStruct const* Graveyard::GetClosestGraveyard(Player* player, TeamId tea // not need to check validity of map object; MapId _MUST_ be valid here if (range.first == range.second && !map->IsBattlegroundOrArena()) { - LOG_ERROR("sql.sql", "Table `graveyard_zone` incomplete: Zone {} Team {} does not have a linked graveyard.", zoneId, teamId); + LOG_ERROR("db.query", "Table `graveyard_zone` incomplete: Zone {} Team {} does not have a linked graveyard.", zoneId, teamId); return GetDefaultGraveyard(teamId); } @@ -185,7 +185,7 @@ GraveyardStruct const* Graveyard::GetClosestGraveyard(Player* player, TeamId tea GraveyardStruct const* entry = sGraveyard->GetGraveyard(graveyardLink.safeLocId); if (!entry) { - LOG_ERROR("sql.sql", "Table `graveyard_zone` has record for not existing `game_graveyard` table {}, skipped.", graveyardLink.safeLocId); + LOG_ERROR("db.query", "Table `graveyard_zone` has record for not existing `game_graveyard` table {}, skipped.", graveyardLink.safeLocId); continue; } @@ -297,7 +297,7 @@ bool Graveyard::AddGraveyardLink(uint32 id, uint32 zoneId, TeamId teamId, bool p // add link to DB if (persist) { - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_INS_GRAVEYARD_ZONE); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_INS_GRAVEYARD_ZONE); stmt->SetData(0, id); stmt->SetData(1, zoneId); @@ -315,7 +315,7 @@ void Graveyard::RemoveGraveyardLink(uint32 id, uint32 zoneId, TeamId teamId, boo GraveyardMapBoundsNonConst range = GraveyardStore.equal_range(zoneId); if (range.first == range.second) { - LOG_ERROR("sql.sql", "Table `graveyard_zone` incomplete: Zone {} Team {} does not have a linked graveyard.", zoneId, teamId); + LOG_ERROR("db.query", "Table `graveyard_zone` incomplete: Zone {} Team {} does not have a linked graveyard.", zoneId, teamId); return; } @@ -348,7 +348,7 @@ void Graveyard::RemoveGraveyardLink(uint32 id, uint32 zoneId, TeamId teamId, boo // remove link from DB if (persist) { - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_GRAVEYARD_ZONE); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_GRAVEYARD_ZONE); stmt->SetData(0, id); stmt->SetData(1, zoneId); @@ -391,25 +391,25 @@ void Graveyard::LoadGraveyardZones() GraveyardStruct const* entry = sGraveyard->GetGraveyard(safeLocId); if (!entry) { - LOG_ERROR("sql.sql", "Table `graveyard_zone` has a record for not existing `game_graveyard` table {}, skipped.", safeLocId); + LOG_ERROR("db.query", "Table `graveyard_zone` has a record for not existing `game_graveyard` table {}, skipped.", safeLocId); continue; } AreaTableEntry const* areaEntry = sAreaTableStore.LookupEntry(zoneId); if (!areaEntry) { - LOG_ERROR("sql.sql", "Table `graveyard_zone` has a record for not existing zone id ({}), skipped.", zoneId); + LOG_ERROR("db.query", "Table `graveyard_zone` has a record for not existing zone id ({}), skipped.", zoneId); continue; } if (team != 0 && team != HORDE && team != ALLIANCE) { - LOG_ERROR("sql.sql", "Table `graveyard_zone` has a record for non player faction ({}), skipped.", team); + LOG_ERROR("db.query", "Table `graveyard_zone` has a record for non player faction ({}), skipped.", team); continue; } if (!AddGraveyardLink(safeLocId, zoneId, teamId, false)) - LOG_ERROR("sql.sql", "Table `graveyard_zone` has a duplicate record for Graveyard (ID: {}) and Zone (ID: {}), skipped.", safeLocId, zoneId); + LOG_ERROR("db.query", "Table `graveyard_zone` has a duplicate record for Graveyard (ID: {}) and Zone (ID: {}), skipped.", safeLocId, zoneId); } while (result->NextRow()); LOG_INFO("server.loading", ">> Loaded {} Graveyard-Zone Links in {} ms", count, GetMSTimeDiffToNow(oldMSTime)); diff --git a/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp index f1da9bbb5d8f3d..2e62540449fd94 100644 --- a/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp @@ -39,7 +39,7 @@ void WaypointMovementGenerator::LoadPath(Creature* creature) if (!i_path) { // No movement found for entry - LOG_ERROR("sql.sql", "WaypointMovementGenerator::LoadPath: creature {} ({}) doesn't have waypoint path id: {}", + LOG_ERROR("db.query", "WaypointMovementGenerator::LoadPath: creature {} ({}) doesn't have waypoint path id: {}", creature->GetName(), creature->GetGUID().ToString(), path_id); return; } diff --git a/src/server/game/Movement/Waypoints/WaypointMgr.cpp b/src/server/game/Movement/Waypoints/WaypointMgr.cpp index 6b8601fa1602e6..7962a977033b63 100644 --- a/src/server/game/Movement/Waypoints/WaypointMgr.cpp +++ b/src/server/game/Movement/Waypoints/WaypointMgr.cpp @@ -86,7 +86,7 @@ void WaypointMgr::Load() if (wp->move_type >= WAYPOINT_MOVE_TYPE_MAX) { - //LOG_ERROR("sql.sql", "Waypoint {} in waypoint_data has invalid move_type, ignoring", wp->id); + //LOG_ERROR("db.query", "Waypoint {} in waypoint_data has invalid move_type, ignoring", wp->id); delete wp; continue; } @@ -114,7 +114,7 @@ void WaypointMgr::ReloadPath(uint32 id) _waypointStore.erase(itr); } - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_BY_ID); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_BY_ID); stmt->SetData(0, id); @@ -149,7 +149,7 @@ void WaypointMgr::ReloadPath(uint32 id) if (wp->move_type >= WAYPOINT_MOVE_TYPE_MAX) { - //LOG_ERROR("sql.sql", "Waypoint {} in waypoint_data has invalid move_type, ignoring", wp->id); + //LOG_ERROR("db.query", "Waypoint {} in waypoint_data has invalid move_type, ignoring", wp->id); delete wp; continue; } diff --git a/src/server/game/Movement/Waypoints/WaypointMgr.h b/src/server/game/Movement/Waypoints/WaypointMgr.h index 0d81e14cff19cb..6d8f484f1ec7c1 100644 --- a/src/server/game/Movement/Waypoints/WaypointMgr.h +++ b/src/server/game/Movement/Waypoints/WaypointMgr.h @@ -21,6 +21,7 @@ #include "Common.h" #include #include +#include enum WaypointMoveType { diff --git a/src/server/game/OutdoorPvP/OutdoorPvP.cpp b/src/server/game/OutdoorPvP/OutdoorPvP.cpp index 7ea5ca9d46ec44..bc3198148b512e 100644 --- a/src/server/game/OutdoorPvP/OutdoorPvP.cpp +++ b/src/server/game/OutdoorPvP/OutdoorPvP.cpp @@ -26,6 +26,7 @@ #include "ObjectMgr.h" #include "OutdoorPvPMgr.h" #include "WorldPacket.h" +#include "DatabaseEnv.h" OPvPCapturePoint::OPvPCapturePoint(OutdoorPvP* pvp): m_capturePointSpawnId(0), m_capturePoint(nullptr), m_maxValue(0.0f), m_minValue(0.0f), m_maxSpeed(0), @@ -163,7 +164,7 @@ bool OPvPCapturePoint::DelCreature(uint32 type) //if (Map* map = sMapMgr->FindMap(cr->GetMapId())) // map->Remove(cr, false); // delete respawn time for this creature - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CREATURE_RESPAWN); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CREATURE_RESPAWN); stmt->SetData(0, spawnId); stmt->SetData(1, m_PvP->GetMap()->GetId()); stmt->SetData(2, 0); // instance id, always 0 for world maps diff --git a/src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp b/src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp index 57fe3166bb868a..cb94162baae95b 100644 --- a/src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp +++ b/src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp @@ -20,6 +20,7 @@ #include "ObjectMgr.h" #include "Player.h" #include "ScriptMgr.h" +#include "DatabaseEnv.h" OutdoorPvPMgr::OutdoorPvPMgr() { @@ -71,7 +72,7 @@ void OutdoorPvPMgr::InitOutdoorPvP() if (typeId >= MAX_OUTDOORPVP_TYPES) { - LOG_ERROR("sql.sql", "Invalid OutdoorPvPTypes value {} in outdoorpvp_template; skipped.", typeId); + LOG_ERROR("db.query", "Invalid OutdoorPvPTypes value {} in outdoorpvp_template; skipped.", typeId); continue; } @@ -90,7 +91,7 @@ void OutdoorPvPMgr::InitOutdoorPvP() OutdoorPvPDataMap::iterator iter = m_OutdoorPvPDatas.find(OutdoorPvPTypes(i)); if (iter == m_OutdoorPvPDatas.end()) { - LOG_ERROR("sql.sql", "Could not initialize OutdoorPvP object for type ID {}; no entry in database.", uint32(i)); + LOG_ERROR("db.query", "Could not initialize OutdoorPvP object for type ID {}; no entry in database.", uint32(i)); continue; } diff --git a/src/server/game/Pools/PoolMgr.cpp b/src/server/game/Pools/PoolMgr.cpp index 703a79dde2fd6a..6574a6dbea874e 100644 --- a/src/server/game/Pools/PoolMgr.cpp +++ b/src/server/game/Pools/PoolMgr.cpp @@ -21,6 +21,7 @@ #include "MapMgr.h" #include "ObjectMgr.h" #include "Transport.h" +#include "DatabaseEnv.h" //////////////////////////////////////////////////////////// // template class ActivePoolData @@ -461,7 +462,7 @@ void PoolGroup::SpawnObject(ActivePoolData& spawns, uint32 limit, uint32 // load state from db if (!triggerFrom) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_POOL_QUEST_SAVE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_POOL_QUEST_SAVE); stmt->SetData(0, poolId); @@ -631,18 +632,18 @@ void PoolMgr::LoadFromDB() CreatureData const* data = sObjectMgr->GetCreatureData(guid); if (!data) { - LOG_ERROR("sql.sql", "`pool_creature` has a non existing creature spawn (GUID: {}) defined for pool id ({}), skipped.", guid, pool_id); + LOG_ERROR("db.query", "`pool_creature` has a non existing creature spawn (GUID: {}) defined for pool id ({}), skipped.", guid, pool_id); continue; } auto it = mPoolTemplate.find(pool_id); if (it == mPoolTemplate.end()) { - LOG_ERROR("sql.sql", "`pool_creature` pool id ({}) is not in `pool_template`, skipped.", pool_id); + LOG_ERROR("db.query", "`pool_creature` pool id ({}) is not in `pool_template`, skipped.", pool_id); continue; } if (chance < 0 || chance > 100) { - LOG_ERROR("sql.sql", "`pool_creature` has an invalid chance ({}) for creature guid ({}) in pool id ({}), skipped.", chance, guid, pool_id); + LOG_ERROR("db.query", "`pool_creature` has an invalid chance ({}) for creature guid ({}) in pool id ({}), skipped.", chance, guid, pool_id); continue; } PoolTemplateData* pPoolTemplate = &mPoolTemplate[pool_id]; @@ -689,7 +690,7 @@ void PoolMgr::LoadFromDB() GameObjectData const* data = sObjectMgr->GetGameObjectData(guid); if (!data) { - LOG_ERROR("sql.sql", "`pool_gameobject` has a non existing gameobject spawn (GUID: {}) defined for pool id ({}), skipped.", guid, pool_id); + LOG_ERROR("db.query", "`pool_gameobject` has a non existing gameobject spawn (GUID: {}) defined for pool id ({}), skipped.", guid, pool_id); continue; } @@ -698,20 +699,20 @@ void PoolMgr::LoadFromDB() goinfo->type != GAMEOBJECT_TYPE_GOOBER && goinfo->type != GAMEOBJECT_TYPE_FISHINGHOLE) { - LOG_ERROR("sql.sql", "`pool_gameobject` has a not lootable gameobject spawn (GUID: {}, type: {}) defined for pool id ({}), skipped.", guid, goinfo->type, pool_id); + LOG_ERROR("db.query", "`pool_gameobject` has a not lootable gameobject spawn (GUID: {}, type: {}) defined for pool id ({}), skipped.", guid, goinfo->type, pool_id); continue; } auto it = mPoolTemplate.find(pool_id); if (it == mPoolTemplate.end()) { - LOG_ERROR("sql.sql", "`pool_gameobject` pool id ({}) is not in `pool_template`, skipped.", pool_id); + LOG_ERROR("db.query", "`pool_gameobject` pool id ({}) is not in `pool_template`, skipped.", pool_id); continue; } if (chance < 0 || chance > 100) { - LOG_ERROR("sql.sql", "`pool_gameobject` has an invalid chance ({}) for gameobject guid ({}) in pool id ({}), skipped.", chance, guid, pool_id); + LOG_ERROR("db.query", "`pool_gameobject` has an invalid chance ({}) for gameobject guid ({}) in pool id ({}), skipped.", chance, guid, pool_id); continue; } @@ -760,7 +761,7 @@ void PoolMgr::LoadFromDB() auto it = mPoolTemplate.find(mother_pool_id); if (it == mPoolTemplate.end()) { - LOG_ERROR("sql.sql", "`pool_pool` mother_pool id ({}) is not in `pool_template`, skipped.", mother_pool_id); + LOG_ERROR("db.query", "`pool_pool` mother_pool id ({}) is not in `pool_template`, skipped.", mother_pool_id); continue; } } @@ -768,18 +769,18 @@ void PoolMgr::LoadFromDB() auto it = mPoolTemplate.find(child_pool_id); if (it == mPoolTemplate.end()) { - LOG_ERROR("sql.sql", "`pool_pool` included pool_id ({}) is not in `pool_template`, skipped.", child_pool_id); + LOG_ERROR("db.query", "`pool_pool` included pool_id ({}) is not in `pool_template`, skipped.", child_pool_id); continue; } } if (mother_pool_id == child_pool_id) { - LOG_ERROR("sql.sql", "`pool_pool` pool_id ({}) includes itself, dead-lock detected, skipped.", child_pool_id); + LOG_ERROR("db.query", "`pool_pool` pool_id ({}) includes itself, dead-lock detected, skipped.", child_pool_id); continue; } if (chance < 0 || chance > 100) { - LOG_ERROR("sql.sql", "`pool_pool` has an invalid chance ({}) for pool id ({}) in mother pool id ({}), skipped.", chance, child_pool_id, mother_pool_id); + LOG_ERROR("db.query", "`pool_pool` has an invalid chance ({}) for pool id ({}) in mother pool id ({}), skipped.", chance, child_pool_id, mother_pool_id); continue; } PoolTemplateData* pPoolTemplateMother = &mPoolTemplate[mother_pool_id]; @@ -809,7 +810,7 @@ void PoolMgr::LoadFromDB() ss << *itr << ' '; ss << "create(s) a circular reference, which can cause the server to freeze.\nRemoving the last link between mother pool " << poolItr->first << " and child pool " << poolItr->second; - LOG_ERROR("sql.sql", "{}", ss.str()); + LOG_ERROR("db.query", "{}", ss.str()); mPoolPoolGroups[poolItr->second].RemoveOneRelation(poolItr->first); mPoolSearchMap.erase(poolItr); --count; @@ -827,7 +828,7 @@ void PoolMgr::LoadFromDB() { uint32 oldMSTime = getMSTime(); - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_QUEST_POOLS); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_QUEST_POOLS); PreparedQueryResult result = WorldDatabase.Query(stmt); if (!result) @@ -859,20 +860,20 @@ void PoolMgr::LoadFromDB() Quest const* quest = sObjectMgr->GetQuestTemplate(entry); if (!quest) { - LOG_ERROR("sql.sql", "`pool_quest` has a non existing quest template (Entry: {}) defined for pool id ({}), skipped.", entry, pool_id); + LOG_ERROR("db.query", "`pool_quest` has a non existing quest template (Entry: {}) defined for pool id ({}), skipped.", entry, pool_id); continue; } auto it = mPoolTemplate.find(pool_id); if (it == mPoolTemplate.end()) { - LOG_ERROR("sql.sql", "`pool_quest` pool id ({}) is not in `pool_template`, skipped.", pool_id); + LOG_ERROR("db.query", "`pool_quest` pool id ({}) is not in `pool_template`, skipped.", pool_id); continue; } if (!quest->IsDailyOrWeekly()) { - LOG_ERROR("sql.sql", "`pool_quest` has an quest ({}) which is not daily or weekly in pool id ({}), use ExclusiveGroup instead, skipped.", entry, pool_id); + LOG_ERROR("db.query", "`pool_quest` has an quest ({}) which is not daily or weekly in pool id ({}), use ExclusiveGroup instead, skipped.", entry, pool_id); continue; } @@ -883,7 +884,7 @@ void PoolMgr::LoadFromDB() if (poolTypeMap[pool_id] != currType) { - LOG_ERROR("sql.sql", "`pool_quest` quest {} is {} but pool ({}) is specified for {}, mixing not allowed, skipped.", + LOG_ERROR("db.query", "`pool_quest` quest {} is {} but pool ({}) is specified for {}, mixing not allowed, skipped.", entry, currType == QUEST_DAILY ? "QUEST_DAILY" : "QUEST_WEEKLY", pool_id, poolTypeMap[pool_id] == QUEST_DAILY ? "QUEST_DAILY" : "QUEST_WEEKLY"); continue; } @@ -893,7 +894,7 @@ void PoolMgr::LoadFromDB() if (creBounds.first == creBounds.second && goBounds.first == goBounds.second) { - LOG_ERROR("sql.sql", "`pool_quest` lists entry ({}) as member of pool ({}) but is not started anywhere, skipped.", entry, pool_id); + LOG_ERROR("db.query", "`pool_quest` lists entry ({}) as member of pool ({}) but is not started anywhere, skipped.", entry, pool_id); continue; } @@ -941,9 +942,9 @@ void PoolMgr::LoadFromDB() if (pool_pool_id) // The pool is a child pool in pool_pool table. Ideally we should remove it from the pool handler to ensure it never gets spawned, // however that could recursively invalidate entire chain of mother pools. It can be done in the future but for now we'll do nothing. - LOG_ERROR("sql.sql", "Pool Id {} has no equal chance pooled entites defined and explicit chance sum is not 100. This broken pool is a child pool of Id {} and cannot be safely removed.", pool_entry, fields[2].Get()); + LOG_ERROR("db.query", "Pool Id {} has no equal chance pooled entites defined and explicit chance sum is not 100. This broken pool is a child pool of Id {} and cannot be safely removed.", pool_entry, fields[2].Get()); else - LOG_ERROR("sql.sql", "Pool Id {} has no equal chance pooled entites defined and explicit chance sum is not 100. The pool will not be spawned.", pool_entry); + LOG_ERROR("db.query", "Pool Id {} has no equal chance pooled entites defined and explicit chance sum is not 100. The pool will not be spawned.", pool_entry); continue; } @@ -984,7 +985,7 @@ void PoolMgr::SaveQuestsToDB(bool daily, bool weekly, bool other) if (!other && !quest->IsDaily() && !quest->IsWeekly()) continue; } - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_POOL_SAVE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_POOL_SAVE); stmt->SetData(0, itr->second.GetPoolId()); trans->Append(stmt); deletedPools.insert(itr->second.GetPoolId()); @@ -994,7 +995,7 @@ void PoolMgr::SaveQuestsToDB(bool daily, bool weekly, bool other) if (deletedPools.find(itr->second) != deletedPools.end()) if (IsSpawnedObject(itr->first)) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_QUEST_POOL_SAVE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_QUEST_POOL_SAVE); stmt->SetData(0, itr->second); stmt->SetData(1, itr->first); trans->Append(stmt); diff --git a/src/server/game/Quests/QuestDef.h b/src/server/game/Quests/QuestDef.h index 734151b5ef548c..ee47d2d396c2cb 100644 --- a/src/server/game/Quests/QuestDef.h +++ b/src/server/game/Quests/QuestDef.h @@ -19,7 +19,7 @@ #define AZEROTHCORE_QUEST_H #include "DBCEnums.h" -#include "DatabaseEnv.h" +#include "DatabaseEnvFwd.h" #include "Define.h" #include "SharedDefines.h" #include "WorldPacket.h" diff --git a/src/server/game/Reputation/ReputationMgr.cpp b/src/server/game/Reputation/ReputationMgr.cpp index b749e267fbee21..cefc30c7a3f236 100644 --- a/src/server/game/Reputation/ReputationMgr.cpp +++ b/src/server/game/Reputation/ReputationMgr.cpp @@ -628,7 +628,7 @@ void ReputationMgr::SaveToDB(CharacterDatabaseTransaction trans) { if (itr->second.needSave) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_REPUTATION_BY_FACTION); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_REPUTATION_BY_FACTION); stmt->SetData(0, _player->GetGUID().GetCounter()); stmt->SetData(1, uint16(itr->second.ID)); trans->Append(stmt); diff --git a/src/server/game/Scripting/ScriptMgr.cpp b/src/server/game/Scripting/ScriptMgr.cpp index 2ddad5cf1de941..0b117eea0a86b4 100644 --- a/src/server/game/Scripting/ScriptMgr.cpp +++ b/src/server/game/Scripting/ScriptMgr.cpp @@ -195,7 +195,7 @@ void ScriptMgr::CheckIfScriptsInDatabaseExist() !ScriptRegistry::GetScriptById(sid) && !ScriptRegistry::GetScriptById(sid)) { - LOG_ERROR("sql.sql", "Script named '{}' is assigned in the database, but has no code!", scriptName); + LOG_ERROR("db.query", "Script named '{}' is assigned in the database, but has no code!", scriptName); } } } diff --git a/src/server/game/Scripting/ScriptMgr.h b/src/server/game/Scripting/ScriptMgr.h index e4fcd3f96e55b9..65f5bddf1dd583 100644 --- a/src/server/game/Scripting/ScriptMgr.h +++ b/src/server/game/Scripting/ScriptMgr.h @@ -2850,7 +2850,7 @@ class ScriptRegistry { // The script uses a script name from database, but isn't assigned to anything. if (script->GetName().find("Smart") == std::string::npos) - LOG_ERROR("sql.sql", "Script named '{}' is not assigned in the database.", + LOG_ERROR("db.query", "Script named '{}' is not assigned in the database.", script->GetName()); } } diff --git a/src/server/game/Scripting/ScriptSystem.cpp b/src/server/game/Scripting/ScriptSystem.cpp index d6aa37b35eb39c..d36e726f0434d5 100644 --- a/src/server/game/Scripting/ScriptSystem.cpp +++ b/src/server/game/Scripting/ScriptSystem.cpp @@ -72,12 +72,12 @@ void SystemMgr::LoadScriptWaypoints() if (!pCInfo) { - LOG_ERROR("sql.sql", "DB table script_waypoint has waypoint for non-existant creature entry {}", temp.uiCreatureEntry); + LOG_ERROR("db.query", "DB table script_waypoint has waypoint for non-existant creature entry {}", temp.uiCreatureEntry); continue; } if (!pCInfo->ScriptID) - LOG_ERROR("sql.sql", "DB table script_waypoint has waypoint for creature entry {}, but creature does not have ScriptName defined and then useless.", temp.uiCreatureEntry); + LOG_ERROR("db.query", "DB table script_waypoint has waypoint for creature entry {}, but creature does not have ScriptName defined and then useless.", temp.uiCreatureEntry); m_mPointMoveMap[uiEntry].push_back(temp); ++count; diff --git a/src/server/game/Server/WorldSession.cpp b/src/server/game/Server/WorldSession.cpp index 71683e8583db88..234ae358104508 100644 --- a/src/server/game/Server/WorldSession.cpp +++ b/src/server/game/Server/WorldSession.cpp @@ -625,7 +625,7 @@ void WorldSession::LogoutPlayer(bool save) { if (sWorld->getBoolConfig(CONFIG_BATTLEGROUND_TRACK_DESERTERS)) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_DESERTER_TRACK); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_DESERTER_TRACK); stmt->SetData(0, _player->GetGUID().GetCounter()); stmt->SetData(1, BG_DESERTION_TYPE_INVITE_LOGOUT); CharacterDatabase.Execute(stmt); @@ -730,7 +730,7 @@ void WorldSession::LogoutPlayer(bool save) LOG_DEBUG("network", "SESSION: Sent SMSG_LOGOUT_COMPLETE Message"); //! Since each account can only have one online character at any given time, ensure all characters for active account are marked as offline - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ACCOUNT_ONLINE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ACCOUNT_ONLINE); stmt->SetData(0, GetAccountId()); CharacterDatabase.Execute(stmt); } @@ -915,7 +915,7 @@ void WorldSession::SetAccountData(AccountDataType type, time_t tm, std::string c index = CHAR_REP_PLAYER_ACCOUNT_DATA; } - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(index); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(index); stmt->SetData(0, id); stmt->SetData(1, type); stmt->SetData(2, uint32(tm)); @@ -966,7 +966,7 @@ void WorldSession::SaveTutorialsData(CharacterDatabaseTransaction trans) if (!m_TutorialsChanged) return; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_HAS_TUTORIALS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_HAS_TUTORIALS); stmt->SetData(0, GetAccountId()); bool hasTutorials = bool(CharacterDatabase.Query(stmt)); @@ -1665,19 +1665,19 @@ class AccountInfoQueryHolderPerRealm : public CharacterDatabaseQueryHolder MAX_QUERIES }; - AccountInfoQueryHolderPerRealm() { SetSize(MAX_QUERIES); } + AccountInfoQueryHolderPerRealm() : CharacterDatabaseQueryHolder("AccountInfoQueryHolderPerRealm") { } bool Initialize(uint32 accountId) { bool ok = true; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ACCOUNT_DATA); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ACCOUNT_DATA); stmt->SetData(0, accountId); - ok = SetPreparedQuery(GLOBAL_ACCOUNT_DATA, stmt) && ok; + ok = AddPreparedQuery(GLOBAL_ACCOUNT_DATA, stmt) && ok; stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_TUTORIALS); stmt->SetData(0, accountId); - ok = SetPreparedQuery(TUTORIALS, stmt) && ok; + ok = AddPreparedQuery(TUTORIALS, stmt) && ok; return ok; } diff --git a/src/server/game/Server/WorldSession.h b/src/server/game/Server/WorldSession.h index 0830a0bf5cb65b..7eb47cb7ac1052 100644 --- a/src/server/game/Server/WorldSession.h +++ b/src/server/game/Server/WorldSession.h @@ -28,7 +28,7 @@ #include "BanMgr.h" #include "CircularBuffer.h" #include "Common.h" -#include "DatabaseEnv.h" +#include "DatabaseEnvFwd.h" #include "GossipDef.h" #include "Packet.h" #include "SharedDefines.h" diff --git a/src/server/game/Server/WorldSocket.cpp b/src/server/game/Server/WorldSocket.cpp index f2ce1d91b88796..c4ef07211389e0 100644 --- a/src/server/game/Server/WorldSocket.cpp +++ b/src/server/game/Server/WorldSocket.cpp @@ -47,7 +47,7 @@ void WorldSocket::Start() { std::string ip_address = GetRemoteIpAddress().to_string(); - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_IP_INFO); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_IP_INFO); stmt->SetData(0, ip_address); _queryProcessor.AddCallback(LoginDatabase.AsyncQuery(stmt).WithPreparedCallback(std::bind(&WorldSocket::CheckIpCallback, this, std::placeholders::_1))); @@ -449,7 +449,7 @@ void WorldSocket::HandleAuthSession(WorldPacket & recvPacket) recvPacket.read(authSession->AddonInfo.contents(), authSession->AddonInfo.size()); // .contents will throw if empty, thats what we want // Get the account information from the auth database - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_INFO_BY_NAME); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_INFO_BY_NAME); stmt->SetData(0, int32(realm.Id.Realm)); stmt->SetData(1, authSession->Account); @@ -473,7 +473,7 @@ void WorldSocket::HandleAuthSessionCallback(std::shared_ptr authSes // For hook purposes, we get Remoteaddress at this point. std::string address = sConfigMgr->GetOption("AllowLoggingIPAddressesInDatabase", true, true) ? GetRemoteIpAddress().to_string() : "0.0.0.0"; - LoginDatabasePreparedStatement* stmt = nullptr; + LoginDatabasePreparedStatement stmt = nullptr; // As we don't know if attempted login process by ip works, we update last_attempt_ip right away stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_LAST_ATTEMPT_IP); @@ -566,7 +566,7 @@ void WorldSocket::HandleAuthSessionCallback(std::shared_ptr authSes { account.MuteTime = GameTime::GetGameTime().count() + llabs(account.MuteTime); - auto* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_MUTE_TIME_LOGIN); + auto stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_MUTE_TIME_LOGIN); stmt->SetData(0, account.MuteTime); stmt->SetData(1, account.Id); LoginDatabase.Execute(stmt); diff --git a/src/server/game/Skills/SkillDiscovery.cpp b/src/server/game/Skills/SkillDiscovery.cpp index f597ef06c0cd86..313128ea19b06e 100644 --- a/src/server/game/Skills/SkillDiscovery.cpp +++ b/src/server/game/Skills/SkillDiscovery.cpp @@ -88,7 +88,7 @@ void LoadSkillDiscoveryTable() { if (reportedReqSpells.find(absReqSkillOrSpell) == reportedReqSpells.end()) { - LOG_ERROR("sql.sql", "Spell (ID: {}) have not existed spell (ID: {}) in `reqSpell` field in `skill_discovery_template` table", spellId, reqSkillOrSpell); + LOG_ERROR("db.query", "Spell (ID: {}) have not existed spell (ID: {}) in `reqSpell` field in `skill_discovery_template` table", spellId, reqSkillOrSpell); reportedReqSpells.insert(absReqSkillOrSpell); } continue; @@ -101,7 +101,7 @@ void LoadSkillDiscoveryTable() { if (reportedReqSpells.find(absReqSkillOrSpell) == reportedReqSpells.end()) { - LOG_ERROR("sql.sql", "Spell (ID: {}) not have MECHANIC_DISCOVERY (28) value in Mechanic field in spell.dbc" + LOG_ERROR("db.query", "Spell (ID: {}) not have MECHANIC_DISCOVERY (28) value in Mechanic field in spell.dbc" " and not 100% chance random discovery ability but listed for spellId {} (and maybe more) in `skill_discovery_template` table", absReqSkillOrSpell, spellId); reportedReqSpells.insert(absReqSkillOrSpell); @@ -117,7 +117,7 @@ void LoadSkillDiscoveryTable() if (bounds.first == bounds.second) { - LOG_ERROR("sql.sql", "Spell (ID: {}) not listed in `SkillLineAbility.dbc` but listed with `reqSpell`=0 in `skill_discovery_template` table", spellId); + LOG_ERROR("db.query", "Spell (ID: {}) not listed in `SkillLineAbility.dbc` but listed with `reqSpell`=0 in `skill_discovery_template` table", spellId); continue; } @@ -126,7 +126,7 @@ void LoadSkillDiscoveryTable() } else { - LOG_ERROR("sql.sql", "Spell (ID: {}) have negative value in `reqSpell` field in `skill_discovery_template` table", spellId); + LOG_ERROR("db.query", "Spell (ID: {}) have negative value in `reqSpell` field in `skill_discovery_template` table", spellId); continue; } @@ -134,7 +134,7 @@ void LoadSkillDiscoveryTable() } while (result->NextRow()); if (!ssNonDiscoverableEntries.str().empty()) - LOG_ERROR("sql.sql", "Some items can't be successfully discovered: have in chance field value < 0.000001 in `skill_discovery_template` DB table . List:\n{}", ssNonDiscoverableEntries.str()); + LOG_ERROR("db.query", "Some items can't be successfully discovered: have in chance field value < 0.000001 in `skill_discovery_template` DB table . List:\n{}", ssNonDiscoverableEntries.str()); // report about empty data for explicit discovery spells for (uint32 spell_id = 1; spell_id < sSpellMgr->GetSpellInfoStoreSize(); ++spell_id) @@ -148,7 +148,7 @@ void LoadSkillDiscoveryTable() continue; if (SkillDiscoveryStore.find(int32(spell_id)) == SkillDiscoveryStore.end()) - LOG_ERROR("sql.sql", "Spell (ID: {}) is 100% chance random discovery ability but not have data in `skill_discovery_template` table", spell_id); + LOG_ERROR("db.query", "Spell (ID: {}) is 100% chance random discovery ability but not have data in `skill_discovery_template` table", spell_id); } LOG_INFO("server.loading", ">> Loaded {} skill discovery definitions in {} ms", count, GetMSTimeDiffToNow(oldMSTime)); diff --git a/src/server/game/Skills/SkillExtraItems.cpp b/src/server/game/Skills/SkillExtraItems.cpp index e6b757a2f76b6b..7f4365ea419a0a 100644 --- a/src/server/game/Skills/SkillExtraItems.cpp +++ b/src/server/game/Skills/SkillExtraItems.cpp @@ -75,28 +75,28 @@ void LoadSkillPerfectItemTable() if (!sSpellMgr->GetSpellInfo(spellId)) { - LOG_ERROR("sql.sql", "Skill perfection data for spell {} has non-existent spell id in `skill_perfect_item_template`!", spellId); + LOG_ERROR("db.query", "Skill perfection data for spell {} has non-existent spell id in `skill_perfect_item_template`!", spellId); continue; } uint32 requiredSpecialization = fields[1].Get(); if (!sSpellMgr->GetSpellInfo(requiredSpecialization)) { - LOG_ERROR("sql.sql", "Skill perfection data for spell {} has non-existent required specialization spell id {} in `skill_perfect_item_template`!", spellId, requiredSpecialization); + LOG_ERROR("db.query", "Skill perfection data for spell {} has non-existent required specialization spell id {} in `skill_perfect_item_template`!", spellId, requiredSpecialization); continue; } float perfectCreateChance = fields[2].Get(); if (perfectCreateChance <= 0.0f) { - LOG_ERROR("sql.sql", "Skill perfection data for spell {} has impossibly low proc chance in `skill_perfect_item_template`!", spellId); + LOG_ERROR("db.query", "Skill perfection data for spell {} has impossibly low proc chance in `skill_perfect_item_template`!", spellId); continue; } uint32 perfectItemType = fields[3].Get(); if (!sObjectMgr->GetItemTemplate(perfectItemType)) { - LOG_ERROR("sql.sql", "Skill perfection data for spell {} references non-existent perfect item id {} in `skill_perfect_item_template`!", spellId, perfectItemType); + LOG_ERROR("db.query", "Skill perfection data for spell {} references non-existent perfect item id {} in `skill_perfect_item_template`!", spellId, perfectItemType); continue; } @@ -161,28 +161,28 @@ void LoadSkillExtraItemTable() if (!sSpellMgr->GetSpellInfo(spellId)) { - LOG_ERROR("sql.sql", "Skill specialization {} has non-existent spell id in `skill_extra_item_template`!", spellId); + LOG_ERROR("db.query", "Skill specialization {} has non-existent spell id in `skill_extra_item_template`!", spellId); continue; } uint32 requiredSpecialization = fields[1].Get(); if (!sSpellMgr->GetSpellInfo(requiredSpecialization)) { - LOG_ERROR("sql.sql", "Skill specialization {} have not existed required specialization spell id {} in `skill_extra_item_template`!", spellId, requiredSpecialization); + LOG_ERROR("db.query", "Skill specialization {} have not existed required specialization spell id {} in `skill_extra_item_template`!", spellId, requiredSpecialization); continue; } float additionalCreateChance = fields[2].Get(); if (additionalCreateChance <= 0.0f) { - LOG_ERROR("sql.sql", "Skill specialization {} has too low additional create chance in `skill_extra_item_template`!", spellId); + LOG_ERROR("db.query", "Skill specialization {} has too low additional create chance in `skill_extra_item_template`!", spellId); continue; } int32 newMaxOrEntry = fields[3].Get(); if (!newMaxOrEntry) { - LOG_ERROR("sql.sql", "Skill specialization {} has 0 max number of extra items in `skill_extra_item_template`!", spellId); + LOG_ERROR("db.query", "Skill specialization {} has 0 max number of extra items in `skill_extra_item_template`!", spellId); continue; } diff --git a/src/server/game/Spells/SpellEffects.cpp b/src/server/game/Spells/SpellEffects.cpp index ce45a55892f067..e983ad7a29e17a 100644 --- a/src/server/game/Spells/SpellEffects.cpp +++ b/src/server/game/Spells/SpellEffects.cpp @@ -4333,7 +4333,7 @@ void Spell::EffectActivateObject(SpellEffIndex effIndex) artKitValue = templateAddon->artKits[artKitIndex]; if (artKitValue == 0) - LOG_ERROR("sql.sql", "GameObject {} hit by spell {} needs `artkit{}` in `gameobject_template_addon`", gameObjTarget->GetEntry(), m_spellInfo->Id, artKitIndex); + LOG_ERROR("db.query", "GameObject {} hit by spell {} needs `artkit{}` in `gameobject_template_addon`", gameObjTarget->GetEntry(), m_spellInfo->Id, artKitIndex); else gameObjTarget->SetGoArtKit(artKitValue); @@ -5403,7 +5403,7 @@ void Spell::EffectTransmitted(SpellEffIndex effIndex) if (!goinfo) { - LOG_ERROR("sql.sql", "Gameobject (Entry: {}) not exist and not created at spell (ID: {}) cast", name_id, m_spellInfo->Id); + LOG_ERROR("db.query", "Gameobject (Entry: {}) not exist and not created at spell (ID: {}) cast", name_id, m_spellInfo->Id); return; } diff --git a/src/server/game/Spells/SpellInfoCorrections.cpp b/src/server/game/Spells/SpellInfoCorrections.cpp index bff534f0adaa62..26ce21a6cdc875 100644 --- a/src/server/game/Spells/SpellInfoCorrections.cpp +++ b/src/server/game/Spells/SpellInfoCorrections.cpp @@ -28,7 +28,7 @@ inline void ApplySpellFix(std::initializer_list spellIds, void(*fix)(Spe SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId); if (!spellInfo) { - LOG_ERROR("sql.sql", "Spell info correction specified for non-existing spell {}", spellId); + LOG_ERROR("db.query", "Spell info correction specified for non-existing spell {}", spellId); continue; } diff --git a/src/server/game/Spells/SpellMgr.cpp b/src/server/game/Spells/SpellMgr.cpp index 103d93d40c3361..00a796250201b0 100644 --- a/src/server/game/Spells/SpellMgr.cpp +++ b/src/server/game/Spells/SpellMgr.cpp @@ -28,11 +28,11 @@ #include "Player.h" #include "SharedDefines.h" #include "Spell.h" -#include "SpellAuraDefines.h" #include "SpellAuras.h" #include "SpellInfo.h" #include "ScriptMgr.h" #include "World.h" +#include "DatabaseEnv.h" bool IsPrimaryProfessionSkill(uint32 skill) { @@ -394,7 +394,7 @@ bool SpellMgr::ComputeIsSpellValid(SpellInfo const* spellInfo, bool msg) if (!spellInfo->IsLootCrafting()) { if (msg) - LOG_ERROR("sql.sql", "Craft spell {} not have create item entry.", spellInfo->Id); + LOG_ERROR("db.query", "Craft spell {} not have create item entry.", spellInfo->Id); return false; } } @@ -402,7 +402,7 @@ bool SpellMgr::ComputeIsSpellValid(SpellInfo const* spellInfo, bool msg) else if (!sObjectMgr->GetItemTemplate(spellInfo->Effects[i].ItemType)) { if (msg) - LOG_ERROR("sql.sql", "Craft spell {} create not-exist in DB item (Entry: {}) and then...", spellInfo->Id, spellInfo->Effects[i].ItemType); + LOG_ERROR("db.query", "Craft spell {} create not-exist in DB item (Entry: {}) and then...", spellInfo->Id, spellInfo->Effects[i].ItemType); return false; } @@ -415,7 +415,7 @@ bool SpellMgr::ComputeIsSpellValid(SpellInfo const* spellInfo, bool msg) if (!ComputeIsSpellValid(spellInfo2, msg)) { if (msg) - LOG_ERROR("sql.sql", "Spell {} learn to invalid spell {}, and then...", spellInfo->Id, spellInfo->Effects[i].TriggerSpell); + LOG_ERROR("db.query", "Spell {} learn to invalid spell {}, and then...", spellInfo->Id, spellInfo->Effects[i].TriggerSpell); return false; } break; @@ -430,7 +430,7 @@ bool SpellMgr::ComputeIsSpellValid(SpellInfo const* spellInfo, bool msg) if (spellInfo->Reagent[j] > 0 && !sObjectMgr->GetItemTemplate(spellInfo->Reagent[j])) { if (msg) - LOG_ERROR("sql.sql", "Craft spell {} have not-exist reagent in DB item (Entry: {}) and then...", spellInfo->Id, spellInfo->Reagent[j]); + LOG_ERROR("db.query", "Craft spell {} have not-exist reagent in DB item (Entry: {}) and then...", spellInfo->Id, spellInfo->Reagent[j]); return false; } } @@ -451,7 +451,7 @@ void DeleteSpellFromAllPlayers(uint32 spellId) CharacterDatabaseStatements stmts[2] = {CHAR_DEL_INVALID_SPELL_SPELLS, CHAR_DEL_INVALID_SPELL_TALENTS}; for (uint8 i = 0; i < 2; i++) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(stmts[i]); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(stmts[i]); stmt->SetData(0, spellId); CharacterDatabase.Execute(stmt); } @@ -521,7 +521,7 @@ uint32 SpellMgr::GetSpellIdForDifficulty(uint32 spellId, Unit const* caster) con if (difficultyEntry->SpellID[mode] <= 0) { - LOG_ERROR("sql.sql", "SpellMgr::GetSpellIdForDifficulty: spell {} mode {} spell is 0. Check spelldifficulty_dbc!", spellId, mode); + LOG_ERROR("db.query", "SpellMgr::GetSpellIdForDifficulty: spell {} mode {} spell is 0. Check spelldifficulty_dbc!", spellId, mode); return spellId; } @@ -1256,7 +1256,7 @@ void SpellMgr::LoadSpellTalentRanks() SpellInfo const* firstSpell = GetSpellInfo(talentInfo->RankID[0]); if (!firstSpell) { - LOG_ERROR("sql.sql", "SpellMgr::LoadSpellTalentRanks: First Rank Spell {} for TalentEntry {} does not exist.", talentInfo->RankID[0], i); + LOG_ERROR("db.query", "SpellMgr::LoadSpellTalentRanks: First Rank Spell {} for TalentEntry {} does not exist.", talentInfo->RankID[0], i); continue; } @@ -1270,7 +1270,7 @@ void SpellMgr::LoadSpellTalentRanks() SpellInfo const* currentSpell = GetSpellInfo(spellId); if (!currentSpell) { - LOG_ERROR("sql.sql", "SpellMgr::LoadSpellTalentRanks: Spell {} (Rank: {}) for TalentEntry {} does not exist.", spellId, rank + 1, i); + LOG_ERROR("db.query", "SpellMgr::LoadSpellTalentRanks: Spell {} (Rank: {}) for TalentEntry {} does not exist.", spellId, rank + 1, i); break; } @@ -1342,13 +1342,13 @@ void SpellMgr::LoadSpellRanks() SpellInfo const* first = GetSpellInfo(lastSpell); if (!first) { - LOG_ERROR("sql.sql", "Spell rank identifier(first_spell_id) {} listed in `spell_ranks` does not exist!", lastSpell); + LOG_ERROR("db.query", "Spell rank identifier(first_spell_id) {} listed in `spell_ranks` does not exist!", lastSpell); continue; } // check if chain is long enough if (rankChain.size() < 2) { - LOG_ERROR("sql.sql", "There is only 1 spell rank for identifier(first_spell_id) {} in `spell_ranks`, entry is not needed!", lastSpell); + LOG_ERROR("db.query", "There is only 1 spell rank for identifier(first_spell_id) {} in `spell_ranks`, entry is not needed!", lastSpell); continue; } int32 curRank = 0; @@ -1359,14 +1359,14 @@ void SpellMgr::LoadSpellRanks() SpellInfo const* spell = GetSpellInfo(itr->first); if (!spell) { - LOG_ERROR("sql.sql", "Spell {} (rank {}) listed in `spell_ranks` for chain {} does not exist!", itr->first, itr->second, lastSpell); + LOG_ERROR("db.query", "Spell {} (rank {}) listed in `spell_ranks` for chain {} does not exist!", itr->first, itr->second, lastSpell); valid = false; break; } ++curRank; if (itr->second != curRank) { - LOG_ERROR("sql.sql", "Spell {} (rank {}) listed in `spell_ranks` for chain {} does not have proper rank value(should be {})!", itr->first, itr->second, lastSpell, curRank); + LOG_ERROR("db.query", "Spell {} (rank {}) listed in `spell_ranks` for chain {} does not have proper rank value(should be {})!", itr->first, itr->second, lastSpell, curRank); valid = false; break; } @@ -1430,26 +1430,26 @@ void SpellMgr::LoadSpellRequired() SpellInfo const* spellInfo = GetSpellInfo(spellId); if (!spellInfo) { - LOG_ERROR("sql.sql", "spell_id {} in `spell_required` table is not found in dbcs, skipped", spellId); + LOG_ERROR("db.query", "spell_id {} in `spell_required` table is not found in dbcs, skipped", spellId); continue; } SpellInfo const* reqSpellInfo = GetSpellInfo(spellReq); if (!reqSpellInfo) { - LOG_ERROR("sql.sql", "req_spell {} in `spell_required` table is not found in dbcs, skipped", spellReq); + LOG_ERROR("db.query", "req_spell {} in `spell_required` table is not found in dbcs, skipped", spellReq); continue; } if (GetFirstSpellInChain(spellId) == GetFirstSpellInChain(spellReq)) { - LOG_ERROR("sql.sql", "req_spell {} and spell_id {} in `spell_required` table are ranks of the same spell, entry not needed, skipped", spellReq, spellId); + LOG_ERROR("db.query", "req_spell {} and spell_id {} in `spell_required` table are ranks of the same spell, entry not needed, skipped", spellReq, spellId); continue; } if (IsSpellRequiringSpell(spellId, spellReq)) { - LOG_ERROR("sql.sql", "duplicated entry of req_spell {} and spell_id {} in `spell_required`, skipped", spellReq, spellId); + LOG_ERROR("db.query", "duplicated entry of req_spell {} and spell_id {} in `spell_required`, skipped", spellReq, spellId); continue; } @@ -1555,20 +1555,20 @@ void SpellMgr::LoadSpellTargetPositions() MapEntry const* mapEntry = sMapStore.LookupEntry(st.target_mapId); if (!mapEntry) { - LOG_ERROR("sql.sql", "Spell (Id: {}, effIndex: {}) target map (ID: {}) does not exist in `Map.dbc`.", Spell_ID, effIndex, st.target_mapId); + LOG_ERROR("db.query", "Spell (Id: {}, effIndex: {}) target map (ID: {}) does not exist in `Map.dbc`.", Spell_ID, effIndex, st.target_mapId); continue; } if (st.target_X == 0 && st.target_Y == 0 && st.target_Z == 0) { - LOG_ERROR("sql.sql", "Spell (Id: {}, effIndex: {}) target coordinates not provided.", Spell_ID, effIndex); + LOG_ERROR("db.query", "Spell (Id: {}, effIndex: {}) target coordinates not provided.", Spell_ID, effIndex); continue; } SpellInfo const* spellInfo = GetSpellInfo(Spell_ID); if (!spellInfo) { - LOG_ERROR("sql.sql", "Spell (ID:{}) listed in `spell_target_position` does not exist.", Spell_ID); + LOG_ERROR("db.query", "Spell (ID:{}) listed in `spell_target_position` does not exist.", Spell_ID); continue; } @@ -1580,7 +1580,7 @@ void SpellMgr::LoadSpellTargetPositions() } else { - LOG_ERROR("sql.sql", "Spell (Id: {}, effIndex: {}) listed in `spell_target_position` does not have target TARGET_DEST_DB (17).", Spell_ID, effIndex); + LOG_ERROR("db.query", "Spell (Id: {}, effIndex: {}) listed in `spell_target_position` does not have target TARGET_DEST_DB (17).", Spell_ID, effIndex); continue; } } while (result->NextRow()); @@ -1651,24 +1651,24 @@ void SpellMgr::LoadSpellGroups() if (!spellInfo) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_group` does not exist", spell_id); + LOG_ERROR("db.query", "Spell {} listed in `spell_group` does not exist", spell_id); continue; } else if (spellInfo->GetRank() > 1) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_group` is not first rank of spell", spell_id); + LOG_ERROR("db.query", "Spell {} listed in `spell_group` is not first rank of spell", spell_id); continue; } if (mSpellGroupMap.find(spell_id) != mSpellGroupMap.end()) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_group` has more than one group", spell_id); + LOG_ERROR("db.query", "Spell {} listed in `spell_group` has more than one group", spell_id); continue; } if (specialFlag >= SPELL_GROUP_SPECIAL_FLAG_MAX) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_group` has invalid special flag!", spell_id); + LOG_ERROR("db.query", "Spell {} listed in `spell_group` has invalid special flag!", spell_id); continue; } @@ -1708,7 +1708,7 @@ void SpellMgr::LoadSpellGroupStackRules() uint8 stack_rule = fields[1].Get(); if (stack_rule >= SPELL_GROUP_STACK_FLAG_MAX) { - LOG_ERROR("sql.sql", "SpellGroupStackRule {} listed in `spell_group_stack_rules` does not exist", stack_rule); + LOG_ERROR("db.query", "SpellGroupStackRule {} listed in `spell_group_stack_rules` does not exist", stack_rule); continue; } @@ -1722,7 +1722,7 @@ void SpellMgr::LoadSpellGroupStackRules() if (!present) { - LOG_ERROR("sql.sql", "SpellGroup id {} listed in `spell_group_stack_rules` does not exist", group_id); + LOG_ERROR("db.query", "SpellGroup id {} listed in `spell_group_stack_rules` does not exist", group_id); continue; } @@ -1767,18 +1767,18 @@ void SpellMgr::LoadSpellProcEvents() SpellInfo const* spellInfo = GetSpellInfo(spellId); if (!spellInfo) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_proc_event` does not exist", spellId); + LOG_ERROR("db.query", "Spell {} listed in `spell_proc_event` does not exist", spellId); continue; } if (allRanks) { if (!spellInfo->IsRanked()) - LOG_ERROR("sql.sql", "Spell {} listed in `spell_proc_event` with all ranks, but spell has no ranks.", spellId); + LOG_ERROR("db.query", "Spell {} listed in `spell_proc_event` with all ranks, but spell has no ranks.", spellId); if (spellInfo->GetFirstRankSpell()->Id != uint32(spellId)) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_proc_event` is not first rank of spell.", spellId); + LOG_ERROR("db.query", "Spell {} listed in `spell_proc_event` is not first rank of spell.", spellId); continue; } } @@ -1807,12 +1807,12 @@ void SpellMgr::LoadSpellProcEvents() { if (mSpellProcEventMap.find(spellInfo->Id) != mSpellProcEventMap.end()) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_proc_event` already has its first rank in table.", spellInfo->Id); + LOG_ERROR("db.query", "Spell {} listed in `spell_proc_event` already has its first rank in table.", spellInfo->Id); break; } if (!spellInfo->ProcFlags && !spellProcEvent.procFlags) - LOG_ERROR("sql.sql", "Spell {} listed in `spell_proc_event` probally not triggered spell", spellInfo->Id); + LOG_ERROR("db.query", "Spell {} listed in `spell_proc_event` probally not triggered spell", spellInfo->Id); mSpellProcEventMap[spellInfo->Id] = spellProcEvent; @@ -1861,7 +1861,7 @@ void SpellMgr::LoadSpellProcs() SpellInfo const* spellInfo = GetSpellInfo(spellId); if (!spellInfo) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_proc` does not exist", spellId); + LOG_ERROR("db.query", "Spell {} listed in `spell_proc` does not exist", spellId); continue; } @@ -1869,7 +1869,7 @@ void SpellMgr::LoadSpellProcs() { if (spellInfo->GetFirstRankSpell()->Id != uint32(spellId)) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_proc` is not first rank of spell.", fields[0].Get()); + LOG_ERROR("db.query", "Spell {} listed in `spell_proc` is not first rank of spell.", fields[0].Get()); continue; } } @@ -1895,7 +1895,7 @@ void SpellMgr::LoadSpellProcs() { if (mSpellProcMap.find(spellInfo->Id) != mSpellProcMap.end()) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_proc` has duplicate entry in the table", spellId); + LOG_ERROR("db.query", "Spell {} listed in `spell_proc` has duplicate entry in the table", spellId); break; } SpellProcEntry procEntry = SpellProcEntry(baseProcEntry); @@ -1910,42 +1910,42 @@ void SpellMgr::LoadSpellProcs() // validate data if (procEntry.SchoolMask & ~SPELL_SCHOOL_MASK_ALL) - LOG_ERROR("sql.sql", "`spell_proc` table entry for SpellId {} has wrong `SchoolMask` set: {}", spellId, procEntry.SchoolMask); + LOG_ERROR("db.query", "`spell_proc` table entry for SpellId {} has wrong `SchoolMask` set: {}", spellId, procEntry.SchoolMask); if (procEntry.SpellFamilyName && (procEntry.SpellFamilyName < 3 || procEntry.SpellFamilyName > 17 || procEntry.SpellFamilyName == 14 || procEntry.SpellFamilyName == 16)) - LOG_ERROR("sql.sql", "`spell_proc` table entry for SpellId {} has wrong `SpellFamilyName` set: {}", spellId, procEntry.SpellFamilyName); + LOG_ERROR("db.query", "`spell_proc` table entry for SpellId {} has wrong `SpellFamilyName` set: {}", spellId, procEntry.SpellFamilyName); if (procEntry.Chance < 0) { - LOG_ERROR("sql.sql", "`spell_proc` table entry for SpellId {} has negative value in `Chance` field", spellId); + LOG_ERROR("db.query", "`spell_proc` table entry for SpellId {} has negative value in `Chance` field", spellId); procEntry.Chance = 0; } if (procEntry.ProcsPerMinute < 0) { - LOG_ERROR("sql.sql", "`spell_proc` table entry for SpellId {} has negative value in `ProcsPerMinute` field", spellId); + LOG_ERROR("db.query", "`spell_proc` table entry for SpellId {} has negative value in `ProcsPerMinute` field", spellId); procEntry.ProcsPerMinute = 0; } if (procEntry.Chance == 0 && procEntry.ProcsPerMinute == 0) - LOG_ERROR("sql.sql", "`spell_proc` table entry for SpellId {} doesn't have `Chance` and `ProcsPerMinute` values defined, proc will not be triggered", spellId); + LOG_ERROR("db.query", "`spell_proc` table entry for SpellId {} doesn't have `Chance` and `ProcsPerMinute` values defined, proc will not be triggered", spellId); if (procEntry.Charges > 99) { - LOG_ERROR("sql.sql", "`spell_proc` table entry for SpellId {} has too big value in `Charges` field", spellId); + LOG_ERROR("db.query", "`spell_proc` table entry for SpellId {} has too big value in `Charges` field", spellId); procEntry.Charges = 99; } if (!procEntry.ProcFlags) - LOG_ERROR("sql.sql", "`spell_proc` table entry for SpellId {} doesn't have `ProcFlags` value defined, proc will not be triggered", spellId); + LOG_ERROR("db.query", "`spell_proc` table entry for SpellId {} doesn't have `ProcFlags` value defined, proc will not be triggered", spellId); if (procEntry.SpellTypeMask & ~PROC_SPELL_TYPE_MASK_ALL) - LOG_ERROR("sql.sql", "`spell_proc` table entry for SpellId {} has wrong `SpellTypeMask` set: {}", spellId, procEntry.SpellTypeMask); + LOG_ERROR("db.query", "`spell_proc` table entry for SpellId {} has wrong `SpellTypeMask` set: {}", spellId, procEntry.SpellTypeMask); if (procEntry.SpellTypeMask && !(procEntry.ProcFlags & (SPELL_PROC_FLAG_MASK | PERIODIC_PROC_FLAG_MASK))) - LOG_ERROR("sql.sql", "`spell_proc` table entry for SpellId {} has `SpellTypeMask` value defined, but it won't be used for defined `ProcFlags` value", spellId); + LOG_ERROR("db.query", "`spell_proc` table entry for SpellId {} has `SpellTypeMask` value defined, but it won't be used for defined `ProcFlags` value", spellId); if (!procEntry.SpellPhaseMask && procEntry.ProcFlags & REQ_SPELL_PHASE_PROC_FLAG_MASK) - LOG_ERROR("sql.sql", "`spell_proc` table entry for SpellId {} doesn't have `SpellPhaseMask` value defined, but it's required for defined `ProcFlags` value, proc will not be triggered", spellId); + LOG_ERROR("db.query", "`spell_proc` table entry for SpellId {} doesn't have `SpellPhaseMask` value defined, but it's required for defined `ProcFlags` value, proc will not be triggered", spellId); if (procEntry.SpellPhaseMask & ~PROC_SPELL_PHASE_MASK_ALL) - LOG_ERROR("sql.sql", "`spell_proc` table entry for SpellId {} has wrong `SpellPhaseMask` set: {}", spellId, procEntry.SpellPhaseMask); + LOG_ERROR("db.query", "`spell_proc` table entry for SpellId {} has wrong `SpellPhaseMask` set: {}", spellId, procEntry.SpellPhaseMask); if (procEntry.SpellPhaseMask && !(procEntry.ProcFlags & REQ_SPELL_PHASE_PROC_FLAG_MASK)) - LOG_ERROR("sql.sql", "`spell_proc` table entry for SpellId {} has `SpellPhaseMask` value defined, but it won't be used for defined `ProcFlags` value", spellId); + LOG_ERROR("db.query", "`spell_proc` table entry for SpellId {} has `SpellPhaseMask` value defined, but it won't be used for defined `ProcFlags` value", spellId); if (procEntry.HitMask & ~PROC_HIT_MASK_ALL) - LOG_ERROR("sql.sql", "`spell_proc` table entry for SpellId {} has wrong `HitMask` set: {}", spellId, procEntry.HitMask); + LOG_ERROR("db.query", "`spell_proc` table entry for SpellId {} has wrong `HitMask` set: {}", spellId, procEntry.HitMask); if (procEntry.HitMask && !(procEntry.ProcFlags & TAKEN_HIT_PROC_FLAG_MASK || (procEntry.ProcFlags & DONE_HIT_PROC_FLAG_MASK && (!procEntry.SpellPhaseMask || procEntry.SpellPhaseMask & (PROC_SPELL_PHASE_HIT | PROC_SPELL_PHASE_FINISH))))) - LOG_ERROR("sql.sql", "`spell_proc` table entry for SpellId {} has `HitMask` value defined, but it won't be used for defined `ProcFlags` and `SpellPhaseMask` values", spellId); + LOG_ERROR("db.query", "`spell_proc` table entry for SpellId {} has `HitMask` value defined, but it won't be used for defined `ProcFlags` and `SpellPhaseMask` values", spellId); mSpellProcMap[spellInfo->Id] = procEntry; @@ -1985,7 +1985,7 @@ void SpellMgr::LoadSpellBonuses() SpellInfo const* spell = GetSpellInfo(entry); if (!spell) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_bonus_data` does not exist", entry); + LOG_ERROR("db.query", "Spell {} listed in `spell_bonus_data` does not exist", entry); continue; } @@ -2026,7 +2026,7 @@ void SpellMgr::LoadSpellThreats() if (!GetSpellInfo(entry)) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_threat` does not exist", entry); + LOG_ERROR("db.query", "Spell {} listed in `spell_threat` does not exist", entry); continue; } @@ -2067,7 +2067,7 @@ void SpellMgr::LoadSpellMixology() if (!GetSpellInfo(entry)) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_mixology` does not exist", entry); + LOG_ERROR("db.query", "Spell {} listed in `spell_mixology` does not exist", entry); continue; } @@ -2134,7 +2134,7 @@ void SpellMgr::LoadSpellPetAuras() SpellInfo const* spellInfo = GetSpellInfo(spell); if (!spellInfo) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_pet_auras` does not exist", spell); + LOG_ERROR("db.query", "Spell {} listed in `spell_pet_auras` does not exist", spell); continue; } if (spellInfo->Effects[eff].Effect != SPELL_EFFECT_DUMMY && @@ -2148,7 +2148,7 @@ void SpellMgr::LoadSpellPetAuras() SpellInfo const* spellInfo2 = GetSpellInfo(aura); if (!spellInfo2) { - LOG_ERROR("sql.sql", "Aura {} listed in `spell_pet_auras` does not exist", aura); + LOG_ERROR("db.query", "Aura {} listed in `spell_pet_auras` does not exist", aura); continue; } @@ -2230,7 +2230,7 @@ void SpellMgr::LoadSpellEnchantProcData() SpellItemEnchantmentEntry const* ench = sSpellItemEnchantmentStore.LookupEntry(enchantId); if (!ench) { - LOG_ERROR("sql.sql", "Enchancment {} listed in `spell_enchant_proc_data` does not exist", enchantId); + LOG_ERROR("db.query", "Enchancment {} listed in `spell_enchant_proc_data` does not exist", enchantId); continue; } @@ -2277,13 +2277,13 @@ void SpellMgr::LoadSpellLinked() SpellInfo const* spellInfo = GetSpellInfo(std::abs(trigger)); if (!spellInfo) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_linked_spell` does not exist", std::abs(trigger)); + LOG_ERROR("db.query", "Spell {} listed in `spell_linked_spell` does not exist", std::abs(trigger)); continue; } spellInfo = GetSpellInfo(std::abs(effect)); if (!spellInfo) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_linked_spell` does not exist", std::abs(effect)); + LOG_ERROR("db.query", "Spell {} listed in `spell_linked_spell` does not exist", std::abs(effect)); continue; } @@ -2532,7 +2532,7 @@ void SpellMgr::LoadSpellAreas() } else { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_area` does not exist", spell); + LOG_ERROR("db.query", "Spell {} listed in `spell_area` does not exist", spell); continue; } @@ -2561,20 +2561,20 @@ void SpellMgr::LoadSpellAreas() if (!ok) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_area` already listed with similar requirements.", spell); + LOG_ERROR("db.query", "Spell {} listed in `spell_area` already listed with similar requirements.", spell); continue; } } if (spellArea.areaId && !sAreaTableStore.LookupEntry(spellArea.areaId)) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_area` have wrong area ({}) requirement", spell, spellArea.areaId); + LOG_ERROR("db.query", "Spell {} listed in `spell_area` have wrong area ({}) requirement", spell, spellArea.areaId); continue; } if (spellArea.questStart && !sObjectMgr->GetQuestTemplate(spellArea.questStart)) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_area` have wrong start quest ({}) requirement", spell, spellArea.questStart); + LOG_ERROR("db.query", "Spell {} listed in `spell_area` have wrong start quest ({}) requirement", spell, spellArea.questStart); continue; } @@ -2582,7 +2582,7 @@ void SpellMgr::LoadSpellAreas() { if (!sObjectMgr->GetQuestTemplate(spellArea.questEnd)) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_area` have wrong end quest ({}) requirement", spell, spellArea.questEnd); + LOG_ERROR("db.query", "Spell {} listed in `spell_area` have wrong end quest ({}) requirement", spell, spellArea.questEnd); continue; } } @@ -2592,13 +2592,13 @@ void SpellMgr::LoadSpellAreas() SpellInfo const* spellInfo = GetSpellInfo(std::abs(spellArea.auraSpell)); if (!spellInfo) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_area` have wrong aura spell ({}) requirement", spell, std::abs(spellArea.auraSpell)); + LOG_ERROR("db.query", "Spell {} listed in `spell_area` have wrong aura spell ({}) requirement", spell, std::abs(spellArea.auraSpell)); continue; } if (uint32(std::abs(spellArea.auraSpell)) == spellArea.spellId) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_area` have aura spell ({}) requirement for itself", spell, std::abs(spellArea.auraSpell)); + LOG_ERROR("db.query", "Spell {} listed in `spell_area` have aura spell ({}) requirement for itself", spell, std::abs(spellArea.auraSpell)); continue; } @@ -2618,7 +2618,7 @@ void SpellMgr::LoadSpellAreas() if (chain) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_area` have aura spell ({}) requirement that itself autocast from aura", spell, spellArea.auraSpell); + LOG_ERROR("db.query", "Spell {} listed in `spell_area` have aura spell ({}) requirement that itself autocast from aura", spell, spellArea.auraSpell); continue; } @@ -2634,7 +2634,7 @@ void SpellMgr::LoadSpellAreas() if (chain) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_area` have aura spell ({}) requirement that itself autocast from aura", spell, spellArea.auraSpell); + LOG_ERROR("db.query", "Spell {} listed in `spell_area` have aura spell ({}) requirement that itself autocast from aura", spell, spellArea.auraSpell); continue; } } @@ -2642,13 +2642,13 @@ void SpellMgr::LoadSpellAreas() if (spellArea.raceMask && (spellArea.raceMask & RACEMASK_ALL_PLAYABLE) == 0) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_area` have wrong race mask ({}) requirement", spell, spellArea.raceMask); + LOG_ERROR("db.query", "Spell {} listed in `spell_area` have wrong race mask ({}) requirement", spell, spellArea.raceMask); continue; } if (spellArea.gender != GENDER_NONE && spellArea.gender != GENDER_FEMALE && spellArea.gender != GENDER_MALE) { - LOG_ERROR("sql.sql", "Spell {} listed in `spell_area` have wrong gender ({}) requirement", spell, spellArea.gender); + LOG_ERROR("db.query", "Spell {} listed in `spell_area` have wrong gender ({}) requirement", spell, spellArea.gender); continue; } @@ -2829,7 +2829,7 @@ void SpellMgr::LoadSpellInfoCustomAttributes() SpellInfo* spellInfo = _GetSpellInfo(spellId); if (!spellInfo) { - LOG_INFO("sql.sql", "Table `spell_custom_attr` has wrong spell (spell_id: {}), ignored.", spellId); + LOG_INFO("db.query", "Table `spell_custom_attr` has wrong spell (spell_id: {}), ignored.", spellId); continue; } @@ -2841,7 +2841,7 @@ void SpellMgr::LoadSpellInfoCustomAttributes() { if ((attributes & (SPELL_ATTR0_CU_NEGATIVE_EFF0 << i)) && (attributes & (SPELL_ATTR0_CU_POSITIVE_EFF0 << i))) { - LOG_ERROR("sql.sql", "Table `spell_custom_attr` has attribute SPELL_ATTR0_CU_NEGATIVE_EFF{} and SPELL_ATTR0_CU_POSITIVE_EFF{} attributes for spell {} which cannot stack together. Attributes will not get applied", static_cast(i), static_cast(i), spellId); + LOG_ERROR("db.query", "Table `spell_custom_attr` has attribute SPELL_ATTR0_CU_NEGATIVE_EFF{} and SPELL_ATTR0_CU_POSITIVE_EFF{} attributes for spell {} which cannot stack together. Attributes will not get applied", static_cast(i), static_cast(i), spellId); attributes &= ~(SPELL_ATTR0_CU_NEGATIVE_EFF0 << i)|(SPELL_ATTR0_CU_POSITIVE_EFF0 << i); } continue; @@ -2849,7 +2849,7 @@ void SpellMgr::LoadSpellInfoCustomAttributes() if (attributes & (SPELL_ATTR0_CU_NEGATIVE_EFF0 << i)) { - LOG_ERROR("sql.sql", "Table `spell_custom_attr` has attribute SPELL_ATTR0_CU_NEGATIVE_EFF{} for spell {} with no EFFECT_{}", static_cast(i), spellId, static_cast(i)); + LOG_ERROR("db.query", "Table `spell_custom_attr` has attribute SPELL_ATTR0_CU_NEGATIVE_EFF{} for spell {} with no EFFECT_{}", static_cast(i), spellId, static_cast(i)); attributes &= ~(SPELL_ATTR0_CU_NEGATIVE_EFF0 << i); } } @@ -2866,7 +2866,7 @@ void SpellMgr::LoadSpellInfoCustomAttributes() if ((attributes & (SPELL_ATTR0_CU_POSITIVE_EFF0 << i))) { - LOG_ERROR("sql.sql", "Table `spell_custom_attr` has attribute SPELL_ATTR0_CU_POSITIVE_EFF{} for spell {} with no EFFECT_{}", uint32(i), spellId, uint32(i)); + LOG_ERROR("db.query", "Table `spell_custom_attr` has attribute SPELL_ATTR0_CU_POSITIVE_EFF{} for spell {} with no EFFECT_{}", uint32(i), spellId, uint32(i)); attributes &= ~(SPELL_ATTR0_CU_POSITIVE_EFF0 << i); } } @@ -2874,7 +2874,7 @@ void SpellMgr::LoadSpellInfoCustomAttributes() if ((attributes & SPELL_ATTR0_CU_FORCE_AURA_SAVING) && (attributes & SPELL_ATTR0_CU_AURA_CANNOT_BE_SAVED)) { - LOG_ERROR("sql.sql", "Table `spell_custom_attr` attribute1 field has attributes SPELL_ATTR1_CU_FORCE_AURA_SAVING and SPELL_ATTR0_CU_AURA_CANNOT_BE_SAVED which cannot stack for spell {}. Both attributes will be ignored.", spellId); + LOG_ERROR("db.query", "Table `spell_custom_attr` attribute1 field has attributes SPELL_ATTR1_CU_FORCE_AURA_SAVING and SPELL_ATTR0_CU_AURA_CANNOT_BE_SAVED which cannot stack for spell {}. Both attributes will be ignored.", spellId); attributes &= ~(SPELL_ATTR0_CU_FORCE_AURA_SAVING | SPELL_ATTR0_CU_AURA_CANNOT_BE_SAVED); } diff --git a/src/server/game/Texts/CreatureTextMgr.cpp b/src/server/game/Texts/CreatureTextMgr.cpp index e477f4580366df..51f76225fda6fc 100644 --- a/src/server/game/Texts/CreatureTextMgr.cpp +++ b/src/server/game/Texts/CreatureTextMgr.cpp @@ -86,7 +86,7 @@ void CreatureTextMgr::LoadCreatureTexts() mTextMap.clear(); // for reload case mTextRepeatMap.clear(); //reset all currently used temp texts - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_CREATURE_TEXT); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_CREATURE_TEXT); PreparedQueryResult result = WorldDatabase.Query(stmt); if (!result) @@ -120,25 +120,25 @@ void CreatureTextMgr::LoadCreatureTexts() { if (!sSoundEntriesStore.LookupEntry(temp.sound)) { - LOG_ERROR("sql.sql", "CreatureTextMgr: Entry {}, Group {} in table `creature_texts` has Sound {} but sound does not exist.", temp.entry, temp.group, temp.sound); + LOG_ERROR("db.query", "CreatureTextMgr: Entry {}, Group {} in table `creature_texts` has Sound {} but sound does not exist.", temp.entry, temp.group, temp.sound); temp.sound = 0; } } if (!GetLanguageDescByID(temp.lang)) { - LOG_ERROR("sql.sql", "CreatureTextMgr: Entry {}, Group {} in table `creature_texts` using Language {} but Language does not exist.", temp.entry, temp.group, uint32(temp.lang)); + LOG_ERROR("db.query", "CreatureTextMgr: Entry {}, Group {} in table `creature_texts` using Language {} but Language does not exist.", temp.entry, temp.group, uint32(temp.lang)); temp.lang = LANG_UNIVERSAL; } if (temp.type >= MAX_CHAT_MSG_TYPE) { - LOG_ERROR("sql.sql", "CreatureTextMgr: Entry {}, Group {} in table `creature_texts` has Type {} but this Chat Type does not exist.", temp.entry, temp.group, uint32(temp.type)); + LOG_ERROR("db.query", "CreatureTextMgr: Entry {}, Group {} in table `creature_texts` has Type {} but this Chat Type does not exist.", temp.entry, temp.group, uint32(temp.type)); temp.type = CHAT_MSG_SAY; } if (temp.emote) { if (!sEmotesStore.LookupEntry(temp.emote)) { - LOG_ERROR("sql.sql", "CreatureTextMgr: Entry {}, Group {} in table `creature_texts` has Emote {} but emote does not exist.", temp.entry, temp.group, uint32(temp.emote)); + LOG_ERROR("db.query", "CreatureTextMgr: Entry {}, Group {} in table `creature_texts` has Emote {} but emote does not exist.", temp.entry, temp.group, uint32(temp.emote)); temp.emote = EMOTE_ONESHOT_NONE; } } @@ -146,13 +146,13 @@ void CreatureTextMgr::LoadCreatureTexts() { if (!sObjectMgr->GetBroadcastText(temp.BroadcastTextId)) { - LOG_ERROR("sql.sql", "CreatureTextMgr: Entry {}, Group {}, Id {} in table `creature_text` has non-existing or incompatible BroadcastTextId {}.", temp.entry, temp.group, temp.id, temp.BroadcastTextId); + LOG_ERROR("db.query", "CreatureTextMgr: Entry {}, Group {}, Id {} in table `creature_text` has non-existing or incompatible BroadcastTextId {}.", temp.entry, temp.group, temp.id, temp.BroadcastTextId); temp.BroadcastTextId = 0; } } if (temp.TextRange > TEXT_RANGE_WORLD) { - LOG_ERROR("sql.sql", "CreatureTextMgr: Entry {}, Group {}, Id {} in table `creature_text` has incorrect TextRange {}.", temp.entry, temp.group, temp.id, temp.TextRange); + LOG_ERROR("db.query", "CreatureTextMgr: Entry {}, Group {}, Id {} in table `creature_text` has incorrect TextRange {}.", temp.entry, temp.group, temp.id, temp.TextRange); temp.TextRange = TEXT_RANGE_NORMAL; } @@ -205,7 +205,7 @@ uint32 CreatureTextMgr::SendChat(Creature* source, uint8 textGroup, WorldObject CreatureTextMap::const_iterator sList = mTextMap.find(source->GetEntry()); if (sList == mTextMap.end()) { - LOG_ERROR("sql.sql", "CreatureTextMgr: Could not find Text for Creature({}) Entry {} in 'creature_text' table. Ignoring.", source->GetName(), source->GetEntry()); + LOG_ERROR("db.query", "CreatureTextMgr: Could not find Text for Creature({}) Entry {} in 'creature_text' table. Ignoring.", source->GetName(), source->GetEntry()); return 0; } @@ -213,7 +213,7 @@ uint32 CreatureTextMgr::SendChat(Creature* source, uint8 textGroup, WorldObject CreatureTextHolder::const_iterator itr = textHolder.find(textGroup); if (itr == textHolder.end()) { - LOG_ERROR("sql.sql", "CreatureTextMgr: Could not find TextGroup {} for Creature {} ({}). Ignoring.", + LOG_ERROR("db.query", "CreatureTextMgr: Could not find TextGroup {} for Creature {} ({}). Ignoring.", uint32(textGroup), source->GetName(), source->GetGUID().ToString()); return 0; } @@ -420,7 +420,7 @@ void CreatureTextMgr::SetRepeatId(Creature* source, uint8 textGroup, uint8 id) if (std::find(repeats.begin(), repeats.end(), id) == repeats.end()) repeats.push_back(id); else - LOG_ERROR("sql.sql", "CreatureTextMgr: TextGroup {} for Creature {} ({}), id {} already added", + LOG_ERROR("db.query", "CreatureTextMgr: TextGroup {} for Creature {} ({}), id {} already added", uint32(textGroup), source->GetName(), source->GetGUID().ToString(), uint32(id)); } diff --git a/src/server/game/Tickets/TicketMgr.cpp b/src/server/game/Tickets/TicketMgr.cpp index 9b19143ac8bf99..7a2e17698161fb 100644 --- a/src/server/game/Tickets/TicketMgr.cpp +++ b/src/server/game/Tickets/TicketMgr.cpp @@ -80,7 +80,7 @@ void GmTicket::SaveToDB(CharacterDatabaseTransaction trans) const // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // id, type, playerGuid, name, description, createTime, mapId, posX, posY, posZ, lastModifiedTime, closedBy, assignedTo, comment, response, completed, escalated, viewed, needMoreHelp, resolvedBy uint8 index = 0; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_GM_TICKET); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_GM_TICKET); stmt->SetData( index, _id); stmt->SetData (++index, uint8(_type)); stmt->SetData(++index, _playerGuid.GetCounter()); @@ -107,7 +107,7 @@ void GmTicket::SaveToDB(CharacterDatabaseTransaction trans) const void GmTicket::DeleteFromDB() { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GM_TICKET); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GM_TICKET); stmt->SetData(0, _id); CharacterDatabase.Execute(stmt); } @@ -293,7 +293,7 @@ void TicketMgr::ResetTickets() _lastTicketId = 0; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ALL_GM_TICKETS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ALL_GM_TICKETS); CharacterDatabase.Execute(stmt); } @@ -309,7 +309,7 @@ void TicketMgr::LoadTickets() _lastTicketId = 0; _openTicketCount = 0; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GM_TICKETS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GM_TICKETS); PreparedQueryResult result = CharacterDatabase.Query(stmt); if (!result) { diff --git a/src/server/game/Tools/CharacterDatabaseCleaner.cpp b/src/server/game/Tools/CharacterDatabaseCleaner.cpp index 794135b21a6f13..0ccb0f6b11e15e 100644 --- a/src/server/game/Tools/CharacterDatabaseCleaner.cpp +++ b/src/server/game/Tools/CharacterDatabaseCleaner.cpp @@ -72,7 +72,7 @@ void CharacterDatabaseCleaner::CheckUnique(const char* column, const char* table QueryResult result = CharacterDatabase.Query("SELECT DISTINCT {} FROM {}", column, table); if (!result) { - LOG_INFO("sql.sql", "Table {} is empty.", table); + LOG_INFO("db.query", "Table {} is empty.", table); return; } diff --git a/src/server/game/Tools/PlayerDump.cpp b/src/server/game/Tools/PlayerDump.cpp index f1e4cb388a65f5..acf0fe525b9db0 100644 --- a/src/server/game/Tools/PlayerDump.cpp +++ b/src/server/game/Tools/PlayerDump.cpp @@ -773,7 +773,7 @@ DumpReturn PlayerDumpReader::LoadDump(std::istream& input, uint32 account, std:: bool incHighest = true; if (guid && guid < sObjectMgr->GetGenerator().GetNextAfterMaxUsed()) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHECK_GUID); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHECK_GUID); stmt->SetData(0, guid); if (PreparedQueryResult result = CharacterDatabase.Query(stmt)) @@ -790,7 +790,7 @@ DumpReturn PlayerDumpReader::LoadDump(std::istream& input, uint32 account, std:: if (ObjectMgr::CheckPlayerName(name, true) == CHAR_NAME_SUCCESS) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHECK_NAME); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHECK_NAME); stmt->SetData(0, name); if (PreparedQueryResult result = CharacterDatabase.Query(stmt)) diff --git a/src/server/game/Warden/WardenCheckMgr.cpp b/src/server/game/Warden/WardenCheckMgr.cpp index 30165978191f81..e9df60901c65ef 100644 --- a/src/server/game/Warden/WardenCheckMgr.cpp +++ b/src/server/game/Warden/WardenCheckMgr.cpp @@ -74,7 +74,7 @@ void WardenCheckMgr::LoadWardenChecks() if (checkType == LUA_EVAL_CHECK && id > 9999) { - LOG_ERROR("warden", "sql.sql: Warden Lua check with id {} found in `warden_checks`. Lua checks may have four-digit IDs at most. Skipped.", id); + LOG_ERROR("warden", "Warden Lua check with id {} found in `warden_checks`. Lua checks may have four-digit IDs at most. Skipped.", id); continue; } @@ -133,7 +133,7 @@ void WardenCheckMgr::LoadWardenChecks() { if (wardenCheck.Length > WARDEN_MAX_LUA_CHECK_LENGTH) { - LOG_ERROR("warden", "sql.sql: Found over-long Lua check for Warden check with id {} in `warden_checks`. Max length is {}. Skipped.", id, WARDEN_MAX_LUA_CHECK_LENGTH); + LOG_ERROR("warden", "Found over-long Lua check for Warden check with id {} in `warden_checks`. Max length is {}. Skipped.", id, WARDEN_MAX_LUA_CHECK_LENGTH); continue; } diff --git a/src/server/game/Weather/WeatherMgr.cpp b/src/server/game/Weather/WeatherMgr.cpp index af3035deb42c8e..94dde857fce43b 100644 --- a/src/server/game/Weather/WeatherMgr.cpp +++ b/src/server/game/Weather/WeatherMgr.cpp @@ -27,6 +27,7 @@ #include "Weather.h" #include "WorldPacket.h" #include "WorldSession.h" +#include "DatabaseEnv.h" #include namespace WeatherMgr @@ -118,19 +119,19 @@ namespace WeatherMgr if (wzc.data[season].rainChance > 100) { wzc.data[season].rainChance = 25; - LOG_ERROR("sql.sql", "Weather for zone {} season {} has wrong rain chance > 100%", zone_id, season); + LOG_ERROR("db.query", "Weather for zone {} season {} has wrong rain chance > 100%", zone_id, season); } if (wzc.data[season].snowChance > 100) { wzc.data[season].snowChance = 25; - LOG_ERROR("sql.sql", "Weather for zone {} season {} has wrong snow chance > 100%", zone_id, season); + LOG_ERROR("db.query", "Weather for zone {} season {} has wrong snow chance > 100%", zone_id, season); } if (wzc.data[season].stormChance > 100) { wzc.data[season].stormChance = 25; - LOG_ERROR("sql.sql", "Weather for zone {} season {} has wrong storm chance > 100%", zone_id, season); + LOG_ERROR("db.query", "Weather for zone {} season {} has wrong storm chance > 100%", zone_id, season); } } diff --git a/src/server/game/World/World.cpp b/src/server/game/World/World.cpp index 559186f0177ebd..743574e91f2a90 100644 --- a/src/server/game/World/World.cpp +++ b/src/server/game/World/World.cpp @@ -41,6 +41,7 @@ #include "CreatureAIRegistry.h" #include "CreatureGroups.h" #include "CreatureTextMgr.h" +#include "DatabaseMgr.h" #include "DBCStores.h" #include "DatabaseEnv.h" #include "DisableMgr.h" @@ -2059,8 +2060,6 @@ void World::SetInitialWorldSettings() // clean logs table every 14 days by default _timers[WUPDATE_AUTOBROADCAST].SetInterval(getIntConfig(CONFIG_AUTOBROADCAST_INTERVAL)); - _timers[WUPDATE_PINGDB].SetInterval(getIntConfig(CONFIG_DB_PING_INTERVAL)*MINUTE * IN_MILLISECONDS); // Mysql ping time in minutes - // our speed up _timers[WUPDATE_5_SECS].SetInterval(5 * IN_MILLISECONDS); @@ -2240,7 +2239,7 @@ void World::LoadMotd() uint32 oldMSTime = getMSTime(); uint32 realmId = sConfigMgr->GetOption("RealmID", 0); - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_MOTD); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_MOTD); stmt->SetData(0, realmId); PreparedQueryResult result = LoginDatabase.Query(stmt); std::string motd; @@ -2299,7 +2298,7 @@ void World::Update(uint32 diff) _timers[WUPDATE_5_SECS].Reset(); // moved here from HandleCharEnumOpcode - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_EXPIRED_BANS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_EXPIRED_BANS); CharacterDatabase.Execute(stmt); } @@ -2389,7 +2388,7 @@ void World::Update(uint32 diff) _timers[WUPDATE_CLEANDB].Reset(); - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_OLD_LOGS); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_OLD_LOGS); stmt->SetData(0, sWorld->getIntConfig(CONFIG_LOGDB_CLEARTIME)); stmt->SetData(1, uint32(currentGameTime.count())); LoginDatabase.Execute(stmt); @@ -2450,7 +2449,7 @@ void World::Update(uint32 diff) _timers[WUPDATE_UPTIME].Reset(); - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_UPTIME_PLAYERS); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_UPTIME_PLAYERS); stmt->SetData(0, uint32(GameTime::GetUptime().count())); stmt->SetData(1, uint16(GetMaxPlayerCount())); stmt->SetData(2, realm.Id.Realm); @@ -2480,17 +2479,6 @@ void World::Update(uint32 diff) _timers[WUPDATE_EVENTS].Reset(); } - ///- Ping to keep MySQL connections alive - if (_timers[WUPDATE_PINGDB].Passed()) - { - METRIC_TIMER("world_update_time", METRIC_TAG("type", "Ping MySQL")); - _timers[WUPDATE_PINGDB].Reset(); - LOG_DEBUG("sql.driver", "Ping MySQL to keep connection alive"); - CharacterDatabase.KeepAlive(); - LoginDatabase.KeepAlive(); - WorldDatabase.KeepAlive(); - } - { METRIC_TIMER("world_update_time", METRIC_TAG("type", "Update instance reset times")); // update the instance reset times @@ -2513,6 +2501,11 @@ void World::Update(uint32 diff) playersSaveScheduler.Update(diff); } + { + METRIC_TIMER("world_update_time", METRIC_TAG("type", "Update db mgr")); + sDatabaseMgr->Update(Milliseconds{ diff }); + } + { METRIC_TIMER("world_update_time", METRIC_TAG("type", "Update metrics")); // Stats logger update @@ -2994,7 +2987,7 @@ void World::ProcessCliCommands() void World::UpdateRealmCharCount(uint32 accountId) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_COUNT); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_COUNT); stmt->SetData(0, accountId); _queryProcessor.AddCallback(CharacterDatabase.AsyncQuery(stmt).WithPreparedCallback(std::bind(&World::_UpdateRealmCharCount, this, std::placeholders::_1))); } @@ -3009,7 +3002,7 @@ void World::_UpdateRealmCharCount(PreparedQueryResult resultCharCount) LoginDatabaseTransaction trans = LoginDatabase.BeginTransaction(); - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_REP_REALM_CHARACTERS); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_REP_REALM_CHARACTERS); stmt->SetData(0, charCount); stmt->SetData(1, accountId); stmt->SetData(2, realm.Id.Realm); @@ -3087,7 +3080,7 @@ void World::InitGuildResetTime() void World::ResetDailyQuests() { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_DAILY); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_DAILY); CharacterDatabase.Execute(stmt); for (SessionMap::const_iterator itr = _sessions.begin(); itr != _sessions.end(); ++itr) @@ -3103,7 +3096,7 @@ void World::ResetDailyQuests() void World::LoadDBAllowedSecurityLevel() { - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_REALMLIST_SECURITY_LEVEL); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_REALMLIST_SECURITY_LEVEL); stmt->SetData(0, int32(realm.Id.Realm)); PreparedQueryResult result = LoginDatabase.Query(stmt); @@ -3122,7 +3115,7 @@ void World::SetPlayerSecurityLimit(AccountTypes _sec) void World::ResetWeeklyQuests() { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_WEEKLY); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_WEEKLY); CharacterDatabase.Execute(stmt); for (SessionMap::const_iterator itr = _sessions.begin(); itr != _sessions.end(); ++itr) @@ -3140,7 +3133,7 @@ void World::ResetMonthlyQuests() { LOG_INFO("server.worldserver", "Monthly quests reset for all characters."); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_MONTHLY); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_MONTHLY); CharacterDatabase.Execute(stmt); for (SessionMap::const_iterator itr = _sessions.begin(); itr != _sessions.end(); ++itr) @@ -3153,7 +3146,7 @@ void World::ResetMonthlyQuests() void World::ResetEventSeasonalQuests(uint16 event_id) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_SEASONAL); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_SEASONAL); stmt->SetData(0, event_id); CharacterDatabase.Execute(stmt); @@ -3166,7 +3159,7 @@ void World::ResetRandomBG() { LOG_DEBUG("server.worldserver", "Random BG status reset for all characters."); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_BATTLEGROUND_RANDOM); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_BATTLEGROUND_RANDOM); CharacterDatabase.Execute(stmt); for (SessionMap::const_iterator itr = _sessions.begin(); itr != _sessions.end(); ++itr) @@ -3259,14 +3252,14 @@ void World::setWorldState(uint32 index, uint64 timeValue) auto const& it = _worldstates.find(index); if (it != _worldstates.end()) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_WORLDSTATE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_WORLDSTATE); stmt->SetData(0, uint32(timeValue)); stmt->SetData(1, index); CharacterDatabase.Execute(stmt); } else { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_WORLDSTATE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_WORLDSTATE); stmt->SetData(0, index); stmt->SetData(1, uint32(timeValue)); CharacterDatabase.Execute(stmt); diff --git a/src/server/game/World/World.h b/src/server/game/World/World.h index f8e0de9b821a6b..f1ba915af19bed 100644 --- a/src/server/game/World/World.h +++ b/src/server/game/World/World.h @@ -67,7 +67,6 @@ enum WorldTimers WUPDATE_CLEANDB, WUPDATE_AUTOBROADCAST, WUPDATE_MAILBOXQUEUE, - WUPDATE_PINGDB, WUPDATE_5_SECS, WUPDATE_WHO_LIST, WUPDATE_COUNT diff --git a/src/server/scripts/Commands/cs_account.cpp b/src/server/scripts/Commands/cs_account.cpp index 1b042b11bdbc52..d5228fbcd325da 100644 --- a/src/server/scripts/Commands/cs_account.cpp +++ b/src/server/scripts/Commands/cs_account.cpp @@ -28,14 +28,13 @@ EndScriptData */ #include "Chat.h" #include "CryptoGenerics.h" #include "IPLocation.h" -#include "Language.h" #include "Player.h" #include "Realm.h" #include "ScriptMgr.h" #include "SecretMgr.h" #include "StringConvert.h" #include "TOTP.h" -#include +#include "DatabaseEnv.h" #include #if AC_COMPILER == AC_COMPILER_GNU @@ -120,7 +119,7 @@ class account_commandscript : public CommandScript uint32 const accountId = handler->GetSession()->GetAccountId(); { // check if 2FA already enabled - auto* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_TOTP_SECRET); + auto stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_TOTP_SECRET); stmt->SetData(0, accountId); PreparedQueryResult result = LoginDatabase.Query(stmt); @@ -154,7 +153,7 @@ class account_commandscript : public CommandScript if (masterKey) Acore::Crypto::AEEncryptWithRandomIV(pair.first->second, *masterKey); - auto* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_TOTP_SECRET); + auto stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_TOTP_SECRET); stmt->SetData(0, pair.first->second); stmt->SetData(1, accountId); LoginDatabase.Execute(stmt); @@ -195,7 +194,7 @@ class account_commandscript : public CommandScript uint32 const accountId = handler->GetSession()->GetAccountId(); Acore::Crypto::TOTP::Secret secret; { // get current TOTP secret - auto* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_TOTP_SECRET); + auto stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_TOTP_SECRET); stmt->SetData(0, accountId); PreparedQueryResult result = LoginDatabase.Query(stmt); @@ -234,7 +233,7 @@ class account_commandscript : public CommandScript if (Acore::Crypto::TOTP::ValidateToken(secret, *token)) { - auto* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_TOTP_SECRET); + auto stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_TOTP_SECRET); stmt->SetData(0); stmt->SetData(1, accountId); LoginDatabase.Execute(stmt); @@ -271,7 +270,7 @@ class account_commandscript : public CommandScript return false; } - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_EXPANSION); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_EXPANSION); stmt->SetData(0, *expansion); stmt->SetData(1, accountId); @@ -392,7 +391,7 @@ class account_commandscript : public CommandScript static bool HandleAccountOnlineListCommand(ChatHandler* handler, char const* /*args*/) { ///- Get the list of accounts ID logged to the realm - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_ONLINE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_ONLINE); PreparedQueryResult result = CharacterDatabase.Query(stmt); @@ -416,7 +415,7 @@ class account_commandscript : public CommandScript ///- Get the username, last IP and GM level of each account // No SQL injection. account is uint32. - LoginDatabasePreparedStatement* loginStmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_INFO); + LoginDatabasePreparedStatement loginStmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_INFO); loginStmt->SetData(0, account); PreparedQueryResult resultLogin = LoginDatabase.Query(loginStmt); @@ -466,7 +465,7 @@ class account_commandscript : public CommandScript return false; } - auto* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_LOCK_COUNTRY); + auto stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_LOCK_COUNTRY); stmt->SetData(0, "00"); stmt->SetData(1, accountId); LoginDatabase.Execute(stmt); @@ -492,7 +491,7 @@ class account_commandscript : public CommandScript { if (IpLocationRecord const* location = sIPLocation->GetLocationRecord(handler->GetSession()->GetRemoteAddress())) { - auto* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_LOCK_COUNTRY); + auto stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_LOCK_COUNTRY); stmt->SetData(0, location->CountryCode); stmt->SetData(1, handler->GetSession()->GetAccountId()); LoginDatabase.Execute(stmt); @@ -507,7 +506,7 @@ class account_commandscript : public CommandScript } else if (param == "off") { - auto* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_LOCK_COUNTRY); + auto stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_LOCK_COUNTRY); stmt->SetData(0, "00"); stmt->SetData(1, handler->GetSession()->GetAccountId()); LoginDatabase.Execute(stmt); @@ -534,7 +533,7 @@ class account_commandscript : public CommandScript if (!param.empty()) { - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_LOCK); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_LOCK); if (param == "on") { @@ -657,7 +656,7 @@ class account_commandscript : public CommandScript if (secret == "off") { - auto* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_TOTP_SECRET); + auto stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_TOTP_SECRET); stmt->SetData(0); stmt->SetData(1, targetAccountId); LoginDatabase.Execute(stmt); @@ -691,7 +690,7 @@ class account_commandscript : public CommandScript if (masterKey) Acore::Crypto::AEEncryptWithRandomIV(*decoded, *masterKey); - auto* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_TOTP_SECRET); + auto stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_TOTP_SECRET); stmt->SetData(0, *decoded); stmt->SetData(1, targetAccountId); LoginDatabase.Execute(stmt); @@ -760,7 +759,7 @@ class account_commandscript : public CommandScript if (!expansion || *expansion > sWorld->getIntConfig(CONFIG_EXPANSION)) return false; - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_EXPANSION); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_EXPANSION); stmt->SetData(0, *expansion); stmt->SetData(1, accountId); @@ -839,7 +838,7 @@ class account_commandscript : public CommandScript // Check and abort if the target gm has a higher rank on one of the realms and the new realm is -1 if (gmRealmID == -1 && !AccountMgr::IsConsoleAccount(playerSecurity)) { - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_ACCESS_GMLEVEL_TEST); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_ACCESS_GMLEVEL_TEST); stmt->SetData(0, targetAccountId); stmt->SetData(1, uint8(gm)); @@ -863,7 +862,7 @@ class account_commandscript : public CommandScript } // If gmRealmID is -1, delete all values for the account id, else, insert values for the specific realm.Id.Realm - LoginDatabasePreparedStatement* stmt; + LoginDatabasePreparedStatement stmt; if (gmRealmID == -1) { diff --git a/src/server/scripts/Commands/cs_achievement.cpp b/src/server/scripts/Commands/cs_achievement.cpp index 070ae2d4f163ea..ada86bec5d15ac 100644 --- a/src/server/scripts/Commands/cs_achievement.cpp +++ b/src/server/scripts/Commands/cs_achievement.cpp @@ -24,9 +24,9 @@ EndScriptData */ #include "AchievementMgr.h" #include "Chat.h" -#include "Language.h" #include "Player.h" #include "ScriptMgr.h" +#include "DatabaseEnv.h" using namespace Acore::ChatCommands; @@ -84,7 +84,7 @@ class achievement_commandscript : public CommandScript } else { - auto* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG); + auto stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG); stmt->SetData(0, uint16(AT_LOGIN_CHECK_ACHIEVS)); stmt->SetData(1, player->GetGUID().GetCounter()); CharacterDatabase.Execute(stmt); diff --git a/src/server/scripts/Commands/cs_ban.cpp b/src/server/scripts/Commands/cs_ban.cpp index d8a596b336b3bf..cb6a82ed20cdbf 100644 --- a/src/server/scripts/Commands/cs_ban.cpp +++ b/src/server/scripts/Commands/cs_ban.cpp @@ -27,11 +27,11 @@ EndScriptData */ #include "CharacterCache.h" #include "Chat.h" #include "GameTime.h" -#include "Language.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Player.h" #include "ScriptMgr.h" +#include "DatabaseEnv.h" /// Ban function modes enum BanMode @@ -338,7 +338,7 @@ class ban_commandscript : public CommandScript else targetGuid = target->GetGUID(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_BANINFO); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_BANINFO); stmt->SetData(0, targetGuid.GetCounter()); PreparedQueryResult result = CharacterDatabase.Query(stmt); @@ -405,7 +405,7 @@ class ban_commandscript : public CommandScript static bool HandleBanListAccountCommand(ChatHandler* handler, char const* args) { - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_EXPIRED_IP_BANS); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_EXPIRED_IP_BANS); LoginDatabase.Execute(stmt); char* filterStr = strtok((char*)args, " "); @@ -415,12 +415,12 @@ class ban_commandscript : public CommandScript if (filter.empty()) { - LoginDatabasePreparedStatement* stmt2 = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_BANNED_ALL); + LoginDatabasePreparedStatement stmt2 = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_BANNED_ALL); result = LoginDatabase.Query(stmt2); } else { - LoginDatabasePreparedStatement* stmt2 = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_BANNED_BY_USERNAME); + LoginDatabasePreparedStatement stmt2 = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_BANNED_BY_USERNAME); stmt2->SetData(0, filter); result = LoginDatabase.Query(stmt2); } @@ -518,7 +518,7 @@ class ban_commandscript : public CommandScript return false; std::string filter(filterStr); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GUID_BY_NAME_FILTER); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GUID_BY_NAME_FILTER); stmt->SetData(0, filter); PreparedQueryResult result = CharacterDatabase.Query(stmt); if (!result) @@ -535,7 +535,7 @@ class ban_commandscript : public CommandScript do { Field* fields = result->Fetch(); - CharacterDatabasePreparedStatement* stmt2 = CharacterDatabase.GetPreparedStatement(CHAR_SEL_BANNED_NAME); + CharacterDatabasePreparedStatement stmt2 = CharacterDatabase.GetPreparedStatement(CHAR_SEL_BANNED_NAME); stmt2->SetData(0, fields[0].Get()); PreparedQueryResult banResult = CharacterDatabase.Query(stmt2); @@ -557,7 +557,7 @@ class ban_commandscript : public CommandScript std::string char_name = fields[1].Get(); - CharacterDatabasePreparedStatement* stmt2 = CharacterDatabase.GetPreparedStatement(CHAR_SEL_BANINFO_LIST); + CharacterDatabasePreparedStatement stmt2 = CharacterDatabase.GetPreparedStatement(CHAR_SEL_BANINFO_LIST); stmt2->SetData(0, fields[0].Get()); PreparedQueryResult banInfo = CharacterDatabase.Query(stmt2); @@ -593,7 +593,7 @@ class ban_commandscript : public CommandScript static bool HandleBanListIPCommand(ChatHandler* handler, char const* args) { - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_EXPIRED_IP_BANS); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_EXPIRED_IP_BANS); LoginDatabase.Execute(stmt); char* filterStr = strtok((char*)args, " "); @@ -604,12 +604,12 @@ class ban_commandscript : public CommandScript if (filter.empty()) { - LoginDatabasePreparedStatement* stmt2 = LoginDatabase.GetPreparedStatement(LOGIN_SEL_IP_BANNED_ALL); + LoginDatabasePreparedStatement stmt2 = LoginDatabase.GetPreparedStatement(LOGIN_SEL_IP_BANNED_ALL); result = LoginDatabase.Query(stmt2); } else { - LoginDatabasePreparedStatement* stmt2 = LoginDatabase.GetPreparedStatement(LOGIN_SEL_IP_BANNED_BY_IP); + LoginDatabasePreparedStatement stmt2 = LoginDatabase.GetPreparedStatement(LOGIN_SEL_IP_BANNED_BY_IP); stmt2->SetData(0, filter); result = LoginDatabase.Query(stmt2); } diff --git a/src/server/scripts/Commands/cs_character.cpp b/src/server/scripts/Commands/cs_character.cpp index 631e52713dea87..6cd49f65898c0f 100644 --- a/src/server/scripts/Commands/cs_character.cpp +++ b/src/server/scripts/Commands/cs_character.cpp @@ -114,7 +114,7 @@ class character_commandscript : public CommandScript static bool GetDeletedCharacterInfoList(DeletedInfoList& foundList, std::string searchString) { PreparedQueryResult result; - CharacterDatabasePreparedStatement* stmt = nullptr; + CharacterDatabasePreparedStatement stmt = nullptr; if (!searchString.empty()) { // search by GUID @@ -232,7 +232,7 @@ class character_commandscript : public CommandScript return; } - auto* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UDP_RESTORE_DELETE_INFO); + auto stmt = CharacterDatabase.GetPreparedStatement(CHAR_UDP_RESTORE_DELETE_INFO); stmt->SetData(0, delInfo.name); stmt->SetData(1, delInfo.accountId); stmt->SetData(2, delInfo.lowGuid); @@ -267,7 +267,7 @@ class character_commandscript : public CommandScript else { // Update level and reset XP, everything else will be updated at login - auto* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_LEVEL); + auto stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_LEVEL); stmt->SetData(0, uint8(newLevel)); stmt->SetData(1, playerGuid.GetCounter()); CharacterDatabase.Execute(stmt); @@ -370,7 +370,7 @@ class character_commandscript : public CommandScript return false; } - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHECK_NAME); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHECK_NAME); stmt->SetData(0, newName); PreparedQueryResult result = CharacterDatabase.Query(stmt); if (result) @@ -421,7 +421,7 @@ class character_commandscript : public CommandScript handler->PSendSysMessage(LANG_RENAME_PLAYER_GUID, handler->playerLink(*player).c_str(), player->GetGUID().GetCounter()); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG); stmt->SetData(0, uint16(AT_LOGIN_RENAME)); stmt->SetData(1, player->GetGUID().GetCounter()); CharacterDatabase.Execute(stmt); @@ -476,7 +476,7 @@ class character_commandscript : public CommandScript else { handler->PSendSysMessage(LANG_CUSTOMIZE_PLAYER_GUID, handler->playerLink(*player).c_str(), player->GetGUID().GetCounter()); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG); stmt->SetData(0, static_cast(AT_LOGIN_CUSTOMIZE)); stmt->SetData(1, player->GetGUID().GetCounter()); CharacterDatabase.Execute(stmt); @@ -500,7 +500,7 @@ class character_commandscript : public CommandScript else { handler->PSendSysMessage(LANG_CUSTOMIZE_PLAYER_GUID, handler->playerLink(*player).c_str(), player->GetGUID().GetCounter()); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG); stmt->SetData(0, uint16(AT_LOGIN_CHANGE_FACTION)); stmt->SetData(1, player->GetGUID().GetCounter()); CharacterDatabase.Execute(stmt); @@ -524,7 +524,7 @@ class character_commandscript : public CommandScript else { handler->PSendSysMessage(LANG_CUSTOMIZE_PLAYER_GUID, handler->playerLink(*player).c_str(), player->GetGUID().GetCounter()); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG); stmt->SetData(0, uint16(AT_LOGIN_CHANGE_RACE)); stmt->SetData(1, player->GetGUID().GetCounter()); CharacterDatabase.Execute(stmt); diff --git a/src/server/scripts/Commands/cs_db.cpp b/src/server/scripts/Commands/cs_db.cpp new file mode 100644 index 00000000000000..ea9af144a95574 --- /dev/null +++ b/src/server/scripts/Commands/cs_db.cpp @@ -0,0 +1,98 @@ +/* + * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU Affero General Public License as published by the + * Free Software Foundation; either version 3 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "Chat.h" +#include "DatabaseEnv.h" +#include "ScriptMgr.h" + +using namespace Acore::ChatCommands; + +class db_commandscript : public CommandScript +{ +public: + db_commandscript() : CommandScript("db_commandscript") { } + + [[nodiscard]] ChatCommandTable GetCommands() const override + { + static ChatCommandTable dbCommandTable = + { + { "info", HandleDBInfoCommand, SEC_ADMINISTRATOR, Console::Yes }, + { "add dynamic connects", HandleDBAddDynamicConnectsCommand, SEC_ADMINISTRATOR, Console::Yes }, + }; + + static ChatCommandTable commandTable = + { + { "db", dbCommandTable }, + }; + + return commandTable; + } + + static bool HandleDBInfoCommand(ChatHandler* handler) + { + LoginDatabase.GetPoolInfo([handler](std::string_view info) + { + handler->PSendSysMessage(Acore::StringFormatFmt("# {}", info).c_str()); + }); + + handler->PSendSysMessage("# --"); + + CharacterDatabase.GetPoolInfo([handler](std::string_view info) + { + handler->PSendSysMessage(Acore::StringFormatFmt("# {}", info).c_str()); + }); + + handler->PSendSysMessage("# --"); + + WorldDatabase.GetPoolInfo([handler](std::string_view info) + { + handler->PSendSysMessage(Acore::StringFormatFmt("# {}", info).c_str()); + }); + + handler->PSendSysMessage("# --"); + return true; + } + + static bool HandleDBAddDynamicConnectsCommand(ChatHandler* handler, uint8 dbType, bool isAsync) + { + switch (dbType) + { + case 1: + isAsync ? LoginDatabase.OpenDynamicAsyncConnect() : LoginDatabase.OpenDynamicSyncConnect(); + handler->PSendSysMessage(Acore::StringFormatFmt("Added new {} dynamic connection for {} DB", isAsync ? "async" : "sync", LoginDatabase.GetPoolName()).c_str()); + break; + case 2: + isAsync ? CharacterDatabase.OpenDynamicAsyncConnect() : CharacterDatabase.OpenDynamicSyncConnect(); + handler->PSendSysMessage(Acore::StringFormatFmt("Added new {} dynamic connection for {} DB", isAsync ? "async" : "sync", CharacterDatabase.GetPoolName()).c_str()); + break; + case 3: + isAsync ? WorldDatabase.OpenDynamicAsyncConnect() : WorldDatabase.OpenDynamicSyncConnect(); + handler->PSendSysMessage(Acore::StringFormatFmt("Added new {} dynamic connection for {} DB", isAsync ? "async" : "sync", WorldDatabase.GetPoolName()).c_str()); + break; + default: + handler->PSendSysMessage(Acore::StringFormatFmt("Incorrect db type: {}", dbType).c_str()); + break; + } + + return true; + } +}; + +void AddSC_db_commandscript() +{ + new db_commandscript(); +} diff --git a/src/server/scripts/Commands/cs_debug.cpp b/src/server/scripts/Commands/cs_debug.cpp index f713503deda97a..866bfca98583c7 100644 --- a/src/server/scripts/Commands/cs_debug.cpp +++ b/src/server/scripts/Commands/cs_debug.cpp @@ -1261,9 +1261,7 @@ class debug_commandscript : public CommandScript static bool HandleWPGPSCommand(ChatHandler* handler) { Player* player = handler->GetSession()->GetPlayer(); - - LOG_INFO("sql.dev", "(@PATH, XX, {0:.3f}, {0:.3f}, {0:.5f}, 0,0, 0,100, 0),", player->GetPositionX(), player->GetPositionY(), player->GetPositionZ()); - + LOG_INFO("db.query", "(@PATH, XX, {0:.3f}, {0:.3f}, {0:.5f}, 0,0, 0,100, 0),", player->GetPositionX(), player->GetPositionY(), player->GetPositionZ()); handler->PSendSysMessage("Waypoint SQL written to SQL Developer log"); return true; } diff --git a/src/server/scripts/Commands/cs_deserter.cpp b/src/server/scripts/Commands/cs_deserter.cpp index b884565ee36b40..7748e4035f3cdb 100644 --- a/src/server/scripts/Commands/cs_deserter.cpp +++ b/src/server/scripts/Commands/cs_deserter.cpp @@ -23,10 +23,10 @@ */ #include "Chat.h" -#include "Language.h" #include "Player.h" #include "ScriptMgr.h" #include "SpellAuras.h" +#include "DatabaseEnv.h" using namespace Acore::ChatCommands; @@ -195,7 +195,7 @@ class deserter_commandscript : public CommandScript } uint8 index = 0; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_AURA); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_AURA); stmt->SetData(index++, guid.GetCounter()); stmt->SetData(index++, guid.GetCounter()); stmt->SetData(index++, 0); diff --git a/src/server/scripts/Commands/cs_disable.cpp b/src/server/scripts/Commands/cs_disable.cpp index 30b28f12e3b031..b791e89b802b32 100644 --- a/src/server/scripts/Commands/cs_disable.cpp +++ b/src/server/scripts/Commands/cs_disable.cpp @@ -25,12 +25,12 @@ EndScriptData */ #include "AchievementMgr.h" #include "Chat.h" #include "DisableMgr.h" -#include "Language.h" #include "ObjectMgr.h" #include "OutdoorPvP.h" #include "Player.h" #include "ScriptMgr.h" #include "SpellMgr.h" +#include "DatabaseEnv.h" using namespace Acore::ChatCommands; @@ -147,7 +147,7 @@ class disable_commandscript : public CommandScript break; } - WorldDatabasePreparedStatement* stmt = nullptr; + WorldDatabasePreparedStatement stmt = nullptr; stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_DISABLES); stmt->SetData(0, entry); stmt->SetData(1, disableType); @@ -235,7 +235,7 @@ class disable_commandscript : public CommandScript break; } - WorldDatabasePreparedStatement* stmt = nullptr; + WorldDatabasePreparedStatement stmt = nullptr; stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_DISABLES); stmt->SetData(0, entry); stmt->SetData(1, disableType); diff --git a/src/server/scripts/Commands/cs_gear.cpp b/src/server/scripts/Commands/cs_gear.cpp index 6e3e4c97cfe8dc..b4451e79565036 100644 --- a/src/server/scripts/Commands/cs_gear.cpp +++ b/src/server/scripts/Commands/cs_gear.cpp @@ -21,6 +21,7 @@ #include "Player.h" #include "ScriptMgr.h" #include "WorldSession.h" +#include "DatabaseEnv.h" using namespace Acore::ChatCommands; @@ -92,7 +93,7 @@ class gear_commandscript : public CommandScript if (sWorld->getIntConfig(CONFIG_MIN_LEVEL_STAT_SAVE)) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_STATS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_STATS); stmt->SetData(0, player->GetGUID().GetCounter()); PreparedQueryResult result = CharacterDatabase.Query(stmt); diff --git a/src/server/scripts/Commands/cs_gm.cpp b/src/server/scripts/Commands/cs_gm.cpp index 06fb48581bb876..f4f91c82113ca4 100644 --- a/src/server/scripts/Commands/cs_gm.cpp +++ b/src/server/scripts/Commands/cs_gm.cpp @@ -156,7 +156,7 @@ class gm_commandscript : public CommandScript static bool HandleGMListFullCommand(ChatHandler* handler) { ///- Get the accounts with GM Level >0 - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_GM_ACCOUNTS); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_GM_ACCOUNTS); stmt->SetData(0, uint8(SEC_MODERATOR)); stmt->SetData(1, int32(realm.Id.Realm)); PreparedQueryResult result = LoginDatabase.Query(stmt); diff --git a/src/server/scripts/Commands/cs_gobject.cpp b/src/server/scripts/Commands/cs_gobject.cpp index a0939b038598ed..d27692999c3a49 100644 --- a/src/server/scripts/Commands/cs_gobject.cpp +++ b/src/server/scripts/Commands/cs_gobject.cpp @@ -34,6 +34,7 @@ EndScriptData */ #include "PoolMgr.h" #include "ScriptMgr.h" #include "Transport.h" +#include "DatabaseEnv.h" using namespace Acore::ChatCommands; @@ -106,7 +107,7 @@ class gobject_commandscript : public CommandScript if (objectInfo->displayId && !sGameObjectDisplayInfoStore.LookupEntry(objectInfo->displayId)) { // report to DB errors log as in loading case - LOG_ERROR("sql.sql", "Gameobject (Entry {} GoType: {}) have invalid displayId ({}), not spawned.", *objectId, objectInfo->type, objectInfo->displayId); + LOG_ERROR("db.query", "Gameobject (Entry {} GoType: {}) have invalid displayId ({}), not spawned.", *objectId, objectInfo->type, objectInfo->displayId); handler->PSendSysMessage(LANG_GAMEOBJECT_HAVE_INVALID_DATA, uint32(objectId)); handler->SetSentErrorMessage(true); return false; @@ -456,7 +457,7 @@ class gobject_commandscript : public CommandScript Player* player = handler->GetSession()->GetPlayer(); - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_GAMEOBJECT_NEAREST); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_GAMEOBJECT_NEAREST); stmt->SetData(0, player->GetPositionX()); stmt->SetData(1, player->GetPositionY()); stmt->SetData(2, player->GetPositionZ()); diff --git a/src/server/scripts/Commands/cs_item.cpp b/src/server/scripts/Commands/cs_item.cpp index 0fad10d3365426..ac59eb64217c85 100644 --- a/src/server/scripts/Commands/cs_item.cpp +++ b/src/server/scripts/Commands/cs_item.cpp @@ -72,7 +72,7 @@ class item_commandscript : public CommandScript } // Check existence of item in recovery table - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_RECOVERY_ITEM); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_RECOVERY_ITEM); stmt->SetData(0, restoreId); PreparedQueryResult fields = CharacterDatabase.Query(stmt); @@ -111,7 +111,7 @@ class item_commandscript : public CommandScript } // Remove from recovery table - CharacterDatabasePreparedStatement* delStmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_RECOVERY_ITEM_BY_RECOVERY_ID); + CharacterDatabasePreparedStatement delStmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_RECOVERY_ITEM_BY_RECOVERY_ID); delStmt->SetData(0, (*fields)[0].Get()); CharacterDatabase.Execute(delStmt); @@ -129,7 +129,7 @@ class item_commandscript : public CommandScript return false; } - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_RECOVERY_ITEM_LIST); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_RECOVERY_ITEM_LIST); stmt->SetData(0, player.GetGUID().GetCounter()); PreparedQueryResult disposedItems = CharacterDatabase.Query(stmt); @@ -260,7 +260,7 @@ class item_commandscript : public CommandScript else { CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt; + CharacterDatabasePreparedStatement stmt; ObjectGuid::LowType guid = player.GetGUID().GetCounter(); diff --git a/src/server/scripts/Commands/cs_list.cpp b/src/server/scripts/Commands/cs_list.cpp index 7e9d44ddfc11dd..d0eb55e6d97d59 100644 --- a/src/server/scripts/Commands/cs_list.cpp +++ b/src/server/scripts/Commands/cs_list.cpp @@ -174,7 +174,7 @@ class list_commandscript : public CommandScript // inventory case uint32 inventoryCount = 0; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_INVENTORY_COUNT_ITEM); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_INVENTORY_COUNT_ITEM); stmt->SetData(0, itemId); result = CharacterDatabase.Query(stmt); diff --git a/src/server/scripts/Commands/cs_lookup.cpp b/src/server/scripts/Commands/cs_lookup.cpp index d4f2ce45b812c0..19e9ba97752412 100644 --- a/src/server/scripts/Commands/cs_lookup.cpp +++ b/src/server/scripts/Commands/cs_lookup.cpp @@ -33,6 +33,7 @@ EndScriptData */ #include "ScriptMgr.h" #include "SpellInfo.h" #include "SpellMgr.h" +#include "DatabaseEnv.h" using namespace Acore::ChatCommands; @@ -1616,7 +1617,7 @@ class lookup_commandscript : public CommandScript ip = *ip; } - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_BY_IP); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_BY_IP); stmt->SetData(0, *ip); PreparedQueryResult result = LoginDatabase.Query(stmt); @@ -1630,7 +1631,7 @@ class lookup_commandscript : public CommandScript return false; } - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_LIST_BY_NAME); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_LIST_BY_NAME); stmt->SetData(0, account); PreparedQueryResult result = LoginDatabase.Query(stmt); @@ -1639,7 +1640,7 @@ class lookup_commandscript : public CommandScript static bool HandleLookupPlayerEmailCommand(ChatHandler* handler, std::string email, Optional limit) { - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_LIST_BY_EMAIL); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_LIST_BY_EMAIL); stmt->SetData(0, email); PreparedQueryResult result = LoginDatabase.Query(stmt); @@ -1671,7 +1672,7 @@ class lookup_commandscript : public CommandScript uint32 accountId = fields[0].Get(); std::string accountName = fields[1].Get(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_GUID_NAME_BY_ACC); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_GUID_NAME_BY_ACC); stmt->SetData(0, accountId); PreparedQueryResult result2 = CharacterDatabase.Query(stmt); diff --git a/src/server/scripts/Commands/cs_misc.cpp b/src/server/scripts/Commands/cs_misc.cpp index 9944653ca0d110..c37c595f8d44a8 100644 --- a/src/server/scripts/Commands/cs_misc.cpp +++ b/src/server/scripts/Commands/cs_misc.cpp @@ -28,8 +28,6 @@ #include "GuildMgr.h" #include "IPLocation.h" #include "InstanceSaveMgr.h" -#include "LFG.h" -#include "Language.h" #include "MapMgr.h" #include "MiscPackets.h" #include "MovementGenerator.h" @@ -43,6 +41,7 @@ #include "TargetedMovementGenerator.h" #include "Tokenize.h" #include "WeatherMgr.h" +#include "DatabaseEnv.h" /// @todo: this import is not necessary for compilation and marked as unused by the IDE // however, for some reasons removing it would cause a damn linking issue @@ -1899,8 +1898,8 @@ class misc_commandscript : public CommandScript Player* playerTarget = target->GetConnectedPlayer(); - CharacterDatabasePreparedStatement* stmt = nullptr; - LoginDatabasePreparedStatement* loginStmt = nullptr; + CharacterDatabasePreparedStatement stmt = nullptr; + LoginDatabasePreparedStatement loginStmt = nullptr; // Account data print variables std::string userName = handler->GetAcoreString(LANG_ERROR); @@ -2066,7 +2065,7 @@ class misc_commandscript : public CommandScript std::string nameLink = handler->playerLink(target->GetName()); // Returns banType, banTime, bannedBy, banreason - LoginDatabasePreparedStatement* banQuery = LoginDatabase.GetPreparedStatement(LOGIN_SEL_PINFO_BANS); + LoginDatabasePreparedStatement banQuery = LoginDatabase.GetPreparedStatement(LOGIN_SEL_PINFO_BANS); banQuery->SetData(0, accId); PreparedQueryResult accBannedResult = LoginDatabase.Query(banQuery); @@ -2087,7 +2086,7 @@ class misc_commandscript : public CommandScript } // Can be used to query data from World database - WorldDatabasePreparedStatement* xpQuery = WorldDatabase.GetPreparedStatement(WORLD_SEL_REQ_XP); + WorldDatabasePreparedStatement xpQuery = WorldDatabase.GetPreparedStatement(WORLD_SEL_REQ_XP); xpQuery->SetData(0, level); PreparedQueryResult xpResult = WorldDatabase.Query(xpQuery); @@ -2098,7 +2097,7 @@ class misc_commandscript : public CommandScript } // Can be used to query data from Characters database - CharacterDatabasePreparedStatement* charXpQuery = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PINFO_XP); + CharacterDatabasePreparedStatement charXpQuery = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PINFO_XP); charXpQuery->SetData(0, lowguid); PreparedQueryResult charXpResult = CharacterDatabase.Query(charXpQuery); @@ -2110,7 +2109,7 @@ class misc_commandscript : public CommandScript if (gguid != 0) { - CharacterDatabasePreparedStatement* guildQuery = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GUILD_MEMBER_EXTENDED); + CharacterDatabasePreparedStatement guildQuery = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GUILD_MEMBER_EXTENDED); guildQuery->SetData(0, lowguid); PreparedQueryResult guildInfoResult = CharacterDatabase.Query(guildQuery); @@ -2312,7 +2311,7 @@ class misc_commandscript : public CommandScript // Mail Data - an own query, because it may or may not be useful. // SQL: "SELECT SUM(CASE WHEN (checked & 1) THEN 1 ELSE 0 END) AS 'readmail', COUNT(*) AS 'totalmail' FROM mail WHERE `receiver` = ?" - CharacterDatabasePreparedStatement* mailQuery = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PINFO_MAILS); + CharacterDatabasePreparedStatement mailQuery = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PINFO_MAILS); mailQuery->SetData(0, lowguid); PreparedQueryResult mailInfoResult = CharacterDatabase.Query(mailQuery); @@ -2423,7 +2422,7 @@ class misc_commandscript : public CommandScript return false; } - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_MUTE_TIME); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_MUTE_TIME); int32 muteDuration = TimeStringToSecs(notSpeakTime); if (muteDuration <= 0) { @@ -2543,7 +2542,7 @@ class misc_commandscript : public CommandScript playerTarget->GetSession()->m_muteTime = 0; } - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_MUTE_TIME); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_MUTE_TIME); stmt->SetData(0, 0); stmt->SetData(1, ""); stmt->SetData(2, ""); @@ -2583,7 +2582,7 @@ class misc_commandscript : public CommandScript // helper for mutehistory static bool HandleMuteInfoHelper(ChatHandler* handler, uint32 accountId, char const* accountName) { - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_MUTE_INFO); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_MUTE_INFO); stmt->SetData(0, accountId); PreparedQueryResult result = LoginDatabase.Query(stmt); @@ -2908,7 +2907,7 @@ class misc_commandscript : public CommandScript } else if (!creatureTarget && target && !target->IsConnected()) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_AURA_FROZEN); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_AURA_FROZEN); stmt->SetData(0, target->GetGUID().GetCounter()); CharacterDatabase.Execute(stmt); handler->PSendSysMessage(LANG_COMMAND_UNFREEZE, target->GetName().c_str()); diff --git a/src/server/scripts/Commands/cs_npc.cpp b/src/server/scripts/Commands/cs_npc.cpp index 7813f5e422ca48..ce6ce1a572705b 100644 --- a/src/server/scripts/Commands/cs_npc.cpp +++ b/src/server/scripts/Commands/cs_npc.cpp @@ -23,16 +23,15 @@ Category: commandscripts EndScriptData */ #include "Chat.h" -#include "CreatureAI.h" #include "CreatureGroups.h" #include "GameTime.h" -#include "Language.h" #include "ObjectMgr.h" #include "Pet.h" #include "Player.h" #include "ScriptMgr.h" #include "TargetedMovementGenerator.h" // for HandleNpcUnFollowCommand #include "Transport.h" +#include "DatabaseEnv.h" #include using namespace Acore::ChatCommands; @@ -315,7 +314,7 @@ class npc_commandscript : public CommandScript } // Update movement type - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_MOVEMENT_TYPE); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_MOVEMENT_TYPE); stmt->SetData(0, uint8(WAYPOINT_MOTION_TYPE)); stmt->SetData(1, uint32(lowGuid)); WorldDatabase.Execute(stmt); @@ -465,7 +464,7 @@ class npc_commandscript : public CommandScript const_cast(cinfo)->faction = factionId; // ..and DB - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_FACTION); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_FACTION); stmt->SetData(0, uint16(factionId)); stmt->SetData(1, creature->GetEntry()); @@ -526,7 +525,7 @@ class npc_commandscript : public CommandScript creature->ReplaceAllNpcFlags(NPCFlags(npcFlags)); - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_NPCFLAG); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_NPCFLAG); stmt->SetData(0, NPCFlags(npcFlags)); stmt->SetData(1, creature->GetEntry()); @@ -690,7 +689,7 @@ class npc_commandscript : public CommandScript Player* player = handler->GetSession()->GetPlayer(); - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_CREATURE_NEAREST); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_CREATURE_NEAREST); stmt->SetData(0, player->GetPositionX()); stmt->SetData(1, player->GetPositionY()); stmt->SetData(2, player->GetPositionZ()); @@ -780,7 +779,7 @@ class npc_commandscript : public CommandScript } } - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_POSITION); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_POSITION); stmt->SetData(0, x); stmt->SetData(1, y); stmt->SetData(2, z); @@ -1005,7 +1004,7 @@ class npc_commandscript : public CommandScript creature->Respawn(); } - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_WANDER_DISTANCE); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_WANDER_DISTANCE); stmt->SetData(0, option); stmt->SetData(1, uint8(mtype)); @@ -1049,7 +1048,7 @@ class npc_commandscript : public CommandScript return false; } - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_SPAWN_TIME_SECS); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_CREATURE_SPAWN_TIME_SECS); stmt->SetData(0, spawnTime); stmt->SetData(1, creature->GetSpawnId()); WorldDatabase.Execute(stmt); @@ -1270,7 +1269,7 @@ class npc_commandscript : public CommandScript sFormationMgr->CreatureGroupMap[lowguid] = group_member; creature->SearchFormation(); - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_INS_CREATURE_FORMATION); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_INS_CREATURE_FORMATION); stmt->SetData(0, leaderGUID); stmt->SetData(1, lowguid); stmt->SetData(2, group_member.follow_dist); diff --git a/src/server/scripts/Commands/cs_quest.cpp b/src/server/scripts/Commands/cs_quest.cpp index 3940ca8d24badb..dd543cc959e291 100644 --- a/src/server/scripts/Commands/cs_quest.cpp +++ b/src/server/scripts/Commands/cs_quest.cpp @@ -28,6 +28,7 @@ EndScriptData */ #include "Player.h" #include "ReputationMgr.h" #include "ScriptMgr.h" +#include "DatabaseEnv.h" using namespace Acore::ChatCommands; @@ -108,7 +109,7 @@ class quest_commandscript : public CommandScript uint8 index = 0; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_CHAR_QUESTSTATUS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_CHAR_QUESTSTATUS); stmt->SetData(index++, guid); stmt->SetData(index++, entry); stmt->SetData(index++, 1); @@ -187,7 +188,7 @@ class quest_commandscript : public CommandScript ObjectGuid::LowType guid = playerTarget->GetGUID().GetCounter(); CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS_REWARDED_BY_QUEST); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS_REWARDED_BY_QUEST); stmt->SetData(0, guid); stmt->SetData(1, entry); trans->Append(stmt); @@ -394,7 +395,7 @@ class quest_commandscript : public CommandScript uint8 index = 0; - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_CHAR_QUESTSTATUS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_CHAR_QUESTSTATUS); stmt->SetData(index++, guid); stmt->SetData(index++, entry); stmt->SetData(index++, 1); @@ -534,7 +535,7 @@ class quest_commandscript : public CommandScript ObjectGuid::LowType guid = playerTarget->GetGUID().GetCounter(); uint8 charLevel = sCharacterCache->GetCharacterLevelByGuid(ObjectGuid(HighGuid::Player, guid)); CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); - CharacterDatabasePreparedStatement* stmt; + CharacterDatabasePreparedStatement stmt; QueryResult result = CharacterDatabase.Query("SELECT 1 FROM character_queststatus WHERE guid = {} AND quest = {} AND status = 1", guid, entry); @@ -720,7 +721,7 @@ class quest_commandscript : public CommandScript // Only reward money, don't subtract, let's not cause an overflow... if (rewMoney > 0) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UDP_CHAR_MONEY_ACCUMULATIVE); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UDP_CHAR_MONEY_ACCUMULATIVE); stmt->SetData(0, rewMoney); stmt->SetData(1, guid); trans->Append(stmt); diff --git a/src/server/scripts/Commands/cs_reload.cpp b/src/server/scripts/Commands/cs_reload.cpp index b7265e89cf2629..a5f138424743eb 100644 --- a/src/server/scripts/Commands/cs_reload.cpp +++ b/src/server/scripts/Commands/cs_reload.cpp @@ -31,7 +31,6 @@ EndScriptData */ #include "DisableMgr.h" #include "GameGraveyard.h" #include "LFGMgr.h" -#include "Language.h" #include "MapMgr.h" #include "ServerMotd.h" #include "ObjectMgr.h" @@ -45,6 +44,7 @@ EndScriptData */ #include "Tokenize.h" #include "WardenCheckMgr.h" #include "WaypointMgr.h" +#include "DatabaseEnv.h" using namespace Acore::ChatCommands; @@ -455,7 +455,7 @@ class reload_commandscript : public CommandScript { uint32 entry = Acore::StringTo(entryStr).value_or(0); - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_CREATURE_TEMPLATE); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_CREATURE_TEMPLATE); stmt->SetData(0, entry); PreparedQueryResult result = WorldDatabase.Query(stmt); diff --git a/src/server/scripts/Commands/cs_reset.cpp b/src/server/scripts/Commands/cs_reset.cpp index fc2f78ddcf7312..8f897c284df444 100644 --- a/src/server/scripts/Commands/cs_reset.cpp +++ b/src/server/scripts/Commands/cs_reset.cpp @@ -24,11 +24,11 @@ EndScriptData */ #include "AchievementMgr.h" #include "Chat.h" -#include "Language.h" #include "ObjectAccessor.h" #include "Pet.h" #include "Player.h" #include "ScriptMgr.h" +#include "DatabaseEnv.h" #if AC_COMPILER == AC_COMPILER_GNU #pragma GCC diagnostic ignored "-Wdeprecated-declarations" @@ -177,7 +177,7 @@ class reset_commandscript : public CommandScript } else { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG); stmt->SetData(0, uint16(AT_LOGIN_RESET_SPELLS)); stmt->SetData(1, targetGuid.GetCounter()); CharacterDatabase.Execute(stmt); @@ -251,7 +251,7 @@ class reset_commandscript : public CommandScript } else if (targetGuid) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG); stmt->SetData(0, uint16(AT_LOGIN_RESET_TALENTS | AT_LOGIN_RESET_PET_TALENTS)); stmt->SetData(1, targetGuid.GetCounter()); CharacterDatabase.Execute(stmt); @@ -297,7 +297,7 @@ class reset_commandscript : public CommandScript return false; } - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ALL_AT_LOGIN_FLAGS); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ALL_AT_LOGIN_FLAGS); stmt->SetData(0, uint16(atLogin)); CharacterDatabase.Execute(stmt); diff --git a/src/server/scripts/Commands/cs_script_loader.cpp b/src/server/scripts/Commands/cs_script_loader.cpp index 4c7433b6b17814..53c7d1050290f9 100644 --- a/src/server/scripts/Commands/cs_script_loader.cpp +++ b/src/server/scripts/Commands/cs_script_loader.cpp @@ -25,6 +25,7 @@ void AddSC_bf_commandscript(); void AddSC_cast_commandscript(); void AddSC_character_commandscript(); void AddSC_cheat_commandscript(); +void AddSC_db_commandscript(); void AddSC_debug_commandscript(); void AddSC_deserter_commandscript(); void AddSC_disable_commandscript(); @@ -76,6 +77,7 @@ void AddCommandsScripts() AddSC_cast_commandscript(); AddSC_character_commandscript(); AddSC_cheat_commandscript(); + AddSC_db_commandscript(); AddSC_debug_commandscript(); AddSC_deserter_commandscript(); AddSC_disable_commandscript(); diff --git a/src/server/scripts/Commands/cs_server.cpp b/src/server/scripts/Commands/cs_server.cpp index 4c89715f7b7e71..d093106fa25dc1 100644 --- a/src/server/scripts/Commands/cs_server.cpp +++ b/src/server/scripts/Commands/cs_server.cpp @@ -23,12 +23,10 @@ EndScriptData */ #include "Chat.h" -#include "Config.h" #include "GameTime.h" #include "GitRevision.h" -#include "Language.h" #include "ModuleMgr.h" -#include "MySQLThreading.h" +#include "DatabaseMgr.h" #include "Player.h" #include "Realm.h" #include "ScriptMgr.h" @@ -37,6 +35,7 @@ #include "UpdateTime.h" #include "VMapFactory.h" #include "VMapMgr2.h" +#include "DatabaseEnv.h" #include #include #include @@ -131,7 +130,7 @@ class server_commandscript : public CommandScript handler->PSendSysMessage("%s", GitRevision::GetFullVersion()); handler->PSendSysMessage("Using SSL version: %s (library: %s)", OPENSSL_VERSION_TEXT, OpenSSL_version(OPENSSL_VERSION)); handler->PSendSysMessage("Using Boost version: %i.%i.%i", BOOST_VERSION / 100000, BOOST_VERSION / 100 % 1000, BOOST_VERSION % 100); - handler->PSendSysMessage("Using MySQL version: %u", MySQL::GetLibraryVersion()); + handler->PSendSysMessage("Using MySQL version: %u", sDatabaseMgr->GetDatabaseLibraryVersion()); handler->PSendSysMessage("Using CMake version: %s", GitRevision::GetCMakeVersion()); handler->PSendSysMessage("Compiled on: %s", GitRevision::GetHostOSVersion()); @@ -211,17 +210,15 @@ class server_commandscript : public CommandScript } handler->PSendSysMessage("Using %s DBC Locale as default. All available DBC locales: %s", localeNames[defaultLocale], availableLocales.c_str()); - handler->PSendSysMessage("Using World DB: %s", sWorld->GetDBVersion()); - - handler->PSendSysMessage("LoginDatabase queue size: %zu", LoginDatabase.QueueSize()); - handler->PSendSysMessage("CharacterDatabase queue size: %zu", CharacterDatabase.QueueSize()); - handler->PSendSysMessage("WorldDatabase queue size: %zu", WorldDatabase.QueueSize()); + handler->PSendSysMessage("LoginDatabase queue size: %zu", LoginDatabase.GetQueueSize()); + handler->PSendSysMessage("CharacterDatabase queue size: %zu", CharacterDatabase.GetQueueSize()); + handler->PSendSysMessage("WorldDatabase queue size: %zu", WorldDatabase.GetQueueSize()); if (Acore::Module::GetEnableModulesList().empty()) handler->SendSysMessage("No modules enabled"); else - handler->SendSysMessage("> List enable modules:"); + handler->SendSysMessage("List enable modules:"); for (auto const& modName : Acore::Module::GetEnableModulesList()) { @@ -524,7 +521,7 @@ class server_commandscript : public CommandScript } LoginDatabaseTransaction trans = LoginDatabase.BeginTransaction(); - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_REP_MOTD); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_REP_MOTD); stmt->SetData(0, Acore::StringTo(realmId).value()); stmt->SetData(1, strMotd); trans->Append(stmt); diff --git a/src/server/scripts/Commands/cs_tele.cpp b/src/server/scripts/Commands/cs_tele.cpp index cf0e14e22f2a71..0df4888fb70293 100644 --- a/src/server/scripts/Commands/cs_tele.cpp +++ b/src/server/scripts/Commands/cs_tele.cpp @@ -185,7 +185,7 @@ class tele_commandscript : public CommandScript target->TeleportTo(target->m_homebindMapId, target->m_homebindX, target->m_homebindY, target->m_homebindZ, target->m_homebindO); else { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_HOMEBIND); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_HOMEBIND); stmt->SetData(0, player->GetGUID().GetCounter()); PreparedQueryResult resultDB = CharacterDatabase.Query(stmt); diff --git a/src/server/scripts/Commands/cs_wp.cpp b/src/server/scripts/Commands/cs_wp.cpp index 988801833fae07..496225b6db9be7 100644 --- a/src/server/scripts/Commands/cs_wp.cpp +++ b/src/server/scripts/Commands/cs_wp.cpp @@ -28,6 +28,7 @@ EndScriptData */ #include "Player.h" #include "ScriptMgr.h" #include "WaypointMgr.h" +#include "DatabaseEnv.h" #if AC_COMPILER == AC_COMPILER_GNU #pragma GCC diagnostic ignored "-Wdeprecated-declarations" @@ -97,7 +98,7 @@ class wp_commandscript : public CommandScript pathid = target->GetWaypointPath(); else { - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_MAX_ID); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_MAX_ID); PreparedQueryResult result = WorldDatabase.Query(stmt); @@ -118,7 +119,7 @@ class wp_commandscript : public CommandScript return true; } - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_MAX_POINT); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_MAX_POINT); stmt->SetData(0, pathid); PreparedQueryResult result = WorldDatabase.Query(stmt); @@ -185,7 +186,7 @@ class wp_commandscript : public CommandScript guidLow = target->GetSpawnId(); - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_CREATURE_ADDON_BY_GUID); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_CREATURE_ADDON_BY_GUID); stmt->SetData(0, guidLow); @@ -254,7 +255,7 @@ class wp_commandscript : public CommandScript { if (target->GetCreatureAddon()->path_id != 0) { - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_CREATURE_ADDON); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_CREATURE_ADDON); stmt->SetData(0, guildLow); WorldDatabase.Execute(stmt); @@ -301,13 +302,13 @@ class wp_commandscript : public CommandScript if (id) { - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_SCRIPT_ID_BY_GUID); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_SCRIPT_ID_BY_GUID); stmt->SetData(0, id); PreparedQueryResult result = WorldDatabase.Query(stmt); if (!result) { - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_INS_WAYPOINT_SCRIPT); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_INS_WAYPOINT_SCRIPT); stmt->SetData(0, id); @@ -320,7 +321,7 @@ class wp_commandscript : public CommandScript } else { - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_SCRIPTS_MAX_ID); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_SCRIPTS_MAX_ID); PreparedQueryResult result = WorldDatabase.Query(stmt); @@ -352,7 +353,7 @@ class wp_commandscript : public CommandScript float a8, a9, a10, a11; char const* a7; - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_SCRIPT_BY_ID); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_SCRIPT_BY_ID); stmt->SetData(0, id); PreparedQueryResult result = WorldDatabase.Query(stmt); @@ -392,7 +393,7 @@ class wp_commandscript : public CommandScript id = atoi(arg_id); - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_SCRIPT_ID_BY_GUID); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_SCRIPT_ID_BY_GUID); stmt->SetData(0, id); @@ -400,7 +401,7 @@ class wp_commandscript : public CommandScript if (result) { - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_WAYPOINT_SCRIPT); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_WAYPOINT_SCRIPT); stmt->SetData(0, id); @@ -463,7 +464,7 @@ class wp_commandscript : public CommandScript uint32 newid = atoi(arg_3); handler->PSendSysMessage("%s%s|r|cff00ffff%u|r|cff00ff00%s|r|cff00ffff%u|r", "|cff00ff00", "Wp Event: Wypoint scipt guid: ", newid, " id changed: ", id); - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_WAYPOINT_SCRIPT_ID); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_WAYPOINT_SCRIPT_ID); stmt->SetData(0, newid); stmt->SetData(1, id); @@ -474,7 +475,7 @@ class wp_commandscript : public CommandScript } else { - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_SCRIPT_ID_BY_GUID); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_SCRIPT_ID_BY_GUID); stmt->SetData(0, id); PreparedQueryResult result = WorldDatabase.Query(stmt); @@ -486,7 +487,7 @@ class wp_commandscript : public CommandScript if (arg_str_2 == "posx") { - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_WAYPOINT_SCRIPT_X); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_WAYPOINT_SCRIPT_X); stmt->SetData(0, float(atof(arg_3))); stmt->SetData(1, id); @@ -498,7 +499,7 @@ class wp_commandscript : public CommandScript } else if (arg_str_2 == "posy") { - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_WAYPOINT_SCRIPT_Y); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_WAYPOINT_SCRIPT_Y); stmt->SetData(0, float(atof(arg_3))); stmt->SetData(1, id); @@ -510,7 +511,7 @@ class wp_commandscript : public CommandScript } else if (arg_str_2 == "posz") { - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_WAYPOINT_SCRIPT_Z); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_WAYPOINT_SCRIPT_Z); stmt->SetData(0, float(atof(arg_3))); stmt->SetData(1, id); @@ -522,7 +523,7 @@ class wp_commandscript : public CommandScript } else if (arg_str_2 == "orientation") { - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_WAYPOINT_SCRIPT_O); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_WAYPOINT_SCRIPT_O); stmt->SetData(0, float(atof(arg_3))); stmt->SetData(1, id); @@ -595,7 +596,7 @@ class wp_commandscript : public CommandScript // User did select a visual waypoint? // Check the creature - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_BY_WPGUID); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_BY_WPGUID); stmt->SetData(0, wpSpawnId); PreparedQueryResult result = WorldDatabase.Query(stmt); @@ -610,7 +611,7 @@ class wp_commandscript : public CommandScript // See also: http://dev.mysql.com/doc/refman/5.0/en/problems-with-float.html std::string maxDiff = "0.01"; - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_BY_POS); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_BY_POS); stmt->SetData(0, target->GetPositionX()); stmt->SetData(1, maxDiff); stmt->SetData(2, target->GetPositionY()); @@ -656,7 +657,7 @@ class wp_commandscript : public CommandScript wpCreature->AddObjectToRemoveList(); } - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_WAYPOINT_DATA); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_WAYPOINT_DATA); stmt->SetData(0, pathid); stmt->SetData(1, point); @@ -713,7 +714,7 @@ class wp_commandscript : public CommandScript //sMapMgr->GetMap(npcCreature->GetMapId())->Add(wpCreature2); } - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_WAYPOINT_DATA_POSITION); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_WAYPOINT_DATA_POSITION); stmt->SetData(0, chr->GetPositionX()); stmt->SetData(1, chr->GetPositionY()); @@ -805,7 +806,7 @@ class wp_commandscript : public CommandScript return false; } - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_ALL_BY_WPGUID); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_ALL_BY_WPGUID); stmt->SetData(0, target->GetSpawnId()); @@ -840,7 +841,7 @@ class wp_commandscript : public CommandScript if (show == "on") { - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_POS_BY_ID); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_POS_BY_ID); stmt->SetData(0, pathid); @@ -876,7 +877,7 @@ class wp_commandscript : public CommandScript handler->PSendSysMessage(LANG_WAYPOINT_NOTREMOVED, wpguid); hasError = true; - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_CREATURE); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_CREATURE); stmt->SetData(0, wpguid); WorldDatabase.Execute(stmt); @@ -920,7 +921,7 @@ class wp_commandscript : public CommandScript } // Set "wpguid" column to the visual waypoint - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_WAYPOINT_DATA_WPGUID); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_UPD_WAYPOINT_DATA_WPGUID); stmt->SetData(0, int32(wpCreature->GetSpawnId())); stmt->SetData(1, pathid); stmt->SetData(2, point); @@ -952,7 +953,7 @@ class wp_commandscript : public CommandScript { handler->PSendSysMessage("|cff00ff00DEBUG: wp first, GUID: %u|r", pathid); - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_POS_FIRST_BY_ID); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_POS_FIRST_BY_ID); stmt->SetData(0, pathid); PreparedQueryResult result = WorldDatabase.Query(stmt); @@ -1002,7 +1003,7 @@ class wp_commandscript : public CommandScript { handler->PSendSysMessage("|cff00ff00DEBUG: wp last, PathID: |r|cff00ffff%u|r", pathid); - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_POS_LAST_BY_ID); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_POS_LAST_BY_ID); stmt->SetData(0, pathid); PreparedQueryResult result = WorldDatabase.Query(stmt); @@ -1050,7 +1051,7 @@ class wp_commandscript : public CommandScript if (show == "off") { - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_CREATURE_BY_ID); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_CREATURE_BY_ID); stmt->SetArguments(1, 1, 1); PreparedQueryResult result = WorldDatabase.Query(stmt); @@ -1073,7 +1074,7 @@ class wp_commandscript : public CommandScript handler->PSendSysMessage(LANG_WAYPOINT_NOTREMOVED, guid); hasError = true; - WorldDatabasePreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_CREATURE); + WorldDatabasePreparedStatement stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_CREATURE); stmt->SetData(0, guid); diff --git a/src/server/scripts/Northrend/zone_dalaran.cpp b/src/server/scripts/Northrend/zone_dalaran.cpp index b874144a1dc5d0..c9b89a0266dca3 100644 --- a/src/server/scripts/Northrend/zone_dalaran.cpp +++ b/src/server/scripts/Northrend/zone_dalaran.cpp @@ -20,6 +20,7 @@ #include "ScriptedCreature.h" #include "ScriptedGossip.h" #include "World.h" +#include "DatabaseEnv.h" // Ours class npc_steam_powered_auctioneer : public CreatureScript diff --git a/src/server/scripts/World/action_ip_logger.cpp b/src/server/scripts/World/action_ip_logger.cpp index 1977217fb1d3d2..69eed00d663ac2 100644 --- a/src/server/scripts/World/action_ip_logger.cpp +++ b/src/server/scripts/World/action_ip_logger.cpp @@ -19,6 +19,7 @@ #include "Group.h" #include "Guild.h" #include "ScriptMgr.h" +#include "DatabaseEnv.h" enum IPLoggingTypes { @@ -140,7 +141,7 @@ class AccountActionIpLogger : public AccountScript { // As we can assume most account actions are NOT failed login, so this is the more accurate check. // For those, we need last_ip... - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_ALDL_IP_LOGGING); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_ALDL_IP_LOGGING); stmt->SetData(0, playerGuid); stmt->SetData(1, characterGuid); @@ -151,7 +152,7 @@ class AccountActionIpLogger : public AccountScript } else // ... but for failed login, we query last_attempt_ip from account table. Which we do with an unique query { - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_FACL_IP_LOGGING); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_FACL_IP_LOGGING); stmt->SetData(0, playerGuid); stmt->SetData(1, characterGuid); @@ -236,7 +237,7 @@ class CharacterActionIpLogger : public PlayerScript } // Once we have done everything, we can insert the new log. - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_CHAR_IP_LOGGING); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_CHAR_IP_LOGGING); stmt->SetData(0, playerGuid); stmt->SetData(1, characterGuid); @@ -299,7 +300,7 @@ class CharacterDeleteActionIpLogger : public PlayerScript } // Once we have done everything, we can insert the new log. - LoginDatabasePreparedStatement* stmt2 = LoginDatabase.GetPreparedStatement(LOGIN_INS_ALDL_IP_LOGGING); + LoginDatabasePreparedStatement stmt2 = LoginDatabase.GetPreparedStatement(LOGIN_INS_ALDL_IP_LOGGING); stmt2->SetData(0, playerGuid); stmt2->SetData(1, characterGuid); stmt2->SetData(2, aType); diff --git a/src/server/scripts/World/npcs_special.cpp b/src/server/scripts/World/npcs_special.cpp index 2a0469507dfd14..3e22ccf633d5db 100644 --- a/src/server/scripts/World/npcs_special.cpp +++ b/src/server/scripts/World/npcs_special.cpp @@ -522,14 +522,14 @@ class npc_air_force_bots : public CreatureScript } if (!SpawnAssoc) - LOG_ERROR("sql.sql", "TCSR: Creature template entry {} has ScriptName npc_air_force_bots, but it's not handled by that script", creature->GetEntry()); + LOG_ERROR("db.query", "TCSR: Creature template entry {} has ScriptName npc_air_force_bots, but it's not handled by that script", creature->GetEntry()); else { CreatureTemplate const* spawnedTemplate = sObjectMgr->GetCreatureTemplate(SpawnAssoc->spawnedCreatureEntry); if (!spawnedTemplate) { - LOG_ERROR("sql.sql", "TCSR: Creature template entry {} does not exist in DB, which is required by npc_air_force_bots", SpawnAssoc->spawnedCreatureEntry); + LOG_ERROR("db.query", "TCSR: Creature template entry {} does not exist in DB, which is required by npc_air_force_bots", SpawnAssoc->spawnedCreatureEntry); SpawnAssoc = nullptr; return; } @@ -549,7 +549,7 @@ class npc_air_force_bots : public CreatureScript SpawnedGUID = summoned->GetGUID(); else { - LOG_ERROR("sql.sql", "TCSR: npc_air_force_bots: wasn't able to spawn Creature {}", SpawnAssoc->spawnedCreatureEntry); + LOG_ERROR("db.query", "TCSR: npc_air_force_bots: wasn't able to spawn Creature {}", SpawnAssoc->spawnedCreatureEntry); SpawnAssoc = nullptr; } diff --git a/src/server/scripts/World/server_mail.cpp b/src/server/scripts/World/server_mail.cpp index 5776753d63366b..7a00d90e1e9dd6 100644 --- a/src/server/scripts/World/server_mail.cpp +++ b/src/server/scripts/World/server_mail.cpp @@ -19,7 +19,7 @@ #include "ScriptMgr.h" #include "Mail.h" #include "ObjectMgr.h" -#include "QueryResult.h" +#include "DatabaseEnv.h" class ServerMailReward : public PlayerScript { @@ -31,7 +31,7 @@ class ServerMailReward : public PlayerScript { for (auto const& servMail : sObjectMgr->GetAllServerMailStore()) { - CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_MAIL_SERVER_CHARACTER); + CharacterDatabasePreparedStatement stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_MAIL_SERVER_CHARACTER); stmt->SetData(0, player->GetGUID().GetCounter()); stmt->SetData(1, servMail.second.id); diff --git a/src/server/shared/Realms/RealmList.cpp b/src/server/shared/Realms/RealmList.cpp index 9b991d86453be3..650b9128a48d9c 100644 --- a/src/server/shared/Realms/RealmList.cpp +++ b/src/server/shared/Realms/RealmList.cpp @@ -134,7 +134,7 @@ void RealmList::UpdateRealms(boost::system::error_code const& error) LOG_DEBUG("server.authserver", "Updating Realm List..."); - LoginDatabasePreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_REALMLIST); + LoginDatabasePreparedStatement stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_REALMLIST); PreparedQueryResult result = LoginDatabase.Query(stmt); std::map existingRealms; diff --git a/src/server/shared/Secrets/SecretMgr.cpp b/src/server/shared/Secrets/SecretMgr.cpp index cfc42e4ca65524..0836450ba07722 100644 --- a/src/server/shared/Secrets/SecretMgr.cpp +++ b/src/server/shared/Secrets/SecretMgr.cpp @@ -109,7 +109,7 @@ void SecretMgr::AttemptLoad(Secrets i, LogLevel errorLevel, std::unique_lock oldDigest; { - auto* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_SECRET_DIGEST); + auto stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_SECRET_DIGEST); stmt->SetData(0, i); PreparedQueryResult result = LoginDatabase.Query(stmt); if (result) @@ -198,7 +198,7 @@ Optional SecretMgr::AttemptTransition(Secrets i, Optional(totpSecret, newSecret->ToByteArray()); - auto* updateStmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_TOTP_SECRET); + auto updateStmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_ACCOUNT_TOTP_SECRET); updateStmt->SetData(0, totpSecret); updateStmt->SetData(1, id); trans->Append(updateStmt); @@ -212,7 +212,7 @@ Optional SecretMgr::AttemptTransition(Secrets i, OptionalSetData(0, i); trans->Append(deleteStmt); } @@ -225,7 +225,7 @@ Optional SecretMgr::AttemptTransition(Secrets i, OptionalSetData(0, i); insertStmt->SetData(1, *hash); trans->Append(insertStmt); diff --git a/src/tools/dbimport/Main.cpp b/src/tools/dbimport/Main.cpp index 0f4ddf5ffa918f..7b4d3abb52a3fb 100644 --- a/src/tools/dbimport/Main.cpp +++ b/src/tools/dbimport/Main.cpp @@ -18,10 +18,9 @@ #include "Banner.h" #include "Config.h" #include "DatabaseEnv.h" -#include "DatabaseLoader.h" +#include "DatabaseMgr.h" #include "IoContext.h" #include "Log.h" -#include "MySQLThreading.h" #include "OpenSSLCrypto.h" #include "Util.h" #include @@ -96,16 +95,12 @@ int main(int argc, char** argv) /// Initialize connection to the database bool StartDB() { - MySQL::Library_Init(); + sDatabaseMgr->AddDatabase(LoginDatabase, "Login"); + sDatabaseMgr->AddDatabase(CharacterDatabase, "Character"); + sDatabaseMgr->AddDatabase(WorldDatabase, "World"); +// sDatabaseMgr->AddDatabase(DBCDatabase, "Dbc"); - // Load databases - DatabaseLoader loader("dbimport"); - loader - .AddDatabase(LoginDatabase, "Login") - .AddDatabase(CharacterDatabase, "Character") - .AddDatabase(WorldDatabase, "World"); - - if (!loader.Load()) + if (!sDatabaseMgr->Load()) return false; LOG_INFO("dbimport", "Started database connection pool."); @@ -115,10 +110,7 @@ bool StartDB() /// Close the connection to the database void StopDB() { - CharacterDatabase.Close(); - WorldDatabase.Close(); - LoginDatabase.Close(); - MySQL::Library_End(); + sDatabaseMgr->CloseAllConnections(); } variables_map GetConsoleArguments(int argc, char** argv, fs::path& configFile) diff --git a/src/tools/dbimport/dbimport.conf.dist b/src/tools/dbimport/dbimport.conf.dist index 656bdd35b8b905..03e23161ed3a2f 100644 --- a/src/tools/dbimport/dbimport.conf.dist +++ b/src/tools/dbimport/dbimport.conf.dist @@ -110,36 +110,21 @@ CharacterDatabaseInfo = "127.0.0.1;3306;acore;acore;acore_characters" Database.Reconnect.Seconds = 5 Database.Reconnect.Attempts = 5 - # -# LoginDatabase.WorkerThreads -# WorldDatabase.WorkerThreads -# CharacterDatabase.WorkerThreads -# Description: The amount of worker threads spawned to handle asynchronous (delayed) MySQL -# statements. Each worker thread is mirrored with its own connection to the -# MySQL server and their own thread on the MySQL server. -# Default: 1 - (LoginDatabase.WorkerThreads) -# 1 - (WorldDatabase.WorkerThreads) -# 1 - (CharacterDatabase.WorkerThreads) +# MaxQueueSize +# Description: Max size queue before open new dynamic async connect for db +# Default: 10 # -LoginDatabase.WorkerThreads = 1 -WorldDatabase.WorkerThreads = 1 -CharacterDatabase.WorkerThreads = 1 +MaxQueueSize = 10 # -# LoginDatabase.SynchThreads -# WorldDatabase.SynchThreads -# CharacterDatabase.SynchThreads -# Description: The amount of MySQL connections spawned to handle. -# Default: 1 - (LoginDatabase.WorkerThreads) -# 1 - (WorldDatabase.WorkerThreads) -# 1 - (CharacterDatabase.WorkerThreads) +# MaxPingTime +# Description: Time (in minutes) between database pings. +# Default: 30 # -LoginDatabase.SynchThreads = 1 -WorldDatabase.SynchThreads = 1 -CharacterDatabase.SynchThreads = 1 +MaxPingTime = 30 ################################################################################################### ###################################################################################################