Ported .Net Core commits:

hondacrx:
- Initial commit: Switch to .Net Core 2.0
- Fix build and removed not needed files
Fabi:
- Updated solution platforms.
- Changed folder structure.
- Change library target framework to netstandard2.0.
- Updated solution platforms again...
- Removed windows specific kernel32 function usage (Ctrl-C handler).
This commit is contained in:
Fabian
2017-10-26 17:23:44 +02:00
parent 227702e19c
commit a3dc7b3f48
844 changed files with 26064 additions and 1824 deletions
+27
View File
@@ -0,0 +1,27 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 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 <http://www.gnu.org/licenses/>.
*/
namespace Framework.Database
{
public static class DB
{
public static LoginDatabase Login = new LoginDatabase();
public static CharacterDatabase Characters = new CharacterDatabase();
public static WorldDatabase World = new WorldDatabase();
public static HotfixDatabase Hotfix = new HotfixDatabase();
}
}
+185
View File
@@ -0,0 +1,185 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 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 <http://www.gnu.org/licenses/>.
*/
using Framework.Configuration;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
namespace Framework.Database
{
public class DatabaseLoader
{
public DatabaseLoader(DatabaseTypeFlags defaultUpdateMask)
{
_autoSetup = ConfigMgr.GetDefaultValue("Updates.AutoSetup", true);
_updateFlags = ConfigMgr.GetDefaultValue("Updates.EnableDatabases", defaultUpdateMask);
}
public void AddDatabase<T>(MySqlBase<T> database, string dbName)
{
bool updatesEnabled = database.IsAutoUpdateEnabled(_updateFlags);
_open.Add(() =>
{
MySqlConnectionInfo connectionObject = new MySqlConnectionInfo
{
Host = ConfigMgr.GetDefaultValue(dbName + "DatabaseInfo.Host", ""),
Port = ConfigMgr.GetDefaultValue(dbName + "DatabaseInfo.Port", ""),
Username = ConfigMgr.GetDefaultValue(dbName + "DatabaseInfo.Username", ""),
Password = ConfigMgr.GetDefaultValue(dbName + "DatabaseInfo.Password", ""),
Database = ConfigMgr.GetDefaultValue(dbName + "DatabaseInfo.Database", "")
};
var error = database.Initialize(connectionObject);
if (error != MySqlErrorCode.None)
{
// Database does not exist
if (error == MySqlErrorCode.UnknownDatabase && updatesEnabled && _autoSetup)
{
Log.outInfo(LogFilter.ServerLoading, $"Database \"{dbName}\" does not exist, do you want to create it? [yes (default) / no]: ");
string answer = Console.ReadLine();
if (string.IsNullOrEmpty(answer) || answer[0] != 'y')
return false;
Log.outInfo(LogFilter.ServerLoading, $"Creating database \"{dbName}\"...");
string sqlString = $"CREATE DATABASE `{dbName}` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci";
// Try to create the database and connect again if auto setup is enabled
if (database.Apply(sqlString) && database.Initialize(connectionObject) == MySqlErrorCode.None)
error = MySqlErrorCode.None;
}
// If the error wasn't handled quit
if (error != MySqlErrorCode.None)
{
Log.outError(LogFilter.ServerLoading, $"\nDatabase {dbName} NOT opened. There were errors opening the MySQL connections. Check your SQLErrors for specific errors.");
return false;
}
Log.outInfo(LogFilter.ServerLoading, "Done.");
}
return true;
});
if (updatesEnabled)
{
// Populate and update only if updates are enabled for this pool
_populate.Add(() =>
{
//Hack used to allow big querys
database.Apply("SET GLOBAL max_allowed_packet=1073741824;");
if (!database.GetUpdater().Populate())
{
Log.outError(LogFilter.ServerLoading, $"Could not populate the {dbName} database, see log for details.");
return false;
}
return true;
});
_update.Add(() =>
{
//Hack used to allow big querys
database.Apply("SET GLOBAL max_allowed_packet=1073741824;");
if (!database.GetUpdater().Update())
{
Log.outError(LogFilter.ServerLoading, $"Could not update the {dbName} database, see log for details.");
return false;
}
return true;
});
}
_prepare.Add(() =>
{
database.LoadPreparedStatements();
return true;
});
}
public bool Load()
{
if (_updateFlags == 0)
Log.outInfo(LogFilter.SqlUpdates, "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 OpenDatabases()
{
return Process(_open);
}
// Processes the elements of the given stack until a predicate returned false.
bool Process(List<Func<bool>> list)
{
while (!list.Empty())
{
if (!list[0].Invoke())
return false;
list.RemoveAt(0);
}
return true;
}
bool PopulateDatabases()
{
return Process(_populate);
}
bool UpdateDatabases()
{
return Process(_update);
}
bool PrepareStatements()
{
return Process(_prepare);
}
bool _autoSetup;
DatabaseTypeFlags _updateFlags;
List<Func<bool>> _open = new List<Func<bool>>();
List<Func<bool>> _populate = new List<Func<bool>>();
List<Func<bool>> _update = new List<Func<bool>>();
List<Func<bool>> _prepare = new List<Func<bool>>();
}
public enum DatabaseTypeFlags
{
None = 0,
Login = 1,
Character = 2,
World = 4,
Hotfix = 8,
All = Login | Character | World | Hotfix
}
}
@@ -0,0 +1,462 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 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 <http://www.gnu.org/licenses/>.
*/
using Framework.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace Framework.Database
{
public class DatabaseUpdater<T>
{
public DatabaseUpdater(MySqlBase<T> database)
{
_database = database;
}
public bool Populate()
{
SQLResult result = _database.Query("SHOW TABLES");
if (!result.IsEmpty() && result.GetRowCount() > 0)
return true;
Log.outInfo(LogFilter.SqlUpdates, $"Database {_database.GetDatabaseName()} is empty, auto populating it...");
string path = GetSourceDirectory();
string fileName = "Unknown";
switch (_database.GetType().Name)
{
case "LoginDatabase":
fileName = @"\sql\base\auth_database.sql";
break;
case "CharacterDatabase":
fileName = @"\sql\base\characters_database.sql";
break;
case "WorldDatabase":
fileName = @"\sql\base\TDB_world_703.00_2016_10_17.sql";
break;
case "HotfixDatabase":
fileName = @"\sql\base\TDB_hotfixes_703.00_2016_10_17.sql";
break;
}
if (!File.Exists(path + fileName))
{
Log.outError(LogFilter.SqlUpdates, $"File \"{fileName}\" is missing, download it from \"http://www.trinitycore.org/f/files/category/1-database/\"" +
" and place it in your worldserver directory.");
return false;
}
// Update database
Log.outInfo(LogFilter.SqlUpdates, $"Applying \'{fileName}\'...");
_database.ApplyFile(path + fileName);
Log.outInfo(LogFilter.SqlUpdates, $"Done Applying \'{fileName}\'");
return true;
}
public bool Update()
{
Log.outInfo(LogFilter.SqlUpdates, $"Updating {_database.GetDatabaseName()} database...");
string sourceDirectory = GetSourceDirectory();
if (!Directory.Exists(sourceDirectory))
{
Log.outError(LogFilter.SqlUpdates, $"DBUpdater: Given source directory {sourceDirectory} does not exist, skipped!");
return false;
}
var availableFiles = GetFileList();
var appliedFiles = ReceiveAppliedFiles();
bool redundancyChecks = ConfigMgr.GetDefaultValue("Updates.Redundancy", true);
bool archivedRedundancy = ConfigMgr.GetDefaultValue("Updates.Redundancy", true);
UpdateResult result = new UpdateResult();
// Count updates
foreach (var entry in appliedFiles)
{
if (entry.Value.State == State.RELEASED)
++result.recent;
else
++result.archived;
}
foreach (var availableQuery in availableFiles)
{
Log.outDebug(LogFilter.SqlUpdates, $"Checking update \"{availableQuery.GetFileName()}\"...");
var applied = appliedFiles.LookupByKey(availableQuery.GetFileName());
if (applied != null)
{
// If redundancy is disabled skip it since the update is already applied.
if (!redundancyChecks)
{
Log.outDebug(LogFilter.SqlUpdates, "Update is already applied, skipping redundancy checks.");
appliedFiles.Remove(availableQuery.GetFileName());
continue;
}
// 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 && (applied.State == State.ARCHIVED) && (availableQuery.state == State.ARCHIVED))
{
Log.outDebug(LogFilter.SqlUpdates, "Update is archived and marked as archived in database, skipping redundancy checks.");
appliedFiles.Remove(availableQuery.GetFileName());
continue;
}
}
// Calculate hash
string hash = CalculateHash(availableQuery.path);
UpdateMode mode = UpdateMode.Apply;
// Update is not in our applied list
if (applied == null)
{
// Catch renames (different filename but same hash)
var hashIter = appliedFiles.Values.FirstOrDefault(p => p.Hash == hash);
if (hashIter != null)
{
// Check if the original file was removed if not we've got a problem.
var renameFile = availableFiles.Find(p => p.GetFileName() == hashIter.Name);
if (renameFile != null)
{
Log.outWarn(LogFilter.SqlUpdates, $"Seems like update \"{availableQuery.GetFileName()}\" \'{hash.Substring(0, 7)}\' was renamed, but the old file is still there! " +
$"Trade it as a new file! (Probably its an unmodified copy of file \"{renameFile.GetFileName()}\")");
}
// Its save to trade the file as renamed here
else
{
Log.outInfo(LogFilter.SqlUpdates, $"Renaming update \"{hashIter.Name}\" to \"{availableQuery.GetFileName()}\" \'{hash.Substring(0, 7)}\'.");
RenameEntry(hashIter.Name, availableQuery.GetFileName());
appliedFiles.Remove(hashIter.Name);
continue;
}
}
// Apply the update if it was never seen before.
else
{
Log.outInfo(LogFilter.SqlUpdates, $"Applying update \"{availableQuery.GetFileName()}\" \'{hash.Substring(0, 7)}\'...");
}
}
// Rehash the update entry if it is contained in our database but with an empty hash.
else if (ConfigMgr.GetDefaultValue("Updates.AllowRehash", true) && string.IsNullOrEmpty(applied.Hash))
{
mode = UpdateMode.Rehash;
Log.outInfo(LogFilter.SqlUpdates, $"Re-hashing update \"{availableQuery.GetFileName()}\" \'{hash.Substring(0, 7)}\'...");
}
else
{
// If the hash of the files differs from the one stored in our database reapply the update (because it was changed).
if (applied.Hash != hash)
{
Log.outInfo(LogFilter.SqlUpdates, $"Reapplying update \"{availableQuery.GetFileName()}\" \'{applied.Hash.Substring(0, 7)}\' . \'{hash.Substring(0, 7)}\' (it changed)...");
}
else
{
// If the file wasn't changed and just moved update its state if necessary.
if (applied.State != availableQuery.state)
{
Log.outDebug(LogFilter.SqlUpdates, $"Updating state of \"{availableQuery.GetFileName()}\" to \'{availableQuery.state}\'...");
UpdateState(availableQuery.GetFileName(), availableQuery.state);
}
Log.outDebug(LogFilter.SqlUpdates, $"Update is already applied and is matching hash \'{hash.Substring(0, 7)}\'.");
appliedFiles.Remove(applied.Name);
continue;
}
}
uint speed = 0;
AppliedFileEntry file = new AppliedFileEntry(availableQuery.GetFileName(), hash, availableQuery.state, 0);
switch (mode)
{
case UpdateMode.Apply:
speed = ApplyTimedFile(availableQuery.path);
goto case UpdateMode.Rehash;
case UpdateMode.Rehash:
UpdateEntry(file, speed);
break;
}
if (applied != null)
appliedFiles.Remove(applied.Name);
if (mode == UpdateMode.Apply)
++result.updated;
}
// Cleanup up orphaned entries if enabled
if (!appliedFiles.Empty())
{
int cleanDeadReferencesMaxCount = ConfigMgr.GetDefaultValue("Updates.CleanDeadRefMaxCount", 3);
bool doCleanup = (cleanDeadReferencesMaxCount < 0) || (appliedFiles.Count <= cleanDeadReferencesMaxCount);
foreach (var entry in appliedFiles)
{
Log.outWarn(LogFilter.SqlUpdates, $"File \'{entry.Key}\' was applied to the database but is missing in your update directory now!");
if (doCleanup)
Log.outInfo(LogFilter.SqlUpdates, $"Deleting orphaned entry \'{entry.Key}\'...");
}
if (doCleanup)
CleanUp(appliedFiles);
else
{
Log.outError(LogFilter.SqlUpdates, $"Cleanup is disabled! There are {appliedFiles.Count} dirty files that were applied to your database but are now missing in your source directory!");
}
}
string info = $"Containing {result.recent} new and {result.archived} archived updates.";
if (result.updated == 0)
Log.outInfo(LogFilter.SqlUpdates, $"{_database.GetDatabaseName()} database is up-to-date! {info}");
else
Log.outInfo(LogFilter.SqlUpdates, $"Applied {result.updated} query(s). {info}");
return true;
}
string GetSourceDirectory()
{
string entry = ConfigMgr.GetDefaultValue("Updates.SourcePath", Environment.CurrentDirectory);
if (!string.IsNullOrEmpty(entry))
return entry;
else
return Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
}
uint ApplyTimedFile(string path)
{
// Benchmark query speed
uint oldMSTime = Time.GetMSTime();
// Update database
_database.ApplyFile(path);
// Return time the query took to apply
return Time.GetMSTimeDiffToNow(oldMSTime);
}
void UpdateEntry(AppliedFileEntry entry, uint speed)
{
string update = $"REPLACE INTO `updates` (`name`, `hash`, `state`, `speed`) VALUES (\"{entry.Name}\", \"{entry.Hash}\", \'{entry.State}\', {speed})";
// Update database
_database.Execute(update);
}
void RenameEntry(string from, string to)
{
// Delete target if it exists
{
string update = $"DELETE FROM `updates` WHERE `name`=\"{to}\"";
// Update database
_database.Execute(update);
}
// Rename
{
string update = $"UPDATE `updates` SET `name`=\"{to}\" WHERE `name`=\"{from}\"";
// Update database
_database.Execute(update);
}
}
void CleanUp(Dictionary<string, AppliedFileEntry> storage)
{
if (storage.Empty())
return;
int remaining = storage.Count;
string update = "DELETE FROM `updates` WHERE `name` IN(";
foreach (var entry in storage)
{
update += $"\"{entry.Key}\"";
if ((--remaining) > 0)
update += ", ";
}
update += ")";
// Update database
_database.Execute(update);
}
void UpdateState(string name, State state)
{
string update = $"UPDATE `updates` SET `state`=\'{state}\' WHERE `name`=\"{name}\"";
// Update database
_database.Execute(update);
}
public List<FileEntry> GetFileList()
{
List<FileEntry> fileList = new List<FileEntry>();
SQLResult result = _database.Query("SELECT `path`, `state` FROM `updates_include`");
if (result.IsEmpty())
return fileList;
do
{
string path = result.Read<string>(0);
if (path[0] == '$')
path = GetSourceDirectory() + path.Substring(1);
if (!Directory.Exists(path))
{
Log.outWarn(LogFilter.SqlUpdates, $"DBUpdater: Given update include directory \"{path}\" isn't existing, skipped!");
continue;
}
State state = result.Read<string>(1).ToEnum<State>();
fileList.AddRange(GetFilesFromDirectory(path, state));
Log.outDebug(LogFilter.SqlUpdates, $"Added applied file \"{path}\" from remote.");
} while (result.NextRow());
return fileList;
}
public Dictionary<string, AppliedFileEntry> ReceiveAppliedFiles()
{
Dictionary<string, AppliedFileEntry> map = new Dictionary<string, AppliedFileEntry>();
SQLResult result = _database.Query("SELECT `name`, `hash`, `state`, UNIX_TIMESTAMP(`timestamp`) FROM `updates` ORDER BY `name` ASC");
if (result.IsEmpty())
return map;
do
{
AppliedFileEntry entry = new AppliedFileEntry(result.Read<string>(0), result.Read<string>(1), result.Read<string>(2).ToEnum<State>(), result.Read<ulong>(3));
map.Add(entry.Name, entry);
}
while (result.NextRow());
return map;
}
IEnumerable<FileEntry> GetFilesFromDirectory(string directory, State state)
{
Queue<string> queue = new Queue<string>();
queue.Enqueue(directory);
while (queue.Count > 0)
{
directory = queue.Dequeue();
try
{
foreach (string subDir in Directory.GetDirectories(directory))
{
queue.Enqueue(subDir);
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
}
string[] files = Directory.GetFiles(directory, "*.sql");
for (int i = 0; i < files.Length; i++)
{
yield return new FileEntry(files[i], state);
}
}
}
string CalculateHash(string fileName)
{
using (SHA1 sha1 = new SHA1Managed())
{
string text = File.ReadAllText(fileName).Replace("\r", "");
return sha1.ComputeHash(Encoding.UTF8.GetBytes(text)).ToHexString();
}
}
protected MySqlBase<T> _database;
}
public class AppliedFileEntry
{
public AppliedFileEntry(string name, string hash, State state, ulong timestamp)
{
Name = name;
Hash = hash;
State = state;
Timestamp = timestamp;
}
public string Name;
public string Hash;
public State State;
public ulong Timestamp;
}
public class FileEntry
{
public FileEntry(string _path, State _state)
{
path = _path;
state = _state;
}
public string GetFileName()
{
return Path.GetFileName(path);
}
public string path;
public State state;
}
struct UpdateResult
{
public int updated;
public int recent;
public int archived;
}
public enum State
{
RELEASED,
ARCHIVED
}
enum UpdateMode
{
Apply,
Rehash
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,324 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 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 <http://www.gnu.org/licenses/>.
*/
namespace Framework.Database
{
public class LoginDatabase : MySqlBase<LoginStatements>
{
public override void PreparedStatements()
{
const string BnetAccountInfo = "ba.id, ba.email, ba.locked, ba.lock_country, ba.last_ip, ba.LoginTicketExpiry, bab.unbandate > UNIX_TIMESTAMP() OR bab.unbandate = bab.bandate, bab.unbandate = bab.bandate";
const string BnetGameAccountInfo = "a.id, a.username, ab.unbandate > UNIX_TIMESTAMP() OR ab.unbandate = ab.bandate, ab.unbandate = ab.bandate, aa.gmlevel";
PrepareStatement(LoginStatements.SEL_REALMLIST, "SELECT id, name, address, localAddress, localSubnetMask, port, icon, flag, timezone, allowedSecurityLevel, population, gamebuild, Region, Battlegroup FROM realmlist WHERE flag <> 3 ORDER BY name");
PrepareStatement(LoginStatements.DEL_EXPIRED_IP_BANS, "DELETE FROM ip_banned WHERE unbandate<>bandate AND unbandate<=UNIX_TIMESTAMP()");
PrepareStatement(LoginStatements.UPD_EXPIRED_ACCOUNT_BANS, "UPDATE account_banned SET active = 0 WHERE active = 1 AND unbandate<>bandate AND unbandate<=UNIX_TIMESTAMP()");
PrepareStatement(LoginStatements.SEL_IP_INFO, "(SELECT unbandate > UNIX_TIMESTAMP() OR unbandate = bandate AS banned, NULL as country FROM ip_banned WHERE ip = ?) " +
"UNION (SELECT NULL AS banned, country FROM ip2nation WHERE INET_NTOA(ip) = ?)");
PrepareStatement(LoginStatements.INS_IP_AUTO_BANNED, "INSERT INTO ip_banned (ip, bandate, unbandate, bannedby, banreason) VALUES (?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, 'Cypher Auth', 'Failed login autoban')");
PrepareStatement(LoginStatements.SEL_IP_BANNED_ALL, "SELECT ip, bandate, unbandate, bannedby, banreason FROM ip_banned WHERE (bandate = unbandate OR unbandate > UNIX_TIMESTAMP()) ORDER BY unbandate");
PrepareStatement(LoginStatements.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");
PrepareStatement(LoginStatements.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");
PrepareStatement(LoginStatements.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");
PrepareStatement(LoginStatements.DEL_ACCOUNT_BANNED, "DELETE FROM account_banned WHERE id = ?");
PrepareStatement(LoginStatements.UPD_ACCOUNT_INFO_CONTINUED_SESSION, "UPDATE account SET sessionkey = ? WHERE id = ?");
PrepareStatement(LoginStatements.SEL_ACCOUNT_INFO_CONTINUED_SESSION, "SELECT username, sessionkey FROM account WHERE id = ?");
PrepareStatement(LoginStatements.UPD_VS, "UPDATE account SET v = ?, s = ? WHERE username = ?");
PrepareStatement(LoginStatements.SEL_LOGON_COUNTRY, "SELECT country FROM ip2nation WHERE ip < ? ORDER BY ip DESC LIMIT 0,1");
PrepareStatement(LoginStatements.SEL_ACCOUNT_ID_BY_NAME, "SELECT id FROM account WHERE username = ?");
PrepareStatement(LoginStatements.SEL_ACCOUNT_LIST_BY_NAME, "SELECT id, username FROM account WHERE username = ?");
PrepareStatement(LoginStatements.SEL_ACCOUNT_INFO_BY_NAME, "SELECT a.id, a.sessionkey, ba.last_ip, ba.locked, ba.lock_country, a.expansion, a.mutetime, ba.locale, a.recruiter, a.os, ba.id, aa.gmLevel, " +
"bab.unbandate > UNIX_TIMESTAMP() OR bab.unbandate = bab.bandate, ab.unbandate > UNIX_TIMESTAMP() OR ab.unbandate = ab.bandate, r.id " +
"FROM account a LEFT JOIN account r ON a.id = r.recruiter LEFT JOIN battlenet_accounts ba ON a.battlenet_account = ba.id " +
"LEFT JOIN account_access aa ON a.id = aa.id AND aa.RealmID IN (-1, ?) LEFT JOIN battlenet_account_bans bab ON ba.id = bab.id LEFT JOIN account_banned ab ON a.id = ab.id AND ab.active = 1 " +
"WHERE a.username = ? ORDER BY aa.RealmID DESC LIMIT 1");
PrepareStatement(LoginStatements.SEL_ACCOUNT_LIST_BY_EMAIL, "SELECT id, username FROM account WHERE email = ?");
PrepareStatement(LoginStatements.SEL_ACCOUNT_BY_IP, "SELECT id, username FROM account WHERE last_ip = ?");
PrepareStatement(LoginStatements.SEL_ACCOUNT_BY_ID, "SELECT 1 FROM account WHERE id = ?");
PrepareStatement(LoginStatements.INS_IP_BANNED, "INSERT INTO ip_banned (ip, bandate, unbandate, bannedby, banreason) VALUES (?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, ?, ?)");
PrepareStatement(LoginStatements.DEL_IP_NOT_BANNED, "DELETE FROM ip_banned WHERE ip = ?");
PrepareStatement(LoginStatements.INS_ACCOUNT_BANNED, "INSERT INTO account_banned VALUES (?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, ?, ?, 1)");
PrepareStatement(LoginStatements.UPD_ACCOUNT_NOT_BANNED, "UPDATE account_banned SET active = 0 WHERE id = ? AND active != 0");
PrepareStatement(LoginStatements.DEL_REALM_CHARACTERS_BY_REALM, "DELETE FROM realmcharacters WHERE acctid = ? AND realmid = ?");
PrepareStatement(LoginStatements.DEL_REALM_CHARACTERS, "DELETE FROM realmcharacters WHERE acctid = ?");
PrepareStatement(LoginStatements.INS_REALM_CHARACTERS, "INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (?, ?, ?)");
PrepareStatement(LoginStatements.SEL_SUM_REALM_CHARACTERS, "SELECT SUM(numchars) FROM realmcharacters WHERE acctid = ?");
PrepareStatement(LoginStatements.INS_ACCOUNT, "INSERT INTO account(username, sha_pass_hash, reg_mail, email, joindate, battlenet_account, battlenet_index) VALUES(?, ?, ?, ?, NOW(), ?, ?)");
PrepareStatement(LoginStatements.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");
PrepareStatement(LoginStatements.UPD_EXPANSION, "UPDATE account SET expansion = ? WHERE id = ?");
PrepareStatement(LoginStatements.UPD_ACCOUNT_LOCK, "UPDATE account SET locked = ? WHERE id = ?");
PrepareStatement(LoginStatements.UPD_ACCOUNT_LOCK_CONTRY, "UPDATE account SET lock_country = ? WHERE id = ?");
PrepareStatement(LoginStatements.INS_LOG, "INSERT INTO logs (time, realm, type, level, string) VALUES (?, ?, ?, ?, ?)");
PrepareStatement(LoginStatements.UPD_USERNAME, "UPDATE account SET v = 0, s = 0, username = ?, sha_pass_hash = ? WHERE id = ?");
PrepareStatement(LoginStatements.UPD_PASSWORD, "UPDATE account SET v = 0, s = 0, sha_pass_hash = ? WHERE id = ?");
PrepareStatement(LoginStatements.UPD_EMAIL, "UPDATE account SET email = ? WHERE id = ?");
PrepareStatement(LoginStatements.UPD_REG_EMAIL, "UPDATE account SET reg_mail = ? WHERE id = ?");
PrepareStatement(LoginStatements.UPD_MUTE_TIME, "UPDATE account SET mutetime = ? , mutereason = ? , muteby = ? WHERE id = ?");
PrepareStatement(LoginStatements.UPD_MUTE_TIME_LOGIN, "UPDATE account SET mutetime = ? WHERE id = ?");
PrepareStatement(LoginStatements.UPD_LAST_IP, "UPDATE account SET last_ip = ? WHERE username = ?");
PrepareStatement(LoginStatements.UPD_LAST_ATTEMPT_IP, "UPDATE account SET last_attempt_ip = ? WHERE username = ?");
PrepareStatement(LoginStatements.UPD_ACCOUNT_ONLINE, "UPDATE account SET online = 1 WHERE id = ?");
PrepareStatement(LoginStatements.UPD_UPTIME_PLAYERS, "UPDATE uptime SET uptime = ?, maxplayers = ? WHERE realmid = ? AND starttime = ?");
PrepareStatement(LoginStatements.DEL_OLD_LOGS, "DELETE FROM logs WHERE (time + ?) < ? AND realm = ?");
PrepareStatement(LoginStatements.DEL_ACCOUNT_ACCESS, "DELETE FROM account_access WHERE id = ?");
PrepareStatement(LoginStatements.DEL_ACCOUNT_ACCESS_BY_REALM, "DELETE FROM account_access WHERE id = ? AND (RealmID = ? OR RealmID = -1)");
PrepareStatement(LoginStatements.INS_ACCOUNT_ACCESS, "INSERT INTO account_access (id,gmlevel,RealmID) VALUES (?, ?, ?)");
PrepareStatement(LoginStatements.GET_ACCOUNT_ID_BY_USERNAME, "SELECT id FROM account WHERE username = ?");
PrepareStatement(LoginStatements.GET_ACCOUNT_ACCESS_GMLEVEL, "SELECT gmlevel FROM account_access WHERE id = ?");
PrepareStatement(LoginStatements.GET_GMLEVEL_BY_REALMID, "SELECT gmlevel FROM account_access WHERE id = ? AND (RealmID = ? OR RealmID = -1)");
PrepareStatement(LoginStatements.GET_USERNAME_BY_ID, "SELECT username FROM account WHERE id = ?");
PrepareStatement(LoginStatements.SEL_CHECK_PASSWORD, "SELECT 1 FROM account WHERE id = ? AND sha_pass_hash = ?");
PrepareStatement(LoginStatements.SEL_CHECK_PASSWORD_BY_NAME, "SELECT 1 FROM account WHERE username = ? AND sha_pass_hash = ?");
PrepareStatement(LoginStatements.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 = ?");
PrepareStatement(LoginStatements.SEL_PINFO_BANS, "SELECT unbandate, bandate = unbandate, bannedby, banreason FROM account_banned WHERE id = ? AND active ORDER BY bandate ASC LIMIT 1");
PrepareStatement(LoginStatements.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 = ?)");
PrepareStatement(LoginStatements.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 = ?");
PrepareStatement(LoginStatements.SEL_ACCOUNT_ACCESS_GMLEVEL_TEST, "SELECT 1 FROM account_access WHERE id = ? AND gmlevel > ?");
PrepareStatement(LoginStatements.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 = ?");
PrepareStatement(LoginStatements.SEL_ACCOUNT_WHOIS, "SELECT username, email, last_ip FROM account WHERE id = ?");
PrepareStatement(LoginStatements.SEL_LAST_ATTEMPT_IP, "SELECT last_attempt_ip FROM account WHERE id = ?");
PrepareStatement(LoginStatements.SEL_LAST_IP, "SELECT last_ip FROM account WHERE id = ?");
PrepareStatement(LoginStatements.SEL_REALMLIST_SECURITY_LEVEL, "SELECT allowedSecurityLevel from realmlist WHERE id = ?");
PrepareStatement(LoginStatements.DEL_ACCOUNT, "DELETE FROM account WHERE id = ?");
PrepareStatement(LoginStatements.SEL_IP2NATION_COUNTRY, "SELECT c.country FROM ip2nationCountries c, ip2nation i WHERE i.ip < ? AND c.code = i.country ORDER BY i.ip DESC LIMIT 0,1");
PrepareStatement(LoginStatements.SEL_AUTOBROADCAST, "SELECT id, weight, text FROM autobroadcast WHERE realmid = ? OR realmid = -1");
PrepareStatement(LoginStatements.GET_EMAIL_BY_ID, "SELECT email FROM account WHERE id = ?");
// 0: uint32, 1: uint32, 2: uint8, 3: uint32, 4: string // Complete name: "Login_Insert_AccountLoginDeLete_IP_Logging"
PrepareStatement(LoginStatements.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())");
// 0: uint32, 1: uint32, 2: uint8, 3: uint32, 4: string // Complete name: "Login_Insert_FailedAccountLogin_IP_Logging"
PrepareStatement(LoginStatements.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())");
// 0: uint32, 1: uint32, 2: uint8, 3: string, 4: string // Complete name: "Login_Insert_CharacterDelete_IP_Logging"
PrepareStatement(LoginStatements.INS_CHAR_IP_LOGGING, "INSERT INTO logs_ip_actions (account_id,character_guid,type,ip,systemnote,unixtime,time) VALUES (?, ?, ?, ?, ?, unix_timestamp(NOW()), NOW())");
// 0: string, 1: string, 2: string // Complete name: "Login_Insert_Failed_Account_Login_due_password_IP_Logging"
PrepareStatement(LoginStatements.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())");
PrepareStatement(LoginStatements.SEL_ACCOUNT_ACCESS_BY_ID, "SELECT gmlevel, RealmID FROM account_access WHERE id = ? and (RealmID = ? OR RealmID = -1) ORDER BY gmlevel desc");
PrepareStatement(LoginStatements.SEL_RBAC_ACCOUNT_PERMISSIONS, "SELECT permissionId, granted FROM rbac_account_permissions WHERE accountId = ? AND (realmId = ? OR realmId = -1) ORDER BY permissionId, realmId");
PrepareStatement(LoginStatements.INS_RBAC_ACCOUNT_PERMISSION, "INSERT INTO rbac_account_permissions (accountId, permissionId, granted, realmId) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE granted = VALUES(granted)");
PrepareStatement(LoginStatements.DEL_RBAC_ACCOUNT_PERMISSION, "DELETE FROM rbac_account_permissions WHERE accountId = ? AND permissionId = ? AND (realmId = ? OR realmId = -1)");
PrepareStatement(LoginStatements.INS_ACCOUNT_MUTE, "INSERT INTO account_muted VALUES (?, UNIX_TIMESTAMP(), ?, ?, ?)");
PrepareStatement(LoginStatements.SEL_ACCOUNT_MUTE_INFO, "SELECT mutedate, mutetime, mutereason, mutedby FROM account_muted WHERE guid = ? ORDER BY mutedate ASC");
PrepareStatement(LoginStatements.DEL_ACCOUNT_MUTED, "DELETE FROM account_muted WHERE guid = ?");
PrepareStatement(LoginStatements.SEL_BNET_AUTHENTICATION, "SELECT ba.id, ba.sha_pass_hash, ba.failed_logins, ba.LoginTicket, ba.LoginTicketExpiry, bab.unbandate > UNIX_TIMESTAMP() OR bab.unbandate = bab.bandate FROM battlenet_accounts ba LEFT JOIN battlenet_account_bans bab ON ba.id = bab.id WHERE email = ?");
PrepareStatement(LoginStatements.UPD_BNET_AUTHENTICATION, "UPDATE battlenet_accounts SET LoginTicket = ?, LoginTicketExpiry = ? WHERE id = ?");
PrepareStatement(LoginStatements.SEL_BNET_ACCOUNT_INFO, "SELECT " + BnetAccountInfo + ", " + BnetGameAccountInfo +
" FROM battlenet_accounts ba LEFT JOIN battlenet_account_bans bab ON ba.id = bab.id LEFT JOIN account a ON ba.id = a.battlenet_account" +
" LEFT JOIN account_banned ab ON a.id = ab.id AND ab.active = 1 LEFT JOIN account_access aa ON a.id = aa.id AND aa.RealmID = -1 WHERE ba.LoginTicket = ? ORDER BY a.id");
PrepareStatement(LoginStatements.UPD_BNET_LAST_LOGIN_INFO, "UPDATE battlenet_accounts SET last_ip = ?, last_login = NOW(), locale = ?, failed_logins = 0, os = ? WHERE id = ?");
PrepareStatement(LoginStatements.UPD_BNET_GAME_ACCOUNT_LOGIN_INFO, "UPDATE account SET sessionkey = ?, last_ip = ?, last_login = NOW(), locale = ?, failed_logins = 0, os = ? WHERE username = ?");
PrepareStatement(LoginStatements.SEL_BNET_CHARACTER_COUNTS_BY_ACCOUNT_ID, "SELECT rc.acctid, rc.numchars, r.id, r.Region, r.Battlegroup FROM realmcharacters rc INNER JOIN realmlist r ON rc.realmid = r.id WHERE rc.acctid = ?");
PrepareStatement(LoginStatements.SEL_BNET_CHARACTER_COUNTS_BY_BNET_ID, "SELECT rc.acctid, rc.numchars, r.id, r.Region, r.Battlegroup FROM realmcharacters rc INNER JOIN realmlist r ON rc.realmid = r.id LEFT JOIN account a ON rc.acctid = a.id WHERE a.battlenet_account = ?");
PrepareStatement(LoginStatements.SEL_BNET_LAST_PLAYER_CHARACTERS, "SELECT lpc.accountId, lpc.region, lpc.battlegroup, lpc.realmId, lpc.characterName, lpc.characterGUID, lpc.lastPlayedTime FROM account_last_played_character lpc LEFT JOIN account a ON lpc.accountId = a.id WHERE a.battlenet_account = ?");
PrepareStatement(LoginStatements.DEL_BNET_LAST_PLAYER_CHARACTERS, "DELETE FROM account_last_played_character WHERE accountId = ? AND region = ? AND battlegroup = ?");
PrepareStatement(LoginStatements.INS_BNET_LAST_PLAYER_CHARACTERS, "INSERT INTO account_last_played_character (accountId, region, battlegroup, realmId, characterName, characterGUID, lastPlayedTime) VALUES (?,?,?,?,?,?,?)");
PrepareStatement(LoginStatements.INS_BNET_ACCOUNT, "INSERT INTO battlenet_accounts (`email`,`sha_pass_hash`) VALUES (?, ?)");
PrepareStatement(LoginStatements.SEL_BNET_ACCOUNT_EMAIL_BY_ID, "SELECT email FROM battlenet_accounts WHERE id = ?");
PrepareStatement(LoginStatements.SEL_BNET_ACCOUNT_ID_BY_EMAIL, "SELECT id FROM battlenet_accounts WHERE email = ?");
PrepareStatement(LoginStatements.UPD_BNET_PASSWORD, "UPDATE battlenet_accounts SET sha_pass_hash = ? WHERE id = ?");
PrepareStatement(LoginStatements.SEL_BNET_CHECK_PASSWORD, "SELECT 1 FROM battlenet_accounts WHERE id = ? AND sha_pass_hash = ?");
PrepareStatement(LoginStatements.UPD_BNET_ACCOUNT_LOCK, "UPDATE battlenet_accounts SET locked = ? WHERE id = ?");
PrepareStatement(LoginStatements.UPD_BNET_ACCOUNT_LOCK_CONTRY, "UPDATE battlenet_accounts SET lock_country = ? WHERE id = ?");
PrepareStatement(LoginStatements.SEL_BNET_ACCOUNT_ID_BY_GAME_ACCOUNT, "SELECT battlenet_account FROM account WHERE id = ?");
PrepareStatement(LoginStatements.UPD_BNET_GAME_ACCOUNT_LINK, "UPDATE account SET battlenet_account = ?, battlenet_index = ? WHERE id = ?");
PrepareStatement(LoginStatements.SEL_BNET_MAX_ACCOUNT_INDEX, "SELECT MAX(battlenet_index) FROM account WHERE battlenet_account = ?");
PrepareStatement(LoginStatements.SEL_BNET_GAME_ACCOUNT_LIST, "SELECT a.id, a.username FROM account a LEFT JOIN battlenet_accounts ba ON a.battlenet_account = ba.id WHERE ba.email = ?");
PrepareStatement(LoginStatements.UPD_BNET_FAILED_LOGINS, "UPDATE battlenet_accounts SET failed_logins = failed_logins + 1 WHERE id = ?");
PrepareStatement(LoginStatements.INS_BNET_ACCOUNT_AUTO_BANNED, "INSERT INTO battlenet_account_bans(id, bandate, unbandate, bannedby, banreason) VALUES(?, UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+?, 'Trinity Auth', 'Failed login autoban')");
PrepareStatement(LoginStatements.DEL_BNET_EXPIRED_ACCOUNT_BANNED, "DELETE FROM battlenet_account_bans WHERE unbandate<>bandate AND unbandate<=UNIX_TIMESTAMP()");
PrepareStatement(LoginStatements.UPD_BNET_RESET_FAILED_LOGINS, "UPDATE battlenet_accounts SET failed_logins = 0 WHERE id = ?");
PrepareStatement(LoginStatements.SEL_LAST_CHAR_UNDELETE, "SELECT LastCharacterUndelete FROM battlenet_accounts WHERE Id = ?");
PrepareStatement(LoginStatements.UPD_LAST_CHAR_UNDELETE, "UPDATE battlenet_accounts SET LastCharacterUndelete = UNIX_TIMESTAMP() WHERE Id = ?");
// Account wide toys
PrepareStatement(LoginStatements.SEL_ACCOUNT_TOYS, "SELECT itemId, isFavourite FROM battlenet_account_toys WHERE accountId = ?");
PrepareStatement(LoginStatements.REP_ACCOUNT_TOYS, "REPLACE INTO battlenet_account_toys (accountId, itemId, isFavourite) VALUES (?, ?, ?)");
// Battle Pets
PrepareStatement(LoginStatements.SEL_BATTLE_PETS, "SELECT guid, species, breed, level, exp, health, quality, flags, name FROM battle_pets WHERE battlenetAccountId = ?");
PrepareStatement(LoginStatements.INS_BATTLE_PETS, "INSERT INTO battle_pets (guid, battlenetAccountId, species, breed, level, exp, health, quality, flags, name) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
PrepareStatement(LoginStatements.DEL_BATTLE_PETS, "DELETE FROM battle_pets WHERE battlenetAccountId = ? AND guid = ?");
PrepareStatement(LoginStatements.UPD_BATTLE_PETS, "UPDATE battle_pets SET level = ?, exp = ?, health = ?, quality = ?, flags = ?, name = ? WHERE battlenetAccountId = ? AND guid = ?");
PrepareStatement(LoginStatements.SEL_BATTLE_PET_SLOTS, "SELECT id, battlePetGuid, locked FROM battle_pet_slots WHERE battlenetAccountId = ?");
PrepareStatement(LoginStatements.INS_BATTLE_PET_SLOTS, "INSERT INTO battle_pet_slots (id, battlenetAccountId, battlePetGuid, locked) VALUES (?, ?, ?, ?)");
PrepareStatement(LoginStatements.DEL_BATTLE_PET_SLOTS, "DELETE FROM battle_pet_slots WHERE battlenetAccountId = ?");
PrepareStatement(LoginStatements.SEL_ACCOUNT_HEIRLOOMS, "SELECT itemId, flags FROM battlenet_account_heirlooms WHERE accountId = ?");
PrepareStatement(LoginStatements.REP_ACCOUNT_HEIRLOOMS, "REPLACE INTO battlenet_account_heirlooms (accountId, itemId, flags) VALUES (?, ?, ?)");
// Account wide mounts
PrepareStatement(LoginStatements.SEL_ACCOUNT_MOUNTS, "SELECT mountSpellId, flags FROM battlenet_account_mounts WHERE battlenetAccountId = ?");
PrepareStatement(LoginStatements.REP_ACCOUNT_MOUNTS, "REPLACE INTO battlenet_account_mounts (battlenetAccountId, mountSpellId, flags) VALUES (?, ?, ?)");
// Transmog collection
PrepareStatement(LoginStatements.SEL_BNET_ITEM_APPEARANCES, "SELECT blobIndex, appearanceMask FROM battlenet_item_appearances WHERE battlenetAccountId = ? ORDER BY blobIndex DESC");
PrepareStatement(LoginStatements.INS_BNET_ITEM_APPEARANCES, "INSERT INTO battlenet_item_appearances (battlenetAccountId, blobIndex, appearanceMask) VALUES (?, ?, ?) " +
"ON DUPLICATE KEY UPDATE appearanceMask = appearanceMask | VALUES(appearanceMask)");
PrepareStatement(LoginStatements.SEL_BNET_ITEM_FAVORITE_APPEARANCES, "SELECT itemModifiedAppearanceId FROM battlenet_item_favorite_appearances WHERE battlenetAccountId = ?");
PrepareStatement(LoginStatements.INS_BNET_ITEM_FAVORITE_APPEARANCE, "INSERT INTO battlenet_item_favorite_appearances (battlenetAccountId, itemModifiedAppearanceId) VALUES (?, ?)");
PrepareStatement(LoginStatements.DEL_BNET_ITEM_FAVORITE_APPEARANCE, "DELETE FROM battlenet_item_favorite_appearances WHERE battlenetAccountId = ? AND itemModifiedAppearanceId = ?");
}
}
public enum LoginStatements
{
SEL_REALMLIST,
DEL_EXPIRED_IP_BANS,
UPD_EXPIRED_ACCOUNT_BANS,
SEL_IP_INFO,
INS_IP_AUTO_BANNED,
SEL_ACCOUNT_BANNED_ALL,
SEL_ACCOUNT_BANNED_BY_USERNAME,
DEL_ACCOUNT_BANNED,
UPD_ACCOUNT_INFO_CONTINUED_SESSION,
SEL_ACCOUNT_INFO_CONTINUED_SESSION,
UPD_VS,
SEL_LOGON_COUNTRY,
SEL_ACCOUNT_ID_BY_NAME,
SEL_ACCOUNT_LIST_BY_NAME,
SEL_ACCOUNT_INFO_BY_NAME,
SEL_ACCOUNT_LIST_BY_EMAIL,
SEL_ACCOUNT_BY_IP,
INS_IP_BANNED,
DEL_IP_NOT_BANNED,
SEL_IP_BANNED_ALL,
SEL_IP_BANNED_BY_IP,
SEL_ACCOUNT_BY_ID,
INS_ACCOUNT_BANNED,
UPD_ACCOUNT_NOT_BANNED,
DEL_REALM_CHARACTERS_BY_REALM,
DEL_REALM_CHARACTERS,
INS_REALM_CHARACTERS,
SEL_SUM_REALM_CHARACTERS,
INS_ACCOUNT,
INS_REALM_CHARACTERS_INIT,
UPD_EXPANSION,
UPD_ACCOUNT_LOCK,
UPD_ACCOUNT_LOCK_CONTRY,
INS_LOG,
UPD_USERNAME,
UPD_PASSWORD,
UPD_EMAIL,
UPD_REG_EMAIL,
UPD_MUTE_TIME,
UPD_MUTE_TIME_LOGIN,
UPD_LAST_IP,
UPD_LAST_ATTEMPT_IP,
UPD_ACCOUNT_ONLINE,
UPD_UPTIME_PLAYERS,
DEL_OLD_LOGS,
DEL_ACCOUNT_ACCESS,
DEL_ACCOUNT_ACCESS_BY_REALM,
INS_ACCOUNT_ACCESS,
GET_ACCOUNT_ID_BY_USERNAME,
GET_ACCOUNT_ACCESS_GMLEVEL,
GET_GMLEVEL_BY_REALMID,
GET_USERNAME_BY_ID,
SEL_CHECK_PASSWORD,
SEL_CHECK_PASSWORD_BY_NAME,
SEL_PINFO,
SEL_PINFO_BANS,
SEL_GM_ACCOUNTS,
SEL_ACCOUNT_INFO,
SEL_ACCOUNT_ACCESS_GMLEVEL_TEST,
SEL_ACCOUNT_ACCESS,
SEL_ACCOUNT_RECRUITER,
SEL_BANS,
SEL_ACCOUNT_WHOIS,
SEL_REALMLIST_SECURITY_LEVEL,
DEL_ACCOUNT,
SEL_IP2NATION_COUNTRY,
SEL_AUTOBROADCAST,
SEL_LAST_ATTEMPT_IP,
SEL_LAST_IP,
GET_EMAIL_BY_ID,
INS_ALDL_IP_LOGGING,
INS_FACL_IP_LOGGING,
INS_CHAR_IP_LOGGING,
INS_FALP_IP_LOGGING,
SEL_ACCOUNT_ACCESS_BY_ID,
SEL_RBAC_ACCOUNT_PERMISSIONS,
INS_RBAC_ACCOUNT_PERMISSION,
DEL_RBAC_ACCOUNT_PERMISSION,
INS_ACCOUNT_MUTE,
SEL_ACCOUNT_MUTE_INFO,
DEL_ACCOUNT_MUTED,
SEL_BNET_AUTHENTICATION,
UPD_BNET_AUTHENTICATION,
SEL_BNET_ACCOUNT_INFO,
UPD_BNET_LAST_LOGIN_INFO,
UPD_BNET_GAME_ACCOUNT_LOGIN_INFO,
SEL_BNET_CHARACTER_COUNTS_BY_ACCOUNT_ID,
SEL_BNET_CHARACTER_COUNTS_BY_BNET_ID,
SEL_BNET_LAST_PLAYER_CHARACTERS,
DEL_BNET_LAST_PLAYER_CHARACTERS,
INS_BNET_LAST_PLAYER_CHARACTERS,
INS_BNET_ACCOUNT,
SEL_BNET_ACCOUNT_EMAIL_BY_ID,
SEL_BNET_ACCOUNT_ID_BY_EMAIL,
UPD_BNET_PASSWORD,
SEL_BNET_ACCOUNT_SALT_BY_ID,
SEL_BNET_CHECK_PASSWORD,
UPD_BNET_ACCOUNT_LOCK,
UPD_BNET_ACCOUNT_LOCK_CONTRY,
SEL_BNET_ACCOUNT_ID_BY_GAME_ACCOUNT,
UPD_BNET_GAME_ACCOUNT_LINK,
SEL_BNET_MAX_ACCOUNT_INDEX,
SEL_BNET_GAME_ACCOUNT_LIST,
UPD_BNET_FAILED_LOGINS,
INS_BNET_ACCOUNT_AUTO_BANNED,
DEL_BNET_EXPIRED_ACCOUNT_BANNED,
UPD_BNET_RESET_FAILED_LOGINS,
SEL_LAST_CHAR_UNDELETE,
UPD_LAST_CHAR_UNDELETE,
SEL_ACCOUNT_TOYS,
REP_ACCOUNT_TOYS,
SEL_BATTLE_PETS,
INS_BATTLE_PETS,
DEL_BATTLE_PETS,
UPD_BATTLE_PETS,
SEL_BATTLE_PET_SLOTS,
INS_BATTLE_PET_SLOTS,
DEL_BATTLE_PET_SLOTS,
SEL_ACCOUNT_HEIRLOOMS,
REP_ACCOUNT_HEIRLOOMS,
SEL_ACCOUNT_MOUNTS,
REP_ACCOUNT_MOUNTS,
SEL_BNET_ITEM_APPEARANCES,
INS_BNET_ITEM_APPEARANCES,
SEL_BNET_ITEM_FAVORITE_APPEARANCES,
INS_BNET_ITEM_FAVORITE_APPEARANCE,
DEL_BNET_ITEM_FAVORITE_APPEARANCE,
MAX_LOGINDATABASE_STATEMENTS
}
}
@@ -0,0 +1,171 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 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 <http://www.gnu.org/licenses/>.
*/
namespace Framework.Database
{
public class WorldDatabase : MySqlBase<WorldStatements>
{
public override void PreparedStatements()
{
PrepareStatement(WorldStatements.SEL_QUEST_POOLS, "SELECT entry, pool_entry FROM pool_quest");
PrepareStatement(WorldStatements.DEL_CRELINKED_RESPAWN, "DELETE FROM linked_respawn WHERE guid = ?");
PrepareStatement(WorldStatements.REP_CREATURE_LINKED_RESPAWN, "REPLACE INTO linked_respawn (guid, linkedGuid) VALUES (?, ?)");
PrepareStatement(WorldStatements.SEL_CREATURE_TEXT, "SELECT entry, groupid, id, text, type, language, probability, emote, duration, sound, BroadcastTextID, TextRange FROM creature_text");
PrepareStatement(WorldStatements.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_param_string, action_type, action_param1, action_param2, action_param3, action_param4, action_param5, action_param6, target_type, target_param1, target_param2, target_param3, target_x, target_y, target_z, target_o FROM smart_scripts ORDER BY entryorguid, source_type, id, link");
PrepareStatement(WorldStatements.SEL_SMARTAI_WP, "SELECT entry, pointid, position_x, position_y, position_z FROM waypoints ORDER BY entry, pointid");
PrepareStatement(WorldStatements.DEL_GAMEOBJECT, "DELETE FROM gameobject WHERE guid = ?");
PrepareStatement(WorldStatements.DEL_EVENT_GAMEOBJECT, "DELETE FROM game_event_gameobject WHERE guid = ?");
PrepareStatement(WorldStatements.INS_GRAVEYARD_ZONE, "INSERT INTO graveyard_zone (ID, GhostZone, faction) VALUES (?, ?, ?)");
PrepareStatement(WorldStatements.DEL_GRAVEYARD_ZONE, "DELETE FROM graveyard_zone WHERE ID = ? AND GhostZone = ? AND faction = ?");
PrepareStatement(WorldStatements.INS_GAME_TELE, "INSERT INTO game_tele (id, position_x, position_y, position_z, orientation, map, name) VALUES (?, ?, ?, ?, ?, ?, ?)");
PrepareStatement(WorldStatements.DEL_GAME_TELE, "DELETE FROM game_tele WHERE name = ?");
PrepareStatement(WorldStatements.INS_NPC_VENDOR, "INSERT INTO npc_vendor (entry, item, maxcount, incrtime, extendedcost, type) VALUES(?, ?, ?, ?, ?, ?)");
PrepareStatement(WorldStatements.DEL_NPC_VENDOR, "DELETE FROM npc_vendor WHERE entry = ? AND item = ? AND type = ?");
PrepareStatement(WorldStatements.SEL_NPC_VENDOR_REF, "SELECT item, maxcount, incrtime, ExtendedCost, type, BonusListIDs, PlayerConditionID, IgnoreFiltering FROM npc_vendor WHERE entry = ? ORDER BY slot ASC");
PrepareStatement(WorldStatements.UPD_CREATURE_MOVEMENT_TYPE, "UPDATE creature SET MovementType = ? WHERE guid = ?");
PrepareStatement(WorldStatements.UPD_CREATURE_FACTION, "UPDATE creature_template SET faction = ? WHERE entry = ?");
PrepareStatement(WorldStatements.UPD_CREATURE_NPCFLAG, "UPDATE creature_template SET npcflag = ? WHERE entry = ?");
PrepareStatement(WorldStatements.UPD_CREATURE_POSITION, "UPDATE creature SET position_x = ?, position_y = ?, position_z = ?, orientation = ? WHERE guid = ?");
PrepareStatement(WorldStatements.UPD_CREATURE_SPAWN_DISTANCE, "UPDATE creature SET spawndist = ?, MovementType = ? WHERE guid = ?");
PrepareStatement(WorldStatements.UPD_CREATURE_SPAWN_TIME_SECS, "UPDATE creature SET spawntimesecs = ? WHERE guid = ?");
PrepareStatement(WorldStatements.INS_CREATURE_FORMATION, "INSERT INTO creature_formations (leaderGUID, memberGUID, dist, angle, groupAI) VALUES (?, ?, ?, ?, ?)");
PrepareStatement(WorldStatements.INS_WAYPOINT_DATA, "INSERT INTO waypoint_data (id, point, position_x, position_y, position_z) VALUES (?, ?, ?, ?, ?)");
PrepareStatement(WorldStatements.DEL_WAYPOINT_DATA, "DELETE FROM waypoint_data WHERE id = ? AND point = ?");
PrepareStatement(WorldStatements.UPD_WAYPOINT_DATA_POINT, "UPDATE waypoint_data SET point = point - 1 WHERE id = ? AND point > ?");
PrepareStatement(WorldStatements.UPD_WAYPOINT_DATA_POSITION, "UPDATE waypoint_data SET position_x = ?, position_y = ?, position_z = ? where id = ? AND point = ?");
PrepareStatement(WorldStatements.UPD_WAYPOINT_DATA_WPGUID, "UPDATE waypoint_data SET wpguid = ? WHERE id = ? and point = ?");
PrepareStatement(WorldStatements.SEL_WAYPOINT_DATA_MAX_ID, "SELECT MAX(id) FROM waypoint_data");
PrepareStatement(WorldStatements.SEL_WAYPOINT_DATA_MAX_POINT, "SELECT MAX(point) FROM waypoint_data WHERE id = ?");
PrepareStatement(WorldStatements.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");
PrepareStatement(WorldStatements.SEL_WAYPOINT_DATA_POS_BY_ID, "SELECT point, position_x, position_y, position_z FROM waypoint_data WHERE id = ?");
PrepareStatement(WorldStatements.SEL_WAYPOINT_DATA_POS_FIRST_BY_ID, "SELECT position_x, position_y, position_z FROM waypoint_data WHERE point = 1 AND id = ?");
PrepareStatement(WorldStatements.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");
PrepareStatement(WorldStatements.SEL_WAYPOINT_DATA_BY_WPGUID, "SELECT id, point FROM waypoint_data WHERE wpguid = ?");
PrepareStatement(WorldStatements.SEL_WAYPOINT_DATA_ALL_BY_WPGUID, "SELECT id, point, delay, move_type, action, action_chance FROM waypoint_data WHERE wpguid = ?");
PrepareStatement(WorldStatements.UPD_WAYPOINT_DATA_ALL_WPGUID, "UPDATE waypoint_data SET wpguid = 0");
PrepareStatement(WorldStatements.SEL_WAYPOINT_DATA_BY_POS, "SELECT id, point FROM waypoint_data WHERE (abs(position_x - ?) <= ?) and (abs(position_y - ?) <= ?) and (abs(position_z - ?) <= ?)");
PrepareStatement(WorldStatements.SEL_WAYPOINT_DATA_WPGUID_BY_ID, "SELECT wpguid FROM waypoint_data WHERE id = ? and wpguid <> 0");
PrepareStatement(WorldStatements.SEL_WAYPOINT_DATA_ACTION, "SELECT DISTINCT action FROM waypoint_data");
PrepareStatement(WorldStatements.SEL_WAYPOINT_SCRIPTS_MAX_ID, "SELECT MAX(guid) FROM waypoint_scripts");
PrepareStatement(WorldStatements.INS_CREATURE_ADDON, "INSERT INTO creature_addon(guid, path_id) VALUES (?, ?)");
PrepareStatement(WorldStatements.UPD_CREATURE_ADDON_PATH, "UPDATE creature_addon SET path_id = ? WHERE guid = ?");
PrepareStatement(WorldStatements.DEL_CREATURE_ADDON, "DELETE FROM creature_addon WHERE guid = ?");
PrepareStatement(WorldStatements.SEL_CREATURE_ADDON_BY_GUID, "SELECT guid FROM creature_addon WHERE guid = ?");
PrepareStatement(WorldStatements.INS_WAYPOINT_SCRIPT, "INSERT INTO waypoint_scripts (guid) VALUES (?)");
PrepareStatement(WorldStatements.DEL_WAYPOINT_SCRIPT, "DELETE FROM waypoint_scripts WHERE guid = ?");
PrepareStatement(WorldStatements.UPD_WAYPOINT_SCRIPT_ID, "UPDATE waypoint_scripts SET id = ? WHERE guid = ?");
PrepareStatement(WorldStatements.UPD_WAYPOINT_SCRIPT_X, "UPDATE waypoint_scripts SET x = ? WHERE guid = ?");
PrepareStatement(WorldStatements.UPD_WAYPOINT_SCRIPT_Y, "UPDATE waypoint_scripts SET y = ? WHERE guid = ?");
PrepareStatement(WorldStatements.UPD_WAYPOINT_SCRIPT_Z, "UPDATE waypoint_scripts SET z = ? WHERE guid = ?");
PrepareStatement(WorldStatements.UPD_WAYPOINT_SCRIPT_O, "UPDATE waypoint_scripts SET o = ? WHERE guid = ?");
PrepareStatement(WorldStatements.SEL_WAYPOINT_SCRIPT_ID_BY_GUID, "SELECT id FROM waypoint_scripts WHERE guid = ?");
PrepareStatement(WorldStatements.DEL_CREATURE, "DELETE FROM creature WHERE guid = ?");
PrepareStatement(WorldStatements.SEL_COMMANDS, "SELECT name, permission, help FROM command");
PrepareStatement(WorldStatements.SEL_CREATURE_TEMPLATE, "SELECT entry, difficulty_entry_1, difficulty_entry_2, difficulty_entry_3, KillCredit1, KillCredit2, modelid1, modelid2, modelid3, modelid4, name, femaleName, subname, IconName, gossip_menu_id, minlevel, maxlevel, HealthScalingExpansion, RequiredExpansion, VignetteID, faction, npcflag, speed_walk, speed_run, scale, rank, dmgschool, BaseAttackTime, RangeAttackTime, BaseVariance, RangeVariance, unit_class, unit_flags, unit_flags2, unit_flags3, dynamicflags, family, trainer_class, type, type_flags, type_flags2, lootid, pickpocketloot, skinloot, resistance1, resistance2, resistance3, resistance4, resistance5, resistance6, spell1, spell2, spell3, spell4, spell5, spell6, spell7, spell8, VehicleId, mingold, maxgold, AIName, MovementType, InhabitType, HoverHeight, HealthModifier, HealthModifierExtra, ManaModifier, ManaModifierExtra, ArmorModifier, DamageModifier, ExperienceModifier, RacialLeader, movementId, RegenHealth, mechanic_immune_mask, flags_extra, ScriptName FROM creature_template WHERE entry = ?");
PrepareStatement(WorldStatements.SEL_WAYPOINT_SCRIPT_BY_ID, "SELECT guid, delay, command, datalong, datalong2, dataint, x, y, z, o FROM waypoint_scripts WHERE id = ?");
PrepareStatement(WorldStatements.SEL_CREATURE_BY_ID, "SELECT guid FROM creature WHERE id = ?");
PrepareStatement(WorldStatements.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)) <= ? ORDER BY order_");
PrepareStatement(WorldStatements.SEL_CREATURE_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 creature WHERE map = ? AND (POW(position_x - ?, 2) + POW(position_y - ?, 2) + POW(position_z - ?, 2)) <= ? ORDER BY order_");
PrepareStatement(WorldStatements.INS_CREATURE, "INSERT INTO creature (guid, id , map, spawnMask, PhaseId, PhaseGroup, modelid, equipment_id, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, currentwaypoint, curhealth, curmana, MovementType, npcflag, unit_flags, unit_flags2, unit_flags3, dynamicflags) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
PrepareStatement(WorldStatements.DEL_GAME_EVENT_CREATURE, "DELETE FROM game_event_creature WHERE guid = ?");
PrepareStatement(WorldStatements.DEL_GAME_EVENT_MODEL_EQUIP, "DELETE FROM game_event_model_equip WHERE guid = ?");
PrepareStatement(WorldStatements.INS_GAMEOBJECT, "INSERT INTO gameobject (guid, id, map, spawnMask, position_x, position_y, position_z, orientation, rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
PrepareStatement(WorldStatements.INS_DISABLES, "INSERT INTO disables (entry, sourceType, flags, comment) VALUES (?, ?, ?, ?)");
PrepareStatement(WorldStatements.SEL_DISABLES, "SELECT entry FROM disables WHERE entry = ? AND sourceType = ?");
PrepareStatement(WorldStatements.DEL_DISABLES, "DELETE FROM disables WHERE entry = ? AND sourceType = ?");
PrepareStatement(WorldStatements.UPD_CREATURE_ZONE_AREA_DATA, "UPDATE creature SET zoneId = ?, areaId = ? WHERE guid = ?");
PrepareStatement(WorldStatements.UPD_GAMEOBJECT_ZONE_AREA_DATA, "UPDATE gameobject SET zoneId = ?, areaId = ? WHERE guid = ?");
PrepareStatement(WorldStatements.SEL_GUILD_REWARDS_REQ_ACHIEVEMENTS, "SELECT AchievementRequired FROM guild_rewards_req_achievements WHERE ItemID = ?");
}
}
public enum WorldStatements
{
SEL_QUEST_POOLS,
DEL_CRELINKED_RESPAWN,
REP_CREATURE_LINKED_RESPAWN,
SEL_CREATURE_TEXT,
SEL_SMART_SCRIPTS,
SEL_SMARTAI_WP,
DEL_GAMEOBJECT,
DEL_EVENT_GAMEOBJECT,
INS_GRAVEYARD_ZONE,
DEL_GRAVEYARD_ZONE,
INS_GAME_TELE,
DEL_GAME_TELE,
INS_NPC_VENDOR,
DEL_NPC_VENDOR,
SEL_NPC_VENDOR_REF,
UPD_CREATURE_MOVEMENT_TYPE,
UPD_CREATURE_FACTION,
UPD_CREATURE_NPCFLAG,
UPD_CREATURE_POSITION,
UPD_CREATURE_SPAWN_DISTANCE,
UPD_CREATURE_SPAWN_TIME_SECS,
INS_CREATURE_FORMATION,
INS_WAYPOINT_DATA,
DEL_WAYPOINT_DATA,
UPD_WAYPOINT_DATA_POINT,
UPD_WAYPOINT_DATA_POSITION,
UPD_WAYPOINT_DATA_WPGUID,
UPD_WAYPOINT_DATA_ALL_WPGUID,
SEL_WAYPOINT_DATA_MAX_ID,
SEL_WAYPOINT_DATA_BY_ID,
SEL_WAYPOINT_DATA_POS_BY_ID,
SEL_WAYPOINT_DATA_POS_FIRST_BY_ID,
SEL_WAYPOINT_DATA_POS_LAST_BY_ID,
SEL_WAYPOINT_DATA_BY_WPGUID,
SEL_WAYPOINT_DATA_ALL_BY_WPGUID,
SEL_WAYPOINT_DATA_MAX_POINT,
SEL_WAYPOINT_DATA_BY_POS,
SEL_WAYPOINT_DATA_WPGUID_BY_ID,
SEL_WAYPOINT_DATA_ACTION,
SEL_WAYPOINT_SCRIPTS_MAX_ID,
UPD_CREATURE_ADDON_PATH,
INS_CREATURE_ADDON,
DEL_CREATURE_ADDON,
SEL_CREATURE_ADDON_BY_GUID,
INS_WAYPOINT_SCRIPT,
DEL_WAYPOINT_SCRIPT,
UPD_WAYPOINT_SCRIPT_ID,
UPD_WAYPOINT_SCRIPT_X,
UPD_WAYPOINT_SCRIPT_Y,
UPD_WAYPOINT_SCRIPT_Z,
UPD_WAYPOINT_SCRIPT_O,
SEL_WAYPOINT_SCRIPT_ID_BY_GUID,
DEL_CREATURE,
SEL_COMMANDS,
SEL_CREATURE_TEMPLATE,
SEL_WAYPOINT_SCRIPT_BY_ID,
SEL_CREATURE_BY_ID,
SEL_GAMEOBJECT_NEAREST,
SEL_CREATURE_NEAREST,
SEL_GAMEOBJECT_TARGET,
INS_CREATURE,
DEL_GAME_EVENT_CREATURE,
DEL_GAME_EVENT_MODEL_EQUIP,
INS_GAMEOBJECT,
SEL_DISABLES,
INS_DISABLES,
DEL_DISABLES,
UPD_CREATURE_ZONE_AREA_DATA,
UPD_GAMEOBJECT_ZONE_AREA_DATA,
SEL_GUILD_REWARDS_REQ_ACHIEVEMENTS,
MAX_WORLDDATABASE_STATEMENTS
}
}
+416
View File
@@ -0,0 +1,416 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 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 <http://www.gnu.org/licenses/>.
*/
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
namespace Framework.Database
{
public class MySqlConnectionInfo
{
public MySqlConnectionInfo(int poolSize = 10)
{
Poolsize = poolSize;
}
public MySqlConnection GetConnection()
{
return new MySqlConnection($"Server={Host};Port={Port};User Id={Username};Password={Password};Database={Database};Allow Zero Datetime=True;Allow User Variables=True;Pooling=true;MaximumPoolSize={Poolsize};");
}
public MySqlConnection GetConnectionNoDatabase()
{
return new MySqlConnection($"Server={Host};Port={Port};User Id={Username};Password={Password};Allow Zero Datetime=True;Allow User Variables=True;Pooling=true;MaximumPoolSize={Poolsize};");
}
public string Host;
public string Port;
public string Username;
public string Password;
public string Database;
public int Poolsize;
}
public abstract class MySqlBase<T>
{
public MySqlErrorCode Initialize(MySqlConnectionInfo connectionInfo)
{
_connectionInfo = connectionInfo;
_updater = new DatabaseUpdater<T>(this);
try
{
using (var connection = _connectionInfo.GetConnection())
{
connection.Open();
Log.outInfo(LogFilter.SqlDriver, $"Connected to MySQL(ver: {connection.ServerVersion}) Database: {_connectionInfo.Database}");
return MySqlErrorCode.None;
}
}
catch (MySqlException ex)
{
return HandleMySQLException(ex);
}
}
public void Execute(string sql, params object[] args)
{
Execute(new PreparedStatement(string.Format(sql, args)));
}
public void Execute(PreparedStatement stmt)
{
try
{
using (var Connection = _connectionInfo.GetConnection())
{
Connection.Open();
using (MySqlCommand cmd = Connection.CreateCommand())
{
cmd.CommandText = stmt.CommandText;
foreach (var parameter in stmt.Parameters)
cmd.Parameters.AddWithValue("@" + parameter.Key, parameter.Value);
cmd.ExecuteNonQuery();
}
}
}
catch (MySqlException ex)
{
HandleMySQLException(ex, stmt.CommandText);
}
}
public void ExecuteOrAppend(SQLTransaction trans, PreparedStatement stmt)
{
if (trans == null)
Execute(stmt);
else
trans.Append(stmt);
}
public SQLResult Query(string sql, params object[] args)
{
return Query(new PreparedStatement(string.Format(sql, args)));
}
public SQLResult Query(PreparedStatement stmt)
{
List<object[]> rows = new List<object[]>();
try
{
using (var Connection = _connectionInfo.GetConnection())
{
Connection.Open();
using (MySqlCommand cmd = Connection.CreateCommand())
{
cmd.CommandText = stmt.CommandText;
foreach (var parameter in stmt.Parameters)
cmd.Parameters.AddWithValue("@" + parameter.Key, parameter.Value);
using (var reader = cmd.ExecuteReader())
{
if (reader.Read() && reader.HasRows)
{
do
{
var row = new object[reader.FieldCount];
reader.GetValues(row);
rows.Add(row);
}
while (reader.Read());
}
}
}
}
}
catch (MySqlException ex)
{
HandleMySQLException(ex, stmt.CommandText);
}
return new SQLResult(rows);
}
public QueryCallback AsyncQuery(string sql, params object[] args)
{
return AsyncQuery(new PreparedStatement(string.Format(sql, args)));
}
public QueryCallback AsyncQuery(PreparedStatement stmt)
{
return new QueryCallback(_AsyncQuery(stmt));
}
async Task<SQLResult> _AsyncQuery(PreparedStatement stmt)
{
List<object[]> rows = new List<object[]>();
try
{
using (var Connection = _connectionInfo.GetConnection())
{
await Connection.OpenAsync();
using (MySqlCommand cmd = Connection.CreateCommand())
{
cmd.CommandText = stmt.CommandText;
foreach (var parameter in stmt.Parameters)
cmd.Parameters.AddWithValue("@" + parameter.Key, parameter.Value);
using (var reader = await cmd.ExecuteReaderAsync())
{
if (await reader.ReadAsync() && reader.HasRows)
{
do
{
var row = new object[reader.FieldCount];
reader.GetValues(row);
rows.Add(row);
}
while (await reader.ReadAsync());
}
}
}
}
}
catch (MySqlException ex)
{
HandleMySQLException(ex, stmt.CommandText);
}
return new SQLResult(rows);
}
public async Task<SQLQueryHolder<R>> DelayQueryHolder<R>(SQLQueryHolder<R> holder)
{
string query = "";
try
{
using (var Connection = _connectionInfo.GetConnection())
{
await Connection.OpenAsync();
foreach (var pair in holder.m_queries)
{
List<object[]> rows = new List<object[]>();
using (MySqlCommand cmd = Connection.CreateCommand())
{
cmd.CommandText = pair.Value.stmt.CommandText;
foreach (var parameter in pair.Value.stmt.Parameters)
cmd.Parameters.AddWithValue("@" + parameter.Key, parameter.Value);
query = cmd.CommandText;
using (var reader = await cmd.ExecuteReaderAsync())
{
if (await reader.ReadAsync() && reader.HasRows)
{
do
{
var row = new object[reader.FieldCount];
reader.GetValues(row);
rows.Add(row);
}
while (await reader.ReadAsync());
}
}
}
holder.SetResult(pair.Key, new SQLResult(rows));
}
}
return holder;
}
catch (MySqlException ex)
{
HandleMySQLException(ex, query);
return holder;
}
}
public void LoadPreparedStatements()
{
PreparedStatements();
}
public void PrepareStatement(T statement, string sql)
{
StringBuilder sb = new StringBuilder();
int index = 0;
for (var i = 0; i < sql.Length; i++)
{
if (sql[i].Equals('?'))
sb.Append("@" + index++);
else
sb.Append(sql[i]);
}
_queries[statement] = sb.ToString();
}
public PreparedStatement GetPreparedStatement(T statement)
{
return new PreparedStatement(_queries[statement]);
}
public bool Apply(string sql)
{
try
{
using (var Connection = _connectionInfo.GetConnectionNoDatabase())
{
using (MySqlCommand cmd = Connection.CreateCommand())
{
Connection.Open();
cmd.CommandText = sql;
return cmd.ExecuteNonQuery() > 0;
}
}
}
catch (MySqlException ex)
{
HandleMySQLException(ex, sql);
return false;
}
}
public bool ApplyFile(string path)
{
try
{
using (var connection = _connectionInfo.GetConnection())
{
using (MySqlCommand cmd = connection.CreateCommand())
{
connection.Open();
cmd.CommandText = File.ReadAllText(path);
return cmd.ExecuteNonQuery() > 0;
}
}
}
catch (MySqlException ex)
{
HandleMySQLException(ex, path);
return false;
}
}
public void EscapeString(ref string str)
{
str = MySqlHelper.EscapeString(str);
}
public void CommitTransaction(SQLTransaction transaction)
{
using (var Connection = _connectionInfo.GetConnection())
{
string query = "";
Connection.Open();
using (MySqlTransaction trans = Connection.BeginTransaction())
{
try
{
using (var scope = new TransactionScope())
{
foreach (var cmd in transaction.commands)
{
cmd.Transaction = trans;
cmd.Connection = Connection;
cmd.ExecuteNonQuery();
query = cmd.CommandText;
}
trans.Commit();
scope.Complete();
}
}
catch (MySqlException ex) //error occurred
{
HandleMySQLException(ex, query);
trans.Rollback();
}
}
}
}
MySqlErrorCode HandleMySQLException(MySqlException ex, string query = "")
{
MySqlErrorCode code = (MySqlErrorCode)ex.Number;
if (ex.InnerException != null)
code = (MySqlErrorCode)((MySqlException)ex.InnerException).Number;
switch (code)
{
case MySqlErrorCode.BadFieldError:
case MySqlErrorCode.NoSuchTable:
Log.outError(LogFilter.Sql, "Your database structure is not up to date. Please make sure you've executed all queries in the sql/updates folders.");
break;
case MySqlErrorCode.ParseError:
Log.outError(LogFilter.Sql, "Error while parsing SQL. Core fix required.");
break;
}
Log.outError(LogFilter.Sql, $"SqlException: {ex.Message} SqlQuery: {query}");
return code;
}
public DatabaseUpdater<T> GetUpdater()
{
return _updater;
}
public bool IsAutoUpdateEnabled(DatabaseTypeFlags updateMask)
{
switch (GetType().Name)
{
case "LoginDatabase":
return updateMask.HasAnyFlag(DatabaseTypeFlags.Login);
case "CharacterDatabase":
return updateMask.HasAnyFlag(DatabaseTypeFlags.Character);
case "WorldDatabase":
return updateMask.HasAnyFlag(DatabaseTypeFlags.World);
case "HotfixDatabase":
return updateMask.HasAnyFlag(DatabaseTypeFlags.Hotfix);
}
return false;
}
public string GetDatabaseName()
{
return _connectionInfo.Database;
}
public abstract void PreparedStatements();
Dictionary<T, string> _queries = new Dictionary<T, string>();
MySqlConnectionInfo _connectionInfo;
DatabaseUpdater<T> _updater;
}
}
@@ -0,0 +1,42 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 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 <http://www.gnu.org/licenses/>.
*/
using System.Collections.Generic;
namespace Framework.Database
{
public class PreparedStatement
{
public PreparedStatement(string commandText)
{
CommandText = commandText;
}
public void AddValue(int index, object value)
{
Parameters.Add(index, value);
}
public void Clear()
{
Parameters.Clear();
}
public string CommandText;
public Dictionary<int, object> Parameters = new Dictionary<int, object>();
}
}
+113
View File
@@ -0,0 +1,113 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 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 <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
namespace Framework.Database
{
public class QueryCallback
{
public QueryCallback(Task<SQLResult> result)
{
_result = result;
}
public QueryCallback WithCallback(Action<SQLResult> callback)
{
return WithChainingCallback((queryCallback, result) => callback(result));
}
public QueryCallback WithCallback<T>(Action<T, SQLResult> callback, T obj)
{
return WithChainingCallback((queryCallback, result) => callback(obj, result));
}
public QueryCallback WithChainingCallback(Action<QueryCallback, SQLResult> callback)
{
_callbacks.Enqueue(new QueryCallbackData(callback));
return this;
}
public void SetNextQuery(QueryCallback next)
{
_result = next._result;
}
public QueryCallbackStatus InvokeIfReady()
{
QueryCallbackData callback = _callbacks.Dequeue();
bool hasNext = true;
while (hasNext)
{
if (_result != null && _result.Wait(0))
{
Task<SQLResult> f = _result;
Action<QueryCallback, SQLResult> cb = callback._result;
_result = null;
cb(this, f.Result);
hasNext = _result != null;
if (_callbacks.Count == 0)
{
Contract.Assert(!hasNext);
return QueryCallbackStatus.Completed;
}
// abort chain
if (!hasNext)
return QueryCallbackStatus.Completed;
callback = _callbacks.Dequeue();
}
else
return QueryCallbackStatus.NotReady;
}
return QueryCallbackStatus.Completed;
}
Task<SQLResult> _result;
Queue<QueryCallbackData> _callbacks = new Queue<QueryCallbackData>();
}
struct QueryCallbackData
{
public QueryCallbackData(Action<QueryCallback, SQLResult> callback)
{
_result = callback;
}
public void Clear()
{
_result = null;
}
public Action<QueryCallback, SQLResult> _result;
}
public enum QueryCallbackStatus
{
NotReady,
NextStep,
Completed
}
}
@@ -0,0 +1,42 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 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 <http://www.gnu.org/licenses/>.
*/
using System.Collections.Generic;
namespace Framework.Database
{
public class QueryCallbackProcessor
{
public void AddQuery(QueryCallback query)
{
_callbacks.Add(query);
}
public void ProcessReadyQueries()
{
if (_callbacks.Empty())
return;
_callbacks.RemoveAll(callback =>
{
return callback.InvokeIfReady() == QueryCallbackStatus.Completed;
});
}
List<QueryCallback> _callbacks = new List<QueryCallback>();
}
}
@@ -0,0 +1,60 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 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 <http://www.gnu.org/licenses/>.
*/
using System.Collections.Generic;
namespace Framework.Database
{
public class SQLQueryHolder<T>
{
public void SetQuery(T index, PreparedStatement _stmt)
{
m_queries[index] = new SQLResultPair(_stmt);
}
public void SetQuery(T index, string sql, params object[] args)
{
SetQuery(index, new PreparedStatement(string.Format(sql, args)));
}
public void SetResult(T index, SQLResult _result)
{
m_queries[index].result = _result;
}
public SQLResult GetResult(T index)
{
if (!m_queries.ContainsKey(index))
return new SQLResult();
return m_queries[index].result;
}
public Dictionary<T, SQLResultPair> m_queries = new Dictionary<T, SQLResultPair>();
public class SQLResultPair
{
public SQLResultPair(PreparedStatement _stmt)
{
stmt = _stmt;
}
public PreparedStatement stmt;
public SQLResult result;
}
}
}
+122
View File
@@ -0,0 +1,122 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 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 <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
namespace Framework.Database
{
public class SQLResult
{
public SQLResult()
{
_rows = new List<object[]>();
}
public SQLResult(List<object[]> values)
{
_rows = values;
}
public T Read<T>(int column)
{
var value = _rows[_rowIndex][column];
if (value.GetType() == typeof(T))
return (T)value;
if (value != DBNull.Value)
return (T)Convert.ChangeType(value, typeof(T));
if (typeof(T).Name == "String")
return (T)Convert.ChangeType("", typeof(T));
return default(T);
}
public T[] ReadValues<T>(int startIndex, int numColumns)
{
T[] values = new T[numColumns];
for (var c = 0; c < numColumns; ++c)
values[c] = Read<T>(startIndex + c);
return values;
}
public bool IsNull(int column)
{
return _rows[_rowIndex][column] == DBNull.Value;
}
public int GetRowCount() { return _rows.Count; }
public bool IsEmpty() { return GetRowCount() == 0; }
public SQLFields GetFields() { return new SQLFields(_rows[_rowIndex]); }
public bool NextRow()
{
if (_rowIndex >= GetRowCount() - 1)
{
_rowIndex = 0;
return false;
}
_rowIndex++;
return true;
}
public void ResetRowIndex()
{
_rowIndex = 0;
}
private int _rowIndex;
List<object[]> _rows;
}
public class SQLFields
{
public SQLFields(object[] row) { _currentRow = row; }
public T Read<T>(int column)
{
var value = _currentRow[column];
if (value.GetType() == typeof(T))
return (T)value;
if (value != DBNull.Value)
return (T)Convert.ChangeType(value, typeof(T));
if (typeof(T).Name == "String")
return (T)Convert.ChangeType("", typeof(T));
return default(T);
}
public T[] ReadValues<T>(int startIndex, int numColumns)
{
T[] values = new T[numColumns];
for (var c = 0; c < numColumns; ++c)
values[c] = Read<T>(startIndex + c);
return values;
}
object[] _currentRow;
}
}
@@ -0,0 +1,46 @@
/*
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 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 <http://www.gnu.org/licenses/>.
*/
using MySql.Data.MySqlClient;
using System.Collections.Generic;
namespace Framework.Database
{
public class SQLTransaction
{
public List<MySqlCommand> commands { get; set; }
public SQLTransaction()
{
commands = new List<MySqlCommand>();
}
public void Append(PreparedStatement stmt)
{
MySqlCommand cmd = new MySqlCommand(stmt.CommandText);
foreach (var parameter in stmt.Parameters)
cmd.Parameters.AddWithValue("@" + parameter.Key, parameter.Value);
commands.Add(cmd);
}
public void Append(string sql, params object[] args)
{
commands.Add(new MySqlCommand(string.Format(sql, args)));
}
}
}