/// <summary> /// Loads limited array of Objects /// </summary> /// <typeparam name="T">Type which has DbAttriibutes</typeparam> /// <param name="limit">Objects Count Limit</param> /// <param name="offset">Objects Offset</param> /// <param name="args">Filter values</param> /// <returns>Array of requested objects</returns> /// <example> /// <code> /// WorkLog [] list = DbGateway.Instance.LoadList{WorkLog}(7, 7, "Type", WorkLogType.Default); /// /// Type Definition: /// /// [DbRecord] /// public class WorkLog /// { /// [DbPrimaryKeyField] /// public ulong Id; /// /// [DbField] /// public WorkLogType Type; /// /// ... /// } /// /// public enum WorkLogType : uint /// { /// Default, /// ... /// } /// </code> /// </example> public T[] LoadListLimited <T>(int limit, int offset, params object[] args) where T : new() { DbRecordInfo recordInfo = DbAttributesManager.GetRecordInfo(typeof(T)); string query = Accessor.BuildWhere(new DbQueryBuilder(Accessor).BuildSelect(recordInfo), args); return(LoadRecords <T>(query, limit, offset, args)); }
/// <summary> /// Saves the specified items to database. /// </summary> /// <param name="items">The items.</param> public void Save(object [] items) { if (items == null || items.Length == 0) { return; } var info = DbAttributesManager.GetRecordInfo(items[0].GetType()); DbIdentityRecordInfo identityInfo = info as DbIdentityRecordInfo; if (identityInfo != null) { foreach (object item in items) { save(item, identityInfo); } } else { foreach (object item in items) { Accessor.Insert(info.TableName, info.GetValues(item)); } } }
private bool ProcessEx(Assembly assembly, XmlFormatter xmlFormatter) { if (Action == Action.Check) { Type[] types = DbAttributesManager.LoadDbRecordTypes(assembly); int errorNumber = 1; for (int i = 0; i < types.Length; i++) { Type type = types[i]; bool isValid = StructureGateway.IsValid(type); if (isValid) { xmlFormatter.AppendUnitTestResult("Mapping Test - " + type.FullName, Outcome.Passed, ""); string message = string.Format( "{0} ({1}) - Ok" , type, assembly.ManifestModule.Name); Console.WriteLine(message); } else { string message = string.Format( "\r\n{3}. {0} ({1}) \r\n{4}\r\n{2}\r\n{4}" , type, assembly.ManifestModule.Name, StructureGateway.LastError, errorNumber++, "----------------------------------------------------------------------------" ); Console.WriteLine(message); ExitCode = ExitCode.Failure; xmlFormatter.AppendUnitTestResult("Mapping Test - " + type.FullName, Outcome.Failed, StructureGateway.LastError); } } return(true); } return(false); }
/// <summary> /// Imports all fields of passed objects to mapped tables\columns in database (Primary Keys and other generated content). /// </summary> /// <param name="records">The records.</param> public void Import(object [] records) { if (records == null || records.Length == 0) { return; } var info = DbAttributesManager.GetRecordInfo(records[0].GetType()); for (int i = 0; i < records.Length; i++) { object record = records[i]; DbIdentityRecordInfo identityRecordInfo = info as DbIdentityRecordInfo; if (identityRecordInfo != null) { object[] values = info.GetValues(record, identityRecordInfo.PrimaryKey.Name, identityRecordInfo.PrimaryKey.GetValue(record)); if (Accessor.IsMsSql) { Accessor.ExecuteNonQuery(DbTextFileGenerator.MsSql.SetIdentityInsertOn(info.TableName)); Accessor.Insert(info.TableName, values); Accessor.ExecuteNonQuery(DbTextFileGenerator.MsSql.SetIdentityInsertOff(info.TableName)); } else { Accessor.Insert(info.TableName, values); } } else { Accessor.Insert(info.TableName, info.GetValues(record)); } } }
/// <summary> /// Remove records filtered by all field marked this DbFieldAttribute (use exact matching) /// </summary> /// <param name="data">an object with DbAttributes</param> /// <returns>Removed Records Count</returns> public uint DeleteByAllFields(object data) { var info = DbAttributesManager.GetRecordInfo(data.GetType()); object[] values = info.GetValues(data); return(Accessor.Delete(info.TableName, values)); }
private void AlterTableEx(DbRecordInfo info) { foreach (KeyValuePair <Type, DbFieldInfo> key in info.ForeignKeys) { DbIdentityRecordInfo primaryInfo = DbAttributesManager.GetRecordInfo(key.Key) as DbIdentityRecordInfo; if (primaryInfo == null) { throw new NdbNotIdentityException(string.Format( "Records without primary kes can't be used as foreign keys.\r\nRecord {0}.\r\nPrimary record type {1}" , info.TableName, key.Key)); } if (primaryInfo.PrimaryKey.FieldType != key.Value.FieldType) { throw new NdbException( "Primary key {0} in {1} is {2}. But Foreign key {3} in {4} is {5}", primaryInfo.PrimaryKey.Name, primaryInfo.TableName, primaryInfo.PrimaryKey.FieldType, key.Value.Name, info.TableName, key.Value.FieldType); } AlterTableEx(primaryInfo); } if (IsTableExists(info.TableName)) { if (!IsValid(info.RecordType)) { AlterTable(info.RecordType); } } else { CreateTable(info.RecordType); } }
/// <summary> /// Loads the result. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="LoadTotalCount">if set to <c>true</c> will load total count.</param> /// <returns></returns> public DbQueryResult <T> LoadResult <T>(bool LoadTotalCount) where T : new() { var result = new DbQueryResult <T>(); if (!LoadTotalCount) { result.Records = Load <T>(); } else { //TODO: (high priority) refactor DbRecordInfo recordInfo = DbAttributesManager.GetRecordInfo(typeof(T)); var sb = new StringBuilder(); new DbQueryBuilder(Gateway.Accessor).BuildSelect(sb, recordInfo); object[] args = buildWhere(sb, Gateway.Accessor); buildOrderBy(sb); sb.Insert(7, "SQL_CALC_FOUND_ROWS "); result.Records = Gateway.LoadRecords <T>(sb.ToString(), limit, offset, args); result.TotalRecordsCount = Gateway.LoadResult <long>("SELECT FOUND_ROWS()"); } return(result); }
/// <summary> /// Removes Tables Associated with Records From cpecifyed Assembly /// </summary> /// <param name="targetAssembly"></param> public Type[] DropTables(Assembly targetAssembly) { Type[] types = DbAttributesManager.LoadDbRecordTypes(targetAssembly); int i = 0; // so "pretty" code tryes to remove all tables. // but checks if we have some problems like not connected to database while (true) { if (i++ == types.Length) { throw new NdbException("Can't drop tables from the following assembly: " + targetAssembly.GetName()); } bool allSuccess = true; foreach (Type type in types) { if (!DropTable(type)) { allSuccess = false; } } if (allSuccess) { break; } } return(types); }
internal override void CreateTable(DbRecordInfo info) { StringBuilder sb = new StringBuilder("CREATE TABLE " + info.TableName + "("); DbIdentityRecordInfo identityRecordInfo = info as DbIdentityRecordInfo; if (identityRecordInfo != null) { DbFieldInfo key = identityRecordInfo.PrimaryKey; if (key.FieldType == typeof(Guid)) { sb.Append(GetDefinition(key) + " NOT NULL"); } else { sb.Append(GetDefinition(key) + " NOT NULL IDENTITY(1,1)"); } sb.Append(','); } foreach (DbFieldInfo field in info.Fields) { sb.Append(GetDefinition(field)); sb.Append(','); } string[] keys = getPrimaryKeys(info); sb.AppendFormat("PRIMARY KEY ({0})", String.Join(",", keys)); DbIndexesInfo indexes = DbAttributesManager.GetIndexes(info.Fields); ProcessIndexes(sb, indexes.Unique, ",UNIQUE ({0})"); //TODO: (MSSQL) CREATE FULLTEXT INDEX //TODO: (MSSQL) CREATE INDEX // ProcessIndexes(sb, indexes.Indexes, ",KEY {1} ({0})"); // ProcessIndexes(sb, indexes.FullText, ",FULLTEXT KEY {1} ({0})"); //process foreign keys foreach (KeyValuePair <Type, DbFieldInfo> key in info.ForeignKeys) { DbIdentityRecordInfo ri = DbAttributesManager.GetRecordInfo(key.Key) as DbIdentityRecordInfo; if (ri == null) { throw new NdbException("Only DbIdentityRecord objects can be used as Foreign Keys"); } sb.AppendFormat( ",FOREIGN KEY ([{1}]) REFERENCES [{0}] ([{2}]) ON DELETE CASCADE ON UPDATE CASCADE" , ri.TableName , key.Value.Name , ri.PrimaryKey.Name); } sb.Append(")"); string query = sb.ToString(); ExecuteNonQuery(query); }
public void CompileTest() { var classToGenerate = "GeneratedUser"; string generateClass = generator.GenerateClass("Users", classToGenerate); Assembly assembly = DbCompilerUtils.Compile(generateClass); Type type = assembly.GetType(generator.Namespace + "." + classToGenerate); ulong count = DbGateway.Instance.LoadCount(type); Assert.AreEqual(1, count); DbRecordInfo info1 = DbAttributesManager.GetRecordInfo(typeof(User)); DbRecordInfo info2 = DbAttributesManager.GetRecordInfo(type); Assert.AreEqual(info1.TableName, info2.TableName, "TableName"); DbFieldInfo pk = (info1 as DbIdentityRecordInfo).PrimaryKey; Assert.AreEqual(pk.FieldType, info2.Fields[0].FieldType); Assert.AreEqual(pk.Name, info2.Fields[0].Name); Assert.AreEqual(typeof(short), info2.Fields[1].FieldType); for (int i = 1; i < info2.Fields.Length - 1; i++) { Assert.AreEqual(info1.Fields[i], info2.Fields[i + 1], "Fields"); } }
public void GetTableNameTest() { var name = DbAttributesManager.GetTableName(typeof(TestWorkLogItem)); Assert.AreEqual("WorkLogs", name); var tableName = DbAttributesManager.GetTableName(typeof(User)); Assert.AreEqual("Users", tableName); }
/// <summary> /// Loads Array of objects /// </summary> /// <returns></returns> public T[] Load <T>() where T : new() { DbRecordInfo recordInfo = DbAttributesManager.GetRecordInfo(typeof(T)); var sb = new StringBuilder(); new DbQueryBuilder(Gateway.Accessor).BuildSelect(sb, recordInfo); object [] args = buildWhere(sb, Gateway.Accessor); buildOrderBy(sb); return(Gateway.LoadRecords <T>(sb.ToString(), limit, offset, args)); }
/// <summary> /// Records count. /// </summary> /// <returns></returns> public ulong LoadCount <T>() { DbRecordInfo recordInfo = DbAttributesManager.GetRecordInfo(typeof(T)); var sb = new StringBuilder(); new DbQueryBuilder(Gateway.Accessor).BuildSelectCount(sb, recordInfo); object [] args = buildWhere(sb, Gateway.Accessor); buildOrderBy(sb); return(Gateway.LoadResult <ulong>(sb.ToString(), args)); }
/// <summary> /// Updates object in database. /// </summary> /// <param name="data"></param> /// <returns>true if one object was updated</returns> public bool Update(object data) { var info = DbAttributesManager.GetRecordInfo(data.GetType()); DbIdentityRecordInfo identityRecordInfo = info as DbIdentityRecordInfo; if (identityRecordInfo != null) { return(1 == update(identityRecordInfo, data)); } throw new NdbException(string.Format( "DbPrimaryKeyField attribute wasn't specifyed on {0} type", data.GetType())); }
/// <summary> /// Checks all objects with DbFieldAttribute to match db /// </summary> /// <param name="assembly"></param> /// <returns></returns> public static bool IsDbRecordsValid(Assembly assembly) { Type[] types = DbAttributesManager.LoadDbRecordTypes(assembly); foreach (Type type in types) { if (!DbStructureGateway.Instance.IsValid(type)) { return(false); } } return(true); }
/// <summary> /// Insert new object to database (if primary key was set, it will be overwrited) /// </summary> /// <param name="data"></param> public void Insert(object data) { var info = DbAttributesManager.GetRecordInfo(data.GetType()); DbIdentityRecordInfo identityRecordInfo = info as DbIdentityRecordInfo; if (identityRecordInfo != null) { insert(identityRecordInfo, data); } else { Accessor.Insert(info.TableName, info.GetValues(data)); } }
/// <summary> /// Checks all classes with DbRecordAttribute to match to associated database tables /// </summary> /// <param name="assembly"></param> public static bool CheckDbRecordTypes(Assembly assembly) { Type[] types = DbAttributesManager.LoadDbRecordTypes(assembly); foreach (var type in types) { if (!DbStructureGateway.Instance.IsValid(type)) { throw new NdbException( string.Format("Not all fields of Type {0} match associated database table:\r\n{1}" , type , DbStructureGateway.Instance.LastError)); } } return(true); }
/// <summary> /// Exports the specified types. /// </summary> /// <param name="types">The types.</param> /// <param name="ExportWithClean">if set to <c>true</c> than all existsing data will be removed first.</param> public void Export(Type[] types, bool ExportWithClean) { string methodName = ExportWithClean ? "ExportWithClean" : "Export"; MethodInfo method = GetType().GetMethod(methodName, new Type[] {}); DbStructureGateway structureGateway = new DbStructureGateway(Source); foreach (Type type in types) { string tableName = DbAttributesManager.GetTableName(type); if (structureGateway.IsTableExists(tableName)) { method.MakeGenericMethod(type).Invoke(this, null); } } }
/// <summary> /// Loads parent record /// </summary> /// <typeparam name="TParentType"></typeparam> /// <param name="data"></param> /// <returns></returns> /// <example> /// <code> /// User user = DbGateway.Instance.LoadParent{User}(TestData.WorkLog); /// /// Types Definitions: /// /// [DbRecord] /// public class WorkLog /// { /// [DbPrimaryKeyField] /// public ulong Id; /// /// [DbForeignKeyField(typeof(User))] /// public ulong UserId; /// /// ... /// } /// /// [DbRecord] /// public class User /// { /// [DbPrimaryKeyField] /// public ulong Id; /// /// ... /// } /// </code> /// </example> public TParentType LoadParent <TParentType>(object data) where TParentType : new() { Type childType = data.GetType(); Type parentType = typeof(TParentType); DbRecordInfo childRecordInfo = DbAttributesManager.GetRecordInfo(childType); if (!childRecordInfo.ForeignKeys.ContainsKey(parentType)) { throw new NdbException(string.Format( "The type '{0}' doesn't contains DbForeignKeyFieldAttribute to type '{1}'", childType, parentType)); } object primaryKey = childRecordInfo.ForeignKeys[parentType].GetValue(data); return(Load <TParentType>(primaryKey)); }
/// <summary> /// Loads child records /// </summary> /// <typeparam name="TChildType">Type of the child objects</typeparam> /// <param name="data">Parent object</param> /// <param name="args">Filter</param> /// <returns>Array of childs</returns> /// <example> /// <code> /// Event[] events = DbGateway.Instance.LoadChilds{Event}(TestData.User); /// /// Types Definitions: /// /// [DbRecord] /// public class Event /// { /// [DbPrimaryKeyField] /// public ulong Id; /// /// ... /// } /// /// [DbRecord] /// public class User /// { /// [DbPrimaryKeyField] /// public ulong Id; /// /// ... /// } /// </code> /// </example> public TChildType[] LoadChilds <TChildType>(object data, params object[] args) where TChildType : new() { Type primaryType = data.GetType(); DbRecordInfo childRecordInfo = DbAttributesManager.GetRecordInfo(typeof(TChildType)); DbIdentityRecordInfo primaryRecordInfo = DbAttributesManager.GetRecordInfo(primaryType) as DbIdentityRecordInfo; if (primaryRecordInfo == null) { throw new NdbNotIdentityException("Only DbIdentityRecord objects can have childs"); } object [] _args = UnionArgs(args, childRecordInfo.ForeignKeys[primaryType].Name, primaryRecordInfo.PrimaryKey.GetValue(data)); return(LoadList <TChildType>(_args)); }
/// <summary> /// Remove object from database /// </summary> /// <param name="data">an object with DbAttributes</param> /// <returns>true if one object has been removed</returns> public bool Delete(object data) { var info = DbAttributesManager.GetRecordInfo(data.GetType()); var identityRecordInfo = info as DbIdentityRecordInfo; if (identityRecordInfo != null) { DbFieldInfo primaryKey = identityRecordInfo.PrimaryKey; return(0 < Accessor.Delete( info.TableName, primaryKey.Name, primaryKey.GetValue(data))); } return(1 < DeleteByAllFields(data)); }
/// <summary> /// Load an object which has DbAttributes from database /// </summary> /// <typeparam name="T">Object Type</typeparam> /// <param name="primaryKey">Object Primary Key</param> /// <returns>object</returns> /// <example> /// <code> /// WorkLog workLog = DbGateway.Instance.Load{WorkLog}(workLogId); /// /// Type Definition: /// /// [DbRecord] /// public class WorkLog /// { /// [DbPrimaryKeyField] /// public ulong Id; /// /// ... /// } /// </code> /// </example> /// <exception cref="NdbException">If Primary Key not found</exception> public T Load <T>(object primaryKey) where T : new() { DbIdentityRecordInfo info = DbAttributesManager.GetRecordInfo(typeof(T)) as DbIdentityRecordInfo; if (info == null) { throw new NdbNotIdentityException("Can't load record of type " + typeof(T)); } T data = new T(); info.PrimaryKey.SetValue(data, primaryKey); if (!load(data, info)) { return(default(T)); } return(data); }
/// <summary> /// Load an object from database /// </summary> /// <param name="data">Object which has DbAttributes</param> /// <param name="args">Filter values</param> /// <returns>true if requested object found in database</returns> /// <example> /// <code> /// WorkLog workLog = new WorkLog(); /// bool success = DbGateway.Instance.Load(workLog, "Date", DateTime.Now); /// /// Type Definition: /// /// [DbRecord] /// public class WorkLog /// { /// [DbPrimaryKeyField] /// public ulong Id; /// /// [DbField] /// public DateTime Date; /// ... /// } /// </code> /// </example> public bool Load(object data, params object[] args) { DbRecordInfo info = DbAttributesManager.GetRecordInfo(data.GetType()); using (IDataReader reader = Accessor.ExecuteReaderEx(new DbQueryBuilder(Accessor).BuildSelect(info), args)) { if (reader.Read()) { Bind(data, reader, info); if (reader.Read()) { throw new NdbException( "There are several records in database which match the specifyed filter"); } return(true); } } return(false); }
/// <summary> /// Load records using association table /// </summary> /// <typeparam name="TTargetType">Type we want to Load</typeparam> /// <typeparam name="TAssociationType">Type which contains associations</typeparam> /// <param name="data">Data object</param> /// <returns>Array of Requested Objects</returns> /// <example> /// <code> /// Task []tasks = DbGateway.Instance.LoadAssociated{Task, TasksAssignment}(TestData.User); /// /// Types Definitions: /// /// [DbRecord] /// public class TasksAssignment /// { /// [DbForeignKeyField(typeof(Task))] /// public ulong TaskId; /// /// [DbForeignKeyField(typeof(User))] /// public ulong UserId; /// /// ... /// } /// /// [DbRecord] /// public class Task /// { /// [DbPrimaryKeyField] /// public ulong Id; /// /// ... /// } /// /// [DbRecord] /// public class User /// { /// [DbPrimaryKeyField] /// public ulong Id; /// /// ... /// } /// </code> /// </example> public TTargetType[] LoadAssociated <TTargetType, TAssociationType>(object data) where TTargetType : new() { Type primaryType = data.GetType(); DbIdentityRecordInfo targetRecordInfo = DbAttributesManager.GetRecordInfo(typeof(TTargetType)) as DbIdentityRecordInfo; if (targetRecordInfo == null) { throw new NdbNotIdentityException("Only DbIdentityRecord objects can have related records"); } DbRecordInfo associationRecordInfo = DbAttributesManager.GetRecordInfo(typeof(TAssociationType)); DbIdentityRecordInfo sourceRecordInfo = DbAttributesManager.GetRecordInfo(primaryType) as DbIdentityRecordInfo; if (sourceRecordInfo == null) { throw new NdbNotIdentityException("Only DbIdentityRecord objects can have related records"); } object primaryKey = sourceRecordInfo.PrimaryKey.GetValue(data); DbQueryBuilder queryBuilder = new DbQueryBuilder(Accessor); string select = queryBuilder.BuildSelect(targetRecordInfo); // below is a self documented query? :) string sql = string.Format( @"{5} INNER JOIN {1} ON {0}.{3}={1}.{2} AND {1}.{4}=@PrimaryKey" // @"SELECT * FROM {0} INNER JOIN {1} ON {0}.{3}={1}.{2} AND {1}.{4}=@PrimaryKey" , targetRecordInfo.TableName , associationRecordInfo.TableName , associationRecordInfo.ForeignKeys[typeof(TTargetType)].Name , targetRecordInfo.PrimaryKey.Name , associationRecordInfo.ForeignKeys[primaryType].Name , select ); return(loadRecords <TTargetType>(targetRecordInfo, sql, "PrimaryKey", primaryKey)); }
public void ImportFromExcel(string [] args) { if (args.Length > 4) { string SourceFileConnectionString = args[3]; string assemblyName = args[4]; var assembly = Assembly.LoadFrom(assemblyName); Type[] types = DbAttributesManager.LoadDbRecordTypes(assembly); var Source = (ExcelAccessor)DbAccessor.Create(DbProvider.Excel, SourceFileConnectionString); Accessor.ShareConnection = true; var Target = new DbGateway(Accessor); DbExcelExport export = new DbExcelExport(Source, Target); export.Export(types, true); ExitCode = ExitCode.Success; } else { ExitCode = ExitCode.Exception; } }
public void GetRecordInfoTest() { var info = DbAttributesManager.GetRecordInfo(typeof(TestWorkLogItem)) as DbIdentityRecordInfo; Assert.IsNotNull(info); Assert.IsNotNull(info.PrimaryKey); Assert.AreEqual(1, info.ForeignKeys.Count); Assert.IsNotNull(info.ForeignKeys[typeof(User)]); Assert.AreEqual("WorkLogs", info.TableName); Assert.AreEqual("SpentMinutes", info.Fields[2].Name); Assert.AreEqual("CreationDate", info.Fields[3].Name); Assert.AreEqual(6, info.Fields.Length); Assert.AreEqual(0, info.Childs.Count); Assert.AreEqual(0, info.Parents.Count); info = DbAttributesManager.GetRecordInfo(typeof(User)) as DbIdentityRecordInfo; Assert.IsNotNull(info); Assert.AreEqual(2, info.Childs.Count); var info2 = DbAttributesManager.GetRecordInfo(typeof(TasksAssignment)); Assert.IsNotNull(info2); Assert.AreEqual(2, info2.Parents.Count); }
public void LoadDbRecordTypes() { Type[] list = DbAttributesManager.LoadDbRecordTypes(Assembly.GetExecutingAssembly()); Assert.Less(0, list.Length); }
/// <summary> /// Loads Count of Records /// </summary> /// <param name="type">Type to load</param> /// <returns>Records Count</returns> public ulong LoadCount(Type type) { return(Accessor.LoadCount(DbAttributesManager.GetTableName(type))); }
/// <summary> /// Removes objects from database /// </summary> /// <param name="type">Type which has DbAttributes</param> /// <param name="args">filter values</param> /// <returns>Count of removed objects</returns> /// <example> /// <code> /// uint count = DbGateway.Instance.Delete(typeof(WorkLog), "Type", WorkLogType.Default); /// </code> /// </example> public uint Delete(Type type, params object[] args) { string tableName = DbAttributesManager.GetTableName(type); return(Accessor.Delete(tableName, args)); }
/// <summary> /// Updates all entities of the specifyed type which match the passed args /// </summary> /// <param name="type"></param> /// <param name="fieldsToUpdate"></param> /// <param name="args"></param> /// <returns>Count of updated objects</returns> public int Update(Type type, object [] fieldsToUpdate, params object[] args) { var info = DbAttributesManager.GetRecordInfo(type); return(Accessor.Update(info.TableName, fieldsToUpdate, args)); }