Esempio n. 1
0
        /// <summary>
        /// 过滤
        /// </summary>
        /// <param name="dialect">Sql方言</param>
        /// <param name="matedata">实体元数据解析器</param>
        /// <param name="register">实体别名注册器</param>
        /// <param name="join">Join子句</param>
        /// <param name="where">Where子句</param>
        /// <param name="type">类型</param>
        /// <param name="alias">表别名</param>
        private void Filter(IDialect dialect, IEntityMatedata matedata, IEntityAliasRegister register, IJoinClause join,
            IWhereClause where, Type type, string alias)
        {
            if (type == null)
            {
                return;
            }

            if (string.IsNullOrWhiteSpace(alias))
            {
                return;
            }

            if (typeof(IDelete).IsAssignableFrom(type) == false)
            {
                return;
            }

            var isDeleted = $"{dialect.SafeName(alias)}.{dialect.SafeName(matedata.GetColumn(type, "IsDeleted"))}";
            if (register.FromType == type)
            {
                where.Where(isDeleted, false);
                return;
            }

            join.Find(type)?.On(isDeleted, false);
        }
Esempio n. 2
0
 /// <summary>
 /// 初始化Sql执行上下文
 /// </summary>
 /// <param name="entityAliasRegister">实体别名注册器</param>
 /// <param name="whereClause">实体别名注册器</param>
 /// <param name="matedata">实体元数据解析器</param>
 /// <param name="dialect">Sql方言</param>
 public SqlContext(IEntityAliasRegister entityAliasRegister, IWhereClause whereClause, IEntityMatedata matedata, IDialect dialect)
 {
     EntityAliasRegister = entityAliasRegister ?? new EntityAliasRegister();
     Where    = whereClause ?? throw new ArgumentNullException(nameof(whereClause));
     Matedata = matedata;
     Dialect  = dialect;
 }
Esempio n. 3
0
        internal WhereClauseBuilder(IWhereClause obj, IStoreMapping storeMapping, StorageDialectSettings dialectSettings)
        {
            _obj             = obj ?? throw new ArgumentNullException(nameof(obj));
            _storeMapping    = storeMapping ?? throw new ArgumentNullException(nameof(storeMapping));
            _dialectSettings = dialectSettings ?? throw new ArgumentNullException(nameof(dialectSettings));
            _builder         = new StringBuilder();
            _parameters      = new Dictionary <string, object>();
            _writeAnd        = () => this.And();
            _writeOr         = () => this.Or();

            //  this._classMap = ClassMapCached.Fetch<TKey, TEntity>();
            this._classMap = ClassMapCached <TKey, TEntity> .ClassMap;
        }
        public void VisitWhere(IWhereClause clause, Expression <Func <CollectVariableVisitor, bool> > visitorExpectation, Expression <Func <IWhereClause, bool> > clauseExpectation)
        {
            // Arrange
            _outputHelper.WriteLine($"{nameof(clause)} : {clause}");

            // Act
            _sut.Visit(clause);

            // Assert
            _sut.Should()
            .Match(visitorExpectation);
            clause.Should()
            .Match(clauseExpectation);
        }
Esempio n. 5
0
 /// <summary>
 /// 克隆
 /// </summary>
 /// <param name="sqlBuilder">源生成器</param>
 protected void Clone(SqlBuilderBase sqlBuilder)
 {
     EntityMatedata    = sqlBuilder.EntityMatedata;
     _parameterManager = sqlBuilder._parameterManager?.Clone();
     EntityResolver    = sqlBuilder.EntityResolver ?? new EntityResolver(EntityMatedata);
     AliasRegister     = sqlBuilder.AliasRegister?.Clone() ?? new EntityAliasRegister();
     _selectClause     = sqlBuilder._selectClause?.Clone(this, AliasRegister);
     _fromClause       = sqlBuilder._fromClause?.Clone(AliasRegister);
     _joinClause       = sqlBuilder._joinClause?.Clone(this, AliasRegister);
     _whereClause      = sqlBuilder._whereClause?.Clone(AliasRegister, _parameterManager);
     _groupByClause    = sqlBuilder._groupByClause?.Clone(AliasRegister);
     _orderByClause    = sqlBuilder._orderByClause?.Clone(AliasRegister);
     _pager            = sqlBuilder._pager;
 }
Esempio n. 6
0
 /// <summary>
 /// 过滤
 /// </summary>
 private void Filter(IWhereClause whereClause, Type type, string alias)
 {
     if (type == null)
     {
         return;
     }
     if (string.IsNullOrWhiteSpace(alias))
     {
         return;
     }
     if (typeof(IDelete).IsAssignableFrom(type))
     {
         whereClause.Where($"{alias}.IsDeleted", false);
     }
 }
Esempio n. 7
0
 /// <summary>
 /// 过滤
 /// </summary>
 private void Filter(IDialect dialect, IEntityMatedata matedata, IWhereClause where, Type type, string alias)
 {
     if (type == null)
     {
         return;
     }
     if (string.IsNullOrWhiteSpace(alias))
     {
         return;
     }
     if (typeof(IDelete).IsAssignableFrom(type))
     {
         where.Where($"{dialect.SafeName( alias )}.{dialect.SafeName( matedata.GetColumn( type, "IsDeleted" ) )}", false);
     }
 }
Esempio n. 8
0
        ///<inheritdoc/>
        public IJoinQuery <SelectQuery> RightOuterJoin(Table table, IWhereClause clause)
        {
            if (table == null)
            {
                throw new ArgumentNullException(nameof(table), $"{nameof(table)} cannot be null");
            }

            if (clause == null)
            {
                throw new ArgumentNullException(nameof(clause), $"{nameof(clause)} cannot be null");
            }

            Joins.Add(new RightOuterJoin(table, clause));

            return(this);
        }
 /// <summary>
 /// 复制Sql生成器
 /// </summary>
 /// <param name="sqlBuilder">源生成器</param>
 protected void Clone(SqlBuilderBase sqlBuilder)
 {
     EntityMatedata    = sqlBuilder.EntityMatedata;
     _parameterManager = sqlBuilder._parameterManager?.Clone();
     EntityResolver    = sqlBuilder.EntityResolver ?? new EntityResolver(EntityMatedata);
     AliasRegister     = sqlBuilder.AliasRegister?.Clone() ?? new EntityAliasRegister();
     _selectClause     = sqlBuilder._selectClause?.Clone(this, AliasRegister);
     _fromClause       = sqlBuilder._fromClause?.Clone(this, AliasRegister);
     _joinClause       = sqlBuilder._joinClause?.Clone(this, AliasRegister, _parameterManager);
     _whereClause      = sqlBuilder._whereClause?.Clone(this, AliasRegister, _parameterManager);
     _groupByClause    = sqlBuilder._groupByClause?.Clone(AliasRegister);
     _orderByClause    = sqlBuilder._orderByClause?.Clone(AliasRegister);
     Pager             = sqlBuilder.Pager;
     OffsetParam       = sqlBuilder.OffsetParam;
     LimitParam        = sqlBuilder.LimitParam;
     UnionItems        = sqlBuilder.UnionItems.Select(t => new BuilderItem(t.Name, t.Builder.Clone())).ToList();
     CteItems          = sqlBuilder.CteItems.Select(t => new BuilderItem(t.Name, t.Builder.Clone())).ToList();
 }
Esempio n. 10
0
        public void Init(
            IInsertClause insert,
            IUpdateClause update,
            IDeleteClause delete,
            ISelectClause select,
            IFromClause from,
            IWhereClause where,
            IGroupByClause groupBy,
            IWhereClause having,
            IOrderByClause orderBy,
            LinkedList <IUnion> unions,
            ISelectQuery parentSelect,
            ICreateTableStatement createTable,
            bool parameterDependent,
            List <ISqlParameter> parameters)
        {
            Insert               = insert;
            Update               = update;
            Delete               = delete;
            Select               = select;
            From                 = from;
            Where                = where;
            GroupBy              = groupBy;
            Having               = having;
            OrderBy              = orderBy;
            Unions               = unions;
            ParentSelect         = parentSelect;
            CreateTable          = createTable;
            IsParameterDependent = parameterDependent;

            Parameters.AddRange(parameters);

            foreach (var col in select.Columns)
            {
                col.Parent = this;
            }

            Select.SetSqlQuery(this);
            From.SetSqlQuery(this);
            Where.SetSqlQuery(this);
            GroupBy.SetSqlQuery(this);
            Having.SetSqlQuery(this);
            OrderBy.SetSqlQuery(this);
        }
Esempio n. 11
0
        /// <summary>
        /// Adds a condition to the "Where" property, and returns self for chainability
        /// </summary>
        /// <param name="condition"></param>
        /// <param name="conditionType"></param>
        /// <returns></returns>
        protected void MergeWhere(IWhere component, JoinType joinType)
        {
            IWhereClause compound = whereClause as IWhereClause;

            if (joinType == JoinType.Or && compound != null && compound.Count == 0)
            {
                throw new Exception("There is no existing condition to OR");
            }
            if (whereClause is IWhereClause && compound.JoinType == joinType)
            {
                compound.Add(component);
            }
            else
            {
                // currently just a single criterion
                whereClause = new WhereClause(joinType, whereClause, component);
            }
            Touch();
        }
Esempio n. 12
0
        public static Arbitrary <DeleteQuery> DeleteQueryGenerators()
        {
            Gen <NonWhiteSpaceString> tableNameGenerator = Arb.Generate <NonWhiteSpaceString>();

            Gen <IList <FieldColumn> > columnsGenerator = FieldColumnGenerators().Generator
                                                          .NonEmptyListOf();

            Gen <IColumn> constraintGenerator = FieldColumnGenerators().Generator
                                                .Select(field => field.As <IColumn>());


            return(Gen.Zip(tableNameGenerator, columnsGenerator, constraintGenerator)
                   .Select(tuple =>
            {
                (NonWhiteSpaceString tableName, IEnumerable <FieldColumn> cols, IColumn constraint) = tuple;
                IWhereClause where = null;

                return new DeleteQuery(tableName.Item)
                .Where(where)
                .Build();
            }).ToArbitrary());
        }
        public virtual void Visit(IWhereClause instance)
        {
            switch (instance)
            {
            case WhereClause wc when wc.Constraint is Variable v:
                bool canBeReplace = _variableVisitor.Variables.Any(variable => variable == v);
                if (canBeReplace)
                {
                    ((WhereClause)instance).Constraint = _variableRewriter.Invoke(v);
                }
                break;

            case CompositeWhereClause cwc:
                foreach (IWhereClause item in cwc.Clauses)
                {
                    Visit(item);
                }
                break;

            default:
                break;
            }
        }
Esempio n. 14
0
 IDeleteQueryBuilder <TRecord> AddWhereClause(IWhereClause clause)
 {
     return(new DeleteQueryBuilder <TRecord>(relationalTransaction, uniqueParameterNameGenerator, tableName, whereClauses.Concat(new [] { clause }), parameterValues));
 }
Esempio n. 15
0
 public LeftOuterJoin(Table table, IWhereClause @on)
     : base(JoinType.LeftOuterJoin, table, @on)
 {
 }
Esempio n. 16
0
 public virtual void VisitWhereClause(IWhereClause value)
 {
     VisitExpression(value.Expression);
 }
 private void WriteWhereClause(IWhereClause value, IFormatter formatter)
 {
     formatter.WriteKeyword("where");
     formatter.Write(" ");
     this.WriteExpression(value.Expression, formatter);
 }
Esempio n. 18
0
        /// <summary>
        /// 添加过滤器列表
        /// </summary>
        private void AddFilters(IWhereClause whereClause)
        {
            var context = new SqlQueryContext(AliasRegister, whereClause);

            SqlFilterCollection.Filters.ForEach(filter => filter.Filter(context));
        }
Esempio n. 19
0
 public Where(IWhereClause whereClause)
 {
     this.whereClause = whereClause;
 }
Esempio n. 20
0
 /// <summary>
 /// 清空Where子句
 /// </summary>
 public ISqlBuilder ClearWhere()
 {
     _isAddFilters = false;
     _whereClause  = CreatewWhereClause();
     return(this);
 }
Esempio n. 21
0
 internal Next(IWhereClause parent) : base(parent.SelectQuery)
 {
     _parent = parent;
 }
Esempio n. 22
0
 public void And(IWhereClause predicate)
 {
     whereAndClauses.Add(new PredicateClause {
         Clause = predicate
     });
 }
Esempio n. 23
0
 public void Or(IWhereClause predicate)
 {
     whereOrClauses.Add(new PredicateClause {
         Clause = predicate
     });
 }
Esempio n. 24
0
 /// <summary>
 /// Builds a new <see cref="RightOuterJoin"/> instance.
 /// </summary>
 /// <param name="table"></param>
 /// <param name="on"></param>
 public RightOuterJoin(Table table, IWhereClause @on)
     : base(JoinType.RightOuterJoin, table, @on)
 {
 }
Esempio n. 25
0
 public InnerJoin(Table table, IWhereClause @on)
     : base(JoinType.InnerJoin, table, @on)
 {
 }
Esempio n. 26
0
 protected JoinBase(JoinType joinType, Table table, IWhereClause on)
 {
     JoinType = joinType;
     Table = table;
     On = @on;
 }
Esempio n. 27
0
 /// <summary>
 /// 清空Where子句
 /// </summary>
 public void ClearWhere()
 {
     _isAddFilters = false;
     _whereClause  = CreatewWhereClause();
 }
Esempio n. 28
0
 /// <summary>
 /// Builds a new <see cref="InnerJoin"/> instance.
 /// </summary>
 /// <param name="table"></param>
 /// <param name="on"></param>
 public InnerJoin(Table table, IWhereClause @on) : base(JoinType.InnerJoin, table, @on)
 {
 }
Esempio n. 29
0
 public bool Equals(IWhereClause other) => Equals(other as WhereClause);
Esempio n. 30
0
 /// <summary>
 /// Builds a new <see cref="JoinBase"/> instance.
 /// </summary>
 /// <param name="joinType">The JOIN operator type</param>
 /// <param name="table">The table onto which the operator will be apply</param>
 /// <param name="on">The "ON" clause</param>
 protected JoinBase(JoinType joinType, Table table, IWhereClause on)
 {
     JoinType = joinType;
     Table    = table;
     On       = @on;
 }
Esempio n. 31
0
        /// <summary>
        /// Converts <paramref name="filter"/> to <see cref="IWhereClause"/>.
        /// </summary>
        /// <param name="filter">The filter to convert</param>
        /// <returns>A <see cref="IWhereClause"/> equivalent of the given <paramref name="filter"/>.</returns>
        public static IWhereClause ToWhere(this IFilter filter)
        {
            IWhereClause clause = null;

            switch (filter)
            {
            case Filter f:
            {
                ClauseOperator clauseOperator;
                object         value = f.Value;

                switch (f.Operator)
                {
                case FilterOperator.EqualTo:
                    clauseOperator = ClauseOperator.EqualTo;
                    break;

                case FilterOperator.NotEqualTo:
                    clauseOperator = ClauseOperator.NotEqualTo;
                    break;

                case FilterOperator.IsNull:
                    clauseOperator = ClauseOperator.IsNull;
                    break;

                case FilterOperator.IsNotNull:
                    clauseOperator = ClauseOperator.IsNotNull;
                    break;

                case FilterOperator.LessThan:
                    clauseOperator = ClauseOperator.LessThan;
                    break;

                case FilterOperator.LessThanOrEqualTo:
                    clauseOperator = ClauseOperator.LessThanOrEqualTo;
                    break;

                case FilterOperator.GreaterThan:
                    clauseOperator = ClauseOperator.GreaterThan;
                    break;

                case FilterOperator.GreaterThanOrEqual:
                    clauseOperator = ClauseOperator.GreaterThanOrEqualTo;
                    break;

                case FilterOperator.StartsWith:
                case FilterOperator.EndsWith:
                case FilterOperator.Contains:
                    clauseOperator = ClauseOperator.Like;
                    if (f.Operator == FilterOperator.StartsWith)
                    {
                        value = $"{value}%";
                    }
                    else if (f.Operator == FilterOperator.EndsWith)
                    {
                        value = $"%{value}";
                    }
                    else
                    {
                        value = $"%{value}%";
                    }
                    break;

                case FilterOperator.NotStartsWith:
                case FilterOperator.NotEndsWith:
                case FilterOperator.NotContains:
                    clauseOperator = ClauseOperator.NotLike;
                    if (f.Operator == FilterOperator.NotStartsWith)
                    {
                        value = $"{value}%";
                    }
                    else if (f.Operator == FilterOperator.NotEndsWith)
                    {
                        value = $"%{value}";
                    }
                    else
                    {
                        value = $"%{value}%";
                    }
                    break;

                default:
                    throw new NotSupportedException($"Unsupported {f.Operator} operator");
                }

                clause = new WhereClause(f.Field.Field(), clauseOperator, value switch
                    {
                        bool b => b.Literal(),
                        DateTime date => date.Literal(),
                        string s => s.Literal(),
                        null => null,
                        long l => l.Literal(),
                        float floatValue => floatValue.Literal(),
                        decimal decimalValue => decimalValue.Literal(),
                        double doubleValue => doubleValue.Literal(),
                        int intValue => intValue.Literal(),
#if NET6_0_OR_GREATER
                        DateOnly date => date.Literal(),
                        TimeOnly time => time.Literal(),
#endif
                        _ => throw new NotSupportedException($"Unexpected '{value?.GetType().Name}' type when building WhereClause")
                    }
                                         );
                break;
            }
Esempio n. 32
0
 public virtual void VisitWhereClause(IWhereClause value)
 {
     this.VisitExpression(value.Expression);
 }
Esempio n. 33
0
 public RightOuterJoin(Table table, IWhereClause @on)
     : base(JoinType.RightOuterJoin, table, @on)
 {
 }
Esempio n. 34
0
 IDeleteQueryBuilder <TRecord> AddWhereClause(IWhereClause clause)
 {
     return(new DeleteQueryBuilder <TRecord>(uniqueParameterNameGenerator, queryBuilder, queryExecutor, whereClauses.Concat(new [] { clause }), parameterValues));
 }
Esempio n. 35
0
 public LeftOuterJoin(Table table, IWhereClause @on)
     : base(JoinType.LeftOuterJoin, table, @on)
 {
 }
Esempio n. 36
0
 /// <summary>
 /// 初始化一个<see cref="SqlQueryContext"/>类型的实例
 /// </summary>
 /// <param name="entityAliasRegister">实体别名注册器</param>
 /// <param name="whereClause">Where子句</param>
 /// <param name="matedata">实体元数据解析器</param>
 public SqlQueryContext(IEntityAliasRegister entityAliasRegister, IWhereClause whereClause, IEntityMatedata matedata)
 {
     EntityAliasRegister = entityAliasRegister ?? new EntityAliasRegister();
     WhereClause         = whereClause ?? throw new ArgumentNullException(nameof(whereClause));
     Matedata            = matedata;
 }
 public virtual IWhereClause TransformWhereClause(IWhereClause value)
 {
     value.Expression = this.TransformExpression(value.Expression);
     return value;
 }