public virtual DatabaseCommand GenerateAlterTable(AlterTableExpression model)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var column in model.DropColumns)
            {
                sb.AppendFormat(DropColumnFormat,
                                Dialect.QuoteTableName(model.TableName),
                                Dialect.QuoteColumnName(column));
                sb.AppendLine(";");
            }
            foreach (var column in model.AlterColumns)
            {
                string columnDefinition = ColumnGenerator.Generate(column);
                sb.AppendFormat(AlterColumnFormat,
                                Dialect.QuoteTableName(model.TableName),
                                columnDefinition);
                sb.AppendLine(";");
            }
            foreach (var column in model.AddColumns)
            {
                string columnDefinition = ColumnGenerator.Generate(column);
                sb.AppendFormat(AddColumnFormat,
                                Dialect.QuoteTableName(model.TableName),
                                columnDefinition);
                sb.AppendLine(";");
            }
            return(new DatabaseCommand(sb.ToString()));
        }
        public virtual DatabaseCommand GenerateCreateTable(CreateTableExpression model)
        {
            string columns = ColumnGenerator.Generate(model.Columns);
            string cmd     = string.Format(CreateTableFormat, Dialect.QuoteTableName(model.TableName), columns);

            return(new DatabaseCommand(cmd));
        }
        [InlineData(20, 11)] //// Huge width, not divisible three
        public void TestGetColumnToHandleRarelyReturnsSameColumnForTwoPlayersAfterSecondTime(int width, int numberOfPlayers)
        {
            // Arrange
            Assert.False(width < numberOfPlayers);
            var handledColumns = new HashSet <int>();
            int repeatCount    = 0;

            // Act
            for (int k = 0; k < numberOfPlayers; ++k)
            {
                var columnGenerator = new ColumnGenerator(k, width, numberOfPlayers);

                int col1 = columnGenerator.GetColumnToHandle(1);
                int col2 = columnGenerator.GetColumnToHandle(2);
                repeatCount += handledColumns.Contains(col1) ? 1 : 0;
                repeatCount += handledColumns.Contains(col2) ? 1 : 0;
                handledColumns.Add(col1);
                handledColumns.Add(col2);
            }

            // Assert
            int val = Math.Max((numberOfPlayers * 2) - width, numberOfPlayers * 2 / width);

            Assert.True(repeatCount <= val, $"Should not repeat, \n expected {repeatCount} <= {val} ");
        }
        public void ApplyColumn(OpenApiSchema schema, OpenApiSchema columnSchema, ColumnGenerator column)
        {
            if ((column.Attribute.Keys & DBColumnKeys.Password) == DBColumnKeys.Password ||
                (column.Attribute.Keys & DBColumnKeys.File) == DBColumnKeys.File)
            {
                return;
            }

            ApplyColumnAttribute(schema, columnSchema, column.Attribute, column.PropertyInfo);
            if (column.Culture != null)
            {
                columnSchema.Extensions.Add("x-culture", new OpenApiString(column.Culture.ToString()));
            }

            var defaultValue = column.PropertyInfo.GetCustomAttribute <DefaultValueAttribute>();

            if (defaultValue != null && defaultValue.Value != null)
            {
                ApplyDefault(columnSchema, defaultValue.Value);
            }

            schema.Properties.Add(column.PropertyName, columnSchema);

            //if (TypeHelper.GetPassword(column.Property))
            //{
            //    schema.Extensions.Add("x-data", column.PropertyName);
            //}
        }
Exemple #5
0
        public void ApplyColumn(Schema schema, Schema columnSchema, ColumnGenerator column)
        {
            if ((column.Attribute.Keys & DBColumnKeys.Password) == DBColumnKeys.Password ||
                (column.Attribute.Keys & DBColumnKeys.File) == DBColumnKeys.File)
            {
                return;
            }

            if (column.GetDataType() == typeof(string) && column.Size > 0)
            {
                columnSchema.MaxLength = column.Size;
            }

            if ((column.Attribute.Keys & DBColumnKeys.Access) == DBColumnKeys.Access ||
                (column.Attribute.Keys & DBColumnKeys.Date) == DBColumnKeys.Date ||
                (column.Attribute.Keys & DBColumnKeys.Stamp) == DBColumnKeys.Stamp ||
                (column.Attribute.Keys & DBColumnKeys.System) == DBColumnKeys.System ||
                column.PropertyInfo?.GetSetMethod() == null)
            {
                columnSchema.ReadOnly = true;
            }
            if (((column.Attribute.Keys & DBColumnKeys.Notnull) == DBColumnKeys.Notnull ||
                 (column.Attribute.Keys & DBColumnKeys.ItemType) == DBColumnKeys.ItemType) ||
                (column.Attribute.Keys & DBColumnKeys.Primary) == DBColumnKeys.Primary)
            {
                if (schema.Required == null)
                {
                    schema.Required = new List <string>();
                }
                schema.Required.Add(column.PropertyName);
            }
            if ((column.Attribute.Keys & DBColumnKeys.Primary) == DBColumnKeys.Primary)
            {
                schema.Extensions.Add("x-id", column.PropertyName);
            }
            if ((column.Attribute.Keys & DBColumnKeys.ItemType) == DBColumnKeys.ItemType)
            {
                schema.Extensions.Add("x-type", column.PropertyName);
            }
            schema.Properties.Add(column.PropertyName, columnSchema);

            var defaultValue = column.PropertyInfo.GetCustomAttribute <DefaultValueAttribute>();

            if (defaultValue != null && defaultValue.Value != null)
            {
                if (defaultValue.Value.GetType().IsEnum)
                {
                    columnSchema.Default = EnumItem.Format(defaultValue.Value);
                }
                else
                {
                    columnSchema.Default = defaultValue.Value.ToString();
                }
            }
            //if (TypeHelper.GetPassword(column.Property))
            //{
            //    schema.Extensions.Add("x-data", column.PropertyName);
            //}
        }
Exemple #6
0
        private void AddColumn(ColumnDefinition columnDefinition, int?index = null)
        {
            var column = ColumnGenerator.CreateColumnForDefinition(columnDefinition);

            SetAssociatedColumn(column, columnDefinition);

            if (!index.HasValue)
            {
                AssociatedObject.Columns.Add(column);
            }
            else
            {
                AssociatedObject.Columns.Insert(index.Value, column);
            }
        }
        [InlineData(40, 11)] //// Huge width, not divisible three
        public void TestGetColumnToHandleNeverReturnsSameColumnForTwoPlayersInitialy(int width, int numberOfPlayers)
        {
            Assert.False(width < numberOfPlayers);

            // A & A & A
            var handledColumns = new HashSet <int>();

            for (int k = 0; k < numberOfPlayers; ++k)
            {
                var columnGenerator = new ColumnGenerator(k, width, numberOfPlayers);
                int col             = columnGenerator.GetColumnToHandle(1);
                Assert.DoesNotContain(col, handledColumns);
                handledColumns.Add(col);
            }
        }
 [InlineData(15, 20)] //// Huge number of players
 public void TestGetColumnToHandleNeverReturnsSameColumnForParticularPlayer(int width, int numberOfPlayers)
 {
     // A & A & A
     for (int k = 0; k < numberOfPlayers; ++k)
     {
         var columnGenerator = new ColumnGenerator(k, width, numberOfPlayers);
         var handledColumns  = new HashSet <int>();
         for (int i = 1; i <= width; ++i)
         {
             int col = columnGenerator.GetColumnToHandle(i);
             Assert.DoesNotContain(col, handledColumns);
             handledColumns.Add(col);
         }
     }
 }
    private static SelectExpression ExtractOrders(SelectExpression sel, out List <OrderExpression>?innerOrders)
    {
        if (sel.Top != null || (sel.OrderBy.Count == 0))
        {
            innerOrders = null;
            return(sel);
        }
        else
        {
            ColumnGenerator cg = new ColumnGenerator(sel.Columns);
            Dictionary <OrderExpression, ColumnDeclaration> newColumns = sel.OrderBy.ToDictionary(o => o, o => cg.NewColumn(o.Expression));

            innerOrders = newColumns.Select(kvp => new OrderExpression(kvp.Key.OrderType, kvp.Value.GetReference(sel.Alias))).ToList();

            return(new SelectExpression(sel.Alias, sel.IsDistinct, sel.Top, sel.Columns.Concat(newColumns.Values), sel.From, sel.Where, null, sel.GroupBy, sel.SelectOptions));
        }
    }
        public MessagePackGridViewModel(object data)
        {
            var  type        = data.GetType();
            Type elementType = type;

            var(isEnumerable, interfaceType) = type.IsEnumerable();
            if (isEnumerable)
            {
                elementType = interfaceType.GetGenericArguments()[0];
                _data.AddRange(ReflectionHelper.GetEnumerableValues(data).Select((x, i) => new TreeViewItem <object>(i + 1, 0, x.ToString(), x)));
            }
            else //not collection
            {
                _data.Add(new TreeViewItem <object>(1, 0, "", data));
            }

            //Header
            _columns.AddRange(ColumnGenerator.GetColumnGenerator(elementType).GenerateColumns(elementType));
        }
Exemple #11
0
    private ReadOnlyCollection <ColumnDeclaration> AnswerAndExpand(ReadOnlyCollection <ColumnDeclaration> columns, Alias currentAlias, Dictionary <ColumnExpression, ColumnExpression?> askedColumns)
    {
        ColumnGenerator cg = new ColumnGenerator(columns);

        foreach (var col in askedColumns.Keys.ToArray())
        {
            if (col.Alias == currentAlias)
            {
                //Expression expr = columns.SingleEx(cd => (cd.Name ?? "-") == col.Name).Expression;
                //askedColumns[col] = expr is SqlConstantExpression ? expr : col;
                askedColumns[col] = col;
            }
            else
            {
                ColumnExpression?colExp = CurrentScope[col];
                //if (expr is ColumnExpression colExp)
                //{
                ColumnDeclaration?cd = cg.Columns.FirstOrDefault(c => c !.Expression.Equals(colExp));
                if (cd == null)
                {
                    cd = cg.MapColumn(colExp !);
                }

                askedColumns[col] = new ColumnExpression(col.Type, currentAlias, cd.Name);
                //}
                //else
                //{
                //    askedColumns[col] = expr;
                //}
            }
        }


        if (columns.Count != cg.Columns.Count())
        {
            return(cg.Columns.NotNull().ToReadOnly());
        }

        return(columns);
    }
Exemple #12
0
    protected internal override Expression VisitSelect(SelectExpression select)
    {
        bool isOuterMost = select == outerMostSelect;

        if (select.IsOrderAlsoByKeys || select.HasIndex || select.Top != null && hasProjectionInProjector)
        {
            if (gatheredKeys == null)
            {
                gatheredKeys = new List <ColumnExpression>();
            }
        }

        List <ColumnExpression>?savedKeys = null;

        if (gatheredKeys != null && (select.IsDistinct || select.GroupBy.HasItems() || select.IsAllAggregates))
        {
            savedKeys = gatheredKeys.ToList();
        }

        if ((AggregateFinder.GetAggregates(select.Columns)?.Any(a => a.AggregateFunction.OrderMatters()) ?? false) && select.From is SelectExpression from)
        {
            var oldOuterMostSelect = outerMostSelect;
            outerMostSelect = from;

            select = (SelectExpression)base.VisitSelect(select);

            outerMostSelect = oldOuterMostSelect;
        }
        else
        {
            select = (SelectExpression)base.VisitSelect(select);
        }


        if (savedKeys != null)
        {
            gatheredKeys = savedKeys;
        }

        List <ColumnDeclaration>?newColumns = null;

        if (select.GroupBy.HasItems())
        {
            gatheredOrderings = null;

            if (gatheredKeys != null)
            {
                ColumnGenerator cg = new ColumnGenerator(select.Columns);

                var newKeys = new List <ColumnDeclaration>();

                foreach (var ge in select.GroupBy)
                {
                    var cd = cg.Columns.NotNull().FirstOrDefault(a => DbExpressionComparer.AreEqual(a.Expression, ge));

                    if (cd != null)
                    {
                        newKeys.Add(cd);
                    }
                    else
                    {
                        newKeys.Add(cg.NewColumn(ge));
                    }
                }

                if (cg.Columns.Count() != select.Columns.Count)
                {
                    newColumns = cg.Columns.NotNull().ToList();
                }

                gatheredKeys.AddRange(newKeys.Select(cd => new ColumnExpression(cd.Expression.Type, select.Alias, cd.Name)));
            }
        }

        if (select.IsAllAggregates)
        {
            if (gatheredKeys != null)
            {
                gatheredKeys.AddRange(select.Columns.Select(cd => new ColumnExpression(cd.Expression.Type, select.Alias, cd.Name)));
            }
        }

        if (select.IsDistinct)
        {
            gatheredOrderings = null;

            if (gatheredKeys != null)
            {
                gatheredKeys.AddRange(select.Columns.Select(cd => cd.GetReference(select.Alias)));
            }
        }

        if (select.IsReverse && !gatheredOrderings.IsNullOrEmpty())
        {
            gatheredOrderings = gatheredOrderings.Select(o => new OrderExpression(
                                                             o.OrderType == OrderType.Ascending ? OrderType.Descending : OrderType.Ascending,
                                                             o.Expression)).ToReadOnly();
        }

        if (select.OrderBy.Count > 0)
        {
            this.PrependOrderings(select.OrderBy);
        }

        ReadOnlyCollection <OrderExpression>?orderings = null;

        if (isOuterMost && !IsCountSumOrAvg(select) || select.Top != null)
        {
            AppendKeys();

            orderings         = gatheredOrderings;
            gatheredOrderings = null;
        }

        if (AreEqual(select.OrderBy, orderings) && !select.IsReverse && newColumns == null)
        {
            return(select);
        }

        return(new SelectExpression(select.Alias, select.IsDistinct, select.Top, (IEnumerable <ColumnDeclaration>?)newColumns ?? select.Columns,
                                    select.From, select.Where, orderings, select.GroupBy, select.SelectOptions & ~SelectOptions.Reverse));
    }
        public virtual DatabaseCommand GenerateAlterColumn(string tableName, string columnName, Models.DbType type, int length, object defaultValue, bool allowNull)
        {
            string columnDefinition = ColumnGenerator.Generate(columnName, type, length, defaultValue, allowNull);

            return(new DatabaseCommand(string.Format(AlterColumnFormat, tableName, columnDefinition)));
        }
        public virtual DatabaseCommand GenerateAddColumn(string tableName, string columnName, Models.DbType type, bool allowNull)
        {
            string columnDefinition = ColumnGenerator.Generate(columnName, type, allowNull);

            return(new DatabaseCommand(string.Format(AddColumnFormat, tableName, columnDefinition)));
        }
        private static void GenerateReferenceProperty(OpenApiSchema schema, SchemaFilterContext context, ColumnGenerator column)
        {
            var refPropertyType = column.ReferencePropertyInfo.PropertyType;
            var referenceSchema = context.SchemaGenerator.GenerateSchema(refPropertyType, context.SchemaRepository);
            var propertySchema  = new OpenApiSchema()
            {
                AllOf = new List <OpenApiSchema> {
                    referenceSchema
                }
            };

            propertySchema.Extensions.Add("x-id", new OpenApiString(column.PropertyName));
            schema.Properties.Add(column.ReferencePropertyInfo.Name, propertySchema);
        }
    protected internal override Expression VisitProjection(ProjectionExpression proj)
    {
        if (currentSource == null)
        {
            currentSource = WithoutOrder(proj.Select);

            Expression projector = this.Visit(proj.Projector);

            if (projector != proj.Projector)
            {
                proj = new ProjectionExpression(proj.Select, projector, proj.UniqueFunction, proj.Type);
            }

            currentSource = null;
            return(proj);
        }
        else
        {
            HashSet <ColumnExpression> columns = ExternalColumnGatherer.Gatherer(proj, currentSource.Alias);

            if (columns.Count == 0)
            {
                Expression projector = Visit(proj.Projector);

                ConstantExpression key   = Expression.Constant(0);
                Type            kvpType  = typeof(KeyValuePair <,>).MakeGenericType(key.Type, projector.Type);
                ConstructorInfo ciKVP    = kvpType.GetConstructor(new[] { key.Type, projector.Type }) !;
                Type            projType = proj.UniqueFunction == null ? typeof(IEnumerable <>).MakeGenericType(kvpType) : kvpType;

                var childProj = new ProjectionExpression(proj.Select,
                                                         Expression.New(ciKVP, key, projector), proj.UniqueFunction, projType);

                return(new ChildProjectionExpression(childProj,
                                                     Expression.Constant(0), inMList != null, inMList ?? proj.Type, new LookupToken()));
            }
            else
            {
                SelectExpression external;
                IEnumerable <ColumnExpression> externalColumns;

                if (!IsKey(currentSource, columns))
                {
                    Alias           aliasDistinct     = aliasGenerator.GetUniqueAlias(currentSource.Alias.Name + "D");
                    ColumnGenerator generatorDistinct = new ColumnGenerator();

                    List <ColumnDeclaration> columnDistinct = columns.Select(ce => generatorDistinct.MapColumn(ce)).ToList();
                    external = new SelectExpression(aliasDistinct, true, null, columnDistinct, currentSource, null, null, null, 0);


                    Dictionary <ColumnExpression, ColumnExpression> distinctReplacements = columnDistinct.ToDictionary(
                        cd => (ColumnExpression)cd.Expression,
                        cd => cd.GetReference(aliasDistinct));

                    proj = (ProjectionExpression)ColumnReplacer.Replace(proj, distinctReplacements);

                    externalColumns = distinctReplacements.Values.ToHashSet();
                }
                else
                {
                    external        = currentSource;
                    externalColumns = columns;
                }

                ColumnGenerator          generatorSM       = new ColumnGenerator();
                List <ColumnDeclaration> columnsSMExternal = externalColumns.Select(ce => generatorSM.MapColumn(ce)).ToList();
                List <ColumnDeclaration> columnsSMInternal = proj.Select.Columns.Select(cd => generatorSM.MapColumn(cd.GetReference(proj.Select.Alias))).ToList();

                SelectExpression @internal = ExtractOrders(proj.Select, out List <OrderExpression>?innerOrders);

                Alias            aliasSM    = aliasGenerator.GetUniqueAlias(@internal.Alias.Name + "SM");
                SelectExpression selectMany = new SelectExpression(aliasSM, false, null, columnsSMExternal.Concat(columnsSMInternal),
                                                                   new JoinExpression(JoinType.CrossApply,
                                                                                      external,
                                                                                      @internal, null), null, innerOrders, null, 0);

                SelectExpression old = currentSource;
                currentSource = WithoutOrder(selectMany);

                var selectManyReplacements = selectMany.Columns.ToDictionary(
                    cd => (ColumnExpression)cd.Expression,
                    cd => cd.GetReference(aliasSM));

                Expression projector = ColumnReplacer.Replace(proj.Projector, selectManyReplacements);

                projector = Visit(projector);

                currentSource = old;

                Expression      key      = TupleReflection.TupleChainConstructor(columnsSMExternal.Select(cd => MakeEquatable(cd.GetReference(aliasSM))));
                Type            kvpType  = typeof(KeyValuePair <,>).MakeGenericType(key.Type, projector.Type);
                ConstructorInfo ciKVP    = kvpType.GetConstructor(new[] { key.Type, projector.Type }) !;
                Type            projType = proj.UniqueFunction == null ? typeof(IEnumerable <>).MakeGenericType(kvpType) : kvpType;

                var childProj = new ProjectionExpression(selectMany,
                                                         Expression.New(ciKVP, key, projector), proj.UniqueFunction, projType);

                return(new ChildProjectionExpression(childProj,
                                                     TupleReflection.TupleChainConstructor(columns.Select(a => MakeEquatable(a))), inMList != null, inMList ?? proj.Type, new LookupToken()));
            }
        }
    }