40 Commits

Author SHA1 Message Date
Railz
aca99302dd Set version to 1.5.15 2019-07-08 14:53:31 +02:00
Railz
7317503759 Added GetListWithQuery 2019-07-08 14:53:03 +02:00
Railz
75f4709db1 Added check if ResolveByPrimaryKey returned any results from database. 2019-07-08 11:57:31 +02:00
Railz
0d07d82ff5 Added table-name remover to matching-system of FillObject 2019-07-08 11:41:53 +02:00
Railz
b6bc82a766 Set version to 1.5.12 2019-06-04 22:25:59 +02:00
Railz
3e8427c4c0 Fixed Guid casting to String (dunno?) 2019-06-04 22:25:34 +02:00
Railz
8816110211 Improved Exception messages (variables)
CLassAction: Added GetList
Set Version to 1.5.11
2019-05-30 13:16:48 +02:00
Alexander B
40936fafcd Set version to 1.5.9 2019-05-15 12:11:23 +02:00
Alexander B
800941d59c Implemented:
QueryBuilder.SelectWithWhere()
ClassAction.GetListWithWhere()
2019-05-15 12:11:01 +02:00
Railz
64c8711754 Set version 2019-05-09 08:02:49 +02:00
Railz
ad3c1da0cd Fixes:
- Fields not matching
- FieldType being lookedUp wrong
- dictionary-access-violation
- guid saved as string not casting
- InsertQuery built wrong
2019-05-08 23:22:20 +02:00
Railz
ba0646f27c Set version to 1.5.7 2019-05-08 21:56:55 +02:00
Railz
76922a4039 Changed cache-check to dictionary
> Fixed bug, not restoring cache
2019-05-08 21:56:34 +02:00
Railz
e3869b26c3 removed inner Exception 2019-04-20 10:29:52 +02:00
Alexander B
be7277fada Set version 1.5.6 2019-04-12 13:36:02 +02:00
Alexander B
b8218fbacd Added InsertAttributesByObject 2019-04-12 13:35:18 +02:00
Alexander B
253f63dfac Added InsertAttributes to generate insert-statements 2019-04-12 12:54:37 +02:00
Alexander B
d6337ef591 Ser version 2019-04-12 11:39:25 +02:00
Alexander B
1253a935b7 Added ResolveByPrimaryKey to resolve an object with set primaryKey/s 2019-04-12 11:33:30 +02:00
Railz
2d4a4d5f7e Changed DbForeignObject no longer needing the Type 2019-04-10 23:07:12 +02:00
Railz
85495af97f Added DbForeignObject for automatic resolving
Added Init() to initialise necessary classes
Changed structure and added a BaseAttribute
Fixed occuring errors to match new system
2019-04-10 22:40:36 +02:00
Railz
9253d77236 Fixed GetByPrimaryKey not having any form to pass primaryKey-data
Set version to 1.4.1
2019-04-10 09:42:03 +02:00
Railz
ef7ac54e36 Set version 2019-04-08 22:22:30 +02:00
Railz
83dc8d6045 Added foreignKeyFieldName for foreignKeys
Added ResolveForeignKeys to ClassActions
Changed ResolveByPrimaryKey to GetByPrimaryKey
Added todo's
2019-04-08 22:21:48 +02:00
Railz
ff6fb08a08 Fixed missing convertion 2019-04-08 20:35:12 +02:00
Railz
d2900f364d Set version 2019-04-08 20:33:05 +02:00
Railz
b014c2f392 Added Method to convert classField-names to according dbAttributes
Added convert in GetListByAttribute
2019-04-08 20:32:44 +02:00
Railz
0ad7221680 Set version 2019-04-08 19:45:47 +02:00
Railz
36da32f870 Added Select/DeleteByAttribute
Added GetListByAttribute
2019-04-08 19:45:04 +02:00
Railz
d8c9867e50 Set version 2019-04-08 13:54:24 +02:00
Railz
166956f10f Added SelectByAttribute and DeleteByAttribute to QueryBuilder 2019-04-08 13:49:11 +02:00
Alexander B
ddb7f6dc89 Fixed ResolveByPrimaryKey - queryExecutor to be able to return multiple rows (via List) 2019-04-02 13:31:26 +02:00
Alexander B
06aa7969bf Removed unesserary variable 2019-04-02 09:49:04 +02:00
Railz
fb6cf14402 Fixed ResolveByPrimaryKey not having runDataLossChecks implemented 2019-04-01 18:52:38 +02:00
Railz
e8e1fb993d Removed ignoreDataMismatch and implemented runDataLossChecks instead 2019-04-01 18:49:37 +02:00
Railz
8633ac1925 Changed wrong comment 2019-04-01 18:38:44 +02:00
Railz
8de75728e0 Fixed ClassAction not being public
Moved SqlSerialise to Function
2019-04-01 18:33:53 +02:00
Railz
0f38c92bbe Added ResolveByPrimaryKey 2019-04-01 17:33:16 +02:00
Railz
46e8ec1180 New Function-class
Changed some references to new Function-class
Added ClassAction.FillObject
Added ClassAction.FillObject
Renamed unecessary plural names to singular
2019-04-01 17:26:30 +02:00
Railz
97b7eaeffe Added comments
Added check if given class is invalid
Changed BuildQuery to support recursive object[] copying
Changed structure
Added DbFunction to handle all Db-related stuff
2019-04-01 16:25:02 +02:00
12 changed files with 853 additions and 182 deletions

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
{
public class BaseAttribute : Attribute
{
public FieldInfo parentField;
public DbObject classAttribute;
public string _attributeName;
public BaseAttribute()
{
}
}
}

View File

@@ -1,22 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
{
[AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
public class DbAttribute : Attribute
public class DbAttribute : BaseAttribute
{
public string _attributeName;
/// <summary>
/// Marks variable as database-attribute
/// </summary>
/// <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;
}
public void Init(FieldInfo fi, DbObject classAttribute)
{
this.parentField = fi;
this.classAttribute = classAttribute;
this._attributeName = this._attributeName ?? fi.Name; // If no alternative attribute-name is specified, use the property-name
}
}
}

View File

@@ -1,25 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
{
[AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
public class DbForeignKey : Attribute
public class DbForeignKey : BaseAttribute
{
public Type _classType;
public string _attributeName;
/// <summary>
/// Marks variable as foreignKey of given class
/// </summary>
/// <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>
public DbForeignKey(Type classType, string attributeName = null)
public DbForeignKey(string attributeName = null)
{
this._classType = classType;
this._attributeName = attributeName;
}
public void Init(FieldInfo fi, DbObject classAttribute)
{
this.parentField = fi;
this.classAttribute = classAttribute;
this._attributeName = this._attributeName ?? fi.Name; // If no alternative attribute-name is specified, use the property-name
}
}
}

View File

@@ -1,23 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
{
[AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
public class DbPrimaryKey : Attribute
public class DbPrimaryKey : BaseAttribute
{
public Type _classType;
public string _attributeName;
/// <summary>
/// Marks variable as primaryKey fo current class
/// </summary>
/// <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)
{
this._attributeName = attributeName;
this._attributeName = attributeName; // Todo: Automatic resolving of name if it is null (?)
}
public void Init(FieldInfo fi, DbObject classAttribute)
{
this.parentField = fi;
this.classAttribute = classAttribute;
this._attributeName = this._attributeName ?? fi.Name; // If no alternative attribute-name is specified, use the property-name
}
}
}

View File

@@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
{
[AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
public class DbForeignObject : Attribute
{
public Type foreignObjectType;
public string _foreignKeyName;
public DbForeignKey foreignKeyAttribute;
public FieldInfo parentField;
public DbObject classAttribute;
/// <summary>
/// Marks variable as foreign-object of an dbObject
/// </summary>
/// <param name="foreignKeyName">Fieldname of foreignKey associated with the foreignObject</param>
public DbForeignObject(string foreignKeyName = null)
{
this._foreignKeyName = foreignKeyName;
}
public void Init(FieldInfo fi, DbObject classAttribute)
{
this.parentField = fi;
this.classAttribute = classAttribute;
this.foreignObjectType = fi.FieldType;
// Init foreign-object class
DbObject foreignClassAttribute = ClassAction.Init(this.foreignObjectType);
// Check if something is weird
if (foreignClassAttribute.primaryKeyAttributes.Count < 1) throw new InvalidOperationException($"'{foreignClassAttribute.parentClassType.Name}' does not have a primaryKey.");
if (foreignClassAttribute.primaryKeyAttributes.Count > 1) throw new InvalidOperationException($"ForeignObject does not support multiple primaryKeys.");
Type primaryKeyType = foreignClassAttribute.primaryKeyAttributes[0].parentField.GetType(); // Read type of primaryKey in foreignObject-class
foreach(DbForeignKey foreignKey in classAttribute.foreignKeyAttributes) // Search for matching foreignKey
{
if(this._foreignKeyName != null) // If i have a name
{
// check if name matches
if (foreignKey.parentField.Name.ToLower() == this._foreignKeyName.ToLower())
{
if(foreignKey.parentField.GetType() == primaryKeyType)
{
this._foreignKeyName = foreignKey.parentField.Name;
foreignKeyAttribute = foreignKey;
break;
}
else
{
// If a name was specified and the key does not match its an error
throw new InvalidOperationException($"ForeignKey='{this._foreignKeyName}' is typeOf='{foreignKey.parentField.GetType().Name}' but primaryKey of foreignObject-class is typeOf='{primaryKeyType.Name}'.");
}
}
}
else // No name
{
// Check if type matches
if (foreignKey.parentField.GetType() == primaryKeyType)
{
this._foreignKeyName = foreignKey.parentField.Name;
foreignKeyAttribute = foreignKey;
break;
}
}
}
// Check if key-retrieval was successful
if (foreignKeyAttribute == null) throw new InvalidOperationException($"No coresponding foreignKey.");
}
}
}

View File

@@ -12,13 +12,68 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
{
public string _tableName;
public Type parentClassType;
// All childrenAttributes
public List<BaseAttribute> baseAttributes = new List<BaseAttribute>() { };
public List<DbPrimaryKey> primaryKeyAttributes = new List<DbPrimaryKey>() { };
public List<DbAttribute> attributeAttributes = new List<DbAttribute>() { };
public List<DbForeignKey> foreignKeyAttributes = new List<DbForeignKey>() { };
public List<DbForeignObject> foreignObjectAttributes = new List<DbForeignObject>() { };
/// <summary>
/// Marks variable as database-table
/// </summary>
/// <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)
{
this._tableName = tableName;
this._tableName = tableName; // Todo: Automatic resolving of name if it is null (?)
}
public void Init(Type classType)
{
this.parentClassType = classType;
this._tableName = this._tableName ?? classType.Name; // If no alternative table-name is specified, use the class-name
// Iterate thru all fields
foreach (System.Reflection.FieldInfo fi in classType.GetRuntimeFields())
{
try
{
// Check if current field is a db-field and initiate it
if (fi.GetCustomAttribute(typeof(DbPrimaryKey), true) is DbPrimaryKey pkey) // PrimaryKey
{
pkey.Init(fi, this);
this.baseAttributes.Add(pkey);
this.primaryKeyAttributes.Add(pkey);
}
else if (fi.GetCustomAttribute(typeof(DbAttribute), true) is DbAttribute att) // Attributes
{
att.Init(fi, this);
this.baseAttributes.Add(att);
this.attributeAttributes.Add(att);
}
else if (fi.GetCustomAttribute(typeof(DbForeignKey), true) is DbForeignKey fkey) // ForeignKeys
{
fkey.Init(fi, this);
this.baseAttributes.Add(fkey);
this.foreignKeyAttributes.Add(fkey);
}
else if (fi.GetCustomAttribute(typeof(DbForeignObject), true) is DbForeignObject fobj) // ForeignObjects
{
fobj.Init(fi, this);
this.foreignObjectAttributes.Add(fobj);
}
}
catch(InvalidOperationException ex)
{
throw new InvalidOperationException($"Cannot init foreignObject-field='{fi.Name}' of class='{classType.Name}'.", ex);
}
}
}
}
}

View File

@@ -0,0 +1,297 @@
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
{
private static Dictionary<Type, DbObject> initiatedClassTypes = new Dictionary<Type, DbObject>() { };
/// <summary>
/// Initiates the attribute-system and preloads all necessary information<para/>
/// INFO: Will initiate necessary foreignObjects recursively!<para/>
/// If an class is already initiated, it will be ignored!
/// </summary>
/// <param name="classType">The classType to preload</param>
/// <returns>DbObject-attribute corresponding to the class</returns>
public static DbObject Init(Type classType)
{
DbObject cachedDbObject;
initiatedClassTypes.TryGetValue(classType, out cachedDbObject);
if (cachedDbObject == null)
{
// Check if given class is marked as dbObject
if (!(classType.GetCustomAttribute(typeof(DbObject), true) is DbObject dbObject)) throw new InvalidOperationException($"Cannot init '{classType.Name}'. Missing Attribute 'DbObject'");
dbObject.Init(classType); // Init dbObject
initiatedClassTypes.Add(classType, dbObject); // Set it to the list
cachedDbObject = dbObject;
}
return cachedDbObject;
}
/// <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>
public static void FillObject<T>(T classObject, Dictionary<string, object> data)
{
Type classType = classObject.GetType();
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType);
// Iterate through data
foreach (KeyValuePair<string, object> data_keySet in data)
{
// Interate through class-fields
foreach (BaseAttribute baseAttribute in dbObject.baseAttributes)
{
// Remove any leading dots and table-specifiers
string dbAttName = data_keySet.Key;
if (dbAttName.Contains("."))
{
string[] dbAttNameSplit = dbAttName.Split('.'); // Split at the '.'
dbAttName = dbAttNameSplit[dbAttNameSplit.Length - 1]; // Copy the ending text
}
// If its a match, set the value
if (baseAttribute._attributeName.ToLower() == data_keySet.Key.ToLower())
{
object value = data_keySet.Value;
//if (baseAttribute.parentField.FieldType == typeof(Guid)) value = new Guid((string)value); // If its a guid, i need to convert
baseAttribute.parentField.SetValue(classObject, value);
break;
}
}
}
}
/// <summary>
/// Gets an dbObject by primaryKey/s
/// </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>
public static T GetByPrimaryKey<T>(Type classType, object primaryKeyValue, Func<string, List<Dictionary<string, object>>> queryExecutor) where T : new()
{
Dictionary<string, object> primaryKeyData = new Dictionary<string, object>() { };
primaryKeyData.Add(null, primaryKeyValue);
return GetByPrimaryKey<T>(classType, primaryKeyData, queryExecutor);
}
public static T GetByPrimaryKey<T>(Type classType, string primaryKeyName, object primaryKeyValue, Func<string, List<Dictionary<string, object>>> queryExecutor) where T : new()
{
Dictionary<string, object> primaryKeyData = new Dictionary<string, object>() { };
primaryKeyData.Add(primaryKeyName, primaryKeyValue);
return GetByPrimaryKey<T>(classType, primaryKeyData, queryExecutor);
}
public static T GetByPrimaryKey<T>(Type classType, Dictionary<string, object> primaryKeyData, Func<string, List<Dictionary<string, object>>> queryExecutor) where T: new()
{
// Create new empty object
T obj = new T();
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType);
// iterate thru them to check and fill object
foreach (DbPrimaryKey primaryKeyAtt in dbObject.primaryKeyAttributes)
{
bool dataMatchFound = false;
// Now search the corresponding primaryKeyData
foreach (KeyValuePair<string, object> primaryKey in primaryKeyData)
{
// primaryKey matches
if(primaryKeyAtt._attributeName.ToLower() == primaryKey.Key.ToLower())
{
// Set data
primaryKeyAtt.parentField.SetValue(obj, primaryKey.Value);
dataMatchFound = true;
break;
}
}
// If no data was found matching this field
if (!dataMatchFound) throw new InvalidOperationException($"Cannot create object with primaryKeyData. No data assigned to field '{primaryKeyAtt.parentField.Name}'");
}
ResolveByPrimaryKey<T>(obj, queryExecutor);
return obj;
}
// ----
/// <summary>
/// Gets all dbObjects of class/table
/// </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>
public static List<T> GetList<T>(Type classType, Func<string, List<Dictionary<string, object>>> queryExecutor) where T : new()
{
// Read dbObject - attribute
DbObject dbObject = ClassAction.Init(classType);
string query = QueryBuilder.SelectByAttribute(dbObject._tableName); // 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); // Fill it
objs.Add(obj); // Add to list
}
return objs; // Return list
}
/// <summary>
/// Gets an dbObject by custom where-clause
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="classObject">Given object (marked with Db-attributes)</param>
/// <param name="whereClause">Custom where-clause params attached to query (SELECT * FROM tableName WHERE whereClause)</param>
/// <param name="queryExecutor">Function to handle query-calls - Has to return Dictionary[attributeName, attributeValue]</param>
public static List<T> GetListWithWhere<T>(Type classType, Func<string, List<Dictionary<string, object>>> queryExecutor, params object[] whereClause) where T : new()
{
// Read dbObject - attribute
DbObject dbObject = ClassAction.Init(classType);
string query = QueryBuilder.SelectWithWhere(dbObject._tableName, whereClause); // 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); // Fill it
objs.Add(obj); // Add to list
}
return objs; // Return list
}
/// <summary>
/// Gets an dbObject by full query
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="classObject">Given object (marked with Db-attributes)</param>
/// <param name="customQuery">Custom sql-query</param>
/// <param name="queryExecutor">Function to handle query-calls - Has to return Dictionary[attributeName, attributeValue]</param>
public static List<T> GetListWithQuery<T>(Type classType, Func<string, List<Dictionary<string, object>>> queryExecutor, params object[] customQuery) where T : new()
{
// Read dbObject - attribute
DbObject dbObject = ClassAction.Init(classType);
string query = QueryBuilder.BuildQuery(customQuery);
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); // Fill it
objs.Add(obj); // Add to list
}
return objs; // Return list
}
/// <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>
/// <returns>List of dbObjects</returns>
public static List<T> GetListByAttribute<T>(Type classType, Dictionary<string, object> fields, Func<string, List<Dictionary<string, object>>> queryExecutor) where T : new()
{
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType);
Function.ConvertAttributeToDbAttributes(classType, fields);
string query = QueryBuilder.SelectByAttribute(dbObject._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); // Fill it
objs.Add(obj); // Add to list
}
return objs; // Return list
}
// -----
/// <summary>
/// Resolves dbObject by primaryKey/s<pragma/>
/// Object needs to have primaryKey/s set!
/// </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>
public static void ResolveByPrimaryKey<T>(T classObject, Func<string, List<Dictionary<string, object>>> queryExecutor)
{
string query = QueryBuilder.SelectByPrimaryKey(classObject); // Generate query
List<Dictionary<string, object>> dataSet = queryExecutor(query); // Execute
if (dataSet.Count == 0) throw new InvalidOperationException($"Cannot fetch '{typeof(T).Name}' by primary key/s. No results!");
FillObject(classObject, dataSet[0]); // Fill the object
}
/// <summary>
/// Resolves all foreignKeys with the database<pragma/>
/// Only works if the foreignKey is single (not assembled)!
/// </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>
public static void ResolveForeignKeys<T>(T classObject, Func<string, List<Dictionary<string, object>>> queryExecutor, int max_depth = 1) where T: new()
{
Type classType = classObject.GetType();
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType);
foreach (DbForeignObject foreignObjectAtt in dbObject.foreignObjectAttributes)
{
object foreignObject_value = foreignObjectAtt.parentField.GetValue(classObject);
// When its empty, get it
if(foreignObject_value == null)
{
foreignObject_value = GetByPrimaryKey<T>(classType, foreignObjectAtt.foreignKeyAttribute.parentField.GetValue(classObject), queryExecutor);
}
// Recursive resolving
if (max_depth - 1 > 0)
{
ResolveForeignKeys(foreignObject_value, queryExecutor, max_depth - 1);
}
}
}
}
}

View File

@@ -4,6 +4,7 @@
<TargetFramework>netcoreapp2.1</TargetFramework>
<RootNamespace>eu.railduction.netcore.dll.Database_Attribute_System</RootNamespace>
<SignAssembly>false</SignAssembly>
<Version>1.5.15</Version>
</PropertyGroup>
</Project>

View File

@@ -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);
}
}
}
}
}

View File

@@ -7,55 +7,107 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
{
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();
// Get db-table-name from class
string tableName = Function.GetDbTableName(classType);
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType);
// Get class db-fields
Dictionary<string, object> dbPrimaryKeys = new Dictionary<string, object>() { };
Dictionary<string, object> dbAttributes = new Dictionary<string, object>() { };
Dictionary<string, object> dbForeignKeys = new Dictionary<string, object>() { };
Function.ReadDbClassFields(classObject, ref dbPrimaryKeys, ref dbAttributes, ref dbForeignKeys);
// Check if 'byPrimaryKey' is possible
if (dbObject.primaryKeyAttributes.Count == 0) throw new InvalidOperationException($"Cannot generate SQL-Query of '{classType.Name}'. No primary-key/s!");
Dictionary<string, object> dbPrimaryKeys = Function.ReadFieldData(Function.ConvertToDerivedList(dbObject.primaryKeyAttributes), classObject);
// Build where statements with primaryKey/s
object[] param = Function.BuildKeyEqualQuery(dbPrimaryKeys, " AND ");
return SelectByAttribute(dbObject._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
param = DbFunction.BuildKeyEqualQuery(dbAttributes, " AND ");
}
string sqlCmd = $"SELECT * FROM {tableName}";
// 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
return BuildQuery(param);
}
/// <summary>
/// Builds an SELECT-Sql-query based on an object with custom where clause<para/>
/// Object needs to have at least 1 attribute!
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tableName">The db-table-name</param>
/// <param name="whereClause">Custom where-clause params attached to query (SELECT * FROM tableName WHERE whereClause)</param>
/// <returns>SELECT-Sql-query</returns>
public static string SelectWithWhere(string tableName, params object[] whereClause)
{
string sqlCmd = $"SELECT * FROM {tableName}";
// Add SQL-command part
if (!(whereClause[0] is string)) throw new InvalidOperationException("Cannot generate SQL-query. WhereClause-params not starting with string!");
whereClause[0] = $"{sqlCmd} WHERE {whereClause[0]}";
public static string UpdateByPrimaryKeys<T>(T classObject)
// Build and return the query
return BuildQuery(whereClause);
}
/// <summary>
/// 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();
// Get db-table-name from class
string tableName = Function.GetDbTableName(classType);
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType);
// Get class db-fields
Dictionary<string, object> dbPrimaryKeys = new Dictionary<string, object>() { };
Dictionary<string, object> dbAttributes = new Dictionary<string, object>() { };
Dictionary<string, object> dbForeignKeys = new Dictionary<string, object>() { };
Function.ReadDbClassFields(classObject, ref dbPrimaryKeys, ref dbAttributes, ref dbForeignKeys);
// Check if 'byPrimaryKey' is possible
if (dbObject.primaryKeyAttributes.Count == 0) throw new InvalidOperationException($"Cannot generate SQL-Query of '{classType.Name}'. No primary-key/s!");
Dictionary<string, object> dbPrimaryKeys = Function.ReadFieldData(Function.ConvertToDerivedList(dbObject.primaryKeyAttributes), classObject);
Dictionary<string, object> dbForeignKeys = Function.ReadFieldData(Function.ConvertToDerivedList(dbObject.foreignKeyAttributes), classObject);
Dictionary<string, object> dbAttributes = Function.ReadFieldData(Function.ConvertToDerivedList(dbObject.attributeAttributes), classObject);
// 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);
}
// Build set-parameters
object[] paramSet = Function.BuildKeyEqualQuery(dbAttributes, ", ");
object[] paramSet = DbFunction.BuildKeyEqualQuery(dbAttributes, ", ");
// Add SQL-command part
paramSet[0] = $"UPDATE {tableName} SET "+ paramSet[0];
paramSet[0] = $"UPDATE {dbObject._tableName} SET "+ paramSet[0];
// Build where-parameters
object[] paramWhere = Function.BuildKeyEqualQuery(dbPrimaryKeys, " AND ");
object[] paramWhere = DbFunction.BuildKeyEqualQuery(dbPrimaryKeys, " AND ");
// Add SQL-command part
paramWhere[0] = " WHERE "+ paramWhere[0];
@@ -63,26 +115,108 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
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();
// Get db-table-name from class
string tableName = Function.GetDbTableName(classType);
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType);
// Get class db-fields
Dictionary<string, object> dbPrimaryKeys = new Dictionary<string, object>() { };
Dictionary<string, object> dbAttributes = new Dictionary<string, object>() { };
Dictionary<string, object> dbForeignKeys = new Dictionary<string, object>() { };
Function.ReadDbClassFields(classObject, ref dbPrimaryKeys, ref dbAttributes, ref dbForeignKeys);
// Build where-parameters
object[] paramWhere = Function.BuildKeyEqualQuery(dbPrimaryKeys, " AND ");
// Add SQL-command part
paramWhere[0] = $"DELETE FROM {tableName} WHERE "+ paramWhere[0];
// Check if 'byPrimaryKey' is possible
if (dbObject.primaryKeyAttributes.Count == 0) throw new InvalidOperationException($"Cannot generate SQL-Query of '{classType.Name}'. No primary-key/s!");
Dictionary<string, object> dbPrimaryKeys = Function.ReadFieldData(Function.ConvertToDerivedList(dbObject.primaryKeyAttributes), classObject);
// Build and return the query
return BuildQuery(paramWhere);
return DeleteByAttribute(dbObject._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>
/// Builds an INSERT-Sql-query based on an object<para/>
/// </summary>
/// <param name="tableName"></param>
/// <param name="dbAttributes"></param>
/// <returns></returns>
public static string InsertAttributesByObject<T>(T classObject)
{
Type classType = classObject.GetType();
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType);
List<string> attributes = new List<string>() { };
List<object> data = new List<object>() { };
foreach(BaseAttribute baseAttribute in dbObject.baseAttributes)
{
attributes.Add(baseAttribute._attributeName);
data.Add(baseAttribute.parentField.GetValue(classObject));
}
return InsertAttributes(dbObject._tableName, attributes, data);
}
public static string InsertAttributes(string tableName, Dictionary<string, object> dbAttributes)
{
if (dbAttributes.Count == 0) throw new InvalidOperationException("Cannot generate SQL-Query. No attributes to insert.");
List<string> attributes = new List<string>() { };
List<object> data = new List<object>() { };
foreach (KeyValuePair<string, object> attribute in dbAttributes)
{
attributes.Add(attribute.Key);
data.Add(attribute.Value);
}
return InsertAttributes(tableName, attributes, data);
}
public static string InsertAttributes(string tableName, List<string> attributes, List<object> data)
{
if (attributes.Count != data.Count) throw new InvalidOperationException("Cannot generate SQL-Query. Attribute-count and data-count not equal.");
string attributesSeperatedByComma = "";
object[] attributeData = new object[attributes.Count*2 -1];
int c = 0;
for(int i=0; i< attributes.Count; i++)
{
attributesSeperatedByComma += attributes[i];
attributeData[c] = data[i];
if(c+1 != attributeData.Length)
{
attributesSeperatedByComma += ", ";
attributeData[c+1] = ",";
}
c +=2;
}
// Build and return the query
return BuildQuery($"INSERT INTO {tableName} ({attributesSeperatedByComma}) VALUES (", attributeData, ")");
}
@@ -90,25 +224,17 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
/// <summary>
/// Build an SQL-query<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>
/// <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)
{
// 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>() { };
foreach (object obj in param)
{
if (!(obj is object[]))
paramz.Add(obj);
else
{
foreach (object obj2 in (object[])obj)
{
paramz.Add(obj2);
}
}
}
Function.RecursiveParameterCopying(ref paramz, (object[])param);
string query = "";
for (int i = 0; i < paramz.Count; i++)
@@ -116,33 +242,9 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
if (i % 2 == 0) query += paramz[i]; // Every 'even' count will just add
else // Every 'uneven' count will handle param as passed variable
{
string paramString = "";
if (paramz[i] == null) // Handle null
{
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!");
}
string paramString = Function.SqlSerialise(paramz[i]);
if(paramString == null) // Unknown type in params
throw new Exception($"Error in query-builder. Type '{paramz[i].GetType().ToString()}' cannot be serialised!");
// Add formed param to query
query += paramString;

View 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;
}
}
}

View File

@@ -0,0 +1,155 @@
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 List<BaseAttribute> ConvertToDerivedList(List<DbPrimaryKey> list)
{
List<BaseAttribute> derivedList = new List<BaseAttribute>() { };
foreach (BaseAttribute key in list)
{
derivedList.Add(key);
}
return derivedList;
}
internal static List<BaseAttribute> ConvertToDerivedList(List<DbAttribute> list)
{
List<BaseAttribute> derivedList = new List<BaseAttribute>() { };
foreach (BaseAttribute key in list)
{
derivedList.Add(key);
}
return derivedList;
}
internal static List<BaseAttribute> ConvertToDerivedList(List<DbForeignKey> list)
{
List<BaseAttribute> derivedList = new List<BaseAttribute>() { };
foreach (BaseAttribute key in list)
{
derivedList.Add(key);
}
return derivedList;
}
internal static Dictionary<string, object> ReadFieldData<T>(List<BaseAttribute> fieldAttributes, T classObject)
{
Dictionary<string, object> fieldData = new Dictionary<string, object>() { };
foreach (BaseAttribute attribute in fieldAttributes)
{
// Read the data and add it
fieldData.Add(
attribute._attributeName,
attribute.parentField.GetValue(classObject)
);
}
return fieldData; // Return the data
}
internal static void ConvertAttributeToDbAttributes(Type classType, Dictionary<string, object> attributeNameAndValues)
{
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType);
Dictionary<string, object> convertedAttributeNameAndValues = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> attributeNameAndValue in attributeNameAndValues)
{
bool nameFound = false;
foreach (BaseAttribute baseAttribute in dbObject.baseAttributes)
{
if (attributeNameAndValue.Key.ToLower() == baseAttribute.parentField.Name.ToLower())
{
convertedAttributeNameAndValues.Add(baseAttribute._attributeName, attributeNameAndValue.Value);
nameFound = true;
break;
}
}
if (!nameFound) throw new InvalidOperationException($"'{attributeNameAndValue.Key}' has no classField!");
}
}
internal static void ConvertAttributeToDbAttributes(Type classType, List<string> attributeNames)
{
// Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType);
for(int i=0; i< dbObject.baseAttributes.Count; i++)
{
bool nameFound = false;
foreach (BaseAttribute baseAttribute in dbObject.baseAttributes)
{
if(attributeNames[i].ToLower() == baseAttribute.parentField.Name.ToLower())
{
attributeNames[i] = baseAttribute._attributeName;
nameFound = true;
break;
}
}
if (!nameFound) throw new InvalidOperationException($"'{attributeNames[i]}' has no classField!");
}
}
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 Guid
{
string guid = ((Guid)obj).ToString(); // Get Guid as string
return "'" + guid + "'"; // wrap in sql-brackets
}
else
{
return null;
}
}
}
}