public string Compile(IColumnSelector value, SelectQuery query, IQueryParameterManager parameters)
        {
            var select = value as ColumnDatePartSelector;


            var format = "DATEADD({0},0, DATEDIFF({0},0, {1}{2}{3}))";

            if (select.Aggregate != Aggregate.None)
            {
                var isInGroupBy = AggregateHelpers.IsInGroupBy(query, select);

                // if its in the group by, dont aggregate it
                if (!isInGroupBy)
                {
                    return(string.Format("{5}(" + format + ") AS {4}",
                                         select.DatePart.ToSqlString(),
                                         select.TableAlias,
                                         string.IsNullOrWhiteSpace(select.TableAlias) ? null : ".",
                                         select.Field.Name,
                                         select.Alias,
                                         select.Aggregate.ToSqlString()
                                         ));
                }
            }

            return(string.Format(format + " AS {4}",
                                 select.DatePart.ToSqlString(),
                                 select.TableAlias,
                                 string.IsNullOrWhiteSpace(select.TableAlias) ? null : ".",
                                 select.Field.Name,
                                 select.Alias
                                 ));
        }
Пример #2
0
        public string Compile(IColumnSelector value, SelectQuery query, IQueryParameterManager parameters)
        {
            var select = value as ColumnSelector;

            if (select.Aggregate != Aggregate.None)
            {
                var isInGroupBy = AggregateHelpers.IsInGroupBy(query, select);

                // if its in the group by, dont aggregate it
                if (!isInGroupBy)
                {
                    return(string.Format("{0}({1}{2}{3}{4}) AS {5}",
                                         select.Aggregate.ToSqlString(),
                                         select.Aggregate == Aggregate.Bit || select.Aggregate == Aggregate.BitMax ? "0+" : null, // fix bit field aggregation for nulls
                                         select.TableAlias,
                                         string.IsNullOrWhiteSpace(select.TableAlias) ? null : ".",
                                         select.Field.Name,
                                         select.Alias));
                }
            }

            return(string.Format("{0}{1}{2} AS {3}",
                                 select.TableAlias,
                                 string.IsNullOrWhiteSpace(select.TableAlias) ? null : ".",
                                 select.Field.Name,
                                 select.Alias));
        }
Пример #3
0
        private Solution SolveTwoPhase()
        {
            Solution tmp_solution = new Solution()
            {
                Quality = Enums.SolutionQuality.Infeasible
            };

            m_RevisedModel.PrintMatrix();

            //1) Solve the matrix for phase I

            /*
             * Steps
             * 1. Modify the constraints so that the RHS of each constraint is nonnegative (This requires that each constraint with a negative RHS be multiplied by -1. Remember that if you multiply an inequality by any negative number, the direction of the inequality is reversed!). After modification, identify each constraint as a ≤, ≥ or = constraint.
             * 2. Convert each inequality constraint to standard form (If constraint i is a ≤ constraint, we add a slack variable si; and if constraint i is a ≥ constraint, we subtract an excess variable ei).
             * 3. Add an artificial variable ai to the constraints identified as ≥ or = constraints at the end of Step 1. Also add the sign restriction ai ≥ 0.
             * 4. In the phase I, ignore the original LP’s objective function, instead solve an LP whose objective function is minimizing w = ai (sum of all the artificial variables). The act of solving the Phase I LP will force the artificial variables to be zero. 5. Since each artificial variable will be in the starting basis, all artificial variables must be eliminated from row 0 before beginning the simplex. Now solve the transformed problem by the simplex.
             */
            m_ColumnSelector = ColumnSelectorFactory.GetSelector(ObjectiveType.Minumum);
            tmp_solution     = Solve(m_RevisedModel.PhaseNonBasisObjectiveMatrix, m_RevisedModel.PhaseBasisObjectiveMatrix, m_RevisedModel.BasisMatrix, m_RevisedModel.BasisInverseMatrix, m_RevisedModel.NonBasisMatrix, m_RevisedModel.BasisRightHandMatrix, m_RevisedModel.BasicVariables, m_RevisedModel.ObjectiveCost);
            //Solving the Phase I LP will result in one of the following three cases:
            //I.Case : If w = 0
            //TODO test //tmp_solution.RightHandValues[tmp_solution.RightHandValues.GetLength(0) - 1, 0] = 0;

            if (tmp_solution.ResultValue + m_RevisedModel.ObjectiveCost == 0)
            {
                m_ColumnSelector = ColumnSelectorFactory.GetSelector(m_RevisedModel.GoalType);
                //transfer the phaseoneobjective function factors
                RevisedSimplexModel tmp_phaseModel = m_RevisedModel;
                tmp_phaseModel.TruncatePhaseResult(tmp_solution);
                //II.Case : If w = 0, and no artificial variables are in the optimal Phase I basis:
                //  i.Drop all columns in the optimal Phase I tableau that correspond to the artificial variables.Drop Phase I row 0.
                //  ii.Combine the original objective function with the constraints from the optimal Phase I tableau(Phase II LP).If original objective function coefficients of BVs are nonzero row operations are done.
                //  iii.Solve Phase II LP using the simplex method.The optimal solution to the Phase II LP is the optimal solution to the original LP.
                //tmp_phaseModel.BasisObjectiveMatrix = new Matrix(1, tmp_solution.BasicVariables.Count);
                //tmp_phaseModel.BasisRightHandMatrix = new Matrix(tmp_solution.BasicVariables.Count,1);
                //for (int i = 0; i < tmp_solution.BasicVariables.Count; i++)
                //{
                //    tmp_phaseModel.BasisObjectiveMatrix[0, i] =tmp_phaseModel.ObjectiveFunction.Terms[tmp_solution.BasicVariables[i]].Factor;
                //    tmp_phaseModel.BasisRightHandMatrix[i,0] = tmp_phaseModel.Subjects[i].RightHandValue;
                //}

                tmp_solution = Solve(tmp_phaseModel.BasisNonObjectiveMatrix, tmp_phaseModel.BasisObjectiveMatrix, tmp_phaseModel.BasisMatrix, tmp_phaseModel.BasisInverseMatrix, tmp_phaseModel.NonBasisMatrix, tmp_phaseModel.BasisRightHandMatrix, tmp_phaseModel.BasicVariables, tmp_phaseModel.ObjectiveCost);
                //tmp_solution = Solve(tmp_phaseModel.PhaseNonOneBasisObjectiveMatrix, tmp_phaseModel.BasisObjectiveMatrix, tmp_phaseModel.PhaseOneBasisMatrix, tmp_phaseModel.BasisMatrix, tmp_phaseModel.PhaseOneNonBasisMatrix, tmp_phaseModel.BasisRightHandMatrix, tmp_solution.BasicVariables, tmp_phaseModel.ObjectiveCost);
                System.Diagnostics.Debug.WriteLine("Solution " + tmp_solution.Quality.ToString());
                //if ( )
                //III.Case : If w = 0, and at least one artificial variable is in the optimal Phase I basis:
                //  i.Drop all columns in the optimal Phase I tableau that correspond to the nonbasic artificial variables and any variable from the original problem that has a negative coefficient in row 0 of the optimal Phase I tableau. Drop Phase I row 0.
                //  ii.Combine the original objective function with the constraints from the optimal Phase I tableau(Phase II LP).If original objective function coefficients of BVs are nonzero row operations are done.
                //  iii.Solve Phase II LP using the simplex method.The optimal solution to the Phase II LP is the optimal solution to the original LP.
                //if ( )
            }
            //II.Case  : If w > 0 then the original LP has no feasible solution(stop here).
            else
            {
                tmp_solution.Quality = SolutionQuality.Infeasible;
            }
            //assign the actual value to the result terms
            return(tmp_solution);
        }
Пример #4
0
        public IColumnConfig Create(ITableConfig table, IColumnSelector selector)
        {
            switch (selector.SelectorType)
            {
            case ColumnSelectorType.ColumnName:
                var property = PropertyResolutionStrategy.GetProperty(table.TableType, selector.ColumnName);
                if (property != null)
                {
                    return(this.Create(table, selector.Identifier, selector.ColumnName, selector.ColumnType, property, selector.Flags));
                }
                else
                {
                    return(this.Create(table, selector.Identifier, selector.ColumnName, selector.ColumnType, selector.Flags));
                }

            case ColumnSelectorType.Property:
                return(this.Create(table, selector.Identifier, selector.ColumnName, selector.ColumnType, selector.Property, selector.Flags));

            case ColumnSelectorType.Expression:
                return(this.Create(table, selector.Identifier, selector.ColumnName, selector.ColumnType, selector.Expression, selector.Flags));

            default:
                throw new NotImplementedException();
            }
        }
Пример #5
0
        public string Compile(IColumnSelector value, SelectQuery query, IQueryParameterManager parameters)
        {
            var select        = value as OrderByColumnSelector;
            var orderByColumn = query.OrderByColumns.First();
            var selectColumn  = new ColumnSelector(orderByColumn.TableAlias, orderByColumn.Field.Name, select.Alias, orderByColumn.Aggregate);

            var selectCompiler = new ColumnSelectorCompiler();

            return(selectCompiler.Compile(selectColumn, query, parameters));
        }
Пример #6
0
 public bool TryCreateColumn(IColumnSelector selector, out IColumnConfig column)
 {
     column = Factories.Column.Create(this, selector);
     if (!ColumnValidator.Validate(this.Config.Database, this, column))
     {
         return(false);
     }
     column = this.Columns.AddOrUpdate(column.Identifier, column);
     this.Reset();
     return(true);
 }
Пример #7
0
        public IColumnConfig GetColumn(IColumnSelector selector)
        {
            var existing = default(IColumnConfig);
            var column   = Factories.Column.Create(this, selector);

            if (!this.Columns.TryGetValue(column.Identifier, out existing) || !ColumnComparer.ColumnConfig.Equals(column, existing))
            {
                return(default(IColumnConfig));
            }
            return(existing);
        }
Пример #8
0
        public IColumnConfig CreateColumn(IColumnSelector selector)
        {
            var column = Factories.Column.Create(this, selector);

            if (!ColumnValidator.Validate(this.Config.Database, this, column))
            {
                throw new InvalidOperationException(string.Format("Table has invalid configuration: {0}", column));
            }
            column = this.Columns.AddOrUpdate(column.Identifier, column);
            this.Reset();
            return(column);
        }
        public string Compile(IColumnSelector value, SelectQuery query, IQueryParameterManager parameters)
        {
            var    select  = value as RowNumberColumnSelector;
            string orderBy = new SelectQueryCompiler().CompileOrderBy(query);

            if (!string.IsNullOrWhiteSpace(orderBy))
            {
                orderBy = orderBy.Replace("\n\t", " ").Replace("\n", " ").Replace("  ", " ");
            }

            if (select.Alias == null)
            {
                return(string.Format("( ROW_NUMBER() OVER({0}) ) ", orderBy));
            }
            return(string.Format("( ROW_NUMBER() OVER({0}) ) AS {1}", orderBy, select.Alias));
        }
        public string Compile(IColumnSelector value, SelectQuery query, IQueryParameterManager parameters)
        {
            var select = value as GroupByColumnSelector;

            if (query.GroupByColumns.Count >= select.Index + 1)
            {
                // date part column selector
                if (query.GroupByColumns[select.Index] is GroupByColumnDatePart)
                {
                    var selector = query.GroupByColumns[select.Index] as GroupByColumnDatePart;

                    if (selector != null)
                    {
                        var column = new ColumnDatePartSelector(selector.TableAlias,
                                                                selector.Field.Name,
                                                                select.Alias,
                                                                selector.DatePart,
                                                                Aggregate.None);

                        var result = new ColumnDatePartSelectorCompiler().Compile(column, query, parameters);
                        return(result);
                    }
                }


                // simple column selector
                if (query.GroupByColumns[select.Index] is GroupByColumn)
                {
                    var selector = query.GroupByColumns[select.Index] as GroupByColumn;

                    if (selector != null)
                    {
                        var column = new ColumnSelector(selector.TableAlias,
                                                        selector.Field.Name,
                                                        select.Alias,
                                                        Aggregate.None);

                        var result = new ColumnSelectorCompiler().Compile(column, query, parameters);
                        return(result);
                    }
                }
            }

            // cannot find the group key column
            return(string.Format("null AS {0}", select.Alias));
        }
Пример #11
0
        public string Compile(IColumnSelector value, SelectQuery query, IQueryParameterManager parameters)
        {
            var select = value as GroupByColumnSelector;

            if (query.GroupByColumns.Count == 1)
            {
                var column = new ColumnSelector(query.GroupByColumns[0].TableAlias,
                                                query.GroupByColumns[0].Field.Name,
                                                select.Alias,
                                                Aggregate.None);

                var result = new ColumnSelectorCompiler().Compile(column, query, parameters);
                return(result);
            }

            // cannot find the group key column
            return(string.Format("null AS {1}"));
        }
        public string Compile(IColumnSelector value, SelectQuery query, IQueryParameterManager parameters)
        {
            var select = value as TotalColumnSelector;

            var count = "( COUNT(1) OVER () )";

            if (select.OnlyOnRowIndex == null)
            {
                return(string.Format("{0} AS {1}", count, select.Alias));
            }

            var rowNumber = new RowNumberColumnSelectorCompiler().Compile(new RowNumberColumnSelector(null), query, parameters);

            return(string.Format("( CASE WHEN {0} = {1} THEN {2} ELSE null END ) AS {3}",
                                 rowNumber,
                                 select.OnlyOnRowIndex,
                                 count,
                                 select.Alias));
        }
Пример #13
0
        public IMemberSpec <TDestination> ForMember(Expression <Func <TDestination, object> > destinationMember,
                                                    IColumnSelector selector)
        {
            if (destinationMember == null)
            {
                throw new ArgumentNullException(nameof(destinationMember));
            }
            if (selector == null)
            {
                throw new ArgumentNullException(nameof(selector));
            }

            DestinationMember = destinationMember;
            _columnSelector   = selector;

            _memberSpecs.Add(this);

            return(new MemberSpec <TDestination>(_memberSpecs));
        }
Пример #14
0
        Solution ISolutionBuilder.getResult()
        {
            Solution tmp_solution = new Solution()
            {
                Quality = Enums.SolutionQuality.Infeasible
            };

            if (m_RevisedModel.IsTwoPhase)
            {
                tmp_solution = SolveTwoPhase();
            }
            else
            {
                m_ColumnSelector = ColumnSelectorFactory.GetSelector(m_RevisedModel.GoalType);
                tmp_solution     = Solve(m_RevisedModel.BasisNonObjectiveMatrix, m_RevisedModel.BasisObjectiveMatrix, m_RevisedModel.BasisMatrix, m_RevisedModel.BasisMatrix.Invert(), m_RevisedModel.NonBasisMatrix, m_RevisedModel.BasisRightHandMatrix, m_RevisedModel.BasicVariables, m_RevisedModel.ObjectiveCost);
            }
            //for feaseble solution, all of rhs values must be positive or zero and Z must be zero after all iteration
            PrepareSolutionResult(m_RevisedModel.NonBasisMatrix, WorkingRightHandValues, m_RevisedModel.ObjectiveFunction.Terms, tmp_solution);

            return(tmp_solution);
        }
Пример #15
0
 public GenericODataController(AdventureWorksContext context, IAuthorizer authorizer, IColumnSelector columnSelector)
 {
     Context        = context;
     Authorizer     = authorizer;
     ColumnSelector = columnSelector;
 }
        public string Compile(IColumnSelector value, SelectQuery query, IQueryParameterManager parameters)
        {
            var select = value as SqlColumnSelector;

            return(select.Sql);
        }
        public string Compile(IColumnSelector value, SelectQuery query, IQueryParameterManager parameters)
        {
            var select = value as CountColumnSelector;

            return(string.Format("COUNT({1}) AS {0}", select.Alias, select.FieldName));
        }
Пример #18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PropertyMapper"/> class.
 /// </summary>
 /// <param name="propertySelector">The <see cref="IPropertySelector"/> that is responsible for selecting the
 /// target properties for a given <see cref="Type"/>.</param>
 /// <param name="columnSelector">The <see cref="IColumnSelector"/> that is responsible for selecting column names
 /// and column ordinals from a given <see cref="IDataRecord"/>.</param>
 public PropertyMapper(IPropertySelector propertySelector, IColumnSelector columnSelector)
 {
     this.propertySelector = propertySelector;
     this.columnSelector   = columnSelector;
 }
Пример #19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PropertyMapper"/> class.
 /// </summary>
 /// <param name="propertySelector">The <see cref="IPropertySelector"/> that is responsible for selecting the 
 /// target properties for a given <see cref="Type"/>.</param>
 /// <param name="columnSelector">The <see cref="IColumnSelector"/> that is responsible for selecting column names 
 /// and column ordinals from a given <see cref="IDataRecord"/>.</param>
 public PropertyMapper(IPropertySelector propertySelector, IColumnSelector columnSelector)
 {
     this.propertySelector = propertySelector;
     this.columnSelector = columnSelector;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="CachedColumnSelector"/> class.
 /// </summary>
 /// <param name="columnSelector">The <see cref="IColumnSelector"/> being decorated.</param>
 public CachedColumnSelector(IColumnSelector columnSelector)
 {
     this.columnSelector = columnSelector;
 }
 public string Compile(IColumnSelector value, SelectQuery query, IQueryParameterManager parameters)
 {
     return("*");
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="CachedColumnSelector"/> class.
 /// </summary>
 /// <param name="columnSelector">The <see cref="IColumnSelector"/> being decorated.</param>
 public CachedColumnSelector(IColumnSelector columnSelector)
 {
     this.columnSelector = columnSelector;
 }