public LogicalExpressionBuilder(Operator oper) { _expression = new LogicalExpression { Operator = oper }; }
public virtual void Visit(LogicalExpression e) { _sql.Append("("); e.Operand1.Accept(this); _sql.Append(" ").Append(e.Operator.GetOperator()).Append(" "); e.Operand2.Accept(this); _sql.Append(")"); }
public void Missing_Close_Bracket_Exception() { try { LogicalExpression logicalExpression = new LogicalExpression("(p>q"); Assert.Fail("Exception expected"); } catch (ParsingException e) { Assert.AreEqual(ParserExceptionType.MissingCloseBracket, e.ExceptionType); Assert.AreEqual(TokenType.OpenBracket, e.Token.Type); } }
public void Initial_Token_Exception() { try { LogicalExpression logicalExpression = new LogicalExpression(")p"); Assert.Fail("Exception expected"); } catch (ParsingException e) { Assert.AreEqual(ParserExceptionType.IllegalInitialToken, e.ExceptionType); Assert.AreEqual(TokenType.CloseBracket, e.Token.Type); } }
public void Expected_Token_Exception() { try { LogicalExpression logicalExpression = new LogicalExpression("p>->p"); Assert.Fail("Exception expected"); } catch (ParsingException e) { Assert.AreEqual(ParserExceptionType.ExpectedToken, e.ExceptionType); Assert.AreEqual(TokenType.Implication, e.Token.Type); } }
public override Expression VisitLogicalExpression(LogicalExpression expression) { WriteTokenIfReq(expression, Token.LeftParenthesis); this.Visit(expression.Left); WriteLogicalOperator(expression.Operator); this.Visit(expression.Right); WriteTokenIfReq(expression, Token.RightParentThesis); return(expression); }
private static LinqExpression Evaluate(this LogicalExpression expression, System.Linq.Expressions.ParameterExpression arg) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } if (arg == null) { throw new ArgumentNullException(nameof(arg)); } LinqExpression leftExpression = null; LinqExpression rightExpression = null; if (expression.AttributeLeft != null) { leftExpression = expression.AttributeLeft.Evaluate(arg); } if (expression.AttributeRight != null) { rightExpression = expression.AttributeRight.Evaluate(arg); } if (leftExpression != null && rightExpression != null) { switch (expression.Operator) { case LogicalOperators.and: return(LinqExpression.And(leftExpression, rightExpression)); case LogicalOperators.or: return(LinqExpression.Or(leftExpression, rightExpression)); } } if (leftExpression != null) { return(leftExpression); } if (rightExpression != null) { return(rightExpression); } return(null); }
private static void ExtractLogicalExpression(LogicalExpression logicalExpression, CompiledExpression compiledExpression, string model, bool retrievedFromCache) { switch (logicalExpression) { case TernaryExpression ternary: ExtractLogicalExpression(ternary.LeftExpression, compiledExpression, model, retrievedFromCache); ExtractLogicalExpression(ternary.MiddleExpression, compiledExpression, model, retrievedFromCache); ExtractLogicalExpression(ternary.RightExpression, compiledExpression, model, retrievedFromCache); break; case BinaryExpression binary: ExtractLogicalExpression(binary.LeftExpression, compiledExpression, model, retrievedFromCache); ExtractLogicalExpression(binary.RightExpression, compiledExpression, model, retrievedFromCache); break; case UnaryExpression unary: ExtractLogicalExpression(unary.Expression, compiledExpression, model, retrievedFromCache); break; case Function function: //parameters.Functions.Add(function.Identifier.Name); if (compiledExpression.CanBeOptimized) { compiledExpression.CanBeOptimized = !NotOptimizableFunctions.Contains(function.Identifier.Name.ToLowerInvariant()); } foreach (var expression in function.Expressions) { ExtractLogicalExpression(expression, compiledExpression, model, retrievedFromCache); } break; case ValueExpression _: //constant value // Intentionally blank break; case Identifier identifier: //Parameter if (!retrievedFromCache) { identifier.Name = StringUtils.CleanFullName(model, identifier.Name); } compiledExpression.Parameters.Add(identifier.Name); break; } }
/// <summary> /// Convert the expression tree into a structured query expression. /// </summary> /// <param name="context">Context information about this query building session, including the target structured query object.</param> /// <returns>A scalar expression that can be used within the query.</returns> protected virtual ScalarExpression OnBuildQuery(QueryBuilderContext context) { // Reflect for attributes Type type = GetType(); var queryEngAttribute = GetQueryEngineOperator(type); if (queryEngAttribute == null) { throw new NotImplementedException(type.Name); } // Build arguments var arguments = new List <ScalarExpression>(); foreach (ExpressionNode argument in Arguments) { ScalarExpression queryExpr = argument.BuildQuery(context); arguments.Add(queryExpr); } // Generic Calculation Expression if (queryEngAttribute.CalculationOperator != null) { var result = new CalculationExpression(); result.Operator = queryEngAttribute.CalculationOperator.Value; result.Expressions = arguments; return(result); } // Generic Comparison Expression if (queryEngAttribute.ComparisonOperator != null) { var result = new ComparisonExpression(); result.Operator = queryEngAttribute.ComparisonOperator.Value; result.Expressions = arguments; return(result); } // Generic Comparison Expression if (queryEngAttribute.LogicalOperator != null) { var result = new LogicalExpression(); result.Operator = queryEngAttribute.LogicalOperator.Value; result.Expressions = arguments; return(result); } throw new InvalidOperationException(type.Name); }
public void Expression_With_Implication_Negation_And_Brackets() { LogicalExpression logicalExpression = new LogicalExpression("p>(-p>q)>-r"); Assert.AreEqual(8, logicalExpression.TruthTable.Length); Assert.AreEqual("01 1000 110", logicalExpression.TruthTable[0]); Assert.AreEqual("01 1000 001", logicalExpression.TruthTable[1]); Assert.AreEqual("01 1011 110", logicalExpression.TruthTable[2]); Assert.AreEqual("01 1011 001", logicalExpression.TruthTable[3]); Assert.AreEqual("11 0110 110", logicalExpression.TruthTable[4]); Assert.AreEqual("11 0110 001", logicalExpression.TruthTable[5]); Assert.AreEqual("11 0111 110", logicalExpression.TruthTable[6]); Assert.AreEqual("11 0111 001", logicalExpression.TruthTable[7]); }
/// <summary> /// Parse the guard of a transition /// </summary> /// <param name="reader"></param> /// <param name="t"></param> public static void ParseGuard(XmlTextReader reader, Transition t) { if (t == null) { throw new System.ArgumentNullException("Error parsing transition: transition not specified properly before reaching guard."); } String guard = reader.GetAttribute(GuardAttributes.equn.ToString()); if (guard.Length > 0) { Antlr.Runtime.Tree.CommonTree tmptree = math.Expression.Parse(guard); t.Guard = LogicalExpression.CreateTerm(tmptree); } }
public LogicalExpression AssignCommandGuider(LogicalExpression lgInputExpression, LogicalExpression lgChildExpression) { if (lgInputExpression == null) { return(null); } if (lgChildExpression == null) { return(null); } LogicalExpression lgRet = null; //Create new command guider and prepare to pass clsCommonCommandGuider clsInputCommandGuider = new clsCommonCommandGuider(); if (lgInputExpression.objCommandGuider is clsCommonCommandGuider) { clsInputCommandGuider = (clsCommonCommandGuider)lgInputExpression.objCommandGuider; } //With each child expression, we will supply a new command guider for it clsCommonCommandGuider clsNewCommandGuider = new clsCommonCommandGuider(); clsNewCommandGuider.objSources = this.objSources; clsNewCommandGuider.intStepPos = clsInputCommandGuider.intStepPos; clsNewCommandGuider.intSourcesID = this.intSourcesID; clsNewCommandGuider.intProcessId = this.intProcessId; clsNewCommandGuider.intToken = clsInputCommandGuider.intToken; if (lgChildExpression is FunctionExpression) { FunctionExpression FunctionExTemp = (FunctionExpression)lgChildExpression; foreach (var setting in this.lstSettingCommand) { if (setting.strDetectCode.ToUpper().Trim() == FunctionExTemp.Identifier.Name.ToUpper().Trim()) { clsNewCommandGuider.clsSettingCommand = setting; } } } lgChildExpression.objCommandGuider = clsNewCommandGuider; lgRet = lgChildExpression; // return(lgRet); }
public override FilterExpression?OnApplyFilter(FilterExpression?existingFilter) { base.OnApplyFilter(existingFilter); if (_clientSettingsProvider.ArePlanetsWithPrivateNameHidden) { AttrAttribute privateNameAttribute = ResourceType.GetAttributeByPropertyName(nameof(Planet.PrivateName)); FilterExpression hasNoPrivateName = new ComparisonExpression(ComparisonOperator.Equals, new ResourceFieldChainExpression(privateNameAttribute), NullConstantExpression.Instance); return(LogicalExpression.Compose(LogicalOperator.And, hasNoPrivateName, existingFilter)); } return(existingFilter); }
public override Expression VisitLogical(LogicalExpression expression, Type argument) { var termQueue = new Queue <Expression>(expression.Terms.Select(filter => Visit(filter, argument))); if (expression.Operator == LogicalOperator.And) { return(Compose(termQueue, Expression.AndAlso)); } if (expression.Operator == LogicalOperator.Or) { return(Compose(termQueue, Expression.OrElse)); } throw new InvalidOperationException($"Unknown logical operator '{expression.Operator}'."); }
public override Object Visit(LogicalExpression node, Object obj) { Object aux = null; node.FirstOperand.LeftExpression = node.LeftExpression; node.SecondOperand.LeftExpression = node.LeftExpression; if ((aux = node.FirstOperand.Accept(this, false)) is SingleIdentifierExpression) { node.FirstOperand = (SingleIdentifierExpression)aux; } if ((aux = node.SecondOperand.Accept(this, false)) is SingleIdentifierExpression) { node.SecondOperand = (SingleIdentifierExpression)aux; } return(null); }
private void SetParameter(ISearchExpression se, Feng.Web.MyCrystalReportViewer reportViewer) { LogicalExpression le = se as LogicalExpression; if (le != null) { SetParameter(le.LeftHandSide, reportViewer); SetParameter(le.RightHandSide, reportViewer); } else { SimpleExpression sse = se as SimpleExpression; reportViewer.CrystalHelper.SetParameter("@" + sse.FullPropertyName + sse.Operator.ToString(), sse.Values); } }
public LogicalExpression Compile(string expression, bool nocache) { if (expression == null) { return(null); } LogicalExpression logicalExpression = null; //NCalc has problem if user function with no parameter such as "Empty()" , "NewLine()"... //We temporary add "null" to these: "Empty()" => "Empty(null)". "NewLine()" => "NewLine(null)"... //After finish analyzing, return expression to null bool blMasking = false; if (expression.Contains("()") == true) //Mother expression or child expression { blMasking = true; expression = expression.Replace("()", "(null)"); //Do masking } if (logicalExpression == null) { var lexer = new NCalc2Lexer(new AntlrInputStream(expression)); var parser = new NCalc2Parser(new CommonTokenStream(lexer)); var errorListener = new ErrorListener(); parser.AddErrorListener(errorListener); logicalExpression = parser.ncalc().retValue; if (blMasking == true) { //In case of User function with no parameter or have child expression with no parameter //if which expression no parameter => return to null logicalExpression = RemoveNullParameterExpression(logicalExpression); } if (errorListener.Errors.Any()) { //throw new EvaluationException(string.Join(Environment.NewLine, errorListener.Errors.ToArray())); //In case of error, then return a logical expression with "expression" same as input string logicalExpression = new ValueExpression(expression, Expressions.ValueType.String); } } return(logicalExpression); }
internal static void SetParameter(CrystalHelper crystalHelper, ISearchExpression se) { if (se == null) { return; } LogicalExpression le = se as LogicalExpression; if (le != null) { SetParameter(crystalHelper, le.LeftHandSide); SetParameter(crystalHelper, le.RightHandSide); } else { SimpleExpression cse = se as SimpleExpression; string simpleParamName = "@" + cse.FullPropertyName; string complexParamName = "@" + cse.FullPropertyName + cse.Operator.ToString(); switch (cse.Operator) { case SimpleOperator.Any: case SimpleOperator.EqProperty: case SimpleOperator.IsNotNull: case SimpleOperator.IsNull: case SimpleOperator.NotEq: case SimpleOperator.NotEqProperty: case SimpleOperator.Sql: throw new ArgumentException(cse.Operator + " is not supported in procedure!"); case SimpleOperator.Ge: case SimpleOperator.Gt: case SimpleOperator.Le: case SimpleOperator.Lt: crystalHelper.SetParameter(complexParamName, cse.Values); break; case SimpleOperator.Eq: case SimpleOperator.GInG: case SimpleOperator.InG: case SimpleOperator.Like: crystalHelper.SetParameter(simpleParamName, cse.Values); break; } } }
public override Object Visit(LogicalExpression node, Object obj) { int indent = Convert.ToInt32(obj); this.printIndentation(indent); this.output.Write("LogicalExpression "); switch (node.Operator) { case LogicalOperator.Or: this.output.Write("||"); break; case LogicalOperator.And: this.output.Write("&&"); break; } this.output.WriteLine(" Type: {0} [{1}:{2}]", printType(node.ExpressionType), node.Location.Line, node.Location.Column); node.FirstOperand.Accept(this, indent + 1); node.SecondOperand.Accept(this, indent + 1); return(null); }
public VariableParameter(string name, VarType type, VarUpdateType update_type, string assumption) : base(name, "", type, update_type, assumption) { Expr param = null; // TODO: refactor all these switches in the constructors into common variable parent class switch (type) { case VarType.index: param = Controller.Instance.Z3.MkIntConst(name); // todo: vs Controller.Instance.IndexType break; case VarType.integer: param = Controller.Instance.Z3.MkIntConst(name); break; case VarType.real: param = Controller.Instance.Z3.MkRealConst(name); break; } if (param != null) { if (!Controller.Instance.Params.ContainsKey(name)) { Controller.Instance.Params.Add(name, param); } } else { throw new System.Exception("Parameter term not created."); } if (assumption != null && assumption.Length > 0) { Antlr.Runtime.Tree.CommonTree tmptree = passel.controller.parsing.math.Expression.Parse(assumption); //Expression.FixTypes(ref tmptree); Expr passump = LogicalExpression.CreateTerm(tmptree); if (!Controller.Instance.ParamsAssumps.ContainsKey(name)) { Controller.Instance.ParamsAssumps.Add(name, passump); Controller.Instance.Z3.Assumptions.Add((BoolExpr)passump); } } }
private static void EnsureValidLogicalExpression(LogicalExpression logicalExpression) { if (logicalExpression == null) { throw new InvalidExecuteQueryException(StringMessages.ErrorInvalidLogicalExpression); } if (logicalExpression.LeftExpression == null) { throw new InvalidExecuteQueryException(StringMessages.ErrorNullLeftValue); } if (logicalExpression.RightExpression == null) { throw new InvalidExecuteQueryException(StringMessages.ErrorNullRightValue); } }
private Query CreateDateFilterQuery() { var query = new Query(); query.RootEntity.ObjectDefinitionFullName = "Webinar"; //Build the expressions var leftExpression = new ComparisonExpression { ExpressionType = ExpressionType.Comparison, LeftValue = new ComparisonValue { Value = "Webinar.StartTime", ValueType = ComparisonValueType.Property }, RightValue = new ComparisonValue { Value = new DateTime(2010, 01, 01), ValueType = ComparisonValueType.Property }, Operator = ComparisonOperator.Equal }; var rightExpression = new ComparisonExpression { ExpressionType = ExpressionType.Comparison, LeftValue = new ComparisonValue { Value = "Webinar.EndTime", ValueType = ComparisonValueType.Property }, RightValue = new ComparisonValue { Value = new DateTime(2013, 01, 01), ValueType = ComparisonValueType.Property }, Operator = ComparisonOperator.Equal }; var logical = new LogicalExpression { ExpressionType = ExpressionType.Logical, LeftExpression = leftExpression, RightExpression = rightExpression, Operator = LogicalOperator.And }; query.Constraints = logical; //we're adding the logical expression: // StartTime <= 1/1/2010 AND EndTime >= 1/1/2013 return(query); }
public LogicalExpression MakeLogical(LogicalExpression rhs) { UnaryOperator logicalOp = new UnaryOperator(); logicalOp.AddNot(new Altova.Types.SchemaString("Not")); UnaryType newUnaryExpression = new UnaryType(); newUnaryExpression.AddUnaryOperator(logicalOp); newUnaryExpression.AddLogicalExpression(rhs); LogicalExpression newLogical = new LogicalExpression(); newLogical.AddUnary(newUnaryExpression); return(newLogical); }
/// <summary> /// Redefine the standard Liquid {% if %} tag to allow "{% elsif %}" or "{% elseif %}". /// </summary> private void RegisterLavaElseIfTag() { var ifTag = LogicalExpression .AndSkip(TagEnd) .And(_anyTagsListParser) .And(ZeroOrMany( TagStart.SkipAnd(Terms.Text("elsif").Or(Terms.Text("elseif"))).SkipAnd(LogicalExpression).AndSkip(TagEnd).And(_anyTagsListParser)) .Then(x => x.Select(e => new ElseIfStatement(e.Item1, e.Item2)).ToList())) .And(ZeroOrOne( CreateTag("else").SkipAnd(_anyTagsListParser)) .Then(x => x != null ? new ElseStatement(x) : null)) .AndSkip(CreateTag("endif").ElseError($"'{{% endif %}}' was expected")) .Then <Statement>(x => new IfStatement(x.Item1, x.Item2, x.Item4, x.Item3)) .ElseError("Invalid 'if' tag"); RegisteredTags["if"] = ifTag; }
//private void ProcessCmd(DbCommand cmd) //{ // foreach (string s in m_funcParams) // { // if (!cmd.Parameters.Contains(s)) // { // cmd.CommandText = cmd.CommandText.Replace(s, "default"); // } // else // { // // remove like % // string likeString = cmd.Parameters[s].Value as string; // if (!string.IsNullOrEmpty(likeString)) // { // if (likeString[0] == '%' && likeString[likeString.Length - 1] == '%') // { // cmd.Parameters[s].Value = likeString.Substring(1, likeString.Length - 2); // } // } // // remove where clause // int idx = cmd.CommandText.IndexOf("WHERE"); // idx = cmd.CommandText.IndexOf(s, idx); // int idx2 = idx; // // jump to "=, >=" // idx2--; // while (cmd.CommandText[idx2] == ' ') // idx2--; // // jump to space // idx2--; // while (cmd.CommandText[idx2] != ' ') // idx2--; // // jump to propertyName // idx2--; // while (cmd.CommandText[idx2] == ' ') // idx2--; // // jump to space // idx2--; // while (cmd.CommandText[idx2] != ' ') // idx2--; // cmd.CommandText = cmd.CommandText.Replace(cmd.CommandText.Substring(idx2 + 1, idx - idx2 - 1 + s.Length), "1 = 1"); // } // } //} private ISearchExpression RemoveFunctionParamSearchExpression(ISearchExpression se, Dictionary <string, object> deletedParam) { if (se == null) { return(null); } if (se is LogicalExpression) { LogicalExpression le = se as LogicalExpression; ISearchExpression ls = RemoveFunctionParamSearchExpression(le.LeftHandSide, deletedParam); ISearchExpression rs = RemoveFunctionParamSearchExpression(le.RightHandSide, deletedParam); switch (le.LogicOperator) { case LogicalOperator.And: return(SearchExpression.And(ls, rs)); case LogicalOperator.Or: return(SearchExpression.Or(ls, rs)); case LogicalOperator.Not: return(SearchExpression.Not(ls)); default: throw new NotSupportedException("Not Supported LogicalOperator!"); } } else if (se is SimpleExpression) { SimpleExpression cse = se as SimpleExpression; string paramName = SearchManager.CreateParamName(cse, null); if (Array.IndexOf(m_funcParams, paramName) != -1) { deletedParam[paramName] = cse.Values; return(null); } else { return(cse); } } else { return(se); } }
private void FillDbCommand(ISearchExpression condition, DbCommand cmd, ref int paramCnt) { SimpleExpression cse = condition as SimpleExpression; if (cse == null) { LogicalExpression l = condition as LogicalExpression; FillDbCommand(l.LeftHandSide, cmd, ref paramCnt); FillDbCommand(l.RightHandSide, cmd, ref paramCnt); } else { string simpleParamName = "@" + cse.FullPropertyName; string complexParamName = "@" + cse.FullPropertyName + cse.Operator.ToString(); switch (cse.Operator) { case SimpleOperator.Any: case SimpleOperator.EqProperty: case SimpleOperator.IsNotNull: case SimpleOperator.IsNull: case SimpleOperator.NotEq: case SimpleOperator.NotEqProperty: case SimpleOperator.Sql: throw new NotSupportedException(cse.Operator + " is not supported in procedure!"); case SimpleOperator.Ge: case SimpleOperator.Gt: case SimpleOperator.Le: case SimpleOperator.Lt: cmd.Parameters.Add(DbHelper.Instance.CreateParameter(complexParamName, cse.Values)); break; case SimpleOperator.Eq: case SimpleOperator.GInG: case SimpleOperator.InG: case SimpleOperator.Like: cmd.Parameters.Add(DbHelper.Instance.CreateParameter(simpleParamName, cse.Values)); break; } paramCnt++; } }
public void NotInArray() { RequiredDataContainer ModelData = SelectDataProvider.GetData(); string HandcraftedQuery = Utils.ReadQueryFromFile("HandcraftedQueries/selectNotInArray.js"); Assert.IsNotNull(HandcraftedQuery); MapRule PersonRule = ModelData.ERMongoMapping.Rules.First(R => R.Source.Name == "Person"); string AgeMap = PersonRule.Rules.First(R => R.Key == "age").Value; LogicalExpression left = new LogicalExpression($"${AgeMap}", LogicalOperator.NOT_IN, new JSArray(new List <object>() { 26, 27, 28, 29 })); SelectArgument Arg = new SelectArgument(left); SelectStage SelectOp = new SelectStage(Arg, ModelData.ERMongoMapping); List <AlgebraOperator> OperatorsToExecute = new List <AlgebraOperator>() { SelectOp }; FromArgument StartArg = new FromArgument(new QueryableEntity(ModelData.EntityRelationshipModel.FindByName("Person")), ModelData.ERMongoMapping); QueryGenerator QueryGen = new QueryGenerator(StartArg, OperatorsToExecute); string GeneratedQuery = QueryGen.Run(); Assert.IsNotNull(GeneratedQuery); QueryRunner Runner = new QueryRunner("mongodb://localhost:27017", "select"); string HandcraftedResult = Runner.GetJSON(HandcraftedQuery); string GeneratedResult = Runner.GetJSON(GeneratedQuery); // Check if either result is null Assert.IsNotNull(HandcraftedResult); Assert.IsNotNull(GeneratedResult); // Check if both results are equal Assert.IsTrue(JToken.DeepEquals(JToken.Parse(HandcraftedResult), JToken.Parse(GeneratedResult))); }
public void Test_when_Context_is_not_set() { //Arrange var expression = new LogicalExpression(new VariableExpression("OfficeNID"), new ConstantExpression("10"), FilterOperator.EqualTo); try { // Act var evaluation = expression.EvaluateAsync(null); var result = evaluation.Result is bool; } catch (AggregateException ae) { Assert.IsTrue(ae.Flatten().InnerExceptions.Select(e => e.GetType() == typeof(NullReferenceException)).Any()); return; } // Assert Assert.Fail("Expected Exception was not thrown"); }
public void Test_when_Right_part_of_Expression_is_not_set() { try { //Arrange var expression = new LogicalExpression(new ConstantExpression("10"), null, FilterOperator.EqualTo); // Act var evaluation = expression.EvaluateAsync(GetDefaultMessageContext); // Assert var result = evaluation.Result is bool; } catch (AggregateException ae) { Assert.IsTrue(ae.Flatten().InnerExceptions.Select(e => e.GetType() == typeof(NullReferenceException)).Any()); return; } Assert.Fail("Expected NullReferenceException did not occur"); }
/// <summary> /// visit LogicalExpression /// </summary> /// <param name="expression"></param> public void Visit(LogicalExpression expression) { VisitorEventArgs <T> args = new VisitorEventArgs <T>(currentNode: expression, stack: _stack); // call the event VisitingLogicalExpression(this, args); // visit subnodes from left to right if (expression.Operator.Arguments >= 1) { Visit(expression.LeftOperand); } if (expression.Operator.Arguments >= 2) { Visit(expression.RightOperand); } // call the event VisitedLogicalExpression(this, args); }
private static void GetSimpleExpressions(ISearchExpression searchExpression, List <SimpleExpression> list) { if (searchExpression is SimpleExpression) { list.Add(searchExpression as SimpleExpression); } else if (searchExpression is LogicalExpression) { LogicalExpression le = searchExpression as LogicalExpression; if (le.LogicOperator == LogicalOperator.And || le.LogicOperator == LogicalOperator.Or) { GetSimpleExpressions(le.LeftHandSide, list); GetSimpleExpressions(le.RightHandSide, list); } else if (le.LogicOperator == LogicalOperator.Not) { GetSimpleExpressions(le.LeftHandSide, list); } } }
protected void EncapsulateNoValue(LogicalExpression expression) { if (expression is ValueExpression) { expression.Accept(this); } else { Result.Append("("); expression.Accept(this); // trim spaces before adding a closing paren while (Result[Result.Length - 1] == ' ') { Result.Remove(Result.Length - 1, 1); } Result.Append(") "); } }
/// <summary> /// Reads a logical expression. /// </summary> /// <param name="leftHandSide">The expression on the left hand side of the operator.</param> /// <param name="previousPrecedence">The precedence of the expression just before this one.</param> /// <param name="unsafeCode">Indicates whether the code being parsed resides in an unsafe code block.</param> /// <returns>Returns the expression.</returns> private LogicalExpression GetLogicalExpression( Expression leftHandSide, ExpressionPrecedence previousPrecedence, bool unsafeCode) { Param.AssertNotNull(leftHandSide, "leftHandSide"); Param.Ignore(previousPrecedence); Param.Ignore(unsafeCode); LogicalExpression expression = null; // Read the details of the expression. OperatorSymbol operatorToken = this.PeekOperatorToken(); Debug.Assert(operatorToken.Category == OperatorCategory.Logical, "Expected a logical operator"); // Check the precedence of the operators to make sure we can gather this statement now. ExpressionPrecedence precedence = this.GetOperatorPrecedence(operatorToken.SymbolType); if (this.CheckPrecedence(previousPrecedence, precedence)) { // Add the operator token to the document and advance the symbol manager up to it. this.symbols.Advance(); this.tokens.Add(operatorToken); // Get the expression on the right-hand side of the operator. Expression rightHandSide = this.GetOperatorRightHandExpression(precedence, unsafeCode); // Create the partial token list for the expression. CsTokenList partialTokens = new CsTokenList(this.tokens, leftHandSide.Tokens.First, this.tokens.Last); // Get the expression operator type. LogicalExpression.Operator type; switch (operatorToken.SymbolType) { case OperatorType.LogicalAnd: type = LogicalExpression.Operator.And; break; case OperatorType.LogicalOr: type = LogicalExpression.Operator.Or; break; case OperatorType.LogicalXor: type = LogicalExpression.Operator.Xor; break; default: Debug.Fail("Unexpected operator type"); throw new InvalidOperationException(); } // Create and return the expression. expression = new LogicalExpression(partialTokens, type, leftHandSide, rightHandSide); } return expression; }
public TernaryExpression(LogicalExpression leftExpression, LogicalExpression middleExpression, LogicalExpression rightExpression) { this.LeftExpression = leftExpression; this.MiddleExpression = middleExpression; this.RightExpression = rightExpression; }
private void AppendWhere(ISelectQuery query) { var where = new LogicalExpression { Operand1 = query.WhereExpressions[0], Operator = Operator.And }; foreach (var whereExpression in query.WhereExpressions.Skip(1)) { where.Operand2 = whereExpression; where = new LogicalExpression { Operand1 = where, Operator = Operator.And }; } var whereExp = where.Operand1; var builder = _meta.DbProvider.CreateWhereCommandBuilder(_meta); whereExp.Accept(builder); var whereCmd = builder.Build(); _cmd.AppendLine("WHERE") .AppendLine(whereCmd.CommandText); foreach (var sqlParameter in whereCmd.Parameters) { _param.Add(sqlParameter.Key, sqlParameter.Value); } }
public Function(Identifier identifier, LogicalExpression[] expressions) { Identifier = identifier; Expressions = expressions; }
public override void Visit(LogicalExpression e) { _expression.SetOperand(e); }
private Query BuildLogicalQuery() { LogicalExpression logicalExpression1 = new LogicalExpression(); logicalExpression1.Operator = LogicalOperator.And; //Top left LogicalExpression leftExpression1 = new LogicalExpression(); leftExpression1.Operator = LogicalOperator.And; ComparisonExpression comparisonLeft1 = new ComparisonExpression(); comparisonLeft1.ExpressionType = ExpressionType.Comparison; comparisonLeft1.Operator = ComparisonOperator.Greater; comparisonLeft1.LeftValue = new ComparisonValue { Value = "Account.CreditMax" }; comparisonLeft1.RightValue = new ComparisonValue { Value = 5000 }; //nested in left ComparisonExpression comparisonRight1 = new ComparisonExpression(); comparisonRight1.ExpressionType = ExpressionType.Comparison; comparisonRight1.Operator = ComparisonOperator.Greater; comparisonRight1.LeftValue = new ComparisonValue { Value = "Account.Profit" }; comparisonRight1.RightValue = new ComparisonValue { Value = 100 }; leftExpression1.LeftExpression = comparisonLeft1; leftExpression1.RightExpression = comparisonRight1; //Top Right LogicalExpression rightExpression = new LogicalExpression(); rightExpression.Operator = LogicalOperator.And; ComparisonExpression comparisonLeft2 = new ComparisonExpression(); comparisonLeft2.ExpressionType = ExpressionType.Comparison; comparisonLeft2.Operator = ComparisonOperator.Greater; comparisonLeft2.LeftValue = new ComparisonValue { Value = "Account.Revenue" }; comparisonLeft2.RightValue = new ComparisonValue { Value = 100 }; //nested in right ComparisonExpression comparisonRight2 = new ComparisonExpression(); comparisonRight2.ExpressionType = ExpressionType.Comparison; comparisonRight2.Operator = ComparisonOperator.Greater; comparisonRight2.LeftValue = new ComparisonValue { Value = "Account.CreditMin" }; comparisonRight2.RightValue = new ComparisonValue { Value = 100 }; rightExpression.LeftExpression = comparisonLeft2; rightExpression.RightExpression = comparisonRight2; logicalExpression1.LeftExpression = leftExpression1; logicalExpression1.RightExpression = rightExpression; var query = new Query { Constraints = logicalExpression1, }; return query; }
public UnaryExpression(UnaryExpressionType type, LogicalExpression expression) { Type = type; Expression = expression; }
public void VisitLogicalExpression(LogicalExpression logicalExpression) { object last = ReturnValue; VisitExpression(logicalExpression.Left); VisitExpression(logicalExpression.Right); ReturnValue = ReturnValue ?? last; }
public MainWindowModel() { CustomValidation = (s) => false; Expression = new LogicalExpression(new ComparisionExpression("First Name", "Ivan"), new ComparisionExpression("Age", "18")); }
public void QueryMultipleFilterWithOrderByValidTest() { string objectName = "ProductPriceLists"; //Create a basic root query entity, //Set the name property and the object definition full name property //Note: 'Name' property is unique and is set by the user // 'ObjectDefinitionFullName' property will be the name of the table referenced var rootEntity = new QueryEntity { Name = objectName, ObjectDefinitionFullName = objectName }; //Create a list of properties for the root entity, not these are column names rootEntity.PropertyList.Add("RecordId"); rootEntity.PropertyList.Add("ProductNumber"); rootEntity.PropertyList.Add("UnitPrice"); rootEntity.PropertyList.Add("BaseUoMQuantity"); //set the sequence direction and field to order by rootEntity.SequenceList.Add(new Sequence("UnitPrice", SequenceDirection.Descending)); //create a new comparison expression object // consider **** SELECT [QueryEntity.PropertyList] FROM [QueryEntity.ObjectDefinitionFullName] // **** WHERE [ComparisonExpression.LeftValue] [ComparisonExpression.Operator] [ComparisonExpression.RightValue] var leftComparisionExpression = new ComparisonExpression { ExpressionType = ExpressionType.Comparison, Operator = ComparisonOperator.Equal, LeftValue = new ComparisonValue(ComparisonValueType.Property, "ProductPriceLists.ProductNumber"), RightValue = new ComparisonValue(ComparisonValueType.Constant, "CONSULT") }; //create another comparison expression to add on the right of the AND clause var rightComparisionExpression = new ComparisonExpression { ExpressionType = ExpressionType.Comparison, Operator = ComparisonOperator.Less, LeftValue = new ComparisonValue(ComparisonValueType.Property, "ProductPriceLists.BaseUoMQuantity"), RightValue = new ComparisonValue(ComparisonValueType.Constant, 50) }; //create a new query object, and set the root entity var query = new Query { IsTestQuery = false, RootEntity = rootEntity }; //create a new logical expression indicating an AND clause in filtering of the query LogicalExpression logicalExpression = new LogicalExpression( //Sets the opertor for the expression LogicalOperator.And, //add the expressions leftComparisionExpression, rightComparisionExpression, //since this is the parent expressions there is no parent to indicate here so set it to null null); //set the contraints in the query query.Constraints = logicalExpression; //set the expression type for the query constraints query.Constraints.ExpressionType = ExpressionType.Logical; //set the parent expression for the right and left comparison expressions since they are now part of the logical expression leftComparisionExpression.ParentExpression = query.Constraints; rightComparisionExpression.ParentExpression = query.Constraints; var queryResults = _sysConnector.ExecuteQuery(query); //force a check of the query results foreach (var queryResult in queryResults) { break; } //validate that results have been returned Assert.IsNotNull(queryResults); Assert.AreNotEqual(0, queryResults.Count()); //validate that data has been returned Assert.AreNotEqual(0, queryResults.ElementAt(0).Properties.Count); //Verify the proper first an last values returned by the query Assert.AreEqual("5500", queryResults.First().Properties["UnitPrice"].ToString()); Assert.AreEqual("150", queryResults.Last().Properties["UnitPrice"].ToString()); }
public override void Visit(LogicalExpression e) { _expression.Operand = e; }
public abstract void Visit(LogicalExpression expression);
private Query CreateDateFilterQuery() { var query = new Query(); query.RootEntity.ObjectDefinitionFullName = "Webinar"; //Build the expressions var leftExpression = new ComparisonExpression { ExpressionType = ExpressionType.Comparison, LeftValue = new ComparisonValue { Value = "Webinar.StartTime", ValueType = ComparisonValueType.Property }, RightValue = new ComparisonValue { Value = new DateTime(2010, 01, 01), ValueType = ComparisonValueType.Property }, Operator = ComparisonOperator.Equal }; var rightExpression = new ComparisonExpression { ExpressionType = ExpressionType.Comparison, LeftValue = new ComparisonValue { Value = "Webinar.EndTime", ValueType = ComparisonValueType.Property }, RightValue = new ComparisonValue { Value = new DateTime(2013, 01, 01), ValueType = ComparisonValueType.Property }, Operator = ComparisonOperator.Equal }; var logical = new LogicalExpression { ExpressionType = ExpressionType.Logical, LeftExpression = leftExpression, RightExpression = rightExpression, Operator = LogicalOperator.And }; query.Constraints = logical; //we're adding the logical expression: // StartTime <= 1/1/2010 AND EndTime >= 1/1/2013 return query; }
public virtual void Visit(LogicalExpression e) { throw new NotSupportedException(); }
public BinaryExpression(BinaryExpressionType type, LogicalExpression leftExpression, LogicalExpression rightExpression) { Type = type; LeftExpression = leftExpression; RightExpression = rightExpression; }
public void UpdateMultipleRowsWithComparisonValidTest() { //create a new data entity DataEntity entity = new DataEntity(); //create a new operation input with a new entity array for the input property OperationInput operationInput = new OperationInput { Input = new DataEntity[1] }; //*** this allows multiple rows to be processed with one query operationInput.AllowMultipleObject = true; //set the first item in the input property entity.ObjectDefinitionFullName = "Addresses"; entity.Properties.Add("Country", "USA"); operationInput.Input[0] = entity; //set the name of the operation operationInput.Name = "update"; //create the right comparison experssion for selecting the records to update ComparisonExpression leftComparisonExpression = new ComparisonExpression(); leftComparisonExpression.ExpressionType = ExpressionType.Comparison; leftComparisonExpression.Operator = ComparisonOperator.IsNull; leftComparisonExpression.LeftValue = new ComparisonValue { ValueType = ComparisonValueType.Property, Value = "Phone" }; leftComparisonExpression.RightValue = null; //create the left comparison experssion for selecting the records to update ComparisonExpression rightComparisonExpression = new ComparisonExpression(); rightComparisonExpression.ExpressionType = ExpressionType.Comparison; rightComparisonExpression.Operator = ComparisonOperator.IsNull; rightComparisonExpression.LeftValue = new ComparisonValue { ValueType = ComparisonValueType.Property, Value = "AddressLine2" }; rightComparisonExpression.RightValue = null; //create a logical expression which will combine the left and right comparison expressions using an AND operator LogicalExpression logicalExpression = new LogicalExpression(); logicalExpression.ExpressionType = ExpressionType.Logical; logicalExpression.LeftExpression = leftComparisonExpression; logicalExpression.RightExpression = rightComparisonExpression; logicalExpression.Operator = LogicalOperator.And; //set the logical expression as the parent of the right and left comparison expressions leftComparisonExpression.ParentExpression = logicalExpression; rightComparisonExpression.ParentExpression = logicalExpression; operationInput.LookupCondition[0] = logicalExpression; //execute the operation from the connector OperationResult operationResult = _sysConnector.ExecuteOperation(operationInput); //validate that the operation was a success Assert.IsTrue(operationResult.Success[0]); //Validate the amount of rows that have been updated //NOTE: this will only work with a clean ScribeSampleRSSource database Assert.AreEqual(10, operationResult.ObjectsAffected[0]); }
public void SimpleAndFilterValidTest() { string objectName = "Addresses"; //Create a basic root query entity, //Set the name property and the object definition full name property //Note: 'Name' property is unique and is set by the user // 'ObjectDefinitionFullName' property will be the name of the table referenced var rootEntity = new QueryEntity { Name = objectName, ObjectDefinitionFullName = objectName }; //Create a list of properties for the root entity, not these are column names rootEntity.PropertyList.Add("RecordId"); rootEntity.PropertyList.Add("ContactName"); rootEntity.PropertyList.Add("ContactTitle"); rootEntity.PropertyList.Add("AddressType"); //create a new query object, and set the root entity var query = new Query { IsTestQuery = false, RootEntity = rootEntity }; //create a new comparison expression object // consider **** SELECT [QueryEntity.PropertyList] FROM [QueryEntity.ObjectDefinitionFullName] // **** WHERE [ComparisonExpression.LeftValue] [ComparisonExpression.Operator] [ComparisonExpression.RightValue] var leftComparisionExpression = new ComparisonExpression { ExpressionType = ExpressionType.Comparison, Operator = ComparisonOperator.Equal, LeftValue = new ComparisonValue(ComparisonValueType.Property, "Addresses.AddressType"), RightValue = new ComparisonValue(ComparisonValueType.Constant, "Main") }; //create another comparison expression to add on the right of the AND clause var rightComparisionExpression = new ComparisonExpression { ExpressionType = ExpressionType.Comparison, Operator = ComparisonOperator.Like, LeftValue = new ComparisonValue(ComparisonValueType.Property, "Addresses.ContactTitle"), RightValue = new ComparisonValue(ComparisonValueType.Constant, "President") }; //create a new logical expression indicating an AND clause in filtering of the query LogicalExpression logicalExpression = new LogicalExpression( //Sets the opertor for the expression LogicalOperator.And, //add the expressions leftComparisionExpression, rightComparisionExpression, //since this is the parent expressions there is no parent to indicate here so set it to null null); //set the contraints in the query query.Constraints = logicalExpression; //set the expression type for the query constraints query.Constraints.ExpressionType = ExpressionType.Logical; //set the parent expression for the right and left comparison expressions since they are now part of the logical expression leftComparisionExpression.ParentExpression = query.Constraints; rightComparisionExpression.ParentExpression = query.Constraints; var queryResults = _sysConnector.ExecuteQuery(query); //force a check of the query results foreach (var queryResult in queryResults) { break; } //validate that results have been returned Assert.IsNotNull(queryResults); Assert.AreNotEqual(0, queryResults.Count()); //validate that data has been returned Assert.AreNotEqual(0, queryResults.ElementAt(0).Properties.Count); //validate that the proper values are returned in the DataEntity properties Assert.AreEqual("President", queryResults.ElementAt(0).Properties["ContactTitle"].ToString()); Assert.AreEqual("Main", queryResults.ElementAt(0).Properties["AddressType"].ToString()); }