refactor(db): Update SqlQueryBuilder references + Various refactors

Consolidates the creation of SQL query builders across multiple classes to ensure a unified approach for database operations.

Replaces manual type checks and specific query creators with a generic method for better maintainability and to prevent errors.

Improves code readability and reduces duplication, facilitating easier updates in the future.
This commit is contained in:
Sakura Akeno Isayeki 2025-04-28 15:50:55 +02:00
parent 27fde1f9ac
commit 084411f847
No known key found for this signature in database
GPG key ID: BAB781B71FD2E7E6
15 changed files with 399 additions and 488 deletions

View file

@ -69,10 +69,9 @@ namespace TShockAPI.DB
new SqlColumn("Date", MySqlDbType.Int64), new SqlColumn("Date", MySqlDbType.Int64),
new SqlColumn("Expiration", MySqlDbType.Int64) new SqlColumn("Expiration", MySqlDbType.Int64)
); );
var creator = new SqlTableCreator(db,
db.GetSqlType() == SqlType.Sqlite var creator = new SqlTableCreator(db, db.GetSqlQueryBuilder());
? (IQueryBuilder)new SqliteQueryCreator()
: new MysqlQueryCreator());
try try
{ {
creator.EnsureTableStructure(table); creator.EnsureTableStructure(table);
@ -106,15 +105,12 @@ namespace TShockAPI.DB
/// </summary> /// </summary>
public void TryConvertBans() public void TryConvertBans()
{ {
int res; int res = database.GetSqlType() switch
if (database.GetSqlType() == SqlType.Mysql)
{ {
res = database.QueryScalar<int>("SELECT COUNT(table_name) FROM information_schema.tables WHERE table_schema = @0 and table_name = 'Bans'", TShock.Config.Settings.MySqlDbName); SqlType.Mysql => database.QueryScalar<int>("SELECT COUNT(table_name) FROM information_schema.tables WHERE table_schema = @0 and table_name = 'Bans'", TShock.Config.Settings.MySqlDbName),
} SqlType.Sqlite => database.QueryScalar<int>("SELECT COUNT(name) FROM sqlite_master WHERE type='table' AND name = 'Bans'"),
else SqlType.Postgres => database.QueryScalar<int>("SELECT COUNT(table_name) FROM information_schema.tables WHERE table_name = 'Bans'"),
{ };
res = database.QueryScalar<int>("SELECT COUNT(name) FROM sqlite_master WHERE type='table' AND name = 'Bans'");
}
if (res != 0) if (res != 0)
{ {
@ -301,16 +297,13 @@ namespace TShockAPI.DB
return new AddBanResult { Message = message }; return new AddBanResult { Message = message };
} }
string query = "INSERT INTO PlayerBans (Identifier, Reason, BanningUser, Date, Expiration) VALUES (@0, @1, @2, @3, @4);"; string query = "INSERT INTO PlayerBans (Identifier, Reason, BanningUser, Date, Expiration) VALUES (@0, @1, @2, @3, @4)" + database.GetSqlType() switch
if (database.GetSqlType() == SqlType.Mysql)
{ {
query += "SELECT LAST_INSERT_ID();"; SqlType.Mysql => /*lang=mysql*/"; SELECT LAST_INSERT_ID();",
} SqlType.Sqlite => /*lang=sqlite*/"; SELECT last_insert_rowid();",
else SqlType.Postgres => /*lang=postgresql*/"RETURNING \"Identifier\";",
{ _ => null
query += "SELECT CAST(last_insert_rowid() as INT);"; };
}
int ticketId = database.QueryScalar<int>(query, args.Identifier, args.Reason, args.BanningUser, args.BanDateTime.Ticks, args.ExpirationDateTime.Ticks); int ticketId = database.QueryScalar<int>(query, args.Identifier, args.Reason, args.BanningUser, args.BanDateTime.Ticks, args.ExpirationDateTime.Ticks);
@ -362,19 +355,18 @@ namespace TShockAPI.DB
return Bans[id]; return Bans[id];
} }
using (var reader = database.QueryReader("SELECT * FROM PlayerBans WHERE TicketNumber=@0", id)) using var reader = database.QueryReader("SELECT * FROM PlayerBans WHERE TicketNumber=@0", id);
{
if (reader.Read())
{
var ticketNumber = reader.Get<int>("TicketNumber");
var identifier = reader.Get<string>("Identifier");
var reason = reader.Get<string>("Reason");
var banningUser = reader.Get<string>("BanningUser");
var date = reader.Get<long>("Date");
var expiration = reader.Get<long>("Expiration");
return new Ban(ticketNumber, identifier, reason, banningUser, date, expiration); if (reader.Read())
} {
var ticketNumber = reader.Get<int>("TicketNumber");
var identifier = reader.Get<string>("Identifier");
var reason = reader.Get<string>("Reason");
var banningUser = reader.Get<string>("BanningUser");
var date = reader.Get<long>("Date");
var expiration = reader.Get<long>("Expiration");
return new Ban(ticketNumber, identifier, reason, banningUser, date, expiration);
} }
return null; return null;
@ -394,19 +386,18 @@ namespace TShockAPI.DB
query += $" AND Expiration > {DateTime.UtcNow.Ticks}"; query += $" AND Expiration > {DateTime.UtcNow.Ticks}";
} }
using (var reader = database.QueryReader(query, identifier)) using var reader = database.QueryReader(query, identifier);
{
while (reader.Read())
{
var ticketNumber = reader.Get<int>("TicketNumber");
var ident = reader.Get<string>("Identifier");
var reason = reader.Get<string>("Reason");
var banningUser = reader.Get<string>("BanningUser");
var date = reader.Get<long>("Date");
var expiration = reader.Get<long>("Expiration");
yield return new Ban(ticketNumber, ident, reason, banningUser, date, expiration); while (reader.Read())
} {
var ticketNumber = reader.Get<int>("TicketNumber");
var ident = reader.Get<string>("Identifier");
var reason = reader.Get<string>("Reason");
var banningUser = reader.Get<string>("BanningUser");
var date = reader.Get<long>("Date");
var expiration = reader.Get<long>("Expiration");
yield return new Ban(ticketNumber, ident, reason, banningUser, date, expiration);
} }
} }
@ -419,27 +410,27 @@ namespace TShockAPI.DB
public IEnumerable<Ban> GetBansByIdentifiers(bool currentOnly = true, params string[] identifiers) public IEnumerable<Ban> GetBansByIdentifiers(bool currentOnly = true, params string[] identifiers)
{ {
//Generate a sequence of '@0, @1, @2, ... etc' //Generate a sequence of '@0, @1, @2, ... etc'
var parameters = string.Join(", ", Enumerable.Range(0, identifiers.Count()).Select(p => $"@{p}")); var parameters = string.Join(", ", Enumerable.Range(0, identifiers.Length).Select(p => $"@{p}"));
string query = $"SELECT * FROM PlayerBans WHERE Identifier IN ({parameters})"; string query = $"SELECT * FROM PlayerBans WHERE Identifier IN ({parameters})";
if (currentOnly) if (currentOnly)
{ {
query += $" AND Expiration > {DateTime.UtcNow.Ticks}"; query += $" AND Expiration > {DateTime.UtcNow.Ticks}";
} }
using (var reader = database.QueryReader(query, identifiers)) using var reader = database.QueryReader(query, identifiers);
{
while (reader.Read())
{
var ticketNumber = reader.Get<int>("TicketNumber");
var identifier = reader.Get<string>("Identifier");
var reason = reader.Get<string>("Reason");
var banningUser = reader.Get<string>("BanningUser");
var date = reader.Get<long>("Date");
var expiration = reader.Get<long>("Expiration");
yield return new Ban(ticketNumber, identifier, reason, banningUser, date, expiration); while (reader.Read())
} {
var ticketNumber = reader.Get<int>("TicketNumber");
var identifier = reader.Get<string>("Identifier");
var reason = reader.Get<string>("Reason");
var banningUser = reader.Get<string>("BanningUser");
var date = reader.Get<long>("Date");
var expiration = reader.Get<long>("Expiration");
yield return new Ban(ticketNumber, identifier, reason, banningUser, date, expiration);
} }
} }
@ -458,21 +449,19 @@ namespace TShockAPI.DB
List<Ban> banlist = new List<Ban>(); List<Ban> banlist = new List<Ban>();
try try
{ {
var orderBy = SortToOrderByMap[sortMethod]; using var reader = database.QueryReader($"SELECT * FROM PlayerBans ORDER BY {SortToOrderByMap[sortMethod]}");
using (var reader = database.QueryReader($"SELECT * FROM PlayerBans ORDER BY {orderBy}"))
{
while (reader.Read())
{
var ticketNumber = reader.Get<int>("TicketNumber");
var identifier = reader.Get<string>("Identifier");
var reason = reader.Get<string>("Reason");
var banningUser = reader.Get<string>("BanningUser");
var date = reader.Get<long>("Date");
var expiration = reader.Get<long>("Expiration");
var ban = new Ban(ticketNumber, identifier, reason, banningUser, date, expiration); while (reader.Read())
banlist.Add(ban); {
} var ticketNumber = reader.Get<int>("TicketNumber");
var identifier = reader.Get<string>("Identifier");
var reason = reader.Get<string>("Reason");
var banningUser = reader.Get<string>("BanningUser");
var date = reader.Get<long>("Date");
var expiration = reader.Get<long>("Expiration");
var ban = new Ban(ticketNumber, identifier, reason, banningUser, date, expiration);
banlist.Add(ban);
} }
} }
catch (Exception ex) catch (Exception ex)
@ -501,7 +490,7 @@ namespace TShockAPI.DB
return false; return false;
} }
internal Dictionary<BanSortMethod, string> SortToOrderByMap = new Dictionary<BanSortMethod, string> private readonly Dictionary<BanSortMethod, string> SortToOrderByMap = new()
{ {
{ BanSortMethod.AddedNewestToOldest, "Date DESC" }, { BanSortMethod.AddedNewestToOldest, "Date DESC" },
{ BanSortMethod.AddedOldestToNewest, "Date ASC" }, { BanSortMethod.AddedOldestToNewest, "Date ASC" },

View file

@ -71,10 +71,8 @@ namespace TShockAPI.DB
new SqlColumn("unlockedSuperCart", MySqlDbType.Int32), new SqlColumn("unlockedSuperCart", MySqlDbType.Int32),
new SqlColumn("enabledSuperCart", MySqlDbType.Int32) new SqlColumn("enabledSuperCart", MySqlDbType.Int32)
); );
var creator = new SqlTableCreator(db,
db.GetSqlType() == SqlType.Sqlite SqlTableCreator creator = new(db, db.GetSqlQueryBuilder());
? (IQueryBuilder) new SqliteQueryCreator()
: new MysqlQueryCreator());
creator.EnsureTableStructure(table); creator.EnsureTableStructure(table);
} }
@ -84,59 +82,57 @@ namespace TShockAPI.DB
try try
{ {
using (var reader = database.QueryReader("SELECT * FROM tsCharacter WHERE Account=@0", acctid)) using var reader = database.QueryReader("SELECT * FROM tsCharacter WHERE Account=@0", acctid);
if (reader.Read())
{ {
if (reader.Read()) playerData.exists = true;
playerData.health = reader.Get<int>("Health");
playerData.maxHealth = reader.Get<int>("MaxHealth");
playerData.mana = reader.Get<int>("Mana");
playerData.maxMana = reader.Get<int>("MaxMana");
List<NetItem> inventory = reader.Get<string>("Inventory").Split('~').Select(NetItem.Parse).ToList();
if (inventory.Count < NetItem.MaxInventory)
{ {
playerData.exists = true; //TODO: unhardcode this - stop using magic numbers and use NetItem numbers
playerData.health = reader.Get<int>("Health"); //Set new armour slots empty
playerData.maxHealth = reader.Get<int>("MaxHealth"); inventory.InsertRange(67, new NetItem[2]);
playerData.mana = reader.Get<int>("Mana"); //Set new vanity slots empty
playerData.maxMana = reader.Get<int>("MaxMana"); inventory.InsertRange(77, new NetItem[2]);
List<NetItem> inventory = reader.Get<string>("Inventory").Split('~').Select(NetItem.Parse).ToList(); //Set new dye slots empty
if (inventory.Count < NetItem.MaxInventory) inventory.InsertRange(87, new NetItem[2]);
{ //Set the rest of the new slots empty
//TODO: unhardcode this - stop using magic numbers and use NetItem numbers inventory.AddRange(new NetItem[NetItem.MaxInventory - inventory.Count]);
//Set new armour slots empty
inventory.InsertRange(67, new NetItem[2]);
//Set new vanity slots empty
inventory.InsertRange(77, new NetItem[2]);
//Set new dye slots empty
inventory.InsertRange(87, new NetItem[2]);
//Set the rest of the new slots empty
inventory.AddRange(new NetItem[NetItem.MaxInventory - inventory.Count]);
}
playerData.inventory = inventory.ToArray();
playerData.extraSlot = reader.Get<int>("extraSlot");
playerData.spawnX = reader.Get<int>("spawnX");
playerData.spawnY = reader.Get<int>("spawnY");
playerData.skinVariant = reader.Get<int?>("skinVariant");
playerData.hair = reader.Get<int?>("hair");
playerData.hairDye = (byte)reader.Get<int>("hairDye");
playerData.hairColor = TShock.Utils.DecodeColor(reader.Get<int?>("hairColor"));
playerData.pantsColor = TShock.Utils.DecodeColor(reader.Get<int?>("pantsColor"));
playerData.shirtColor = TShock.Utils.DecodeColor(reader.Get<int?>("shirtColor"));
playerData.underShirtColor = TShock.Utils.DecodeColor(reader.Get<int?>("underShirtColor"));
playerData.shoeColor = TShock.Utils.DecodeColor(reader.Get<int?>("shoeColor"));
playerData.hideVisuals = TShock.Utils.DecodeBoolArray(reader.Get<int?>("hideVisuals"));
playerData.skinColor = TShock.Utils.DecodeColor(reader.Get<int?>("skinColor"));
playerData.eyeColor = TShock.Utils.DecodeColor(reader.Get<int?>("eyeColor"));
playerData.questsCompleted = reader.Get<int>("questsCompleted");
playerData.usingBiomeTorches = reader.Get<int>("usingBiomeTorches");
playerData.happyFunTorchTime = reader.Get<int>("happyFunTorchTime");
playerData.unlockedBiomeTorches = reader.Get<int>("unlockedBiomeTorches");
playerData.currentLoadoutIndex = reader.Get<int>("currentLoadoutIndex");
playerData.ateArtisanBread = reader.Get<int>("ateArtisanBread");
playerData.usedAegisCrystal = reader.Get<int>("usedAegisCrystal");
playerData.usedAegisFruit = reader.Get<int>("usedAegisFruit");
playerData.usedArcaneCrystal = reader.Get<int>("usedArcaneCrystal");
playerData.usedGalaxyPearl = reader.Get<int>("usedGalaxyPearl");
playerData.usedGummyWorm = reader.Get<int>("usedGummyWorm");
playerData.usedAmbrosia = reader.Get<int>("usedAmbrosia");
playerData.unlockedSuperCart = reader.Get<int>("unlockedSuperCart");
playerData.enabledSuperCart = reader.Get<int>("enabledSuperCart");
return playerData;
} }
playerData.inventory = inventory.ToArray();
playerData.extraSlot = reader.Get<int>("extraSlot");
playerData.spawnX = reader.Get<int>("spawnX");
playerData.spawnY = reader.Get<int>("spawnY");
playerData.skinVariant = reader.Get<int?>("skinVariant");
playerData.hair = reader.Get<int?>("hair");
playerData.hairDye = (byte)reader.Get<int>("hairDye");
playerData.hairColor = TShock.Utils.DecodeColor(reader.Get<int?>("hairColor"));
playerData.pantsColor = TShock.Utils.DecodeColor(reader.Get<int?>("pantsColor"));
playerData.shirtColor = TShock.Utils.DecodeColor(reader.Get<int?>("shirtColor"));
playerData.underShirtColor = TShock.Utils.DecodeColor(reader.Get<int?>("underShirtColor"));
playerData.shoeColor = TShock.Utils.DecodeColor(reader.Get<int?>("shoeColor"));
playerData.hideVisuals = TShock.Utils.DecodeBoolArray(reader.Get<int?>("hideVisuals"));
playerData.skinColor = TShock.Utils.DecodeColor(reader.Get<int?>("skinColor"));
playerData.eyeColor = TShock.Utils.DecodeColor(reader.Get<int?>("eyeColor"));
playerData.questsCompleted = reader.Get<int>("questsCompleted");
playerData.usingBiomeTorches = reader.Get<int>("usingBiomeTorches");
playerData.happyFunTorchTime = reader.Get<int>("happyFunTorchTime");
playerData.unlockedBiomeTorches = reader.Get<int>("unlockedBiomeTorches");
playerData.currentLoadoutIndex = reader.Get<int>("currentLoadoutIndex");
playerData.ateArtisanBread = reader.Get<int>("ateArtisanBread");
playerData.usedAegisCrystal = reader.Get<int>("usedAegisCrystal");
playerData.usedAegisFruit = reader.Get<int>("usedAegisFruit");
playerData.usedArcaneCrystal = reader.Get<int>("usedArcaneCrystal");
playerData.usedGalaxyPearl = reader.Get<int>("usedGalaxyPearl");
playerData.usedGummyWorm = reader.Get<int>("usedGummyWorm");
playerData.usedAmbrosia = reader.Get<int>("usedAmbrosia");
playerData.unlockedSuperCart = reader.Get<int>("unlockedSuperCart");
playerData.enabledSuperCart = reader.Get<int>("enabledSuperCart");
return playerData;
} }
} }
catch (Exception ex) catch (Exception ex)
@ -155,7 +151,7 @@ namespace TShockAPI.DB
if (items.Count < NetItem.MaxInventory) if (items.Count < NetItem.MaxInventory)
items.AddRange(new NetItem[NetItem.MaxInventory - items.Count]); items.AddRange(new NetItem[NetItem.MaxInventory - items.Count]);
string initialItems = String.Join("~", items.Take(NetItem.MaxInventory)); string initialItems = string.Join("~", items.Take(NetItem.MaxInventory));
try try
{ {
database.Query("INSERT INTO tsCharacter (Account, Health, MaxHealth, Mana, MaxMana, Inventory, spawnX, spawnY, questsCompleted) VALUES (@0, @1, @2, @3, @4, @5, @6, @7, @8);", database.Query("INSERT INTO tsCharacter (Account, Health, MaxHealth, Mana, MaxMana, Inventory, spawnX, spawnY, questsCompleted) VALUES (@0, @1, @2, @3, @4, @5, @6, @7, @8);",
@ -205,7 +201,7 @@ namespace TShockAPI.DB
{ {
database.Query( database.Query(
"INSERT INTO tsCharacter (Account, Health, MaxHealth, Mana, MaxMana, Inventory, extraSlot, spawnX, spawnY, skinVariant, hair, hairDye, hairColor, pantsColor, shirtColor, underShirtColor, shoeColor, hideVisuals, skinColor, eyeColor, questsCompleted, usingBiomeTorches, happyFunTorchTime, unlockedBiomeTorches, currentLoadoutIndex,ateArtisanBread, usedAegisCrystal, usedAegisFruit, usedArcaneCrystal, usedGalaxyPearl, usedGummyWorm, usedAmbrosia, unlockedSuperCart, enabledSuperCart) VALUES (@0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12, @13, @14, @15, @16, @17, @18, @19, @20, @21, @22, @23, @24, @25, @26, @27, @28, @29, @30, @31, @32, @33);", "INSERT INTO tsCharacter (Account, Health, MaxHealth, Mana, MaxMana, Inventory, extraSlot, spawnX, spawnY, skinVariant, hair, hairDye, hairColor, pantsColor, shirtColor, underShirtColor, shoeColor, hideVisuals, skinColor, eyeColor, questsCompleted, usingBiomeTorches, happyFunTorchTime, unlockedBiomeTorches, currentLoadoutIndex,ateArtisanBread, usedAegisCrystal, usedAegisFruit, usedArcaneCrystal, usedGalaxyPearl, usedGummyWorm, usedAmbrosia, unlockedSuperCart, enabledSuperCart) VALUES (@0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12, @13, @14, @15, @16, @17, @18, @19, @20, @21, @22, @23, @24, @25, @26, @27, @28, @29, @30, @31, @32, @33);",
player.Account.ID, playerData.health, playerData.maxHealth, playerData.mana, playerData.maxMana, String.Join("~", playerData.inventory), playerData.extraSlot, player.TPlayer.SpawnX, player.TPlayer.SpawnY, player.TPlayer.skinVariant, player.TPlayer.hair, player.TPlayer.hairDye, TShock.Utils.EncodeColor(player.TPlayer.hairColor), TShock.Utils.EncodeColor(player.TPlayer.pantsColor),TShock.Utils.EncodeColor(player.TPlayer.shirtColor), TShock.Utils.EncodeColor(player.TPlayer.underShirtColor), TShock.Utils.EncodeColor(player.TPlayer.shoeColor), TShock.Utils.EncodeBoolArray(player.TPlayer.hideVisibleAccessory), TShock.Utils.EncodeColor(player.TPlayer.skinColor),TShock.Utils.EncodeColor(player.TPlayer.eyeColor), player.TPlayer.anglerQuestsFinished, player.TPlayer.UsingBiomeTorches ? 1 : 0, player.TPlayer.happyFunTorchTime ? 1 : 0, player.TPlayer.unlockedBiomeTorches ? 1 : 0, player.TPlayer.CurrentLoadoutIndex, player.TPlayer.ateArtisanBread ? 1 : 0, player.TPlayer.usedAegisCrystal ? 1 : 0, player.TPlayer.usedAegisFruit ? 1 : 0, player.TPlayer.usedArcaneCrystal ? 1 : 0, player.TPlayer.usedGalaxyPearl ? 1 : 0, player.TPlayer.usedGummyWorm ? 1 : 0, player.TPlayer.usedAmbrosia ? 1 : 0, player.TPlayer.unlockedSuperCart ? 1 : 0, player.TPlayer.enabledSuperCart ? 1 : 0); player.Account.ID, playerData.health, playerData.maxHealth, playerData.mana, playerData.maxMana, string.Join("~", playerData.inventory), playerData.extraSlot, player.TPlayer.SpawnX, player.TPlayer.SpawnY, player.TPlayer.skinVariant, player.TPlayer.hair, player.TPlayer.hairDye, TShock.Utils.EncodeColor(player.TPlayer.hairColor), TShock.Utils.EncodeColor(player.TPlayer.pantsColor),TShock.Utils.EncodeColor(player.TPlayer.shirtColor), TShock.Utils.EncodeColor(player.TPlayer.underShirtColor), TShock.Utils.EncodeColor(player.TPlayer.shoeColor), TShock.Utils.EncodeBoolArray(player.TPlayer.hideVisibleAccessory), TShock.Utils.EncodeColor(player.TPlayer.skinColor),TShock.Utils.EncodeColor(player.TPlayer.eyeColor), player.TPlayer.anglerQuestsFinished, player.TPlayer.UsingBiomeTorches ? 1 : 0, player.TPlayer.happyFunTorchTime ? 1 : 0, player.TPlayer.unlockedBiomeTorches ? 1 : 0, player.TPlayer.CurrentLoadoutIndex, player.TPlayer.ateArtisanBread ? 1 : 0, player.TPlayer.usedAegisCrystal ? 1 : 0, player.TPlayer.usedAegisFruit ? 1 : 0, player.TPlayer.usedArcaneCrystal ? 1 : 0, player.TPlayer.usedGalaxyPearl ? 1 : 0, player.TPlayer.usedGummyWorm ? 1 : 0, player.TPlayer.usedAmbrosia ? 1 : 0, player.TPlayer.unlockedSuperCart ? 1 : 0, player.TPlayer.enabledSuperCart ? 1 : 0);
return true; return true;
} }
catch (Exception ex) catch (Exception ex)
@ -219,7 +215,7 @@ namespace TShockAPI.DB
{ {
database.Query( database.Query(
"UPDATE tsCharacter SET Health = @0, MaxHealth = @1, Mana = @2, MaxMana = @3, Inventory = @4, spawnX = @6, spawnY = @7, hair = @8, hairDye = @9, hairColor = @10, pantsColor = @11, shirtColor = @12, underShirtColor = @13, shoeColor = @14, hideVisuals = @15, skinColor = @16, eyeColor = @17, questsCompleted = @18, skinVariant = @19, extraSlot = @20, usingBiomeTorches = @21, happyFunTorchTime = @22, unlockedBiomeTorches = @23, currentLoadoutIndex = @24, ateArtisanBread = @25, usedAegisCrystal = @26, usedAegisFruit = @27, usedArcaneCrystal = @28, usedGalaxyPearl = @29, usedGummyWorm = @30, usedAmbrosia = @31, unlockedSuperCart = @32, enabledSuperCart = @33 WHERE Account = @5;", "UPDATE tsCharacter SET Health = @0, MaxHealth = @1, Mana = @2, MaxMana = @3, Inventory = @4, spawnX = @6, spawnY = @7, hair = @8, hairDye = @9, hairColor = @10, pantsColor = @11, shirtColor = @12, underShirtColor = @13, shoeColor = @14, hideVisuals = @15, skinColor = @16, eyeColor = @17, questsCompleted = @18, skinVariant = @19, extraSlot = @20, usingBiomeTorches = @21, happyFunTorchTime = @22, unlockedBiomeTorches = @23, currentLoadoutIndex = @24, ateArtisanBread = @25, usedAegisCrystal = @26, usedAegisFruit = @27, usedArcaneCrystal = @28, usedGalaxyPearl = @29, usedGummyWorm = @30, usedAmbrosia = @31, unlockedSuperCart = @32, enabledSuperCart = @33 WHERE Account = @5;",
playerData.health, playerData.maxHealth, playerData.mana, playerData.maxMana, String.Join("~", playerData.inventory), player.Account.ID, player.TPlayer.SpawnX, player.TPlayer.SpawnY, player.TPlayer.hair, player.TPlayer.hairDye, TShock.Utils.EncodeColor(player.TPlayer.hairColor), TShock.Utils.EncodeColor(player.TPlayer.pantsColor), TShock.Utils.EncodeColor(player.TPlayer.shirtColor), TShock.Utils.EncodeColor(player.TPlayer.underShirtColor), TShock.Utils.EncodeColor(player.TPlayer.shoeColor), TShock.Utils.EncodeBoolArray(player.TPlayer.hideVisibleAccessory), TShock.Utils.EncodeColor(player.TPlayer.skinColor), TShock.Utils.EncodeColor(player.TPlayer.eyeColor), player.TPlayer.anglerQuestsFinished, player.TPlayer.skinVariant, player.TPlayer.extraAccessory ? 1 : 0, player.TPlayer.UsingBiomeTorches ? 1 : 0, player.TPlayer.happyFunTorchTime ? 1 : 0, player.TPlayer.unlockedBiomeTorches ? 1 : 0, player.TPlayer.CurrentLoadoutIndex, player.TPlayer.ateArtisanBread ? 1 : 0, player.TPlayer.usedAegisCrystal ? 1 : 0, player.TPlayer.usedAegisFruit ? 1 : 0, player.TPlayer.usedArcaneCrystal ? 1 : 0, player.TPlayer.usedGalaxyPearl ? 1 : 0, player.TPlayer.usedGummyWorm ? 1 : 0, player.TPlayer.usedAmbrosia ? 1 : 0, player.TPlayer.unlockedSuperCart ? 1 : 0, player.TPlayer.enabledSuperCart ? 1 : 0); playerData.health, playerData.maxHealth, playerData.mana, playerData.maxMana, string.Join("~", playerData.inventory), player.Account.ID, player.TPlayer.SpawnX, player.TPlayer.SpawnY, player.TPlayer.hair, player.TPlayer.hairDye, TShock.Utils.EncodeColor(player.TPlayer.hairColor), TShock.Utils.EncodeColor(player.TPlayer.pantsColor), TShock.Utils.EncodeColor(player.TPlayer.shirtColor), TShock.Utils.EncodeColor(player.TPlayer.underShirtColor), TShock.Utils.EncodeColor(player.TPlayer.shoeColor), TShock.Utils.EncodeBoolArray(player.TPlayer.hideVisibleAccessory), TShock.Utils.EncodeColor(player.TPlayer.skinColor), TShock.Utils.EncodeColor(player.TPlayer.eyeColor), player.TPlayer.anglerQuestsFinished, player.TPlayer.skinVariant, player.TPlayer.extraAccessory ? 1 : 0, player.TPlayer.UsingBiomeTorches ? 1 : 0, player.TPlayer.happyFunTorchTime ? 1 : 0, player.TPlayer.unlockedBiomeTorches ? 1 : 0, player.TPlayer.CurrentLoadoutIndex, player.TPlayer.ateArtisanBread ? 1 : 0, player.TPlayer.usedAegisCrystal ? 1 : 0, player.TPlayer.usedAegisFruit ? 1 : 0, player.TPlayer.usedArcaneCrystal ? 1 : 0, player.TPlayer.usedGalaxyPearl ? 1 : 0, player.TPlayer.usedGummyWorm ? 1 : 0, player.TPlayer.usedAmbrosia ? 1 : 0, player.TPlayer.unlockedSuperCart ? 1 : 0, player.TPlayer.enabledSuperCart ? 1 : 0);
return true; return true;
} }
catch (Exception ex) catch (Exception ex)
@ -280,7 +276,7 @@ namespace TShockAPI.DB
playerData.maxHealth, playerData.maxHealth,
playerData.mana, playerData.mana,
playerData.maxMana, playerData.maxMana,
String.Join("~", playerData.inventory), string.Join("~", playerData.inventory),
playerData.extraSlot, playerData.extraSlot,
playerData.spawnX, playerData.spawnX,
playerData.spawnX, playerData.spawnX,
@ -326,7 +322,7 @@ namespace TShockAPI.DB
playerData.maxHealth, playerData.maxHealth,
playerData.mana, playerData.mana,
playerData.maxMana, playerData.maxMana,
String.Join("~", playerData.inventory), string.Join("~", playerData.inventory),
player.Account.ID, player.Account.ID,
playerData.spawnX, playerData.spawnX,
playerData.spawnX, playerData.spawnX,

View file

@ -51,10 +51,9 @@ namespace TShockAPI.DB
new SqlColumn("Prefix", MySqlDbType.Text), new SqlColumn("Prefix", MySqlDbType.Text),
new SqlColumn("Suffix", MySqlDbType.Text) new SqlColumn("Suffix", MySqlDbType.Text)
); );
var creator = new SqlTableCreator(db,
db.GetSqlType() == SqlType.Sqlite SqlTableCreator creator = new(db, db.GetSqlQueryBuilder());
? (IQueryBuilder)new SqliteQueryCreator()
: new MysqlQueryCreator());
if (creator.EnsureTableStructure(table)) if (creator.EnsureTableStructure(table))
{ {
// Add default groups if they don't exist // Add default groups if they don't exist
@ -294,7 +293,7 @@ namespace TShockAPI.DB
/// <param name="parentname">parent of group</param> /// <param name="parentname">parent of group</param>
/// <param name="permissions">permissions</param> /// <param name="permissions">permissions</param>
/// <param name="chatcolor">chatcolor</param> /// <param name="chatcolor">chatcolor</param>
public void AddGroup(String name, string parentname, String permissions, String chatcolor) public void AddGroup(string name, string parentname, string permissions, string chatcolor)
{ {
if (GroupExists(name)) if (GroupExists(name))
{ {
@ -383,7 +382,7 @@ namespace TShockAPI.DB
/// <param name="name">The group's name.</param> /// <param name="name">The group's name.</param>
/// <param name="newName">The new name.</param> /// <param name="newName">The new name.</param>
/// <returns>The result from the operation to be sent back to the user.</returns> /// <returns>The result from the operation to be sent back to the user.</returns>
public String RenameGroup(string name, string newName) public string RenameGroup(string name, string newName)
{ {
if (!GroupExists(name)) if (!GroupExists(name))
{ {
@ -395,87 +394,83 @@ namespace TShockAPI.DB
throw new GroupExistsException(newName); throw new GroupExistsException(newName);
} }
using (var db = database.CloneEx()) using var db = database.CloneEx();
db.Open();
using var transaction = db.BeginTransaction();
try
{ {
db.Open(); using (var command = db.CreateCommand())
using (var transaction = db.BeginTransaction())
{ {
try command.CommandText = "UPDATE GroupList SET GroupName = @0 WHERE GroupName = @1";
{ command.AddParameter("@0", newName);
using (var command = db.CreateCommand()) command.AddParameter("@1", name);
{ command.ExecuteNonQuery();
command.CommandText = "UPDATE GroupList SET GroupName = @0 WHERE GroupName = @1"; }
command.AddParameter("@0", newName);
command.AddParameter("@1", name);
command.ExecuteNonQuery();
}
var oldGroup = GetGroupByName(name); var oldGroup = GetGroupByName(name);
var newGroup = new Group(newName, oldGroup.Parent, oldGroup.ChatColor, oldGroup.Permissions) var newGroup = new Group(newName, oldGroup.Parent, oldGroup.ChatColor, oldGroup.Permissions)
{ {
Prefix = oldGroup.Prefix, Prefix = oldGroup.Prefix,
Suffix = oldGroup.Suffix Suffix = oldGroup.Suffix
}; };
groups.Remove(oldGroup); groups.Remove(oldGroup);
groups.Add(newGroup); groups.Add(newGroup);
// We need to check if the old group has been referenced as a parent and update those references accordingly // We need to check if the old group has been referenced as a parent and update those references accordingly
using (var command = db.CreateCommand()) using (var command = db.CreateCommand())
{ {
command.CommandText = "UPDATE GroupList SET Parent = @0 WHERE Parent = @1"; command.CommandText = "UPDATE GroupList SET Parent = @0 WHERE Parent = @1";
command.AddParameter("@0", newName); command.AddParameter("@0", newName);
command.AddParameter("@1", name); command.AddParameter("@1", name);
command.ExecuteNonQuery(); command.ExecuteNonQuery();
} }
foreach (var group in groups.Where(g => g.Parent != null && g.Parent == oldGroup)) foreach (var group in groups.Where(g => g.Parent != null && g.Parent == oldGroup))
{ {
group.Parent = newGroup; group.Parent = newGroup;
} }
// Read the config file to prevent the possible loss of any unsaved changes // Read the config file to prevent the possible loss of any unsaved changes
TShock.Config.Read(FileTools.ConfigPath, out bool writeConfig); TShock.Config.Read(FileTools.ConfigPath, out bool writeConfig);
if (TShock.Config.Settings.DefaultGuestGroupName == oldGroup.Name) if (TShock.Config.Settings.DefaultGuestGroupName == oldGroup.Name)
{ {
TShock.Config.Settings.DefaultGuestGroupName = newGroup.Name; TShock.Config.Settings.DefaultGuestGroupName = newGroup.Name;
Group.DefaultGroup = newGroup; Group.DefaultGroup = newGroup;
} }
if (TShock.Config.Settings.DefaultRegistrationGroupName == oldGroup.Name) if (TShock.Config.Settings.DefaultRegistrationGroupName == oldGroup.Name)
{ {
TShock.Config.Settings.DefaultRegistrationGroupName = newGroup.Name; TShock.Config.Settings.DefaultRegistrationGroupName = newGroup.Name;
} }
if (writeConfig) if (writeConfig)
{ {
TShock.Config.Write(FileTools.ConfigPath); TShock.Config.Write(FileTools.ConfigPath);
} }
// We also need to check if any users belong to the old group and automatically apply changes // We also need to check if any users belong to the old group and automatically apply changes
using (var command = db.CreateCommand()) using (var command = db.CreateCommand())
{ {
command.CommandText = "UPDATE Users SET Usergroup = @0 WHERE Usergroup = @1"; command.CommandText = "UPDATE Users SET Usergroup = @0 WHERE Usergroup = @1";
command.AddParameter("@0", newName); command.AddParameter("@0", newName);
command.AddParameter("@1", name); command.AddParameter("@1", name);
command.ExecuteNonQuery(); command.ExecuteNonQuery();
} }
foreach (var player in TShock.Players.Where(p => p?.Group == oldGroup)) foreach (var player in TShock.Players.Where(p => p?.Group == oldGroup))
{ {
player.Group = newGroup; player.Group = newGroup;
} }
transaction.Commit(); transaction.Commit();
return GetString($"Group {name} has been renamed to {newName}."); return GetString($"Group {name} has been renamed to {newName}.");
} }
catch (Exception ex) catch (Exception ex)
{ {
TShock.Log.Error(GetString($"An exception has occurred during database transaction: {ex.Message}")); TShock.Log.Error(GetString($"An exception has occurred during database transaction: {ex.Message}"));
try try
{ {
transaction.Rollback(); transaction.Rollback();
} }
catch (Exception rollbackEx) catch (Exception rollbackEx)
{ {
TShock.Log.Error(GetString($"An exception has occurred during database rollback: {rollbackEx.Message}")); TShock.Log.Error(GetString($"An exception has occurred during database rollback: {rollbackEx.Message}"));
}
}
} }
} }
@ -488,7 +483,7 @@ namespace TShockAPI.DB
/// <param name="name">The group's name.</param> /// <param name="name">The group's name.</param>
/// <param name="exceptions">Whether exceptions will be thrown in case something goes wrong.</param> /// <param name="exceptions">Whether exceptions will be thrown in case something goes wrong.</param>
/// <returns>The result from the operation to be sent back to the user.</returns> /// <returns>The result from the operation to be sent back to the user.</returns>
public String DeleteGroup(String name, bool exceptions = false) public string DeleteGroup(string name, bool exceptions = false)
{ {
if (!GroupExists(name)) if (!GroupExists(name))
{ {
@ -521,7 +516,7 @@ namespace TShockAPI.DB
/// <param name="name">The group name.</param> /// <param name="name">The group name.</param>
/// <param name="permissions">The permission list.</param> /// <param name="permissions">The permission list.</param>
/// <returns>The result from the operation to be sent back to the user.</returns> /// <returns>The result from the operation to be sent back to the user.</returns>
public String AddPermissions(String name, List<String> permissions) public string AddPermissions(string name, List<string> permissions)
{ {
if (!GroupExists(name)) if (!GroupExists(name))
return GetString($"Group {name} doesn't exist."); return GetString($"Group {name} doesn't exist.");
@ -544,7 +539,7 @@ namespace TShockAPI.DB
/// <param name="name">The group name.</param> /// <param name="name">The group name.</param>
/// <param name="permissions">The permission list.</param> /// <param name="permissions">The permission list.</param>
/// <returns>The result from the operation to be sent back to the user.</returns> /// <returns>The result from the operation to be sent back to the user.</returns>
public String DeletePermissions(String name, List<String> permissions) public string DeletePermissions(string name, List<string> permissions)
{ {
if (!GroupExists(name)) if (!GroupExists(name))
return GetString($"Group {name} doesn't exist."); return GetString($"Group {name} doesn't exist.");

View file

@ -39,10 +39,9 @@ namespace TShockAPI.DB
new SqlColumn("ItemName", MySqlDbType.VarChar, 50) {Primary = true}, new SqlColumn("ItemName", MySqlDbType.VarChar, 50) {Primary = true},
new SqlColumn("AllowedGroups", MySqlDbType.Text) new SqlColumn("AllowedGroups", MySqlDbType.Text)
); );
var creator = new SqlTableCreator(db,
db.GetSqlType() == SqlType.Sqlite SqlTableCreator creator = new(db, db.GetSqlQueryBuilder());
? (IQueryBuilder) new SqliteQueryCreator()
: new MysqlQueryCreator());
creator.EnsureTableStructure(table); creator.EnsureTableStructure(table);
UpdateItemBans(); UpdateItemBans();
} }
@ -51,14 +50,13 @@ namespace TShockAPI.DB
{ {
ItemBans.Clear(); ItemBans.Clear();
using (var reader = database.QueryReader("SELECT * FROM ItemBans")) using var reader = database.QueryReader("SELECT * FROM ItemBans");
while (reader != null && reader.Read())
{ {
while (reader != null && reader.Read()) ItemBan ban = new ItemBan(reader.Get<string>("ItemName"));
{ ban.SetAllowedGroups(reader.Get<string>("AllowedGroups"));
ItemBan ban = new ItemBan(reader.Get<string>("ItemName")); ItemBans.Add(ban);
ban.SetAllowedGroups(reader.Get<string>("AllowedGroups"));
ItemBans.Add(ban);
}
} }
} }
@ -92,14 +90,7 @@ namespace TShockAPI.DB
} }
} }
public bool ItemIsBanned(string name) public bool ItemIsBanned(string name) => ItemBans.Contains(new(name));
{
if (ItemBans.Contains(new ItemBan(name)))
{
return true;
}
return false;
}
public bool ItemIsBanned(string name, TSPlayer ply) public bool ItemIsBanned(string name, TSPlayer ply)
{ {
@ -109,13 +100,12 @@ namespace TShockAPI.DB
public bool AllowGroup(string item, string name) public bool AllowGroup(string item, string name)
{ {
string groupsNew = "";
ItemBan b = GetItemBanByName(item); ItemBan b = GetItemBanByName(item);
if (b != null) if (b != null)
{ {
try try
{ {
groupsNew = String.Join(",", b.AllowedGroups); string groupsNew = string.Join(",", b.AllowedGroups);
if (groupsNew.Length > 0) if (groupsNew.Length > 0)
groupsNew += ","; groupsNew += ",";
groupsNew += name; groupsNew += name;
@ -123,7 +113,7 @@ namespace TShockAPI.DB
int q = database.Query("UPDATE ItemBans SET AllowedGroups=@0 WHERE ItemName=@1", groupsNew, int q = database.Query("UPDATE ItemBans SET AllowedGroups=@0 WHERE ItemName=@1", groupsNew,
item); item);
return q > 0; return q > 0;
} }
catch (Exception ex) catch (Exception ex)
@ -141,12 +131,12 @@ namespace TShockAPI.DB
if (b != null) if (b != null)
{ {
try try
{ {
b.RemoveGroup(group); b.RemoveGroup(group);
string groups = string.Join(",", b.AllowedGroups); string groups = string.Join(",", b.AllowedGroups);
int q = database.Query("UPDATE ItemBans SET AllowedGroups=@0 WHERE ItemName=@1", groups, int q = database.Query("UPDATE ItemBans SET AllowedGroups=@0 WHERE ItemName=@1", groups,
item); item);
if (q > 0) if (q > 0)
return true; return true;
} }
@ -158,7 +148,7 @@ namespace TShockAPI.DB
return false; return false;
} }
public ItemBan GetItemBanByName(String name) public ItemBan GetItemBanByName(string name)
{ {
for (int i = 0; i < ItemBans.Count; i++) for (int i = 0; i < ItemBans.Count; i++)
{ {
@ -189,10 +179,7 @@ namespace TShockAPI.DB
AllowedGroups = new List<string>(); AllowedGroups = new List<string>();
} }
public bool Equals(ItemBan other) public bool Equals(ItemBan other) => Name == other.Name;
{
return Name == other.Name;
}
public bool HasPermissionToUseItem(TSPlayer ply) public bool HasPermissionToUseItem(TSPlayer ply)
{ {
@ -225,12 +212,12 @@ namespace TShockAPI.DB
// could add in the other permissions in this class instead of a giant if switch. // could add in the other permissions in this class instead of a giant if switch.
} }
public void SetAllowedGroups(String groups) public void SetAllowedGroups(string groups)
{ {
// prevent null pointer exceptions // prevent null pointer exceptions
if (!string.IsNullOrEmpty(groups)) if (!string.IsNullOrEmpty(groups))
{ {
List<String> groupArr = groups.Split(',').ToList(); List<string> groupArr = groups.Split(',').ToList();
for (int i = 0; i < groupArr.Count; i++) for (int i = 0; i < groupArr.Count; i++)
{ {
@ -245,10 +232,10 @@ namespace TShockAPI.DB
{ {
return AllowedGroups.Remove(groupName); return AllowedGroups.Remove(groupName);
} }
public override string ToString() public override string ToString()
{ {
return Name + (AllowedGroups.Count > 0 ? " (" + String.Join(",", AllowedGroups) + ")" : ""); return Name + (AllowedGroups.Count > 0 ? " (" + string.Join(",", AllowedGroups) + ")" : "");
} }
} }
} }

View file

@ -39,10 +39,8 @@ namespace TShockAPI.DB
new SqlColumn("ProjectileID", MySqlDbType.Int32) {Primary = true}, new SqlColumn("ProjectileID", MySqlDbType.Int32) {Primary = true},
new SqlColumn("AllowedGroups", MySqlDbType.Text) new SqlColumn("AllowedGroups", MySqlDbType.Text)
); );
var creator = new SqlTableCreator(db,
db.GetSqlType() == SqlType.Sqlite SqlTableCreator creator = new(db, db.GetSqlQueryBuilder());
? (IQueryBuilder) new SqliteQueryCreator()
: new MysqlQueryCreator());
creator.EnsureTableStructure(table); creator.EnsureTableStructure(table);
UpdateBans(); UpdateBans();
} }
@ -51,14 +49,13 @@ namespace TShockAPI.DB
{ {
ProjectileBans.Clear(); ProjectileBans.Clear();
using (var reader = database.QueryReader("SELECT * FROM ProjectileBans")) using var reader = database.QueryReader("SELECT * FROM ProjectileBans");
while (reader != null && reader.Read())
{ {
while (reader != null && reader.Read()) ProjectileBan ban = new ProjectileBan((short) reader.Get<int>("ProjectileID"));
{ ban.SetAllowedGroups(reader.Get<string>("AllowedGroups"));
ProjectileBan ban = new ProjectileBan((short) reader.Get<Int32>("ProjectileID")); ProjectileBans.Add(ban);
ban.SetAllowedGroups(reader.Get<string>("AllowedGroups"));
ProjectileBans.Add(ban);
}
} }
} }
@ -93,14 +90,7 @@ namespace TShockAPI.DB
} }
} }
public bool ProjectileIsBanned(short id) public bool ProjectileIsBanned(short id) => ProjectileBans.Contains(new(id));
{
if (ProjectileBans.Contains(new ProjectileBan(id)))
{
return true;
}
return false;
}
public bool ProjectileIsBanned(short id, TSPlayer ply) public bool ProjectileIsBanned(short id, TSPlayer ply)
{ {
@ -114,13 +104,12 @@ namespace TShockAPI.DB
public bool AllowGroup(short id, string name) public bool AllowGroup(short id, string name)
{ {
string groupsNew = "";
ProjectileBan b = GetBanById(id); ProjectileBan b = GetBanById(id);
if (b != null) if (b != null)
{ {
try try
{ {
groupsNew = String.Join(",", b.AllowedGroups); string groupsNew = string.Join(",", b.AllowedGroups);
if (groupsNew.Length > 0) if (groupsNew.Length > 0)
groupsNew += ","; groupsNew += ",";
groupsNew += name; groupsNew += name;
@ -194,10 +183,7 @@ namespace TShockAPI.DB
AllowedGroups = new List<string>(); AllowedGroups = new List<string>();
} }
public bool Equals(ProjectileBan other) public bool Equals(ProjectileBan other) => ID == other.ID;
{
return ID == other.ID;
}
public bool HasPermissionToCreateProjectile(TSPlayer ply) public bool HasPermissionToCreateProjectile(TSPlayer ply)
{ {
@ -230,12 +216,12 @@ namespace TShockAPI.DB
// could add in the other permissions in this class instead of a giant if switch. // could add in the other permissions in this class instead of a giant if switch.
} }
public void SetAllowedGroups(String groups) public void SetAllowedGroups(string groups)
{ {
// prevent null pointer exceptions // prevent null pointer exceptions
if (!string.IsNullOrEmpty(groups)) if (!string.IsNullOrEmpty(groups))
{ {
List<String> groupArr = groups.Split(',').ToList(); List<string> groupArr = groups.Split(',').ToList();
for (int i = 0; i < groupArr.Count; i++) for (int i = 0; i < groupArr.Count; i++)
{ {
@ -246,14 +232,8 @@ namespace TShockAPI.DB
} }
} }
public bool RemoveGroup(string groupName) public bool RemoveGroup(string groupName) => AllowedGroups.Remove(groupName);
{
return AllowedGroups.Remove(groupName);
}
public override string ToString() public override string ToString() => ID + (AllowedGroups.Count > 0 ? $" ({string.Join(",", AllowedGroups)})" : "");
{
return ID + (AllowedGroups.Count > 0 ? " (" + String.Join(",", AllowedGroups) + ")" : "");
}
} }
} }

View file

@ -1,4 +1,4 @@
/* /*
TShock, a server mod for Terraria TShock, a server mod for Terraria
Copyright (C) 2011-2019 Pryaxis & TShock Contributors Copyright (C) 2011-2019 Pryaxis & TShock Contributors
@ -56,10 +56,7 @@ namespace TShockAPI.DB
new SqlColumn("Owner", MySqlDbType.VarChar, 50), new SqlColumn("Owner", MySqlDbType.VarChar, 50),
new SqlColumn("Z", MySqlDbType.Int32){ DefaultValue = "0" } new SqlColumn("Z", MySqlDbType.Int32){ DefaultValue = "0" }
); );
var creator = new SqlTableCreator(db, SqlTableCreator creator = new(db, db.GetSqlQueryBuilder());
db.GetSqlType() == SqlType.Sqlite
? (IQueryBuilder) new SqliteQueryCreator()
: new MysqlQueryCreator());
creator.EnsureTableStructure(table); creator.EnsureTableStructure(table);
} }
@ -70,49 +67,46 @@ namespace TShockAPI.DB
{ {
try try
{ {
using (var reader = database.QueryReader("SELECT * FROM Regions WHERE WorldID=@0", Main.worldID.ToString())) using var reader = database.QueryReader("SELECT * FROM Regions WHERE WorldID=@0", Main.worldID.ToString());
Regions.Clear();
while (reader.Read())
{ {
Regions.Clear(); int id = reader.Get<int>("Id");
while (reader.Read()) int X1 = reader.Get<int>("X1");
int Y1 = reader.Get<int>("Y1");
int height = reader.Get<int>("height");
int width = reader.Get<int>("width");
int Protected = reader.Get<int>("Protected");
string mergedids = reader.Get<string>("UserIds");
string name = reader.Get<string>("RegionName");
string owner = reader.Get<string>("Owner");
string groups = reader.Get<string>("Groups");
int z = reader.Get<int>("Z");
string[] splitids = mergedids.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
Region r = new Region(id, new Rectangle(X1, Y1, width, height), name, owner, Protected != 0, Main.worldID.ToString(), z);
r.SetAllowedGroups(groups);
try
{ {
int id = reader.Get<int>("Id"); foreach (string t in splitids)
int X1 = reader.Get<int>("X1");
int Y1 = reader.Get<int>("Y1");
int height = reader.Get<int>("height");
int width = reader.Get<int>("width");
int Protected = reader.Get<int>("Protected");
string mergedids = reader.Get<string>("UserIds");
string name = reader.Get<string>("RegionName");
string owner = reader.Get<string>("Owner");
string groups = reader.Get<string>("Groups");
int z = reader.Get<int>("Z");
string[] splitids = mergedids.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
Region r = new Region(id, new Rectangle(X1, Y1, width, height), name, owner, Protected != 0, Main.worldID.ToString(), z);
r.SetAllowedGroups(groups);
try
{ {
for (int i = 0; i < splitids.Length; i++) if (int.TryParse(t, out int userid)) // if unparsable, it's not an int, so silently skip
{ r.AllowedIDs.Add(userid);
int userid; else
TShock.Log.Warn(GetString($"One of your UserIDs is not a usable integer: {t}"));
if (Int32.TryParse(splitids[i], out userid)) // if unparsable, it's not an int, so silently skip
r.AllowedIDs.Add(userid);
else
TShock.Log.Warn(GetString($"One of your UserIDs is not a usable integer: {splitids[i]}"));
}
} }
catch (Exception e)
{
TShock.Log.Error(GetString("Your database contains invalid UserIDs (they should be integers)."));
TShock.Log.Error(GetString("A lot of things will fail because of this. You must manually delete and re-create the allowed field."));
TShock.Log.Error(e.ToString());
TShock.Log.Error(e.StackTrace);
}
Regions.Add(r);
} }
catch (Exception e)
{
TShock.Log.Error(GetString("Your database contains invalid UserIDs (they should be integers)."));
TShock.Log.Error(GetString("A lot of things will fail because of this. You must manually delete and re-create the allowed field."));
TShock.Log.Error(e.ToString());
TShock.Log.Error(e.StackTrace);
}
Regions.Add(r);
} }
} }
catch (Exception ex) catch (Exception ex)
@ -296,10 +290,7 @@ namespace TShockAPI.DB
/// <param name="x">X coordinate</param> /// <param name="x">X coordinate</param>
/// <param name="y">Y coordinate</param> /// <param name="y">Y coordinate</param>
/// <returns>Whether any regions exist at the given (x, y) coordinate</returns> /// <returns>Whether any regions exist at the given (x, y) coordinate</returns>
public bool InArea(int x, int y) public bool InArea(int x, int y) => Regions.Any(r => r.InArea(x, y));
{
return Regions.Any(r => r.InArea(x, y));
}
/// <summary> /// <summary>
/// Checks if any regions exist at the given (x, y) coordinate /// Checks if any regions exist at the given (x, y) coordinate
@ -308,10 +299,7 @@ namespace TShockAPI.DB
/// <param name="x">X coordinate</param> /// <param name="x">X coordinate</param>
/// <param name="y">Y coordinate</param> /// <param name="y">Y coordinate</param>
/// <returns>The names of any regions that exist at the given (x, y) coordinate</returns> /// <returns>The names of any regions that exist at the given (x, y) coordinate</returns>
public IEnumerable<string> InAreaRegionName(int x, int y) public IEnumerable<string> InAreaRegionName(int x, int y) => Regions.Where(r => r.InArea(x, y)).Select(r => r.Name);
{
return Regions.Where(r => r.InArea(x, y)).Select(r => r.Name);
}
/// <summary> /// <summary>
/// Checks if any regions exist at the given (x, y) coordinate /// Checks if any regions exist at the given (x, y) coordinate
@ -320,10 +308,7 @@ namespace TShockAPI.DB
/// <param name="x">X coordinate</param> /// <param name="x">X coordinate</param>
/// <param name="y">Y coordinate</param> /// <param name="y">Y coordinate</param>
/// <returns>The IDs of any regions that exist at the given (x, y) coordinate</returns> /// <returns>The IDs of any regions that exist at the given (x, y) coordinate</returns>
public IEnumerable<int> InAreaRegionID(int x, int y) public IEnumerable<int> InAreaRegionID(int x, int y) => Regions.Where(r => r.InArea(x, y)).Select(r => r.ID);
{
return Regions.Where(r => r.InArea(x, y)).Select(r => r.ID);
}
/// <summary> /// <summary>
/// Checks if any regions exist at the given (x, y) coordinate /// Checks if any regions exist at the given (x, y) coordinate
@ -332,10 +317,7 @@ namespace TShockAPI.DB
/// <param name="x">X coordinate</param> /// <param name="x">X coordinate</param>
/// <param name="y">Y coordinate</param> /// <param name="y">Y coordinate</param>
/// <returns>The <see cref="Region"/> objects of any regions that exist at the given (x, y) coordinate</returns> /// <returns>The <see cref="Region"/> objects of any regions that exist at the given (x, y) coordinate</returns>
public IEnumerable<Region> InAreaRegion(int x, int y) public IEnumerable<Region> InAreaRegion(int x, int y) => Regions.Where(r => r.InArea(x, y));
{
return Regions.Where(r => r.InArea(x, y));
}
/// <summary> /// <summary>
/// Changes the size of a given region /// Changes the size of a given region
@ -414,7 +396,6 @@ namespace TShockAPI.DB
/// <returns>true if renamed successfully, false otherwise</returns> /// <returns>true if renamed successfully, false otherwise</returns>
public bool RenameRegion(string oldName, string newName) public bool RenameRegion(string oldName, string newName)
{ {
Region region = null;
string worldID = Main.worldID.ToString(); string worldID = Main.worldID.ToString();
bool result = false; bool result = false;
@ -426,7 +407,7 @@ namespace TShockAPI.DB
if (q > 0) if (q > 0)
{ {
region = Regions.First(r => r.Name == oldName && r.WorldID == worldID); Region region = Regions.First(r => r.Name == oldName && r.WorldID == worldID);
region.Name = newName; region.Name = newName;
Hooks.RegionHooks.OnRegionRenamed(region, oldName, newName); Hooks.RegionHooks.OnRegionRenamed(region, oldName, newName);
result = true; result = true;
@ -523,7 +504,7 @@ namespace TShockAPI.DB
{ {
try try
{ {
Region region = Regions.First(r => String.Equals(regionName, r.Name, StringComparison.OrdinalIgnoreCase)); Region region = Regions.First(r => string.Equals(regionName, r.Name, StringComparison.OrdinalIgnoreCase));
region.Area = new Rectangle(x, y, width, height); region.Area = new Rectangle(x, y, width, height);
if (database.Query("UPDATE Regions SET X1 = @0, Y1 = @1, width = @2, height = @3 WHERE RegionName = @4 AND WorldID = @5", if (database.Query("UPDATE Regions SET X1 = @0, Y1 = @1, width = @2, height = @3 WHERE RegionName = @4 AND WorldID = @5",
@ -547,11 +528,9 @@ namespace TShockAPI.DB
var regions = new List<Region>(); var regions = new List<Region>();
try try
{ {
using (var reader = database.QueryReader("SELECT RegionName FROM Regions WHERE WorldID=@0", worldid)) using var reader = database.QueryReader("SELECT RegionName FROM Regions WHERE WorldID=@0", worldid);
{ while (reader.Read())
while (reader.Read()) regions.Add(new Region {Name = reader.Get<string>("RegionName")});
regions.Add(new Region {Name = reader.Get<string>("RegionName")});
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -565,20 +544,14 @@ namespace TShockAPI.DB
/// </summary> /// </summary>
/// <param name="name">Region name</param> /// <param name="name">Region name</param>
/// <returns>The region with the given name, or null if not found</returns> /// <returns>The region with the given name, or null if not found</returns>
public Region GetRegionByName(String name) public Region GetRegionByName(string name) => Regions.FirstOrDefault(r => r.Name.Equals(name) && r.WorldID == Main.worldID.ToString());
{
return Regions.FirstOrDefault(r => r.Name.Equals(name) && r.WorldID == Main.worldID.ToString());
}
/// <summary> /// <summary>
/// Returns a region with the given ID /// Returns a region with the given ID
/// </summary> /// </summary>
/// <param name="id">Region ID</param> /// <param name="id">Region ID</param>
/// <returns>The region with the given ID, or null if not found</returns> /// <returns>The region with the given ID, or null if not found</returns>
public Region GetRegionByID(int id) public Region GetRegionByID(int id) => Regions.FirstOrDefault(r => r.ID == id && r.WorldID == Main.worldID.ToString());
{
return Regions.FirstOrDefault(r => r.ID == id && r.WorldID == Main.worldID.ToString());
}
/// <summary> /// <summary>
/// Changes the owner of the region with the given name /// Changes the owner of the region with the given name
@ -799,12 +772,12 @@ namespace TShockAPI.DB
/// Sets the user IDs which are allowed to use the region /// Sets the user IDs which are allowed to use the region
/// </summary> /// </summary>
/// <param name="ids">String of IDs to set</param> /// <param name="ids">String of IDs to set</param>
public void SetAllowedIDs(String ids) public void SetAllowedIDs(string ids)
{ {
String[] idArr = ids.Split(','); string[] idArr = ids.Split(',');
List<int> idList = new List<int>(); List<int> idList = new List<int>();
foreach (String id in idArr) foreach (string id in idArr)
{ {
int i = 0; int i = 0;
if (int.TryParse(id, out i) && i != 0) if (int.TryParse(id, out i) && i != 0)
@ -819,12 +792,12 @@ namespace TShockAPI.DB
/// Sets the group names which are allowed to use the region /// Sets the group names which are allowed to use the region
/// </summary> /// </summary>
/// <param name="groups">String of group names to set</param> /// <param name="groups">String of group names to set</param>
public void SetAllowedGroups(String groups) public void SetAllowedGroups(string groups)
{ {
// prevent null pointer exceptions // prevent null pointer exceptions
if (!string.IsNullOrEmpty(groups)) if (!string.IsNullOrEmpty(groups))
{ {
List<String> groupList = groups.Split(',').ToList(); List<string> groupList = groups.Split(',').ToList();
for (int i = 0; i < groupList.Count; i++) for (int i = 0; i < groupList.Count; i++)
{ {

View file

@ -40,10 +40,7 @@ namespace TShockAPI.DB
new SqlColumn("Y", MySqlDbType.Int32), new SqlColumn("Y", MySqlDbType.Int32),
new SqlColumn("WorldID", MySqlDbType.Text) new SqlColumn("WorldID", MySqlDbType.Text)
); );
var creator = new SqlTableCreator(db, SqlTableCreator creator = new(db, db.GetSqlQueryBuilder());
db.GetSqlType() == SqlType.Sqlite
? (IQueryBuilder) new SqliteQueryCreator()
: new MysqlQueryCreator());
creator.EnsureTableStructure(table); creator.EnsureTableStructure(table);
} }
@ -51,19 +48,17 @@ namespace TShockAPI.DB
{ {
try try
{ {
using (var reader = database.QueryReader("SELECT * FROM RememberedPos WHERE Name=@0", name)) using var reader = database.QueryReader("SELECT * FROM RememberedPos WHERE Name=@0", name);
if (reader.Read())
{ {
if (reader.Read()) int checkX=reader.Get<int>("X");
{ int checkY=reader.Get<int>("Y");
int checkX=reader.Get<int>("X"); //fix leftover inconsistencies
int checkY=reader.Get<int>("Y"); if (checkX==0)
//fix leftover inconsistencies checkX++;
if (checkX==0) if (checkY==0)
checkX++; checkY++;
if (checkY==0) return new Vector2(checkX, checkY);
checkY++;
return new Vector2(checkX, checkY);
}
} }
} }
catch (Exception ex) catch (Exception ex)
@ -80,12 +75,10 @@ namespace TShockAPI.DB
{ {
try try
{ {
using (var reader = database.QueryReader("SELECT * FROM RememberedPos WHERE Name=@0 AND IP=@1 AND WorldID=@2", name, IP, Main.worldID.ToString())) using var reader = database.QueryReader("SELECT * FROM RememberedPos WHERE Name=@0 AND IP=@1 AND WorldID=@2", name, IP, Main.worldID.ToString());
if (reader.Read())
{ {
if (reader.Read()) return new Vector2(reader.Get<int>("X"), reader.Get<int>("Y"));
{
return new Vector2(reader.Get<int>("X"), reader.Get<int>("Y"));
}
} }
} }
catch (Exception ex) catch (Exception ex)

View file

@ -41,10 +41,9 @@ namespace TShockAPI.DB
new SqlColumn("AmountSacrificed", MySqlDbType.Int32), new SqlColumn("AmountSacrificed", MySqlDbType.Int32),
new SqlColumn("TimeSacrificed", MySqlDbType.DateTime) new SqlColumn("TimeSacrificed", MySqlDbType.DateTime)
); );
var creator = new SqlTableCreator(db,
db.GetSqlType() == SqlType.Sqlite SqlTableCreator creator = new(db, db.GetSqlQueryBuilder());
? (IQueryBuilder)new SqliteQueryCreator()
: new MysqlQueryCreator());
try try
{ {
creator.EnsureTableStructure(table); creator.EnsureTableStructure(table);
@ -85,15 +84,14 @@ namespace TShockAPI.DB
where WorldId = @0 where WorldId = @0
group by itemId"; group by itemId";
try { try
using (var reader = database.QueryReader(sql, Main.worldID)) {
using var reader = database.QueryReader(sql, Main.worldID);
while (reader.Read())
{ {
while (reader.Read()) var itemId = reader.Get<int>("itemId");
{ var amount = reader.Get<int>("totalSacrificed");
var itemId = reader.Get<Int32>("itemId"); sacrificedItems[itemId] = amount;
var amount = reader.Get<Int32>("totalSacrificed");
sacrificedItems[itemId] = amount;
}
} }
} }
catch (Exception ex) catch (Exception ex)

View file

@ -75,31 +75,44 @@ namespace TShockAPI.DB
public List<string> GetColumns(SqlTable table) public List<string> GetColumns(SqlTable table)
{ {
var ret = new List<string>(); List<string> ret = new();
var name = database.GetSqlType(); switch (database.GetSqlType())
if (name == SqlType.Sqlite)
{ {
using (var reader = database.QueryReader("PRAGMA table_info({0})".SFormat(table.Name))) case SqlType.Sqlite:
{ {
using QueryResult reader = database.QueryReader("PRAGMA table_info({0})".SFormat(table.Name));
while (reader.Read()) while (reader.Read())
{
ret.Add(reader.Get<string>("name")); ret.Add(reader.Get<string>("name"));
}
break;
} }
} case SqlType.Mysql:
else if (name == SqlType.Mysql)
{
using (
var reader =
database.QueryReader(
"SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME=@0 AND TABLE_SCHEMA=@1", table.Name,
database.Database))
{ {
using QueryResult reader =
database.QueryReader("SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME=@0 AND TABLE_SCHEMA=@1", table.Name, database.Database);
while (reader.Read()) while (reader.Read())
{
ret.Add(reader.Get<string>("COLUMN_NAME")); ret.Add(reader.Get<string>("COLUMN_NAME"));
}
break;
} }
} case SqlType.Postgres:
else {
{ using QueryResult reader =
throw new NotSupportedException(); database.QueryReader("SELECT column_name FROM information_schema.columns WHERE table_name=@0", table.Name);
while (reader.Read())
{
ret.Add(reader.Get<string>("column_name"));
}
break;
}
default: throw new NotSupportedException();
} }
return ret; return ret;
@ -110,4 +123,4 @@ namespace TShockAPI.DB
database.Query(creator.DeleteRow(table, wheres)); database.Query(creator.DeleteRow(table, wheres));
} }
} }
} }

View file

@ -59,11 +59,9 @@ namespace TShockAPI.DB
{ {
List<object> values = new List<object>(); List<object> values = new List<object>();
using (var reader = database.QueryReader(creator.ReadColumn(table, wheres))) using var reader = database.QueryReader(creator.ReadColumn(table, wheres));
{ while (reader.Read())
while (reader.Read()) values.Add(reader.Reader.Get<object>(column));
values.Add(reader.Reader.Get<object>(column));
}
return values; return values;
} }

View file

@ -39,10 +39,8 @@ namespace TShockAPI.DB
new SqlColumn("TileId", MySqlDbType.Int32) { Primary = true }, new SqlColumn("TileId", MySqlDbType.Int32) { Primary = true },
new SqlColumn("AllowedGroups", MySqlDbType.Text) new SqlColumn("AllowedGroups", MySqlDbType.Text)
); );
var creator = new SqlTableCreator(db,
db.GetSqlType() == SqlType.Sqlite SqlTableCreator creator = new(db, db.GetSqlQueryBuilder());
? (IQueryBuilder)new SqliteQueryCreator()
: new MysqlQueryCreator());
creator.EnsureTableStructure(table); creator.EnsureTableStructure(table);
UpdateBans(); UpdateBans();
} }
@ -51,14 +49,12 @@ namespace TShockAPI.DB
{ {
TileBans.Clear(); TileBans.Clear();
using (var reader = database.QueryReader("SELECT * FROM TileBans")) using var reader = database.QueryReader("SELECT * FROM TileBans");
while (reader != null && reader.Read())
{ {
while (reader != null && reader.Read()) TileBan ban = new TileBan((short)reader.Get<int>("TileId"));
{ ban.SetAllowedGroups(reader.Get<string>("AllowedGroups"));
TileBan ban = new TileBan((short)reader.Get<Int32>("TileId")); TileBans.Add(ban);
ban.SetAllowedGroups(reader.Get<string>("AllowedGroups"));
TileBans.Add(ban);
}
} }
} }
@ -120,7 +116,7 @@ namespace TShockAPI.DB
{ {
try try
{ {
groupsNew = String.Join(",", b.AllowedGroups); groupsNew = string.Join(",", b.AllowedGroups);
if (groupsNew.Length > 0) if (groupsNew.Length > 0)
groupsNew += ","; groupsNew += ",";
groupsNew += name; groupsNew += name;
@ -230,12 +226,12 @@ namespace TShockAPI.DB
// could add in the other permissions in this class instead of a giant if switch. // could add in the other permissions in this class instead of a giant if switch.
} }
public void SetAllowedGroups(String groups) public void SetAllowedGroups(string groups)
{ {
// prevent null pointer exceptions // prevent null pointer exceptions
if (!string.IsNullOrEmpty(groups)) if (!string.IsNullOrEmpty(groups))
{ {
List<String> groupArr = groups.Split(',').ToList(); List<string> groupArr = groups.Split(',').ToList();
for (int i = 0; i < groupArr.Count; i++) for (int i = 0; i < groupArr.Count; i++)
{ {
@ -253,7 +249,7 @@ namespace TShockAPI.DB
public override string ToString() public override string ToString()
{ {
return ID + (AllowedGroups.Count > 0 ? " (" + String.Join(",", AllowedGroups) + ")" : ""); return ID + (AllowedGroups.Count > 0 ? " (" + string.Join(",", AllowedGroups) + ")" : "");
} }
} }
} }

View file

@ -53,10 +53,8 @@ namespace TShockAPI.DB
new SqlColumn("LastAccessed", MySqlDbType.Text), new SqlColumn("LastAccessed", MySqlDbType.Text),
new SqlColumn("KnownIPs", MySqlDbType.Text) new SqlColumn("KnownIPs", MySqlDbType.Text)
); );
var creator = new SqlTableCreator(db,
db.GetSqlType() == SqlType.Sqlite SqlTableCreator creator = new(db, db.GetSqlQueryBuilder());
? (IQueryBuilder) new SqliteQueryCreator()
: new MysqlQueryCreator());
creator.EnsureTableStructure(table); creator.EnsureTableStructure(table);
} }
@ -241,12 +239,10 @@ namespace TShockAPI.DB
{ {
try try
{ {
using (var reader = _database.QueryReader("SELECT * FROM Users WHERE Username=@0", username)) using var reader = _database.QueryReader("SELECT * FROM Users WHERE Username=@0", username);
if (reader.Read())
{ {
if (reader.Read()) return reader.Get<int>("ID");
{
return reader.Get<int>("ID");
}
} }
} }
catch (Exception ex) catch (Exception ex)
@ -310,16 +306,14 @@ namespace TShockAPI.DB
try try
{ {
using (var result = _database.QueryReader(query, arg)) using var result = _database.QueryReader(query, arg);
if (result.Read())
{ {
if (result.Read()) account = LoadUserAccountFromResult(account, result);
{ // Check for multiple matches
account = LoadUserAccountFromResult(account, result); if (!result.Read())
// Check for multiple matches return account;
if (!result.Read()) multiple = true;
return account;
multiple = true;
}
} }
} }
catch (Exception ex) catch (Exception ex)
@ -339,14 +333,12 @@ namespace TShockAPI.DB
try try
{ {
List<UserAccount> accounts = new List<UserAccount>(); List<UserAccount> accounts = new List<UserAccount>();
using (var reader = _database.QueryReader("SELECT * FROM Users")) using var reader = _database.QueryReader("SELECT * FROM Users");
while (reader.Read())
{ {
while (reader.Read()) accounts.Add(LoadUserAccountFromResult(new UserAccount(), reader));
{
accounts.Add(LoadUserAccountFromResult(new UserAccount(), reader));
}
return accounts;
} }
return accounts;
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -367,14 +359,13 @@ namespace TShockAPI.DB
{ {
List<UserAccount> accounts = new List<UserAccount>(); List<UserAccount> accounts = new List<UserAccount>();
string search = notAtStart ? string.Format("%{0}%", username) : string.Format("{0}%", username); string search = notAtStart ? string.Format("%{0}%", username) : string.Format("{0}%", username);
using (var reader = _database.QueryReader("SELECT * FROM Users WHERE Username LIKE @0", using var reader = _database.QueryReader("SELECT * FROM Users WHERE Username LIKE @0",
search)) search);
while (reader.Read())
{ {
while (reader.Read()) accounts.Add(LoadUserAccountFromResult(new UserAccount(), reader));
{
accounts.Add(LoadUserAccountFromResult(new UserAccount(), reader));
}
} }
return accounts; return accounts;
} }
catch (Exception ex) catch (Exception ex)
@ -497,7 +488,7 @@ namespace TShockAPI.DB
int currentWorkFactor; int currentWorkFactor;
try try
{ {
currentWorkFactor = Int32.Parse((Password.Split('$')[2])); currentWorkFactor = int.Parse((Password.Split('$')[2]));
} }
catch (FormatException) catch (FormatException)
{ {

View file

@ -49,10 +49,8 @@ namespace TShockAPI.DB
new SqlColumn("WorldID", MySqlDbType.VarChar, 50) { Unique = true }, new SqlColumn("WorldID", MySqlDbType.VarChar, 50) { Unique = true },
new SqlColumn("Private", MySqlDbType.Text) new SqlColumn("Private", MySqlDbType.Text)
); );
var creator = new SqlTableCreator(db,
db.GetSqlType() == SqlType.Sqlite SqlTableCreator creator = new(db, db.GetSqlQueryBuilder());
? (IQueryBuilder) new SqliteQueryCreator()
: new MysqlQueryCreator());
creator.EnsureTableStructure(table); creator.EnsureTableStructure(table);
} }
@ -88,16 +86,14 @@ namespace TShockAPI.DB
{ {
Warps.Clear(); Warps.Clear();
using (var reader = database.QueryReader("SELECT * FROM Warps WHERE WorldID = @0", using var reader = database.QueryReader("SELECT * FROM Warps WHERE WorldID = @0",
Main.worldID.ToString())) Main.worldID.ToString());
while (reader.Read())
{ {
while (reader.Read()) Warps.Add(new Warp(
{ new Point(reader.Get<int>("X"), reader.Get<int>("Y")),
Warps.Add(new Warp( reader.Get<string>("WarpName"),
new Point(reader.Get<int>("X"), reader.Get<int>("Y")), (reader.Get<string>("Private") ?? "0") != "0"));
reader.Get<string>("WarpName"),
(reader.Get<string>("Private") ?? "0") != "0"));
}
} }
} }
@ -113,7 +109,7 @@ namespace TShockAPI.DB
if (database.Query("DELETE FROM Warps WHERE WarpName = @0 AND WorldID = @1", if (database.Query("DELETE FROM Warps WHERE WarpName = @0 AND WorldID = @1",
warpName, Main.worldID.ToString()) > 0) warpName, Main.worldID.ToString()) > 0)
{ {
Warps.RemoveAll(w => String.Equals(w.Name, warpName, StringComparison.OrdinalIgnoreCase)); Warps.RemoveAll(w => string.Equals(w.Name, warpName, StringComparison.OrdinalIgnoreCase));
return true; return true;
} }
} }
@ -131,7 +127,7 @@ namespace TShockAPI.DB
/// <returns>The warp, if it exists, or else null.</returns> /// <returns>The warp, if it exists, or else null.</returns>
public Warp Find(string warpName) public Warp Find(string warpName)
{ {
return Warps.FirstOrDefault(w => String.Equals(w.Name, warpName, StringComparison.OrdinalIgnoreCase)); return Warps.FirstOrDefault(w => string.Equals(w.Name, warpName, StringComparison.OrdinalIgnoreCase));
} }
/// <summary> /// <summary>
@ -148,7 +144,7 @@ namespace TShockAPI.DB
if (database.Query("UPDATE Warps SET X = @0, Y = @1 WHERE WarpName = @2 AND WorldID = @3", if (database.Query("UPDATE Warps SET X = @0, Y = @1 WHERE WarpName = @2 AND WorldID = @3",
x, y, warpName, Main.worldID.ToString()) > 0) x, y, warpName, Main.worldID.ToString()) > 0)
{ {
Warps.Find(w => String.Equals(w.Name, warpName, StringComparison.OrdinalIgnoreCase)).Position = new Point(x, y); Warps.Find(w => string.Equals(w.Name, warpName, StringComparison.OrdinalIgnoreCase)).Position = new Point(x, y);
return true; return true;
} }
} }
@ -172,7 +168,7 @@ namespace TShockAPI.DB
if (database.Query("UPDATE Warps SET Private = @0 WHERE WarpName = @1 AND WorldID = @2", if (database.Query("UPDATE Warps SET Private = @0 WHERE WarpName = @1 AND WorldID = @2",
state ? "1" : "0", warpName, Main.worldID.ToString()) > 0) state ? "1" : "0", warpName, Main.worldID.ToString()) > 0)
{ {
Warps.Find(w => String.Equals(w.Name, warpName, StringComparison.OrdinalIgnoreCase)).IsPrivate = state; Warps.Find(w => string.Equals(w.Name, warpName, StringComparison.OrdinalIgnoreCase)).IsPrivate = state;
return true; return true;
} }
} }

View file

@ -23,6 +23,7 @@ using System.Diagnostics.CodeAnalysis;
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using MySql.Data.MySqlClient; using MySql.Data.MySqlClient;
using Npgsql; using Npgsql;
using TShockAPI.DB.Queries;
namespace TShockAPI.DB namespace TShockAPI.DB
{ {
@ -154,6 +155,14 @@ namespace TShockAPI.DB
_ => SqlType.Unknown _ => SqlType.Unknown
}; };
public static IQueryBuilder GetSqlQueryBuilder(this IDbConnection db) => db.GetSqlType() switch
{
SqlType.Sqlite => new SqliteQueryCreator(),
SqlType.Mysql => new MysqlQueryCreator(),
SqlType.Postgres => new PostgresQueryCreator(),
_ => throw new NotSupportedException("Database type not supported.")
};
private static readonly Dictionary<Type, Func<IDataReader, int, object>> ReadFuncs = new Dictionary private static readonly Dictionary<Type, Func<IDataReader, int, object>> ReadFuncs = new Dictionary
<Type, Func<IDataReader, int, object>> <Type, Func<IDataReader, int, object>>
{ {

View file

@ -62,7 +62,7 @@ namespace TShockAPI
/// <param name="clearTextLog"></param> /// <param name="clearTextLog"></param>
public SqlLog(IDbConnection db, string textlogFilepath, bool clearTextLog) public SqlLog(IDbConnection db, string textlogFilepath, bool clearTextLog)
{ {
FileName = string.Format("{0}://database", db.GetSqlType()); FileName = $"{db.GetSqlType()}://database";
_database = db; _database = db;
_backupLog = new TextLog(textlogFilepath, clearTextLog); _backupLog = new TextLog(textlogFilepath, clearTextLog);
@ -74,10 +74,7 @@ namespace TShockAPI
new SqlColumn("Message", MySqlDbType.Text) new SqlColumn("Message", MySqlDbType.Text)
); );
var creator = new SqlTableCreator(db, SqlTableCreator creator = new(db, db.GetSqlQueryBuilder());
db.GetSqlType() == SqlType.Sqlite
? (IQueryBuilder) new SqliteQueryCreator()
: new MysqlQueryCreator());
creator.EnsureTableStructure(table); creator.EnsureTableStructure(table);
} }