Ban rewrite and various other adjustments

This commit is contained in:
Chris 2020-11-26 17:20:19 +10:30
parent ce523e1436
commit cde4cc5f04
11 changed files with 742 additions and 276 deletions

View file

@ -46,7 +46,6 @@ namespace TShockAPI.DB
com.CommandText = query;
for (int i = 0; i < args.Length; i++)
com.AddParameter("@" + i, args[i]);
return com.ExecuteNonQuery();
}
}
@ -81,6 +80,36 @@ namespace TShockAPI.DB
}
}
/// <summary>
/// Executes a query on a database, returning the first column of the first row of the result set.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="olddb">Database to query</param>
/// <param name="query">Query string with parameters as @0, @1, etc.</param>
/// <param name="args">Parameters to be put in the query</param>
/// <returns></returns>
public static T QueryScalar<T>(this IDbConnection olddb, string query, params object[] args)
{
using (var db = olddb.CloneEx())
{
db.Open();
using (var com = db.CreateCommand())
{
com.CommandText = query;
for (int i = 0; i < args.Length; i++)
com.AddParameter("@" + i, args[i]);
object output = com.ExecuteScalar();
if (typeof(IConvertible).IsAssignableFrom(output.GetType()))
{
return (T)Convert.ChangeType(output, typeof(T));
}
return (T)output;
}
}
}
public static QueryResult QueryReaderDict(this IDbConnection olddb, string query, Dictionary<string, object> values)
{
var db = olddb.CloneEx();
@ -156,10 +185,10 @@ namespace TShockAPI.DB
typeof (Int32?),
(s, i) => s.IsDBNull(i) ? null : (object)s.GetInt32(i)
},
{
/*{
typeof (Int64),
(s, i) => s.GetInt64(i)
},
},*/
{
typeof (Int64?),
(s, i) => s.IsDBNull(i) ? null : (object)s.GetInt64(i)
@ -210,12 +239,24 @@ namespace TShockAPI.DB
public static T Get<T>(this IDataReader reader, int column)
{
if (reader.IsDBNull(column))
return default(T);
return default;
if (ReadFuncs.ContainsKey(typeof(T)))
return (T)ReadFuncs[typeof(T)](reader, column);
throw new NotImplementedException();
Type t;
if (typeof(T) != (t = reader.GetFieldType(column)))
{
string columnName = reader.GetName(column);
throw new InvalidCastException($"Received type '{typeof(T).Name}', however column '{columnName}' expects type '{t.Name}'");
}
if (reader.IsDBNull(column))
{
return default;
}
return (T)reader.GetValue(column);
}
}

View file

@ -16,6 +16,7 @@ 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 Microsoft.Xna.Framework;
using System;
namespace TShockAPI
@ -27,5 +28,16 @@ namespace TShockAPI
{
return String.Format(str, args);
}
/// <summary>
/// Wraps the string representation of an object with a Terraria color code for the given color
/// </summary>
/// <param name="obj"></param>
/// <param name="color"></param>
/// <returns></returns>
public static string Color(this object obj, string color)
{
return $"[c/{color}:{obj}]";
}
}
}
}