/// <summary> /// Initializes a new instance of the <see cref="SavePropertiesQuery{TMappedClass}"/> class. /// </summary> /// <param name="mappingInformation">Mapping information</param> /// <param name="objectPool">The object pool.</param> public DeletePropertiesQuery(IMappingSource mappingInformation, ObjectPool <StringBuilder> objectPool) : base(mappingInformation, objectPool) { IDProperties = MappingInformation.GetChildMappings(typeof(TMappedClass)) .SelectMany(x => MappingInformation.GetParentMapping(x.ObjectType)) .Distinct() .SelectMany(x => x.IDProperties); }
/// <summary> /// Deletes the cascade. /// </summary> /// <param name="object">The object.</param> /// <param name="source">The source.</param> /// <param name="batch">The batch.</param> /// <param name="objectsSeen">The objects seen.</param> private void DeleteCascade(object @object, IMappingSource source, SQLHelper batch, IList <object> objectsSeen) { var ParentMappings = source.GetParentMapping(@object.GetType()); CascadeMapProperties(@object, source, batch, objectsSeen, ParentMappings); CascadeManyToManyProperties(@object, source, batch, objectsSeen, ParentMappings); CascadeManyToOneProperties(@object, source, batch, objectsSeen, ParentMappings); }
/// <summary> /// Initializes a new instance of the <see cref="QueryData{TObject}"/> class. /// </summary> /// <param name="source">The source.</param> /// <exception cref="ArgumentNullException">source</exception> public QueryData(IMappingSource source) { Source = source ?? throw new ArgumentNullException(nameof(source)); SelectValues = new List <PropertyInfo>(); Parameters = new List <IParameter>(); WhereClause = new WhereClause <TObject>(null); OrderByValues = new List <OrderByClause>(); }
public MemberMapping(TypeMapping typeMapping, IMappingSource source, IMappingTarget target) : base(typeMapping.GlobalConfig, source.MemberType, target.MemberType) { this.InstanceTypeMapping = typeMapping; this.SourceMember = source; this.TargetMember = target; }
/// <summary> /// Initializes a new instance of the <see cref="SessionQueryInfo"/> class. /// </summary> /// <param name="source">The source.</param> /// <param name="childMappings">The child mappings.</param> /// <param name="parentMappings">The parent mappings.</param> public SessionQueryInfo(IMappingSource source, IMapping[] childMappings, IMapping[] parentMappings) { ChildMappings = childMappings; ParentMappings = parentMappings; AssociatedMapping = System.Array.Find(ParentMappings, x => x.IDProperties.Count > 0); Source = source; IDProperties = ParentMappings.SelectMany(x => x.IDProperties).ToArray(); IDColumnInfo = IDProperties.SelectMany(x => x.GetColumnInfo()).ToArray(); }
public TranslationContext(IMappingSource mappingSource, List <ISqlElement> areas, SqlQuery sqlQuery) { this.mappingSource = mappingSource; this.areas = areas; this.sqlQuery = sqlQuery; queryEntityRegistry = new QueryEntityRegistry(mappingSource); queryEntityAccessor = new QueryEntityAccessor(queryEntityRegistry, nameGenerator); }
/// <summary> /// Initializes a new instance of the <see cref="DeleteQuery{TMappedClass}"/> class. /// </summary> /// <param name="mappingInformation">The mapping information.</param> /// <param name="objectPool">The object pool.</param> public DeleteQuery(IMappingSource mappingInformation, ObjectPool <StringBuilder> objectPool) : base(mappingInformation, objectPool) { ParentMappings = MappingInformation.GetChildMappings <TMappedClass>() .SelectMany(x => MappingInformation.GetParentMapping(x.ObjectType)) .Distinct(); IDProperties = ParentMappings.SelectMany(x => x.IDProperties); GenerateQuery(); }
/// <summary> /// Creates the batch and gets the list of objects seen. /// </summary> /// <param name="source">The source.</param> /// <param name="dynamoFactory">The dynamo factory.</param> /// <param name="Batch">The batch.</param> /// <param name="ObjectsSeen">The objects seen.</param> private void CreateBatch(IMappingSource source, DynamoFactory dynamoFactory, out SQLHelper Batch, out List <object> ObjectsSeen) { Batch = QueryProviderManager.CreateBatch(source.Source, dynamoFactory); ObjectsSeen = new List <object>(); for (int x = 0, ObjectsLength = Objects.Length; x < ObjectsLength; ++x) { Delete(Objects[x], source, Batch, ObjectsSeen); } }
/// <summary> /// Initializes a new instance of the <see cref="SavePropertiesQuery{TMappedClass}"/> class. /// </summary> /// <param name="mappingInformation">Mapping information</param> /// <param name="objectPool">The object pool.</param> public SavePropertiesQuery(IMappingSource mappingInformation, ObjectPool <StringBuilder> objectPool) : base(mappingInformation, objectPool) { IDProperties = MappingInformation.GetChildMappings(typeof(TMappedClass)) .SelectMany(x => MappingInformation.GetParentMapping(x.ObjectType)) .Distinct() .SelectMany(x => x.IDProperties); Queries = new ListMapping <string, QueryGeneratorData>(); SetupQueries(); }
/// <summary> /// Initializes a new instance of the <see cref="UpdateQuery{TMappedClass}"/> class. /// </summary> /// <param name="mappingInformation">The mapping information.</param> /// <param name="objectPool">The object pool.</param> public UpdateQuery(IMappingSource mappingInformation, ObjectPool <StringBuilder> objectPool) : base(mappingInformation, objectPool) { var ParentMappings = MappingInformation.GetChildMappings(typeof(TMappedClass)) .SelectMany(x => mappingInformation.GetParentMapping(x.ObjectType)) .Distinct(); IDProperties = ParentMappings.SelectMany(x => x.IDProperties); ReferenceProperties = ParentMappings.SelectMany(x => x.ReferenceProperties); }
/// <summary> /// Initializes a new instance of the <see cref="DataLoadQuery{TMappedClass}"/> class. /// </summary> /// <param name="mappingInformation">Mapping information</param> /// <param name="objectPool">The object pool.</param> public DataLoadQuery(IMappingSource mappingInformation, ObjectPool <StringBuilder> objectPool) : base(mappingInformation, objectPool) { IDProperties = MappingInformation.GetChildMappings(MappedClassType) .SelectMany(x => MappingInformation.GetParentMapping(x.ObjectType)) .Distinct() .SelectMany(x => x.IDProperties) .ToArray(); IDColumnInfo = IDProperties.Select(x => x.GetColumnInfo()[0]).ToArray(); }
public TranslationContext(IMappingSource mappingSource, List <ISqlElement> areas, SqlQuery sqlQuery) { this.mappingSource = mappingSource; this.areas = areas; this.sqlQuery = sqlQuery; queryEntityRegistry = new QueryEntityRegistry(mappingSource); queryEntityTree = new QueryEntityTree(queryEntityRegistry, nameGenerator); enumSqlBuilder = new EnumSqlBuilder(queryEntityTree, nameGenerator); }
/// <summary> /// Optimizes the operator based on the mapping source. /// </summary> /// <param name="mappingSource">The mapping source.</param> /// <returns></returns> public IOperator Optimize(IMappingSource mappingSource) { InternalOperator = InternalOperator.Optimize(mappingSource); if (InternalOperator is null) { return(null !); } return(Operator == ExpressionType.Not ? InternalOperator.LogicallyNegate() : (this)); }
/// <summary> /// Sets the column names. /// </summary> /// <param name="mappingSource">The mapping source.</param> /// <param name="mapping">The mapping.</param> public void SetColumnNames(IMappingSource mappingSource, IMapping mapping) { var ParentMapping = mappingSource.GetParentMapping(mapping.ObjectType).FirstOrDefault(x => x.ContainsProperty(InternalProperty.Name)); if (ParentMapping is null) { return; } Column = ParentMapping.GetColumnName(InternalProperty.Name); }
public QueryToSqlTranslator(IMappingSource mappingSource, int[] areas) { queryParser = new QueryParser(); this.mappingSource = mappingSource; if (areas.Length > 0) { this.areas = areas.Select(x => new LiteralExpression { Value = x }) .Cast <ISqlElement>() .ToList(); } }
/// <summary> /// Initializes a new instance of the <see cref="SQLServerGenerator{TMappedClass}"/> class. /// </summary> /// <param name="mappingInformation">The mapping information.</param> /// <param name="objectPool">The object pool.</param> /// <exception cref="System.ArgumentNullException">mappingInformation</exception> public SQLServerGenerator(IMappingSource mappingInformation, ObjectPool <StringBuilder> objectPool) : base(mappingInformation, new IQueryGenerator <TMappedClass>[] { new DeleteQuery <TMappedClass>(mappingInformation, objectPool), new InsertQuery <TMappedClass>(mappingInformation, objectPool), new UpdateQuery <TMappedClass>(mappingInformation, objectPool), new LinqQueryGenerator <TMappedClass>(mappingInformation, objectPool), new LoadPropertiesQuery <TMappedClass>(mappingInformation, objectPool), new SavePropertiesQuery <TMappedClass>(mappingInformation, objectPool), new DeletePropertiesQuery <TMappedClass>(mappingInformation, objectPool), new DataLoadQuery <TMappedClass>(mappingInformation, objectPool) }) { }
/// <summary> /// Initializes a new instance of the <see cref="GeneratorBaseClass{TMappedClass}"/> class. /// </summary> /// <param name="mappingInformation">The mapping information.</param> /// <param name="queryGenerators">The query generators.</param> /// <exception cref="ArgumentNullException"> /// linqQueryGenerator or mappingInformation or queryGenerators /// </exception> /// <exception cref="ArgumentException">Mapping not found for type: AssociatedType</exception> protected GeneratorBaseClass(IMappingSource mappingInformation, IEnumerable <IQueryGenerator <TMappedClass> > queryGenerators) { MappingInformation = mappingInformation ?? throw new ArgumentNullException(nameof(mappingInformation)); if (!MappingInformation.GetChildMappings(AssociatedType).Any()) { throw new ArgumentException("Mapping not found for type: " + AssociatedType); } QueryGenerators = queryGenerators?.ToDictionary(x => x.QueryType) ?? throw new ArgumentNullException(nameof(queryGenerators)); LinqQueryGenerator = (ILinqQueryGenerator <TMappedClass>)queryGenerators.FirstOrDefault(x => x.QueryType == QueryType.LinqQuery); DataQueryGenerator = (IDataQueryGenerator <TMappedClass>)queryGenerators.FirstOrDefault(x => x.QueryType == QueryType.LoadData); }
/// <summary> /// Executes this instance. /// </summary> /// <param name="source">Mapping source.</param> /// <param name="dynamoFactory">The dynamo factory.</param> /// <returns>The number of rows that are modified.</returns> public override Task <int> ExecuteAsync(IMappingSource source, DynamoFactory dynamoFactory) { if (Objects.Length == 0) { return(Task.FromResult(0)); } CreateBatch(source, dynamoFactory, out var Batch, out var ObjectsSeen); if (ObjectsSeen.Count == 0) { return(Task.FromResult(0)); } return(Batch.RemoveDuplicateCommands().ExecuteScalarAsync <int>()); }
/// <summary> /// Executes this instance. /// </summary> /// <param name="source">The source.</param> /// <returns>The number of rows that are modified.</returns> public override int Execute(IMappingSource source, DynamoFactory dynamoFactory) { if (Objects.Length == 0) { return(0); } CreateBatch(source, dynamoFactory, out var Batch, out var ObjectsSeen); if (ObjectsSeen.Count == 0) { return(0); } return(Task.Run(async() => await Batch.RemoveDuplicateCommands().ExecuteScalarAsync <int>().ConfigureAwait(false)).GetAwaiter().GetResult()); }
/// <summary> /// Finds the property. /// </summary> /// <typeparam name="TObject">The type of the object.</typeparam> /// <typeparam name="TData">The type of the data.</typeparam> /// <param name="source">The source.</param> /// <param name="propertyName">Name of the property.</param> /// <returns>The property</returns> private static IClassProperty FindProperty <TObject, TData>(IMappingSource source, string propertyName) where TObject : class where TData : class { var ParentMappings = source.GetChildMappings(typeof(TObject)).SelectMany(x => source.GetParentMapping(x.ObjectType)).Distinct(); IClassProperty Property = ParentMappings.SelectMany(x => x.ManyToManyProperties).FirstOrDefault(x => x.Name == propertyName); if (Property != null) { return(Property); } Property = ParentMappings.SelectMany(x => x.ManyToOneProperties).FirstOrDefault(x => x.Name == propertyName); return(Property ?? ParentMappings.SelectMany(x => x.MapProperties).FirstOrDefault(x => x.Name == propertyName)); }
/// <summary> /// Sets up the property (used internally) /// </summary> /// <param name="mappings"></param> public override void Setup(IMappingSource mappings) { ForeignMapping = mappings.GetChildMappings <DataType>() .SelectMany(x => mappings.GetParentMapping(x.ObjectType)) .Where(x => x.IDProperties.Count > 0) .Distinct() .ToList(); if (ForeignMapping is null) { throw new ArgumentException($"Foreign key IDs could not be found for {typeof(ClassType).Name}.{Name}"); } var ParentMappings = mappings.GetChildMappings(ParentMapping.ObjectType).SelectMany(x => mappings.GetParentMapping(x.ObjectType)).Distinct(); SetNullOnDelete = !OnDeleteDoNothingValue && ForeignMapping.Any(x => !ParentMappings.Contains(x)); }
/// <summary> /// Deletes the joins if it needs to. /// </summary> /// <param name="object">The object.</param> /// <param name="source">The source.</param> /// <param name="batch">The batch.</param> /// <param name="ManyToManyProperty">The many to many property.</param> /// <param name="ManyToManyValueList">The many to many value list.</param> private void DeleteJoins(object @object, IMappingSource source, SQLHelper batch, IManyToManyProperty ManyToManyProperty, IList ManyToManyValueList) { if (ManyToManyProperty.DatabaseJoinsCascade) { return; } ManyToManyValueList.Clear(); var LinksGenerator = QueryProviderManager.CreateGenerator(ManyToManyProperty.ParentMapping.ObjectType, source); var TempQueries = LinksGenerator.GenerateQueries(QueryType.JoinsDelete, @object, ManyToManyProperty); for (int x = 0, TempQueriesLength = TempQueries.Length; x < TempQueriesLength; ++x) { var TempQuery = TempQueries[x]; batch.AddQuery(TempQuery.DatabaseCommandType, TempQuery.QueryString, TempQuery.Parameters !); } }
/// <summary> /// Initializes a new instance of the <see cref="InsertQuery{TMappedClass}"/> class. /// </summary> /// <param name="mappingInformation">The mapping information.</param> /// <param name="objectPool">The object pool.</param> public InsertQuery(IMappingSource mappingInformation, ObjectPool <StringBuilder> objectPool) : base(mappingInformation, objectPool) { if (!MappingInformation.TypeGraphs.ContainsKey(AssociatedType)) { return; } var TypeGraph = MappingInformation.TypeGraphs[AssociatedType]; QueryDeclarationText = GenerateInsertQueryDeclarations(); QueryText = GenerateInsertQuery(TypeGraph?.Root); var ParentMappings = MappingInformation.GetParentMapping(typeof(TMappedClass)); IDProperties = ParentMappings.SelectMany(x => x.IDProperties); ReferenceProperties = ParentMappings.SelectMany(x => x.ReferenceProperties); }
/// <summary> /// Maps the input string contents /// </summary> /// <param name="mappingSource">The mapping provider</param> /// <param name="file">The contents to map</param> /// <param name="failedMappings">The list of failed mappings to generate a report for</param> /// <returns>The mapped string contents</returns> public static string MapString(IMappingSource mappingSource, string file, List <string> failedMappings = null) { Lumberjack.PushCategory("Mapper"); // Create regexes for matching intermediary names var rgxClass = new Regex("class_\\d+", RegexOptions.Compiled); var rgxField = new Regex("field_\\d+", RegexOptions.Compiled); var rgxMethod = new Regex("method_\\d+", RegexOptions.Compiled); // Replace all of the intermediary names file = rgxClass.Replace(file, match => CheckMatch(mappingSource.GetClassByInt(match.Value), match, failedMappings)); file = rgxField.Replace(file, match => CheckMatch(mappingSource.GetFieldByInt(match.Value), match, failedMappings)); file = rgxMethod.Replace(file, match => CheckMatch(mappingSource.GetMethodByInt(match.Value), match, failedMappings)); Lumberjack.PopCategory(); return(file); }
/// <summary> /// Sets up the property (used internally) /// </summary> /// <param name="mappings">The mappings.</param> /// <param name="sourceSpec">The source spec.</param> /// <exception cref="ArgumentException">Foreign key IDs could not be found for {typeof(ClassType).Name}.{Name}</exception> public override void Setup(IMappingSource mappings, ISource sourceSpec) { if (mappings is null || sourceSpec is null) { return; } ForeignMapping = mappings.GetChildMappings <TDataType>() .SelectMany(x => mappings.GetParentMapping(x.ObjectType)) .Where(x => x.IDProperties.Count > 0) .Distinct() .ToList(); var ParentMappings = mappings.GetChildMappings(ParentMapping.ObjectType).SelectMany(x => mappings.GetParentMapping(x.ObjectType)).Distinct(); var ActualParent = ParentMappings.FirstOrDefault(x => x.IDProperties.Count > 0); var ParentTable = sourceSpec.Tables.Find(x => x.Name == ActualParent.TableName); foreach (var TempMapping in ForeignMapping) { var SetNullOnDelete = !ParentMappings.Contains(TempMapping); foreach (var IDMapping in TempMapping.IDProperties) { if (ParentTable.Columns.Any(x => x.Name == ColumnName + TempMapping.TableName + IDMapping.ColumnName)) { continue; } ParentTable.AddColumn <object>(ColumnName + TempMapping.TableName + IDMapping.ColumnName, IDMapping.PropertyType.To(DbType.Int32), IDMapping.MaxLength, true, false, false, false, false, TempMapping.TableName, IDMapping.ColumnName, null !, "", false, false, !OnDeleteDoNothingValue && SetNullOnDelete); } } }
/// <summary> /// Sets up the property (used internally) /// </summary> /// <param name="mappings">The mappings.</param> /// <param name="sourceSpec">The source spec.</param> /// <exception cref="ArgumentException">Foreign key IDs could not be found for {typeof(ClassType).Name}.{Name}</exception> public override void Setup(IMappingSource mappings, ISource sourceSpec) { ForeignMapping = mappings.GetChildMappings <DataType>() .SelectMany(x => mappings.GetParentMapping(x.ObjectType)) .Where(x => x.IDProperties.Count > 0) .Distinct() .ToList(); if (ForeignMapping is null) { throw new ArgumentException($"Foreign key IDs could not be found for {typeof(ClassType).Name}.{Name}"); } foreach (var TempMapping in ForeignMapping) { var ForeignTable = sourceSpec.Tables.Find(x => x.Name == TempMapping.TableName); var ParentMappings = mappings.GetChildMappings(ParentMapping.ObjectType).SelectMany(x => mappings.GetParentMapping(x.ObjectType)).Distinct(); var ParentIDs = ParentMappings.SelectMany(x => x.IDProperties); var SetNullOnDelete = !ParentMappings.Contains(TempMapping); foreach (var IDMapping in ParentIDs) { if (ForeignTable.Columns.Any(x => x.Name == ColumnName + IDMapping.ParentMapping.TableName + IDMapping.ColumnName)) { continue; } ForeignTable.AddColumn <object>(ColumnName + IDMapping.ParentMapping.TableName + IDMapping.ColumnName, IDMapping.PropertyType.To(DbType.Int32), IDMapping.MaxLength, true, false, false, false, false, IDMapping.ParentMapping.TableName, IDMapping.ColumnName, null !, "", false, false, !OnDeleteDoNothingValue && SetNullOnDelete); } } }
/// <summary> /// Optimizes the operator based on the mapping source. /// </summary> /// <param name="mappingSource">The mapping source.</param> public IOperator Optimize(IMappingSource mappingSource) { if (InternalOperator is null) { return(this); } var IsValid = mappingSource.GetChildMappings(ObjectType).Any(); InternalOperator = IsValid ? InternalOperator.Optimize(mappingSource) : null; if (InternalOperator?.TypeCode != typeof(bool)) { InternalOperator = null; } return(this); }
/// <summary> /// Initializes a new instance of the <see cref="DataModel"/> class. /// </summary> /// <param name="source">The source.</param> /// <param name="config">The configuration.</param> /// <param name="logger">The logger.</param> /// <param name="dataModeler">The data modeler.</param> /// <param name="sherlock">The sherlock.</param> /// <param name="batch">The batch.</param> /// <exception cref="ArgumentNullException">source or config or logger</exception> public DataModel(IMappingSource source, IConfiguration config, ILogger logger, DataModeler dataModeler, Sherlock sherlock, SQLHelper batch) { if (config is null) { throw new ArgumentNullException(nameof(config)); } if (source is null) { throw new ArgumentNullException(nameof(source)); } logger ??= Log.Logger ?? new LoggerConfiguration().CreateLogger() ?? throw new ArgumentNullException(nameof(logger)); var sourceConnection = new Connection(config, source.Source.Provider, source.Source.Name); var sourceSpec = DataModeler.CreateSource(sourceConnection.DatabaseName ?? string.Empty); SourceSpec = sourceSpec; GeneratedSchemaChanges = Task.Run(async() => await GenerateSchemaAsync(source, logger, dataModeler, sourceConnection, sourceSpec).ConfigureAwait(false)).GetAwaiter().GetResult(); Task.Run(async() => await AnalyzeSchemaAsync(sherlock, logger, source, sourceConnection, batch).ConfigureAwait(false)).GetAwaiter().GetResult(); }
/// <summary> /// Sets the column information. /// </summary> /// <param name="mappings">The mappings.</param> public override void SetColumnInfo(IMappingSource mappings) { var Prefix = string.Empty; var ParentMappings = mappings.GetChildMappings(ParentMapping.ObjectType).SelectMany(x => mappings.GetParentMapping(x.ObjectType)).Distinct(); var ParentIDMappings = ParentMappings.SelectMany(x => x.IDProperties); var ParentWithID = ParentMappings.FirstOrDefault(x => x.IDProperties.Count > 0); if (ForeignMapping.Any(TempMapping => ParentWithID == TempMapping)) { Prefix = "Parent_"; } var TempColumns = new List <IQueryColumnInfo>(); TempColumns.AddRange(ParentIDMappings.ForEach(x => { return(new ComplexColumnInfo <ClassType, ClassType>( x.GetColumnInfo()[0], Prefix + x.ParentMapping.TableName + x.ColumnName, y => y, false, ParentMapping.SchemaName, TableName ?? string.Empty )); })); TempColumns.AddRange(ForeignMapping.SelectMany(TempMapping => { return(TempMapping.IDProperties.ForEach(x => { return new ComplexListColumnInfo <ClassType, DataType>( x.GetColumnInfo()[0], x.ParentMapping.TableName + x.ColumnName, CompiledExpression, true, ParentMapping.SchemaName, TableName ?? string.Empty ); })); })); Columns = TempColumns.ToArray(); }
/// <summary> /// Generates the schema. /// </summary> /// <param name="source">The source.</param> /// <param name="logger">The logger.</param> /// <param name="dataModeler">The data modeler.</param> /// <param name="sourceConnection">The source connection.</param> /// <param name="sourceSpec">The source spec.</param> /// <returns>The generated schema changes.</returns> private static async Task <string[]> GenerateSchemaAsync(IMappingSource source, ILogger logger, DataModeler dataModeler, IConnection sourceConnection, ISource sourceSpec) { if (!source.UpdateSchema && !source.GenerateSchema) { return(Array.Empty <string>()); } var Debug = logger.IsEnabled(LogEventLevel.Debug); var Generator = dataModeler.GetSchemaGenerator(source.Source.Provider); if (Generator is null) { return(Array.Empty <string>()); } logger.Information("Getting structure for {Info:l}", sourceConnection.DatabaseName); var OriginalSource = !string.IsNullOrEmpty(sourceConnection.DatabaseName) ? (await Generator.GetSourceStructureAsync(sourceConnection).ConfigureAwait(false)) : null; SetupTableStructures(logger, sourceConnection, source, sourceSpec); logger.Information("Generating schema changes for {Info:l}", sourceConnection.DatabaseName); var GeneratedSchemaChanges = Generator.GenerateSchema(sourceSpec, OriginalSource !) ?? Array.Empty <string>(); if (Debug) { logger.Debug("Schema changes generated: {GeneratedSchemaChanges}", GeneratedSchemaChanges); } if (!source.UpdateSchema) { return(GeneratedSchemaChanges); } logger.Information("Applying schema changes for {Info:l}", sourceConnection.DatabaseName); await Generator.SetupAsync(GeneratedSchemaChanges, sourceConnection).ConfigureAwait(false); return(GeneratedSchemaChanges); }