/// <summary> /// Returns a command appropriate for modifying a column in MYSQL /// </summary> /// <param name="type">The type (Table info)</param> /// <param name="dfi">The field to edit</param> /// <param name="targetFieldType">the new column type</param> /// <returns></returns> public override IEnumerable <IDbCommand> GetModifyColumnCommand(DatabaseTypeInfo type, DataFieldInfo dfi, string targetFieldType) { MySqlCommand cmd = new MySqlCommand(); cmd.CommandText = string.Format(_ModifyColumn, ResolveTableName(type, false), dfi.EscapedFieldName, targetFieldType); yield return(cmd); }
/// <summary> /// Returns a command for removing a column from a table /// </summary> /// <param name="type">The type to remove the column from</param> /// <param name="dfi">The column to remove</param> /// <returns></returns> public override IDbCommand GetRemoveColumnCommand(DatabaseTypeInfo type, DataFieldInfo dfi) { SqlCommand scmd = new SqlCommand(); scmd.CommandText = string.Format("ALTER TABLE {0}.{1} DROP COLUMN [{2}]", type.Schema, type.TableName, dfi.FieldName); return(scmd); }
/// <summary> /// Returns a command for creating a new table /// </summary> /// <param name="ti">The type to create a table for</param> /// <returns></returns> public override IEnumerable <IDbCommand> GetAddTableCommand(DatabaseTypeInfo ti) { List <IDbCommand> toReturn = new List <IDbCommand>(); StringBuilder sb = new StringBuilder(); StringBuilder pFields = new StringBuilder(); SqlCommand cmd = new SqlCommand(); sb.AppendFormat("CREATE TABLE {0}.{1} (", ti.Schema, ti.TableName); for (int i = 0; i < ti.DataFields.Count; i++) { DataFieldInfo dfi = ti.DataFields[i]; if (i > 0) { sb.Append(","); } if (dfi.PrimaryKey) { if (pFields.Length > 0) { pFields.Append(","); } pFields.Append(dfi.FieldName); if (dfi.PropertyType == typeof(int) && ti.PrimaryKeys.Count == 1) { sb.AppendFormat("{0} {1} NOT NULL IDENTITY(1,1) ", dfi.EscapedFieldName, TranslateTypeToSql(dfi)); } else { sb.AppendFormat("{0} {1} NOT NULL ", dfi.EscapedFieldName, TranslateTypeToSql(dfi)); } } else { sb.AppendFormat("{0} {1} NULL ", dfi.EscapedFieldName, TranslateTypeToSql(dfi)); } if (dfi.PrimaryKeyType != null) { SqlCommand fk = new SqlCommand(); fk.CommandText = GetForeignKeySql(dfi, ti, DataStore.TypeInformationParser.GetTypeInfo(dfi.PrimaryKeyType)); toReturn.Add(fk); } } sb.Append(") ON [PRIMARY];"); if (pFields.Length > 0) { SqlCommand pKey = new SqlCommand(); pKey.CommandText = string.Format("ALTER TABLE {0}.{1} ADD CONSTRAINT PK_{3}_{4} PRIMARY KEY CLUSTERED ({2})", ti.Schema, ti.TableName, pFields.ToString(), ti.UnEscapedSchema, ti.UnescapedTableName); toReturn.Insert(0, pKey); } cmd.CommandText = sb.ToString(); toReturn.Insert(0, cmd); return(toReturn); }
/// <summary> /// Gets the name of the column. /// </summary> /// <param name="memberInfo">The member info.</param> /// <returns></returns> public string GetColumnName(MemberInfo memberInfo) { DatabaseTypeInfo ti = _dstore.Connection.CommandGenerator.TypeParser.GetTypeInfo(memberInfo.DeclaringType); DataFieldInfo field = ti.DataFields.Where(R => R.PropertyName.Equals(memberInfo.Name, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); return(field != null ? field.EscapedFieldName : ""); }
/// <summary> /// Returns a command for removing a column from a table /// </summary> /// <param name="type">The type to remove the column from</param> /// <param name="dfi">The column to remove</param> /// <returns></returns> public override IDbCommand GetRemoveColumnCommand(DatabaseTypeInfo type, DataFieldInfo dfi) { NpgsqlCommand command = new NpgsqlCommand(); command.CommandText = string.Format("ALTER TABLE {0} DROP COLUMN {1};", ResolveTableName(type, false), dfi.FieldName); return(command); }
/// <summary> /// Gets a lot of information from a type /// </summary> /// <param name="type">The type to parse</param> /// <param name="bypassValidate">If true, type will not validate against datastore</param> /// <returns></returns> public virtual DatabaseTypeInfo GetTypeInfo(Type type, bool bypassValidate = false) { DatabaseTypeInfo toReturn = Cache.GetObject(type); if (toReturn == null) { lock (Cache) { toReturn = Cache.GetObject(type); if (toReturn == null) { toReturn = new DatabaseTypeInfo(type); if (!type.IsSystemType()) { ParseBypass(type, toReturn); ParseDataInfo(type, toReturn); } StoreTypeInfo(bypassValidate, type, toReturn); } } } return(toReturn); }
/// <summary> /// Determines whether the specified entity is mapped. /// </summary> /// <param name="entity">The entity.</param> /// <param name="member">The member.</param> /// <returns> /// <c>true</c> if the specified entity is mapped; otherwise, <c>false</c>. /// </returns> public bool IsMapped(MappingEntity entity, MemberInfo member) { DatabaseTypeInfo ti = _dstore.Connection.CommandGenerator.TypeParser.GetTypeInfo(entity.EntityType); DataFieldInfo field = ti.DataFields.Where(R => R.PropertyName.Equals(member.Name, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); return(field != null && field.LoadField); }
public virtual void Test_Can_Parse_Object() { DatabaseTypeInfo ti = dstore.Connection.CommandGenerator.TypeParser.GetTypeInfo(typeof(TestItem)); Assert.IsNotNull(ti); Assert.IsNotNull(ti.DataFields); foreach (DataFieldInfo dfi in ti.DataFields) { Assert.IsTrue(dfi.LoadField); if (dfi.PrimaryKey) { Assert.IsFalse(dfi.SetOnInsert); } else { Assert.IsTrue(dfi.SetOnInsert); } Assert.IsTrue(!string.IsNullOrEmpty(dfi.FieldName)); Assert.IsNotNull(dfi.Getter); Assert.IsNotNull(dfi.Setter); } Assert.IsFalse(ti.BypassValidation); Assert.IsNotNull(ti.AdditionalInit); Assert.IsTrue(ti.AdditionalInit.Count == 0); }
public virtual void Test_Can_parse_ByPass() { DatabaseTypeInfo ti = dstore.Connection.CommandGenerator.TypeParser.GetTypeInfo(typeof(TestItemBypassValidation)); Assert.IsNotNull(ti); Assert.IsTrue(ti.BypassValidation); }
/// <summary> /// Returns a list of columns comma separated, appropriate for select from /// </summary> /// <param name="type">The type</param> /// <returns></returns> public virtual string GetSelectList(Type type) { DatabaseTypeInfo ti = TypeParser.GetTypeInfo(type); if (ti.SelectString == null) { StringBuilder sb = new StringBuilder(); foreach (DataFieldInfo dfi in ti.DataFields) { if (!dfi.LoadField) { continue; } if (sb.Length > 0) { sb.Append(","); } sb.Append(ResolveFieldName(dfi.PropertyName, type)); } ti.SelectString = sb.ToString(); } return(ti.SelectString); }
/// <summary> /// Gets a lot of information from a type /// </summary> /// <param name="type">The type to parse</param> /// <param name="bypassValidate">If true, type will not validate against datastore</param> /// <returns></returns> public virtual DatabaseTypeInfo GetTypeInfo(Type type, bool bypassValidate = false) { DatabaseTypeInfo toReturn = _cache.GetObject(type); if (toReturn == null) { if (toReturn == null) { toReturn = new DatabaseTypeInfo(type); toReturn.IsDynamic = type.IsDynamic(); if (!type.IsSystemType()) { ParseBypass(type, toReturn); ParseDataInfo(type, toReturn); } lock (this) { if (_cache.StoreObject(type, toReturn)) { OnTypeParsed?.Invoke(this, new TypeParsedEventArgs(toReturn, type, bypassValidate)); } else { toReturn = _cache.GetObject(type); } } } } return(toReturn); }
/// <summary> /// Generates a select for a single object /// </summary> /// <param name="item">The item to load (primary key needs to be set)</param> /// <returns></returns> public virtual IDbCommand GetSelectCommand(object item) { Type t = item.GetType(); DatabaseTypeInfo ti = TypeParser.GetTypeInfo(t); IDbCommand cmd = _connection.GetCommand(); StringBuilder sb = new StringBuilder(); sb.AppendFormat("SELECT {0} FROM {1} WHERE ", GetSelectList(t), ResolveTableName(ti)); for (int i = 0; i < ti.PrimaryKeys.Count; i++) { DataFieldInfo dfi = ti.PrimaryKeys[i]; object value = dfi.Getter(item); if (value != null) { if (i > 0) { sb.Append(" AND "); } string pName = GetParameterName(cmd); sb.Append(string.Concat(dfi.EscapedFieldName, "=", pName)); cmd.Parameters.Add(_connection.GetParameter(pName, value)); } } cmd.CommandText = sb.ToString(); return(cmd); }
public override void Test_Can_Get_Tables() { DatabaseTypeInfo ti = dstore.Connection.CommandGenerator.TypeParser.GetTypeInfo(typeof(TestItemTwoKeys)); IEnumerable <DBObject> tables = dstore.SchemaValidator.TableValidator.GetObjects(); Assert.IsTrue(tables.Count() > 0); foreach (DBObject t in tables) { if (t.Name.StartsWith("sqlite")) { continue; } Assert.IsTrue(t != null); Assert.IsTrue(t.Name != ""); Assert.IsTrue(t.Schema != ""); Assert.IsNotNull(t.Columns); Assert.IsTrue(t.Columns.Count > 0); foreach (Column c in t.Columns) { Assert.IsTrue(c != null); Assert.IsTrue(c.Name != ""); } } }
/// <summary> /// Checks for deleted columns. /// </summary> /// <param name="typeInfo">The type info.</param> /// <param name="t">The t.</param> /// <param name="valid">The valid.</param> /// <returns></returns> protected virtual bool CheckForDeletedColumns(DatabaseTypeInfo typeInfo, DBObject t, List <Column> valid) { if (CanRemoveColumns) { bool dirty = false; if (valid.Count != t.Columns.Count) { dirty = true; foreach (Column c in t.Columns) { Column found = valid.Where(R => R.Name.Equals(c.Name, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); if (found == null) { RemoveColumn(new DataFieldInfo() { FieldName = c.Name }, typeInfo); } } } return(dirty); } else { return(false); } }
/// <summary> /// Parses data field information from a type /// </summary> /// <param name="type">The type to parse</param> /// <param name="toAdd">What to add the data to</param> protected void ParseDataFields(Type type, DatabaseTypeInfo toAdd) { toAdd.DataFields = new List <DataFieldInfo>(); PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.Public); foreach (PropertyInfo pi in properties) { DataFieldAttribute dField = pi.GetCustomAttributes(typeof(DataFieldAttribute), true).FirstOrDefault() as DataFieldAttribute; IgnoredFieldAttribute ignoredField = pi.GetCustomAttributes(typeof(IgnoredFieldAttribute), true).FirstOrDefault() as IgnoredFieldAttribute; if (ignoredField == null) { DataFieldInfo dfi = new DataFieldInfo(); dfi.PropertyType = pi.PropertyType; ParseWithNoDefaults(dfi, dField); ParseFieldName(dfi, dField, pi); ParsePrimaryFieldType(dfi, pi); ParseSetOnInsert(dfi, dField); ParseLoad(dfi, dField); ParsePropertyInfo(type, dfi, pi); toAdd.DataFields.Add(dfi); } } }
public override void Read(Vault vault, BinaryReader br) { br.ReadUInt32(); // mNumClasses br.ReadUInt32(); // padding br.ReadUInt32(); // mDefaultDataSize _numTypes = br.ReadUInt32(); // mNumTypes _typeNames = br.ReadPointer(); // mTypenames //br.ReadUInt32(); //br.ReadUInt32(); //_numTypes = br.ReadUInt32(); ////br.ReadUInt32(); //_typeNames = br./*ReadPointer*/ReadInt32(); // Pointer if (_typeNames == 0) { throw new InvalidDataException("NULL pointer to mTypeNames is no good!"); } for (var i = 0; i < _numTypes; i++) { var typeInfo = new DatabaseTypeInfo { Size = br.ReadUInt32() }; vault.Database.Types.Add(typeInfo); } }
/// <summary> /// Determines the table name to use on the data store /// </summary> /// <param name="type">The type</param> /// <param name="toAdd">What to add the data to</param> protected void ParseTableName(Type type, DatabaseTypeInfo toAdd) { TableNameAttribute tName = type.GetCustomAttributes(typeof(TableNameAttribute), true).FirstOrDefault() as TableNameAttribute; if (tName != null) { toAdd.UnescapedTableName = tName.TableName; toAdd.UnEscapedSchema = tName.Schema; } if (string.IsNullOrEmpty(toAdd.UnEscapedSchema)) { toAdd.UnEscapedSchema = _connection.Connection.DefaultSchema; } if (string.IsNullOrEmpty(toAdd.UnescapedTableName)) { toAdd.UnescapedTableName = GenTableName(type); } //escape table name toAdd.TableName = string.Concat(_connection.Connection.LeftEscapeCharacter, toAdd.UnescapedTableName, _connection.Connection.RightEscapeCharacter); if (!string.IsNullOrEmpty(toAdd.UnEscapedSchema)) { toAdd.Schema = string.Concat(_connection.Connection.LeftEscapeCharacter, toAdd.UnEscapedSchema, _connection.Connection.RightEscapeCharacter); } }
/// <summary> /// Fires the created event /// </summary> /// <param name="ti">The ti.</param> protected void FireCreated(DatabaseTypeInfo ti) { if (OnObjectCreated != null) { OnObjectCreated(this, new ObjectCreatedEventArgs(ti)); } }
private void ProcessBulkInsert(IList list, Type t, DatabaseTypeInfo ti, DBObject table) { DataTable dt = new DataTable(); AddColumnsToTable(dt, ti, table); foreach (object record in list) { DataRow dr = dt.NewRow(); foreach (DataFieldInfo dfi in ti.DataFields) { object item = dfi.Getter(record); if (item == null) { dr[dfi.FieldName] = DBNull.Value; } else { dr[dfi.FieldName] = item; } } dt.Rows.Add(dr); } WriteToServer(dt, this.CommandGenerator.ResolveTableName(t)); }
private object BuildObject(IQueryRow dt, DatabaseTypeInfo ti) { object toReturn = ObjectBuilder.BuildObject(this, dt, ti); FireObjectLoaded(toReturn); return(toReturn); }
/// <summary> /// Gets the primary key. /// </summary> /// <param name="entity">The entity.</param> /// <param name="instance">The instance.</param> /// <returns></returns> public object GetPrimaryKey(MappingEntity entity, object instance) { object firstKey = null; List <object> keys = null; DatabaseTypeInfo ti = _dstore.Connection.CommandGenerator.TypeParser.GetTypeInfo(entity.EntityType); foreach (DataFieldInfo v in ti.PrimaryKeys) { if (firstKey == null) { firstKey = v.Getter(instance); } else { if (keys == null) { keys = new List <object>(); keys.Add(firstKey); } keys.Add(v.Getter(instance)); } } if (keys != null) { return(new CompoundKey(keys.ToArray())); } return(firstKey); }
/// <summary> /// Executes a db command and fills in a list of objects with the result data /// </summary> /// <typeparam name="ReturnType">The type of object to return</typeparam> /// <param name="objectType">The type of object to return.</param> /// <param name="command">The command to execute</param> /// <returns></returns> protected virtual IEnumerable <ReturnType> ExecuteCommandLoadList <ReturnType>(Type objectType, IDbCommand command) { DatabaseTypeInfo ti = Connection.CommandGenerator.TypeParser.GetTypeInfo(objectType); using (IQueryData dt = ExecuteCommands.ExecuteCommandQuery(command, Connection)) { if (dt.QuerySuccessful) { foreach (IQueryRow row in dt) { ReturnType toAdd; if (objectType.IsSystemType()) { toAdd = (ReturnType)Connection.CLRConverter.ConvertToType(row.GetDataForRowField(0), typeof(ReturnType)); } else { toAdd = (ReturnType)BuildObject(row, ti); } yield return(toAdd); } } } }
/// <summary> /// Validates an existing view. /// </summary> /// <param name="ti">The ti.</param> /// <param name="obj">The obj.</param> protected virtual void ValidateExistingView(DatabaseTypeInfo ti, DBObject obj) { List <string> Missing = new List <string>(); foreach (DataFieldInfo dfi in ti.DataFields) { Column c = obj.Columns.Where(R => R.Name.Equals(dfi.FieldName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); if (c == null) { Missing.Add(dfi.FieldName); } } if (Missing.Count > 0) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < Missing.Count; i++) { if (i > 0) { sb.Append(","); } sb.AppendFormat(" {0}", Missing[i]); } throw new DataStoreException(string.Format("The view {0} is missing the following columns {1}", ti.TableName, sb.ToString())); } }
/// <summary> /// Creates an object and inits the primary key field /// </summary> /// <param name="item">The item.</param> /// <param name="key">The key.</param> /// <param name="ti">The type info.</param> /// <returns></returns> protected static object CreateObjectSetKey(Type item, object key, DatabaseTypeInfo ti) { object toReturn = item.GetConstructor(new Type[] { }).Invoke(new object[] { }); ti.PrimaryKeys[0].Setter(toReturn, key); return(toReturn); }
protected void RetrieveDataStore() { _dstore = GetDataStore().GetNewInstance(); _tables = new ModifyTableValidator(_dstore); _tables.CanAddColumns = true; _tables.CanRemoveColumns = true; _tables.CanUpdateColumns = true; _views = _dstore.SchemaValidator.ViewValidator; if (_views == null) { _views = new ViewValidator(_dstore); } DatabaseTypeInfo ti = _dstore.TypeInformationParser.GetTypeInfo(typeof(RanMigration)); if (_dstore.SchemaValidator.TableValidator == null || !_dstore.SchemaValidator.TableValidator.CanAddColumns) { _tables.ValidateObject(ti); } _dstore.SchemaValidator = new DoesNothingValidator(); }
private void CheckForMultipleKeys(DatabaseTypeInfo toAdd) { if (toAdd.PrimaryKeys.Count > 1) { toAdd.PrimaryKeys.ForEach(R => R.SetOnInsert = true); } }
/// <summary> /// Gets a command for changing a column type /// </summary> /// <param name="type">The type</param> /// <param name="dfi">The field</param> /// <param name="targetFieldType">The new column type</param> /// <returns></returns> public override IEnumerable <IDbCommand> GetModifyColumnCommand(DatabaseTypeInfo type, DataFieldInfo dfi, string targetFieldType) { SqlCommand cmd = new SqlCommand(); cmd.CommandText = string.Format("ALTER TABLE {0} ALTER COLUMN [{1}] {2}", ResolveTableName(type), dfi.FieldName, targetFieldType); yield return(cmd); }
/// <summary> /// Parses the additional init and OnTableCreate attributes /// </summary> /// <param name="type">The type to parse</param> /// <param name="toAdd">What to add the data to</param> protected void ParseFunctionAttributes(Type type, DatabaseTypeInfo toAdd) { toAdd.AdditionalInit = new List <AdditionalInitFunction>(); toAdd.OnTableCreate = new List <AdditionalInitFunction>(); MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static); foreach (MethodInfo mi in methods) { QueryPredicateAttribute qpred = mi.GetCustomAttributes(typeof(QueryPredicateAttribute), true).FirstOrDefault() as QueryPredicateAttribute; if (qpred != null) { toAdd.QueryPredicate = new QueryPredicateFunction(mi); } AdditionalInitAttribute aAtt = mi.GetCustomAttributes(typeof(AdditionalInitAttribute), true).FirstOrDefault() as AdditionalInitAttribute; if (aAtt != null) { toAdd.AdditionalInit.Add(new AdditionalInitFunction(mi)); } OnTableCreateAttribute tcAtt = mi.GetCustomAttributes(typeof(OnTableCreateAttribute), true).FirstOrDefault() as OnTableCreateAttribute; if (tcAtt != null) { toAdd.OnTableCreate.Add(new AdditionalInitFunction(mi)); } } }
private async Task <object> BuildObjectAsync(IQueryRow dt, DatabaseTypeInfo ti) { object toReturn = await Task.Run(() => ObjectBuilder.BuildObject(_dstore, dt, ti)); FireObjectLoaded(toReturn); return(toReturn); }
/// <summary> /// Returns a command for removing a column from a table /// </summary> /// <param name="type">The type to remove the column from</param> /// <param name="dfi">The column to remove</param> /// <returns></returns> public override IDbCommand GetRemoveColumnCommand(DatabaseTypeInfo type, DataFieldInfo dfi) { SqlCeCommand scmd = new SqlCeCommand(); scmd.CommandText = string.Format("ALTER TABLE {0} DROP COLUMN [{1}]", ResolveTableName(type), dfi.FieldName); return(scmd); }