Modularise more database functions.

This commit is contained in:
UnknownShadow200 2016-09-05 17:53:41 +10:00
parent f070829052
commit 629de5e663
14 changed files with 52 additions and 47 deletions

View File

@ -37,9 +37,8 @@ namespace MCGalaxy.BlockBehaviour {
if (checkPos && p.level.PosToInt(x, y, z) == p.lastWalkthrough) return true; if (checkPos && p.level.PosToInt(x, y, z) == p.lastWalkthrough) return true;
p.RevertBlock(x, y, z); p.RevertBlock(x, y, z);
try { try {
//safe against SQL injections because no user input is given here DataTable Portals = Database.Backend.GetRows("Portals" + p.level.name, "*",
DataTable Portals = Database.Fill("SELECT * FROM `Portals" + p.level.name + "WHERE EntryX=@0 AND EntryY=@1 AND EntryZ=@2", x, y, z);
"` WHERE EntryX=@0 AND EntryY=@1 AND EntryZ=@2", x, y, z);
int last = Portals.Rows.Count - 1; int last = Portals.Rows.Count - 1;
if (last == -1) { Portals.Dispose(); return true; } if (last == -1) { Portals.Dispose(); return true; }
byte rotX = p.rot[0], rotY = p.rot[1]; byte rotX = p.rot[0], rotY = p.rot[1];
@ -74,9 +73,8 @@ namespace MCGalaxy.BlockBehaviour {
if (checkPos && p.level.PosToInt(x, y, z) == p.lastWalkthrough) return true; if (checkPos && p.level.PosToInt(x, y, z) == p.lastWalkthrough) return true;
p.RevertBlock(x, y, z); p.RevertBlock(x, y, z);
try { try {
//safe against SQL injections because no user input is given here DataTable Messages = Database.Backend.GetRows("Messages" + p.level.name, "*",
DataTable Messages = Database.Fill("SELECT * FROM `Messages" + p.level.name + "WHERE X=@0 AND Y=@1 AND Z=@2", x, y, z);
"` WHERE X=@0 AND Y=@1 AND Z=@2", x, y, z);
int last = Messages.Rows.Count - 1; int last = Messages.Rows.Count - 1;
if (last == -1) { Messages.Dispose(); return true; } if (last == -1) { Messages.Dispose(); return true; }
string message = Messages.Rows[last]["Message"].ToString().Trim(); string message = Messages.Rows[last]["Message"].ToString().Trim();

View File

@ -36,8 +36,7 @@ namespace MCGalaxy.Commands {
} }
if (message == "") { if (message == "") {
//safe against SQL injections because no user input is given here using (DataTable Inbox = Database.Backend.GetRows("Inbox" + p.name, "*", "ORDER BY TimeSent")) {
using (DataTable Inbox = Database.Fill("SELECT * FROM `Inbox" + p.name + "` ORDER BY TimeSent")) {
if (Inbox.Rows.Count == 0) { Player.Message(p, "No messages found."); return; } if (Inbox.Rows.Count == 0) { Player.Message(p, "No messages found."); return; }
int i = 0; int i = 0;
foreach (DataRow row in Inbox.Rows) { foreach (DataRow row in Inbox.Rows) {
@ -57,8 +56,7 @@ namespace MCGalaxy.Commands {
Player.Message(p, "Message number must be greater than or equal to 0."); return; Player.Message(p, "Message number must be greater than or equal to 0."); return;
} }
//safe against SQL injections because no user input is given here using (DataTable Inbox = Database.Backend.GetRows("Inbox" + p.name, "*", "ORDER BY TimeSent")) {
using (DataTable Inbox = Database.Fill("SELECT * FROM `Inbox" + p.name + "` ORDER BY TimeSent")) {
if (num != -1 && num >= Inbox.Rows.Count) { if (num != -1 && num >= Inbox.Rows.Count) {
Player.Message(p, "\"" + num + "\" does not exist."); return; Player.Message(p, "\"" + num + "\" does not exist."); return;
} }
@ -81,8 +79,7 @@ namespace MCGalaxy.Commands {
if (!int.TryParse(message, out num)) { Player.Message(p, "Incorrect number given."); return; } if (!int.TryParse(message, out num)) { Player.Message(p, "Incorrect number given."); return; }
if (num < 0) { Player.Message(p, "Message number must be greater than or equal to 0."); return; } if (num < 0) { Player.Message(p, "Message number must be greater than or equal to 0."); return; }
//safe against SQL injections because no user input is given here using (DataTable Inbox = Database.Backend.GetRows("Inbox" + p.name, "*", "ORDER BY TimeSent")) {
using (DataTable Inbox = Database.Fill("SELECT * FROM `Inbox" + p.name + "` ORDER BY TimeSent")) {
if (num >= Inbox.Rows.Count) { if (num >= Inbox.Rows.Count) {
Player.Message(p, "Message number \"" + num + "\" does not exist."); return; Player.Message(p, "Message number \"" + num + "\" does not exist."); return;
} }

View File

@ -51,9 +51,8 @@ namespace MCGalaxy.Commands {
DateTime now = DateTime.Now; DateTime now = DateTime.Now;
bool foundOne = false; bool foundOne = false;
//safe against SQL injections because no user input is given here DataTable Blocks = Database.Backend.GetRows("Block" + p.level.name, "*",
DataTable Blocks = Database.Fill("SELECT * FROM `Block" + p.level.name + "WHERE X=@0 AND Y=@1 AND Z=@2", x, y, z);
"` WHERE X=@0 AND Y=@1 AND Z=@2", x, y, z);
for (int i = 0; i < Blocks.Rows.Count; i++) { for (int i = 0; i < Blocks.Rows.Count; i++) {
foundOne = true; foundOne = true;
DataRow row = Blocks.Rows[i]; DataRow row = Blocks.Rows[i];
@ -94,9 +93,8 @@ namespace MCGalaxy.Commands {
if (!Block.Props[block].IsMessageBlock) return; if (!Block.Props[block].IsMessageBlock) return;
try { try {
//safe against SQL injections because no user input is given here DataTable Messages = Database.Backend.GetRows("Messages" + p.level.name, "*",
DataTable Messages = Database.Fill("SELECT * FROM `Messages" + p.level.name + "WHERE X=@0 AND Y=@1 AND Z=@2", x, y, z);
"` WHERE X=@0 AND Y=@1 AND Z=@2", x, y, z);
int last = Messages.Rows.Count - 1; int last = Messages.Rows.Count - 1;
if (last == -1) { Messages.Dispose(); return; } if (last == -1) { Messages.Dispose(); return; }

View File

@ -65,7 +65,7 @@ namespace MCGalaxy.Commands {
// Use fast path if possible TODO: fast path for mysql // Use fast path if possible TODO: fast path for mysql
int count = 0; int count = 0;
if (!Server.useMySQL) { if (!Server.useMySQL) {
DataTable maxTable = Database.Fill("SELECT MAX(_ROWID_) FROM Players LIMIT 1;"); DataTable maxTable = Database.Backend.GetRows("Players", "MAX(_ROWID_)", "LIMIT 1");
if (maxTable.Rows.Count > 0) { if (maxTable.Rows.Count > 0) {
string row = maxTable.Rows[0]["MAX(_ROWID_)"].ToString(); string row = maxTable.Rows[0]["MAX(_ROWID_)"].ToString();
maxTable.Dispose(); maxTable.Dispose();
@ -73,7 +73,7 @@ namespace MCGalaxy.Commands {
} }
} }
DataTable table = Database.Fill("SELECT COUNT(id) FROM Players"); DataTable table = Database.Backend.GetAllRows("Players", "COUNT(id)");
count = int.Parse(table.Rows[0]["COUNT(id)"].ToString()); count = int.Parse(table.Rows[0]["COUNT(id)"].ToString());
table.Dispose(); table.Dispose();
return count; return count;

View File

@ -117,11 +117,12 @@ namespace MCGalaxy.Commands.Building {
Database.Execute(String.Format(LevelDB.createMessages, lvlName)); Database.Execute(String.Format(LevelDB.createMessages, lvlName));
int count = 0; int count = 0;
string syntax = "SELECT * FROM `Messages" + lvlName + "` WHERE X=@0 AND Y=@1 AND Z=@2"; using (DataTable Messages = Database.Backend.GetRows("Messages" + lvlName, "*",
using (DataTable Messages = Database.Fill(syntax, x, y, z)) "WHERE X=@0 AND Y=@1 AND Z=@2", x, y, z)) {
count = Messages.Rows.Count; count = Messages.Rows.Count;
}
syntax = count == 0 ? string syntax = count == 0 ?
"INSERT INTO `Messages" + lvlName + "` (X, Y, Z, Message) VALUES (@0, @1, @2, @3)" "INSERT INTO `Messages" + lvlName + "` (X, Y, Z, Message) VALUES (@0, @1, @2, @3)"
: "UPDATE `Messages" + lvlName + "` SET Message=@3 WHERE X=@0 AND Y=@1 AND Z=@2"; : "UPDATE `Messages" + lvlName + "` SET Message=@3 WHERE X=@0 AND Y=@1 AND Z=@2";
Database.Execute(syntax, x, y, z, data.message); Database.Execute(syntax, x, y, z, data.message);

View File

@ -97,11 +97,12 @@ namespace MCGalaxy.Commands.Building {
Database.Execute(String.Format(LevelDB.createPortals, lvlName)); Database.Execute(String.Format(LevelDB.createPortals, lvlName));
int count = 0; int count = 0;
string syntax = "SELECT * FROM `Portals" + lvlName + "` WHERE EntryX=@0 AND EntryY=@1 AND EntryZ=@2"; using (DataTable portals = Database.Backend.GetRows("Portals" + lvlName, "*",
using (DataTable portals = Database.Fill(syntax, P.x, P.y, P.z)) "WHERE EntryX=@0 AND EntryY=@1 AND EntryZ=@2", P.x, P.y, P.z)) {
count = portals.Rows.Count; count = portals.Rows.Count;
}
syntax = count == 0 ? string syntax = count == 0 ?
"INSERT INTO `Portals" + lvlName + "` (EntryX, EntryY, EntryZ, ExitX, ExitY, ExitZ, ExitMap) VALUES (@0, @1, @2, @3, @4, @5, @6)" "INSERT INTO `Portals" + lvlName + "` (EntryX, EntryY, EntryZ, ExitX, ExitY, ExitZ, ExitMap) VALUES (@0, @1, @2, @3, @4, @5, @6)"
: "UPDATE `Portals" + lvlName + "` SET ExitMap=@6, ExitX=@3, ExitY=@4, ExitZ=@5 WHERE EntryX=@0 AND EntryY=@1 AND EntryZ=@2"; : "UPDATE `Portals" + lvlName + "` SET ExitMap=@6, ExitX=@3, ExitY=@4, ExitZ=@5 WHERE EntryX=@0 AND EntryY=@1 AND EntryZ=@2";
Database.Execute(syntax, P.x, P.y, P.z, x, y, z, p.level.name); Database.Execute(syntax, P.x, P.y, P.z, x, y, z, p.level.name);

View File

@ -71,5 +71,14 @@ namespace MCGalaxy.SQL {
string syntax = "SELECT " + columns + " FROM `" + table + "`"; string syntax = "SELECT " + columns + " FROM `" + table + "`";
return Database.Fill(syntax); return Database.Fill(syntax);
} }
/// <summary> Retrieves rows for the given table from the database. </summary>
/// <remarks> modifier is SQL which can be used to retrieve only certain rows,
/// return rows in a certain order, etc.</remarks>
public virtual DataTable GetRows(string table, string columns,
string modifier, params object[] args) {
string syntax = "SELECT " + columns + " FROM `" + table + "` " + modifier;
return Database.Fill(syntax, args);
}
} }
} }

View File

@ -47,9 +47,11 @@ namespace MCGalaxy.SQL {
public override bool TableExists(string table) { public override bool TableExists(string table) {
const string syntax = "SELECT * FROM information_schema.tables WHERE table_schema = @1 AND table_name = @0"; using (DataTable results = GetRows("information_schema.tables", "*",
using (DataTable results = Database.Fill(syntax, table, Server.MySQLDatabaseName)) "WHERE table_schema = @1 AND table_name = @",
table, Server.MySQLDatabaseName)) {
return results.Rows.Count > 0; return results.Rows.Count > 0;
}
} }
public override void RenameTable(string srcTable, string dstTable) { public override void RenameTable(string srcTable, string dstTable) {

View File

@ -46,9 +46,10 @@ namespace MCGalaxy.SQL {
public override bool TableExists(string table) { public override bool TableExists(string table) {
const string syntax = "SELECT name FROM sqlite_master WHERE type='table' AND name=@0"; using (DataTable results = GetRows("sqlite_master", "name",
using (DataTable results = Database.Fill(syntax, table)) "WHERE type='table' AND name=@0", table)) {
return results.Rows.Count > 0; return results.Rows.Count > 0;
}
} }
public override void RenameTable(string srcTable, string dstTable) { public override void RenameTable(string srcTable, string dstTable) {

View File

@ -132,7 +132,7 @@ PRIMARY KEY(player)
EcoStats stats = default(EcoStats); EcoStats stats = default(EcoStats);
stats.Player = name; stats.Player = name;
using (DataTable eco = Database.Fill("SELECT * FROM Economy WHERE player=@0", name)) { using (DataTable eco = Database.Backend.GetRows("Economy", "*", "WHERE player=@0", name)) {
if (eco.Rows.Count > 0) { if (eco.Rows.Count > 0) {
stats.TotalSpent = int.Parse(eco.Rows[0]["total"].ToString()); stats.TotalSpent = int.Parse(eco.Rows[0]["total"].ToString());
stats.Purchase = eco.Rows[0]["purchase"].ToString(); stats.Purchase = eco.Rows[0]["purchase"].ToString();

View File

@ -270,7 +270,7 @@ Additional4 INT{2});"; // reserve space for possible future additions
} }
public ZombieStats LoadZombieStats(string name) { public ZombieStats LoadZombieStats(string name) {
DataTable table = Database.Fill("SELECT * FROM ZombieStats WHERE Name=@0", name); DataTable table = Database.Backend.GetRows("ZombieStats", "*", "WHERE Name=@0", name);
ZombieStats stats = default(ZombieStats); ZombieStats stats = default(ZombieStats);
if (table.Rows.Count > 0) { if (table.Rows.Count > 0) {
@ -286,7 +286,7 @@ Additional4 INT{2});"; // reserve space for possible future additions
public void SaveZombieStats(Player p) { public void SaveZombieStats(Player p) {
if (p.Game.TotalRoundsSurvived == 0 && p.Game.TotalInfected == 0) return; if (p.Game.TotalRoundsSurvived == 0 && p.Game.TotalInfected == 0) return;
DataTable table = Database.Fill("SELECT * FROM ZombieStats WHERE Name=@0", p.name); DataTable table = Database.Backend.GetRows("ZombieStats", "*", "WHERE Name=@0", p.name);
string syntax = table.Rows.Count == 0 ? string syntax = table.Rows.Count == 0 ?
"INSERT INTO ZombieStats (TotalRounds, MaxRounds, TotalInfected, MaxInfected, Name) VALUES (@0, @1, @2, @3, @4)" "INSERT INTO ZombieStats (TotalRounds, MaxRounds, TotalInfected, MaxInfected, Name) VALUES (@0, @1, @2, @3, @4)"

View File

@ -239,7 +239,7 @@ namespace MCGalaxy {
timeLogged = DateTime.Now; timeLogged = DateTime.Now;
lastLogin = DateTime.Now; lastLogin = DateTime.Now;
time = new TimeSpan(0, 0, 0, 1); time = new TimeSpan(0, 0, 0, 1);
DataTable playerDb = Database.Fill("SELECT * FROM Players WHERE Name=@0", name); DataTable playerDb = Database.Backend.GetRows("Players", "*", "WHERE Name=@0", name);
if (playerDb.Rows.Count == 0) if (playerDb.Rows.Count == 0)
InitPlayerStats(playerDb); InitPlayerStats(playerDb);

View File

@ -167,7 +167,7 @@ namespace MCGalaxy {
/// <summary> Retrieves from the database the names of all players whose /// <summary> Retrieves from the database the names of all players whose
/// last IP address matches the given IP address. </summary> /// last IP address matches the given IP address. </summary>
public static List<string> FindAccounts(string ip) { public static List<string> FindAccounts(string ip) {
DataTable clones = Database.Fill("SELECT Name FROM Players WHERE IP=@0", ip); DataTable clones = Database.Backend.GetRows("Players", "Name", "WHERE IP=@0", ip);
List<string> alts = new List<string>(); List<string> alts = new List<string>();
foreach (DataRow row in clones.Rows) { foreach (DataRow row in clones.Rows) {
@ -180,19 +180,17 @@ namespace MCGalaxy {
} }
internal static DataTable Query(string name, string selector) { internal static DataTable Query(string name, string columns) {
string syntax = Server.useMySQL ? string suffix = Server.useMySQL ? " utf8_general_ci" : " NOCASE";
"SELECT " + selector + " FROM Players WHERE Name=@0 COLLATE utf8_general_ci" : return Database.Backend.GetRows("Players", columns,
"SELECT " + selector + " FROM Players WHERE Name=@0 COLLATE NOCASE"; "WHERE Name=@0 COLLATE" + suffix, name);
return Database.Fill(syntax, name);
} }
internal static DataRow QueryMulti(Player p, string name, string selector) { internal static DataRow QueryMulti(Player p, string name, string columns) {
string syntax = Server.useMySQL ? string suffix = Server.useMySQL ? "" : " COLLATE NOCASE";
"SELECT " + selector + " FROM Players WHERE Name LIKE @0 LIMIT 21" : using (DataTable results = Database.Backend.GetRows("Players", columns,
"SELECT " + selector + " FROM Players WHERE Name LIKE @0 LIMIT 21 COLLATE NOCASE"; "WHERE Name LIKE @0 LIMIT 21" + suffix,
"%" + name + "%")) {
using (DataTable results = Database.Fill(syntax, "%" + name + "%")) {
int matches = 0; int matches = 0;
return Utils.FindMatches<DataRow>(p, name, out matches, results.Rows, return Utils.FindMatches<DataRow>(p, name, out matches, results.Rows,
r => true, r => r["Name"].ToString(), "players", 20); r => true, r => r["Name"].ToString(), "players", 20);

View File

@ -56,7 +56,7 @@ namespace MCGalaxy {
sql.WriteLine(); sql.WriteLine();
WriteTableSchema(tableName, sql); WriteTableSchema(tableName, sql);
using (DataTable data = Database.Fill("SELECT * FROM `" + tableName + "`")) { using (DataTable data = Database.Backend.GetAllRows(tableName, "*")) {
if (data.Rows.Count == 0) { if (data.Rows.Count == 0) {
sql.WriteLine("-- No data in table `{0}`!", tableName); sql.WriteLine("-- No data in table `{0}`!", tableName);
sql.WriteLine(); sql.WriteLine();