Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ef7ac54e36 | ||
|
|
83dc8d6045 | ||
|
|
ff6fb08a08 | ||
|
|
d2900f364d | ||
|
|
b014c2f392 | ||
|
|
0ad7221680 | ||
|
|
36da32f870 | ||
|
|
d8c9867e50 | ||
|
|
166956f10f | ||
|
|
ddb7f6dc89 | ||
|
|
06aa7969bf | ||
|
|
fb6cf14402 | ||
|
|
e8e1fb993d | ||
|
|
8633ac1925 | ||
|
|
8de75728e0 | ||
|
|
0f38c92bbe | ||
|
|
46e8ec1180 | ||
|
|
97b7eaeffe |
@@ -16,7 +16,7 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
|
|||||||
/// <param name="dbAttributeName">Name of database-attribute (case-sensitivity is determined from database-attribute-settings) ['null' if the same as field-name]</param>
|
/// <param name="dbAttributeName">Name of database-attribute (case-sensitivity is determined from database-attribute-settings) ['null' if the same as field-name]</param>
|
||||||
public DbAttribute(string attributeName = null)
|
public DbAttribute(string attributeName = null)
|
||||||
{
|
{
|
||||||
this._attributeName = attributeName;
|
this._attributeName = attributeName; // Todo: Automatic resolving of name if it is null (?)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
|
namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
|
||||||
@@ -10,16 +11,33 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
|
|||||||
{
|
{
|
||||||
public Type _classType;
|
public Type _classType;
|
||||||
public string _attributeName;
|
public string _attributeName;
|
||||||
|
public string _foreignKeyFieldName;
|
||||||
|
public FieldInfo _foreignKeyField;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Marks variable as foreignKey of given class
|
/// Marks variable as foreignKey of given class
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="classType">Type of class to which this is the ForeignKey</param>
|
/// <param name="classType">Type of class to which this is the ForeignKey</param>
|
||||||
/// <param name="dbAttributeName">Name of database-attribute (case-sensitivity is determined from database-attribute-settings) ['null' if the same as field-name]</param>
|
/// <param name="dbAttributeName">Name of database-attribute (case-sensitivity is determined from database-attribute-settings) ['null' if the same as field-name]</param>
|
||||||
public DbForeignKey(Type classType, string attributeName = null)
|
/// <param name="foreignKeyFieldName">Name of foreignKey-fieldName ['null' if the same as classType-name]</param>
|
||||||
|
public DbForeignKey(Type classType, string foreignKeyFieldName = null, string attributeName = null)
|
||||||
{
|
{
|
||||||
this._classType = classType;
|
this._classType = classType;
|
||||||
this._attributeName = attributeName;
|
this._attributeName = attributeName; // Todo: Automatic resolving of name if it is null (?)
|
||||||
|
|
||||||
|
bool fieldFound = false;
|
||||||
|
foreach (System.Reflection.FieldInfo fi in classType.GetRuntimeFields())
|
||||||
|
{
|
||||||
|
if(fi.Name.ToLower() == foreignKeyFieldName.ToLower())
|
||||||
|
{
|
||||||
|
this._foreignKeyFieldName = fi.Name;
|
||||||
|
this._foreignKeyField = fi;
|
||||||
|
|
||||||
|
fieldFound = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!fieldFound) throw new InvalidOperationException($"Field with name='{foreignKeyFieldName}' not found in {classType.Name}.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
|
|||||||
/// <param name="tableName">Name of database-table (case-sensitivity is determined from database-table-settings) ['null' if the same as class-name]</param>
|
/// <param name="tableName">Name of database-table (case-sensitivity is determined from database-table-settings) ['null' if the same as class-name]</param>
|
||||||
public DbObject(string tableName = null)
|
public DbObject(string tableName = null)
|
||||||
{
|
{
|
||||||
this._tableName = tableName;
|
this._tableName = tableName; // Todo: Automatic resolving of name if it is null (?)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
|
|||||||
/// <param name="dbAttributeName">Name of database-attribute (case-sensitivity is determined from database-attribute-settings) ['null' if the same as field-name]</param>
|
/// <param name="dbAttributeName">Name of database-attribute (case-sensitivity is determined from database-attribute-settings) ['null' if the same as field-name]</param>
|
||||||
public DbPrimaryKey(string attributeName = null)
|
public DbPrimaryKey(string attributeName = null)
|
||||||
{
|
{
|
||||||
this._attributeName = attributeName;
|
this._attributeName = attributeName; // Todo: Automatic resolving of name if it is null (?)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
162
Database-Attribute_System/ClassAction.cs
Normal file
162
Database-Attribute_System/ClassAction.cs
Normal file
@@ -0,0 +1,162 @@
|
|||||||
|
using eu.railduction.netcore.dll.Database_Attribute_System.Attributes;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace eu.railduction.netcore.dll.Database_Attribute_System
|
||||||
|
{
|
||||||
|
public class ClassAction
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Fills an given dbObject with given data<para/>
|
||||||
|
/// Data-attribute-names and class-fieldNames have to match! (non case-sensitive)
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <param name="classObject">Given object (marked with Db-attributes)</param>
|
||||||
|
/// <param name="data">The data</param>
|
||||||
|
/// <param name="runDataLossChecks">This checks if any class-field and data-attribute does not exists in either (Slower)</param>
|
||||||
|
public static void FillObject<T>(T classObject, Dictionary<string, object> data, bool runDataLossChecks = true)
|
||||||
|
{
|
||||||
|
Type classType = classObject.GetType();
|
||||||
|
|
||||||
|
string tableName = Function.GetDbTableName(classType);
|
||||||
|
|
||||||
|
// Get class-fields
|
||||||
|
Dictionary<string, FieldInfo> dbFields = Function.ReadDbClassFields(classType);
|
||||||
|
|
||||||
|
if (runDataLossChecks)
|
||||||
|
{
|
||||||
|
// Check every data-attribute for match in class-fields
|
||||||
|
foreach (KeyValuePair<string, object> data_keySet in data)
|
||||||
|
{
|
||||||
|
bool isFound = false;
|
||||||
|
foreach (KeyValuePair<string, FieldInfo> field_keySet in dbFields)
|
||||||
|
{
|
||||||
|
if (field_keySet.Key.ToLower() == data_keySet.Key.ToLower())
|
||||||
|
isFound = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isFound)
|
||||||
|
throw new InvalidOperationException($"Could not fill object. Data-Attribute '{data_keySet.Key}' was not found in class!");
|
||||||
|
}
|
||||||
|
// Check every class-field for match in data-attributes
|
||||||
|
foreach (KeyValuePair<string, FieldInfo> field_keySet in dbFields)
|
||||||
|
{
|
||||||
|
bool isFound = false;
|
||||||
|
foreach (KeyValuePair<string, object> data_keySet in data)
|
||||||
|
{
|
||||||
|
if (field_keySet.Key.ToLower() == data_keySet.Key.ToLower())
|
||||||
|
isFound = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isFound)
|
||||||
|
throw new InvalidOperationException($"Could not fill object. Class-field '{field_keySet.Key}' was not found in data!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Iterate through data
|
||||||
|
foreach (KeyValuePair<string, object> data_keySet in data)
|
||||||
|
{
|
||||||
|
// Interate through class-fields
|
||||||
|
foreach (KeyValuePair<string, FieldInfo> field_keySet in dbFields)
|
||||||
|
{
|
||||||
|
// If its a match, set the value
|
||||||
|
if (field_keySet.Key.ToLower() == data_keySet.Key.ToLower())
|
||||||
|
{
|
||||||
|
field_keySet.Value.SetValue(classObject, data_keySet.Value);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets an dbObject
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <param name="classObject">Given object (marked with Db-attributes)</param>
|
||||||
|
/// <param name="queryExecutor">Function to handle query-calls - Has to return Dictionary[attributeName, attributeValue]</param>
|
||||||
|
/// <param name="runDataLossChecks">This checks if any class-field and data-attribute does not exists in either (Slower)</param>
|
||||||
|
public static T GetByPrimaryKey<T>(Type classType, Func<string, List<Dictionary<string, object>>> queryExecutor, bool runDataLossChecks = true) where T: new()
|
||||||
|
{
|
||||||
|
T obj = new T();
|
||||||
|
|
||||||
|
string query = QueryBuilder.SelectByPrimaryKey(obj); // Generate query
|
||||||
|
List<Dictionary<string, object>> dataSet = queryExecutor(query); // Execute
|
||||||
|
FillObject(obj, dataSet[0], runDataLossChecks); // Fill the object
|
||||||
|
|
||||||
|
return obj;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets a list of dbObjects by attribute/s
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <param name="classType">Type of class</param>
|
||||||
|
/// <param name="fields">class-fields for select</param>
|
||||||
|
/// <param name="queryExecutor">Function to handle query-calls - Has to return Dictionary[attributeName, attributeValue]</param>
|
||||||
|
/// <param name="runDataLossChecks">This checks if any class-field and data-attribute does not exists in either (Slower)</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static List<T> GetListByAttribute<T>(Type classType, Dictionary<string, object> fields, Func<string, List<Dictionary<string, object>>> queryExecutor, bool runDataLossChecks = true) where T : new()
|
||||||
|
{
|
||||||
|
string tableName = Function.GetDbTableName(classType); // Get database-tableName
|
||||||
|
|
||||||
|
Function.ConvertAttributeToDbAttributes(classType, fields);
|
||||||
|
|
||||||
|
string query = QueryBuilder.SelectByAttribute(tableName, fields); // Generate query
|
||||||
|
List<Dictionary<string, object>> dataSet = queryExecutor(query); // Execute
|
||||||
|
|
||||||
|
List<T> objs = new List<T>() { };
|
||||||
|
foreach(Dictionary<string, object> data in dataSet)
|
||||||
|
{
|
||||||
|
T obj = new T(); // New object
|
||||||
|
FillObject(obj, data, runDataLossChecks); // Fill it
|
||||||
|
objs.Add(obj); // Add to list
|
||||||
|
}
|
||||||
|
|
||||||
|
return objs; // Return list
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Resolves all foreignKeys with the database
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <param name="classObject">Given object (marked with Db-attributes)</param>
|
||||||
|
/// <param name="queryExecutor">Function to handle query-calls - Has to return Dictionary[attributeName, attributeValue]</param>
|
||||||
|
/// <param name="max_depth">Determents how deep resolving will be executed</param>
|
||||||
|
/// <param name="runDataLossChecks">This checks if any class-field and data-attribute does not exists in either (Slower)</param>
|
||||||
|
public static void ResolveForeignKeys<T>(T classObject, Func<string, List<Dictionary<string, object>>> queryExecutor, int max_depth = 1, bool runDataLossChecks = true) where T: new()
|
||||||
|
{
|
||||||
|
Type classType = classObject.GetType();
|
||||||
|
|
||||||
|
// Get class-fields
|
||||||
|
Dictionary<string, FieldInfo> dbFields = Function.ReadDbClassFields(classType);
|
||||||
|
|
||||||
|
foreach (KeyValuePair<string, FieldInfo> dbField in dbFields)
|
||||||
|
{
|
||||||
|
// If field is foreignKey
|
||||||
|
if (dbField.Value.GetCustomAttribute(typeof(DbForeignKey), true) is DbForeignKey fkey)
|
||||||
|
{
|
||||||
|
FieldInfo f_Field = fkey._foreignKeyField;
|
||||||
|
object f_value = f_Field.GetValue(classObject);
|
||||||
|
|
||||||
|
// When its empty, get it
|
||||||
|
if(f_value == null)
|
||||||
|
{
|
||||||
|
f_value = GetByPrimaryKey<T>(classType, queryExecutor, runDataLossChecks); ;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recursive resolving
|
||||||
|
if (max_depth - 1 > 0)
|
||||||
|
{
|
||||||
|
ResolveForeignKeys(f_value, queryExecutor, max_depth - 1, runDataLossChecks);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
<TargetFramework>netcoreapp2.1</TargetFramework>
|
<TargetFramework>netcoreapp2.1</TargetFramework>
|
||||||
<RootNamespace>eu.railduction.netcore.dll.Database_Attribute_System</RootNamespace>
|
<RootNamespace>eu.railduction.netcore.dll.Database_Attribute_System</RootNamespace>
|
||||||
<SignAssembly>false</SignAssembly>
|
<SignAssembly>false</SignAssembly>
|
||||||
|
<Version>1.4</Version>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -1,86 +0,0 @@
|
|||||||
using eu.railduction.netcore.dll.Database_Attribute_System.Attributes;
|
|
||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Reflection;
|
|
||||||
using System.Text;
|
|
||||||
|
|
||||||
namespace eu.railduction.netcore.dll.Database_Attribute_System
|
|
||||||
{
|
|
||||||
class Function
|
|
||||||
{
|
|
||||||
public static string SqlEscape(string str)
|
|
||||||
{
|
|
||||||
string str_cpy = str.Replace(@"'", @"\'");
|
|
||||||
return str_cpy;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static string SqlSerialise(DateTime dt)
|
|
||||||
{
|
|
||||||
return dt.ToString("yyyy-MM-dd HH:mm:ss");
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public static object[] BuildKeyEqualQuery(Dictionary<string, object> keysets, string seperator)
|
|
||||||
{
|
|
||||||
object[] param = new object[keysets.Count * 2];
|
|
||||||
int c = 0;
|
|
||||||
foreach (KeyValuePair<string, object> keyset in keysets)
|
|
||||||
{
|
|
||||||
string sql_string = "";
|
|
||||||
|
|
||||||
if (c != 0) sql_string += seperator;
|
|
||||||
sql_string += $"{keyset.Key}=";
|
|
||||||
|
|
||||||
param[c] = sql_string;
|
|
||||||
param[c + 1] = keyset.Value;
|
|
||||||
|
|
||||||
c += 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
return param;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static string GetDbTableName(Type classType)
|
|
||||||
{
|
|
||||||
// Check if class has attribute 'DbObject' and get the database table-name
|
|
||||||
if (!(classType.GetCustomAttribute(typeof(DbObject), true) is DbObject dbObjectAttribute)) throw new InvalidOperationException("Cannot generate SQL-Query of class. Missing Attribute 'DbObject'");
|
|
||||||
string tableName = dbObjectAttribute._tableName ?? classType.Name; // If no alternative table-name is specified, use the class-name
|
|
||||||
|
|
||||||
return tableName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void ReadDbClassFields<T>(T classObject, ref Dictionary<string, object> dbPrimaryKeys, ref Dictionary<string, object> dbAttributes, ref Dictionary<string, object> dbForeignKeys)
|
|
||||||
{
|
|
||||||
Type classType = typeof(T);
|
|
||||||
|
|
||||||
// Reset lists (just in case)
|
|
||||||
dbPrimaryKeys = new Dictionary<string, object> () { };
|
|
||||||
dbAttributes = new Dictionary<string, object>() { };
|
|
||||||
dbForeignKeys = new Dictionary<string, object>() { };
|
|
||||||
|
|
||||||
// Iterate thru all properties
|
|
||||||
foreach (System.Reflection.FieldInfo fi in classType.GetRuntimeFields())
|
|
||||||
{
|
|
||||||
// Check if current field is a db-field
|
|
||||||
if (fi.GetCustomAttribute(typeof(DbPrimaryKey), true) is DbPrimaryKey pkey) // PrimaryKey
|
|
||||||
{
|
|
||||||
string dbAttributeName = pkey._attributeName ?? fi.Name; // If no alternative attribute-name is specified, use the property-name
|
|
||||||
object value = fi.GetValue(classObject);
|
|
||||||
dbPrimaryKeys.Add(dbAttributeName, value);
|
|
||||||
}
|
|
||||||
else if (fi.GetCustomAttribute(typeof(DbAttribute), true) is DbAttribute att) // Attributes
|
|
||||||
{
|
|
||||||
string dbAttributeName = att._attributeName ?? fi.Name; // If no alternative attribute-name is specified, use the property-name
|
|
||||||
object value = fi.GetValue(classObject);
|
|
||||||
dbAttributes.Add(dbAttributeName, value);
|
|
||||||
}
|
|
||||||
else if (fi.GetCustomAttribute(typeof(DbForeignKey), true) is DbForeignKey fkey) // ForeignKeys
|
|
||||||
{
|
|
||||||
string dbAttributeName = fkey._attributeName ?? fi.Name; // If no alternative attribute-name is specified, use the property-name
|
|
||||||
object value = fi.GetValue(classObject);
|
|
||||||
dbForeignKeys.Add(dbAttributeName, value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -7,7 +7,14 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
|
|||||||
{
|
{
|
||||||
public class QueryBuilder
|
public class QueryBuilder
|
||||||
{
|
{
|
||||||
public static string SelectByPrimaryKeys<T>(T classObject)
|
/// <summary>
|
||||||
|
/// Builds an SELECT-Sql-query based on an object
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <param name="classObject">Given object (marked with Db-attributes)</param>
|
||||||
|
/// <param name="tableName">The db-table-name</param>
|
||||||
|
/// <returns>SELECT-Sql-query</returns>
|
||||||
|
public static string SelectByPrimaryKey<T>(T classObject)
|
||||||
{
|
{
|
||||||
Type classType = classObject.GetType();
|
Type classType = classObject.GetType();
|
||||||
|
|
||||||
@@ -19,18 +26,47 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
|
|||||||
Dictionary<string, object> dbAttributes = new Dictionary<string, object>() { };
|
Dictionary<string, object> dbAttributes = new Dictionary<string, object>() { };
|
||||||
Dictionary<string, object> dbForeignKeys = new Dictionary<string, object>() { };
|
Dictionary<string, object> dbForeignKeys = new Dictionary<string, object>() { };
|
||||||
Function.ReadDbClassFields(classObject, ref dbPrimaryKeys, ref dbAttributes, ref dbForeignKeys);
|
Function.ReadDbClassFields(classObject, ref dbPrimaryKeys, ref dbAttributes, ref dbForeignKeys);
|
||||||
|
if (dbPrimaryKeys.Count == 0) throw new InvalidOperationException($"Cannot generate SQL-Query of '{classType.Name}'. No primary-key/s found!");
|
||||||
|
|
||||||
|
return SelectByAttribute(tableName, dbPrimaryKeys);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds an SELECT-Sql-query based on an object<para/>
|
||||||
|
/// Object needs to have at least 1 attribute!
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <param name="tableName">The db-table-name</param>
|
||||||
|
/// <param name="dbAttributes">The db-attributes with dbAttribute-name and value<para/>If null is given, it will generate a default 'SELECT * FROM tableName'</param>
|
||||||
|
/// <returns>SELECT-Sql-query</returns>
|
||||||
|
public static string SelectByAttribute(string tableName, Dictionary<string, object> dbAttributes = null)
|
||||||
|
{
|
||||||
|
object[] param = new object[1];
|
||||||
|
if (dbAttributes != null)
|
||||||
|
{
|
||||||
// Build where statements with primaryKey/s
|
// Build where statements with primaryKey/s
|
||||||
object[] param = Function.BuildKeyEqualQuery(dbPrimaryKeys, " AND ");
|
param = DbFunction.BuildKeyEqualQuery(dbAttributes, " AND ");
|
||||||
|
}
|
||||||
|
|
||||||
|
string sqlCmd = $"SELECT * FROM {tableName}";
|
||||||
// Add SQL-command part
|
// Add SQL-command part
|
||||||
param[0] = $"SELECT * FROM {tableName} WHERE "+ param[0];
|
if (dbAttributes != null)
|
||||||
|
param[0] = $"{sqlCmd} WHERE {param[0]}";
|
||||||
|
else
|
||||||
|
param[0] = sqlCmd;
|
||||||
|
|
||||||
// Build and return the query
|
// Build and return the query
|
||||||
return BuildQuery(param);
|
return BuildQuery(param);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
public static string UpdateByPrimaryKeys<T>(T classObject)
|
/// Builds an UPDATE-Sql-query based on an object<para/>
|
||||||
|
/// Object needs to have at least 1 primary-key!
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <param name="classObject">Given object (marked with Db-attributes)</param>
|
||||||
|
/// <returns>UPDATE-Sql-query</returns>
|
||||||
|
public static string UpdateByPrimaryKey<T>(T classObject)
|
||||||
{
|
{
|
||||||
Type classType = classObject.GetType();
|
Type classType = classObject.GetType();
|
||||||
|
|
||||||
@@ -42,20 +78,21 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
|
|||||||
Dictionary<string, object> dbAttributes = new Dictionary<string, object>() { };
|
Dictionary<string, object> dbAttributes = new Dictionary<string, object>() { };
|
||||||
Dictionary<string, object> dbForeignKeys = new Dictionary<string, object>() { };
|
Dictionary<string, object> dbForeignKeys = new Dictionary<string, object>() { };
|
||||||
Function.ReadDbClassFields(classObject, ref dbPrimaryKeys, ref dbAttributes, ref dbForeignKeys);
|
Function.ReadDbClassFields(classObject, ref dbPrimaryKeys, ref dbAttributes, ref dbForeignKeys);
|
||||||
|
if (dbPrimaryKeys.Count == 0) throw new InvalidOperationException($"Cannot generate SQL-Query of '{classType.Name}'. No primary-key/s found!");
|
||||||
|
|
||||||
// Add foreign-keys to attributes
|
// Add foreign-keys to attributes
|
||||||
foreach(KeyValuePair<string, object> dbForeignKey in dbForeignKeys)
|
foreach (KeyValuePair<string, object> dbForeignKey in dbForeignKeys)
|
||||||
{
|
{
|
||||||
dbAttributes.Add(dbForeignKey.Key, dbForeignKey.Value);
|
dbAttributes.Add(dbForeignKey.Key, dbForeignKey.Value);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build set-parameters
|
// Build set-parameters
|
||||||
object[] paramSet = Function.BuildKeyEqualQuery(dbAttributes, ", ");
|
object[] paramSet = DbFunction.BuildKeyEqualQuery(dbAttributes, ", ");
|
||||||
// Add SQL-command part
|
// Add SQL-command part
|
||||||
paramSet[0] = $"UPDATE {tableName} SET "+ paramSet[0];
|
paramSet[0] = $"UPDATE {tableName} SET "+ paramSet[0];
|
||||||
|
|
||||||
// Build where-parameters
|
// Build where-parameters
|
||||||
object[] paramWhere = Function.BuildKeyEqualQuery(dbPrimaryKeys, " AND ");
|
object[] paramWhere = DbFunction.BuildKeyEqualQuery(dbPrimaryKeys, " AND ");
|
||||||
// Add SQL-command part
|
// Add SQL-command part
|
||||||
paramWhere[0] = " WHERE "+ paramWhere[0];
|
paramWhere[0] = " WHERE "+ paramWhere[0];
|
||||||
|
|
||||||
@@ -63,7 +100,14 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
|
|||||||
return BuildQuery(paramSet, paramWhere);
|
return BuildQuery(paramSet, paramWhere);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static string DeleteByPrimaryKeys<T>(T classObject)
|
/// <summary>
|
||||||
|
/// Builds an DELETE-Sql-query based on an object<para/>
|
||||||
|
/// Object needs to have at least 1 primary-key!
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <param name="classObject">Given object (marked with Db-attributes)</param>
|
||||||
|
/// <returns>DELETE-Sql-query</returns>
|
||||||
|
public static string DeleteByPrimaryKey<T>(T classObject)
|
||||||
{
|
{
|
||||||
Type classType = classObject.GetType();
|
Type classType = classObject.GetType();
|
||||||
|
|
||||||
@@ -75,40 +119,50 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
|
|||||||
Dictionary<string, object> dbAttributes = new Dictionary<string, object>() { };
|
Dictionary<string, object> dbAttributes = new Dictionary<string, object>() { };
|
||||||
Dictionary<string, object> dbForeignKeys = new Dictionary<string, object>() { };
|
Dictionary<string, object> dbForeignKeys = new Dictionary<string, object>() { };
|
||||||
Function.ReadDbClassFields(classObject, ref dbPrimaryKeys, ref dbAttributes, ref dbForeignKeys);
|
Function.ReadDbClassFields(classObject, ref dbPrimaryKeys, ref dbAttributes, ref dbForeignKeys);
|
||||||
|
if (dbPrimaryKeys.Count == 0) throw new InvalidOperationException($"Cannot generate SQL-Query of '{classType.Name}'. No primary-key/s found!");
|
||||||
// Build where-parameters
|
|
||||||
object[] paramWhere = Function.BuildKeyEqualQuery(dbPrimaryKeys, " AND ");
|
|
||||||
// Add SQL-command part
|
|
||||||
paramWhere[0] = $"DELETE FROM {tableName} WHERE "+ paramWhere[0];
|
|
||||||
|
|
||||||
// Build and return the query
|
// Build and return the query
|
||||||
return BuildQuery(paramWhere);
|
return DeleteByAttribute(tableName, dbPrimaryKeys);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static string DeleteByAttribute(string tableName, Dictionary<string, object> dbAttributes = null)
|
||||||
|
{
|
||||||
|
object[] param = new object[1];
|
||||||
|
if (dbAttributes != null)
|
||||||
|
{
|
||||||
|
// Build where statements with primaryKey/s
|
||||||
|
param = DbFunction.BuildKeyEqualQuery(dbAttributes, " AND ");
|
||||||
|
}
|
||||||
|
|
||||||
|
string sqlCmd = $"DELETE FROM {tableName}";
|
||||||
|
// Add SQL-command part
|
||||||
|
if (dbAttributes != null)
|
||||||
|
param[0] = $"{sqlCmd} WHERE {param[0]}";
|
||||||
|
else
|
||||||
|
param[0] = sqlCmd;
|
||||||
|
|
||||||
|
// Build and return the query
|
||||||
|
return BuildQuery(param);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Build an SQL-query<para/>
|
/// Build an SQL-query<para/>
|
||||||
/// Will build the query-string based on the <paramref name="param"/>s including serialising and escaping for SQL.<para/>
|
/// Will build the query-string based on the <paramref name="param"/>s including serialising and escaping for SQL.<para/>
|
||||||
|
/// (Supported-Types: null, string, byte, int, float, double, DateTime, Guid)
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="param">Params with alternating query-parts and objects beginning with a query-part
|
/// <param name="param">Params with alternating query-parts and objects beginning with a query-part
|
||||||
/// <para/>Example: "SELECT * FROM table WHERE id=", id, " AND name=", name</param>
|
/// <para/>Example: "SELECT * FROM table WHERE id=", id, " AND name=", name<para/>
|
||||||
|
/// Info: Any object[] will be opened recursively and added as <paramref name="param"/> accordingly!
|
||||||
|
/// </param>
|
||||||
public static string BuildQuery(params object[] param)
|
public static string BuildQuery(params object[] param)
|
||||||
{
|
{
|
||||||
// Convert array to list and add object[] to it accordingly
|
// Convert array to list and add object[] to it recursively
|
||||||
List<object> paramz = new List<object>() { };
|
List<object> paramz = new List<object>() { };
|
||||||
foreach (object obj in param)
|
Function.RecursiveParameterCopying(ref paramz, (object[])param);
|
||||||
{
|
|
||||||
if (!(obj is object[]))
|
|
||||||
paramz.Add(obj);
|
|
||||||
else
|
|
||||||
{
|
|
||||||
foreach (object obj2 in (object[])obj)
|
|
||||||
{
|
|
||||||
paramz.Add(obj2);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
string query = "";
|
string query = "";
|
||||||
for (int i = 0; i < paramz.Count; i++)
|
for (int i = 0; i < paramz.Count; i++)
|
||||||
@@ -116,33 +170,9 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
|
|||||||
if (i % 2 == 0) query += paramz[i]; // Every 'even' count will just add
|
if (i % 2 == 0) query += paramz[i]; // Every 'even' count will just add
|
||||||
else // Every 'uneven' count will handle param as passed variable
|
else // Every 'uneven' count will handle param as passed variable
|
||||||
{
|
{
|
||||||
string paramString = "";
|
string paramString = Function.SqlSerialise(paramz[i]);
|
||||||
if (paramz[i] == null) // Handle null
|
if(paramString == null) // Unknown type in params
|
||||||
{
|
throw new Exception($"Error in query-builder. Type '{paramz[i].GetType().ToString()}' cannot be serialised!");
|
||||||
paramString = "null";
|
|
||||||
}
|
|
||||||
else if (paramz[i].GetType() == typeof(string)) // Handle strings
|
|
||||||
{
|
|
||||||
paramString = "'" + Function.SqlEscape((string)paramz[i]) + "'"; // wrap in sql-brackets and escape sql, if any
|
|
||||||
}
|
|
||||||
else if (paramz[i].GetType() == typeof(int) || paramz[i].GetType() == typeof(float) || paramz[i].GetType() == typeof(double)) // Handle int, float & double
|
|
||||||
{
|
|
||||||
paramString = paramz[i].ToString().Replace(",", "."); // just format to string and form comma to sql-comma
|
|
||||||
}
|
|
||||||
else if (paramz[i].GetType() == typeof(DateTime)) // Handle DateTime
|
|
||||||
{
|
|
||||||
DateTime dateTime = (DateTime)paramz[i];
|
|
||||||
paramString = "'" + Function.SqlSerialise(dateTime) + "'"; // wrap in sql-brackets and convert to sql-datetime
|
|
||||||
}
|
|
||||||
else if (paramz[i].GetType() == typeof(Guid)) // Handle DateTime
|
|
||||||
{
|
|
||||||
string guid = ((Guid)paramz[i]).ToString(); // Get Guid as string
|
|
||||||
paramString = "'" + guid + "'"; // wrap in sql-brackets
|
|
||||||
}
|
|
||||||
else // Unknown type in params
|
|
||||||
{
|
|
||||||
throw new Exception($"Error in query-builder: Type '{paramz[i].GetType().ToString()}' cannot be used!");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add formed param to query
|
// Add formed param to query
|
||||||
query += paramString;
|
query += paramString;
|
||||||
|
|||||||
31
Database-Attribute_System/internal/DbFunction.cs
Normal file
31
Database-Attribute_System/internal/DbFunction.cs
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
using eu.railduction.netcore.dll.Database_Attribute_System.Attributes;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace eu.railduction.netcore.dll.Database_Attribute_System
|
||||||
|
{
|
||||||
|
class DbFunction
|
||||||
|
{
|
||||||
|
internal static object[] BuildKeyEqualQuery(Dictionary<string, object> keysets, string seperator)
|
||||||
|
{
|
||||||
|
object[] param = new object[keysets.Count * 2];
|
||||||
|
int c = 0;
|
||||||
|
foreach (KeyValuePair<string, object> keyset in keysets)
|
||||||
|
{
|
||||||
|
string sql_string = "";
|
||||||
|
|
||||||
|
if (c != 0) sql_string += seperator;
|
||||||
|
sql_string += $"{keyset.Key}=";
|
||||||
|
|
||||||
|
param[c] = sql_string;
|
||||||
|
param[c + 1] = keyset.Value;
|
||||||
|
|
||||||
|
c += 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
return param;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
182
Database-Attribute_System/internal/Function.cs
Normal file
182
Database-Attribute_System/internal/Function.cs
Normal file
@@ -0,0 +1,182 @@
|
|||||||
|
using eu.railduction.netcore.dll.Database_Attribute_System.Attributes;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace eu.railduction.netcore.dll.Database_Attribute_System
|
||||||
|
{
|
||||||
|
internal class Function
|
||||||
|
{
|
||||||
|
public static string SqlEscape(string str)
|
||||||
|
{
|
||||||
|
string str_cpy = str.Replace(@"'", @"\'");
|
||||||
|
return str_cpy;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string SqlSerialise(DateTime dt, string format = "yyyy-MM-dd HH:mm:ss")
|
||||||
|
{
|
||||||
|
return dt.ToString(format);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recursive object[] copying
|
||||||
|
internal static void RecursiveParameterCopying(ref List<object> paramz, object[] objects)
|
||||||
|
{
|
||||||
|
foreach (object obj in objects)
|
||||||
|
{
|
||||||
|
if (!(obj is object[]))
|
||||||
|
paramz.Add(obj);
|
||||||
|
else
|
||||||
|
RecursiveParameterCopying(ref paramz, (object[])obj);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void ConvertAttributeToDbAttributes(Type classType, Dictionary<string, object> attributeNameAndValues)
|
||||||
|
{
|
||||||
|
Dictionary<string, FieldInfo> classFields = ReadDbClassFields(classType);
|
||||||
|
|
||||||
|
foreach (KeyValuePair<string, object> attributeNameAndValue in attributeNameAndValues)
|
||||||
|
{
|
||||||
|
bool nameFound = false;
|
||||||
|
foreach (KeyValuePair<string, FieldInfo> classField in classFields)
|
||||||
|
{
|
||||||
|
if (attributeNameAndValue.Key.ToLower() == classField.Value.Name.ToLower())
|
||||||
|
{
|
||||||
|
attributeNameAndValues.Remove(attributeNameAndValue.Key);
|
||||||
|
|
||||||
|
attributeNameAndValues.Add(classField.Key, attributeNameAndValue.Value);
|
||||||
|
|
||||||
|
nameFound = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!nameFound) throw new InvalidOperationException($"{attributeNameAndValue.Key} has no classField!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
internal static void ConvertAttributeToDbAttributes(Type classType, List<string> attributeNames)
|
||||||
|
{
|
||||||
|
Dictionary<string, FieldInfo> classFields = ReadDbClassFields(classType);
|
||||||
|
|
||||||
|
List<string> dbAttributes = new List<string>() { };
|
||||||
|
for(int i=0; i< attributeNames.Count; i++)
|
||||||
|
{
|
||||||
|
bool nameFound = false;
|
||||||
|
foreach (KeyValuePair<string, FieldInfo> classField in classFields)
|
||||||
|
{
|
||||||
|
if(attributeNames[i].ToLower() == classField.Value.Name.ToLower())
|
||||||
|
{
|
||||||
|
attributeNames[i] = classField.Key;
|
||||||
|
|
||||||
|
nameFound = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!nameFound) throw new InvalidOperationException($"{attributeNames[i]} has no classField!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void ReadDbClassFields<T>(T classObject, ref Dictionary<string, object> dbPrimaryKeys, ref Dictionary<string, object> dbAttributes, ref Dictionary<string, object> dbForeignKeys)
|
||||||
|
{
|
||||||
|
Type classType = typeof(T);
|
||||||
|
|
||||||
|
// Reset lists (just in case)
|
||||||
|
dbPrimaryKeys = new Dictionary<string, object>() { };
|
||||||
|
dbAttributes = new Dictionary<string, object>() { };
|
||||||
|
dbForeignKeys = new Dictionary<string, object>() { };
|
||||||
|
|
||||||
|
// Iterate thru all properties
|
||||||
|
foreach (System.Reflection.FieldInfo fi in classType.GetRuntimeFields())
|
||||||
|
{
|
||||||
|
// Check if current field is a db-field
|
||||||
|
if (fi.GetCustomAttribute(typeof(DbPrimaryKey), true) is DbPrimaryKey pkey) // PrimaryKey
|
||||||
|
{
|
||||||
|
string dbAttributeName = pkey._attributeName ?? fi.Name; // If no alternative attribute-name is specified, use the property-name
|
||||||
|
object value = fi.GetValue(classObject);
|
||||||
|
dbPrimaryKeys.Add(dbAttributeName, value);
|
||||||
|
}
|
||||||
|
else if (fi.GetCustomAttribute(typeof(DbAttribute), true) is DbAttribute att) // Attributes
|
||||||
|
{
|
||||||
|
string dbAttributeName = att._attributeName ?? fi.Name; // If no alternative attribute-name is specified, use the property-name
|
||||||
|
object value = fi.GetValue(classObject);
|
||||||
|
dbAttributes.Add(dbAttributeName, value);
|
||||||
|
}
|
||||||
|
else if (fi.GetCustomAttribute(typeof(DbForeignKey), true) is DbForeignKey fkey) // ForeignKeys
|
||||||
|
{
|
||||||
|
string dbAttributeName = fkey._attributeName ?? fi.Name; // If no alternative attribute-name is specified, use the property-name
|
||||||
|
object value = fi.GetValue(classObject);
|
||||||
|
dbForeignKeys.Add(dbAttributeName, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static Dictionary<string, FieldInfo> ReadDbClassFields(Type classType)
|
||||||
|
{
|
||||||
|
Dictionary<string, FieldInfo> dbFields = new Dictionary<string, FieldInfo>();
|
||||||
|
|
||||||
|
// Iterate thru all properties
|
||||||
|
foreach (System.Reflection.FieldInfo fi in classType.GetRuntimeFields())
|
||||||
|
{
|
||||||
|
// Check if current field is a db-field
|
||||||
|
if (fi.GetCustomAttribute(typeof(DbPrimaryKey), true) is DbPrimaryKey pkey) // PrimaryKey
|
||||||
|
{
|
||||||
|
string dbAttributeName = pkey._attributeName ?? fi.Name; // If no alternative attribute-name is specified, use the property-name
|
||||||
|
dbFields.Add(dbAttributeName, fi);
|
||||||
|
}
|
||||||
|
else if (fi.GetCustomAttribute(typeof(DbAttribute), true) is DbAttribute att) // Attributes
|
||||||
|
{
|
||||||
|
string dbAttributeName = att._attributeName ?? fi.Name; // If no alternative attribute-name is specified, use the property-name
|
||||||
|
dbFields.Add(dbAttributeName, fi);
|
||||||
|
}
|
||||||
|
else if (fi.GetCustomAttribute(typeof(DbForeignKey), true) is DbForeignKey fkey) // ForeignKeys
|
||||||
|
{
|
||||||
|
string dbAttributeName = fkey._attributeName ?? fi.Name; // If no alternative attribute-name is specified, use the property-name
|
||||||
|
dbFields.Add(dbAttributeName, fi);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return dbFields;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string GetDbTableName(Type classType)
|
||||||
|
{
|
||||||
|
// Check if class has attribute 'DbObject' and get the database table-name
|
||||||
|
if (!(classType.GetCustomAttribute(typeof(DbObject), true) is DbObject dbObjectAttribute)) throw new InvalidOperationException($"Cannot generate SQL-Query of '{classType.Name}'. Missing Attribute 'DbObject'");
|
||||||
|
string tableName = dbObjectAttribute._tableName ?? classType.Name; // If no alternative table-name is specified, use the class-name
|
||||||
|
|
||||||
|
return tableName;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static string SqlSerialise(object obj)
|
||||||
|
{
|
||||||
|
if (obj == null) // Handle null
|
||||||
|
{
|
||||||
|
return "null";
|
||||||
|
}
|
||||||
|
else if (obj.GetType() == typeof(string)) // Handle strings
|
||||||
|
{
|
||||||
|
return "'" + SqlEscape((string)obj) + "'"; // wrap in sql-brackets and escape sql, if any
|
||||||
|
}
|
||||||
|
else if (obj.GetType() == typeof(byte) || obj.GetType() == typeof(int) || obj.GetType() == typeof(float) || obj.GetType() == typeof(double)) // Handle int, float & double
|
||||||
|
{
|
||||||
|
return obj.ToString().Replace(",", "."); // just format to string and form comma to sql-comma
|
||||||
|
}
|
||||||
|
else if (obj.GetType() == typeof(DateTime)) // Handle DateTime
|
||||||
|
{
|
||||||
|
DateTime dateTime = (DateTime)obj;
|
||||||
|
return "'" + SqlSerialise(dateTime) + "'"; // wrap in sql-brackets and convert to sql-datetime
|
||||||
|
}
|
||||||
|
else if (obj.GetType() == typeof(Guid)) // Handle DateTime
|
||||||
|
{
|
||||||
|
string guid = ((Guid)obj).ToString(); // Get Guid as string
|
||||||
|
return "'" + guid + "'"; // wrap in sql-brackets
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user