private static BoolExpression TileToBoolExpr(Tile <FragmentQuery> tile) { switch (tile.OpKind) { case TileOpKind.Union: return(BoolExpression.CreateOr(QueryRewriter.TileToBoolExpr(tile.Arg1), QueryRewriter.TileToBoolExpr(tile.Arg2))); case TileOpKind.Join: return(BoolExpression.CreateAnd(QueryRewriter.TileToBoolExpr(tile.Arg1), QueryRewriter.TileToBoolExpr(tile.Arg2))); case TileOpKind.AntiSemiJoin: return(BoolExpression.CreateAnd(QueryRewriter.TileToBoolExpr(tile.Arg1), BoolExpression.CreateNot(QueryRewriter.TileToBoolExpr(tile.Arg2)))); case TileOpKind.Named: FragmentQuery namedQuery = ((TileNamed <FragmentQuery>)tile).NamedQuery; if (namedQuery.Condition.IsAlwaysTrue()) { return(BoolExpression.True); } return(namedQuery.FromVariable); default: return((BoolExpression)null); } }
// <summary> // Takes in a JoinTreeNode and a Contition Property Map and creates an BoolExpression // for the Condition Map. // </summary> private static BoolExpression GetConditionExpression(MemberPath member, ConditionPropertyMapping conditionMap) { //Get the member for which the condition is being specified EdmMember conditionMember = (conditionMap.Column != null) ? conditionMap.Column : conditionMap.Property; var conditionMemberNode = new MemberPath(member, conditionMember); //Check if this is a IsNull condition MemberRestriction conditionExpression = null; if (conditionMap.IsNull.HasValue) { // for conditions on scalars, create NodeValue nodes, otherwise NodeType var conditionConstant = conditionMap.IsNull.Value ? Constant.Null : Constant.NotNull; if (MetadataHelper.IsNonRefSimpleMember(conditionMember)) { conditionExpression = new ScalarRestriction(conditionMemberNode, conditionConstant); } else { conditionExpression = new TypeRestriction(conditionMemberNode, conditionConstant); } } else { conditionExpression = new ScalarRestriction(conditionMemberNode, new ScalarConstant(conditionMap.Value)); } Debug.Assert(conditionExpression != null); return(BoolExpression.CreateLiteral(conditionExpression, null)); }
internal FragmentQuery GetDomainQuery( IEnumerable <FragmentQuery> fragmentQueries, EdmType generatedType) { if (this._context.ViewTarget != ViewTarget.QueryView) { return(FragmentQuery.Create((IEnumerable <MemberPath>) this._keyAttributes, BoolExpression.CreateOr(fragmentQueries.Select <FragmentQuery, BoolExpression>((Func <FragmentQuery, BoolExpression>)(fragmentQuery => fragmentQuery.Condition)).ToArray <BoolExpression>()))); } BoolExpression literal; if (generatedType == null) { literal = BoolExpression.True; } else { IEnumerable <EdmType> types; if (this._typesGenerationMode == ViewGenMode.OfTypeOnlyViews) { types = (IEnumerable <EdmType>) new HashSet <EdmType>() { this._generatedType } } ; else { types = MetadataHelper.GetTypeAndSubtypesOf(generatedType, (ItemCollection)this._context.EdmItemCollection, false); } literal = BoolExpression.CreateLiteral((BoolLiteral) new TypeRestriction(new MemberProjectedSlot(this._extentPath), new Domain(QueryRewriter.GetTypeConstants(types), this._domainMap.GetDomain(this._extentPath))), this._domainMap); } return(FragmentQuery.Create((IEnumerable <MemberPath>) this._keyAttributes, literal)); }
/// <summary> /// Initializes a <see cref="CqlBlock"/> with the SELECT (<paramref name="slotInfos"/>), FROM (<paramref name="children"/>), /// WHERE (<paramref name="whereClause"/>), AS (<paramref name="blockAliasNum"/>). /// </summary> protected CqlBlock(SlotInfo[] slotInfos, List <CqlBlock> children, BoolExpression whereClause, CqlIdentifiers identifiers, int blockAliasNum) { m_slots = new ReadOnlyCollection <SlotInfo>(slotInfos); m_children = new ReadOnlyCollection <CqlBlock>(children); m_whereClause = whereClause; m_blockAlias = identifiers.GetBlockAlias(blockAliasNum); }
// effects: Given the cells for the extent (extentCells) along with // the signatures (multiconstants + needed attributes) for this extent, generates // the left cell wrappers for it extent (viewTarget indicates whether // the view is for querying or update purposes // Modifies m_cellWrappers to contain this list private bool CreateLeftCellWrappers(IList <Cell> extentCells, ViewTarget viewTarget) { var alignedCells = AlignFields(extentCells, m_memberMaps.ProjectedSlotMap, viewTarget); Debug.Assert(alignedCells.Count == extentCells.Count, "Cell counts disagree"); // Go through all the cells and create cell wrappers that can be used for generating the view m_cellWrappers = new List <LeftCellWrapper>(); for (var i = 0; i < alignedCells.Count; i++) { var alignedCell = alignedCells[i]; var left = alignedCell.GetLeftQuery(viewTarget); var right = alignedCell.GetRightQuery(viewTarget); // Obtain the non-null projected slots into attributes var attributes = left.GetNonNullSlots(); var fromVariable = BoolExpression.CreateLiteral( new CellIdBoolean(m_identifiers, extentCells[i].CellNumber), m_memberMaps.LeftDomainMap); var leftFragmentQuery = FragmentQuery.Create(fromVariable, left); if (viewTarget == ViewTarget.UpdateView) { leftFragmentQuery = m_leftFragmentQP.CreateDerivedViewBySelectingConstantAttributes(leftFragmentQuery) ?? leftFragmentQuery; } var leftWrapper = new LeftCellWrapper( m_viewTarget, attributes, leftFragmentQuery, left, right, m_memberMaps, extentCells[i]); m_cellWrappers.Add(leftWrapper); } return(true); }
/// <summary> /// Initializes a <see cref="CqlBlock"/> with the SELECT (<paramref name="slotInfos"/>), FROM (<paramref name="children"/>), /// WHERE (<paramref name="whereClause"/>), AS (<paramref name="blockAliasNum"/>). /// </summary> protected CqlBlock(SlotInfo[] slotInfos, List<CqlBlock> children, BoolExpression whereClause, CqlIdentifiers identifiers, int blockAliasNum) { m_slots = new ReadOnlyCollection<SlotInfo>(slotInfos); m_children = new ReadOnlyCollection<CqlBlock>(children); m_whereClause = whereClause; m_blockAlias = identifiers.GetBlockAlias(blockAliasNum); }
public Then(BoolExpression condition, Action thenAction, Action elseAction, object cookie) { this.condition=condition; this.thenAction=thenAction; this.elseAction=elseAction; this.cookie=cookie; }
// Checks equivalence of two C-side queries // inExtentConstraint holds a role variable that effectively denotes that some extent is non-empty private bool CheckEquivalence( FragmentQuery cQuery, FragmentQuery sQuery, BoolExpression inExtentCondition, out BoolExpression unsatisfiedConstraint) { var cMinusSx = _viewgenContext.RightFragmentQP.Difference(cQuery, sQuery); var sMinusCx = _viewgenContext.RightFragmentQP.Difference(sQuery, cQuery); // add in-extent condition var cMinusS = FragmentQuery.Create(BoolExpression.CreateAnd(cMinusSx.Condition, inExtentCondition)); var sMinusC = FragmentQuery.Create(BoolExpression.CreateAnd(sMinusCx.Condition, inExtentCondition)); unsatisfiedConstraint = null; var forwardInclusion = true; var backwardInclusion = true; if (_viewgenContext.RightFragmentQP.IsSatisfiable(cMinusS)) { unsatisfiedConstraint = cMinusS.Condition; forwardInclusion = false; } if (_viewgenContext.RightFragmentQP.IsSatisfiable(sMinusC)) { unsatisfiedConstraint = sMinusC.Condition; backwardInclusion = false; } if (forwardInclusion && backwardInclusion) { return(true); } else { unsatisfiedConstraint.ExpensiveSimplify(); return(false); } }
private static BoolExpression CreateIsOfTypeCondition(MemberPath currentPath, IEnumerable <EdmType> derivedTypes, MemberDomainMap domainMap) { Domain typeDomain = new Domain(derivedTypes.Select(derivedType => (Constant) new TypeConstant(derivedType)), domainMap.GetDomain(currentPath)); BoolExpression typeCondition = BoolExpression.CreateLiteral(new TypeRestriction(new MemberProjectedSlot(currentPath), typeDomain), domainMap); return(typeCondition); }
internal void CreateEquivalenceConstraintForOneToOneForeignKeyAssociation(AssociationSet assocSet, MemberDomainMap domainMap, EdmItemCollection edmItemCollection) { AssociationType assocType = assocSet.ElementType; foreach (ReferentialConstraint constraint in assocType.ReferentialConstraints) { AssociationEndMember toEndMember = (AssociationEndMember)constraint.ToRole; AssociationEndMember fromEndMember = (AssociationEndMember)constraint.FromRole; EntitySet toEntitySet = MetadataHelper.GetEntitySetAtEnd(assocSet, toEndMember); EntitySet fromEntitySet = MetadataHelper.GetEntitySetAtEnd(assocSet, fromEndMember); // Check if the keys of the entitySet's are equal to what is specified in the constraint IEnumerable <EdmMember> toProperties = Helpers.AsSuperTypeList <EdmProperty, EdmMember>(constraint.ToProperties); if (Helpers.IsSetEqual(toProperties, toEntitySet.ElementType.KeyMembers, EqualityComparer <EdmMember> .Default)) { //make sure that the method called with a 1:1 association Debug.Assert(constraint.FromRole.RelationshipMultiplicity.Equals(RelationshipMultiplicity.One)); Debug.Assert(constraint.ToRole.RelationshipMultiplicity.Equals(RelationshipMultiplicity.One)); // Create an Equivalence between the two Sets participating in this AssociationSet BoolExpression fromSetExpression = BoolExpression.CreateLiteral(new RoleBoolean(fromEntitySet), domainMap); BoolExpression toSetExpression = BoolExpression.CreateLiteral(new RoleBoolean(toEntitySet), domainMap); AddEquivalence(fromSetExpression.Tree, toSetExpression.Tree); } } }
public Soway.Query.BoolExp.BoolExpression GetQueryExp(Soway.Service.Report.BoolExp exp, QueryModel model, Model.SqlCon con, Soway.Query.QueryInstance ins) { Soway.Query.BoolExp.BoolExpresstionFacotry fac = new Query.BoolExp.BoolExpresstionFacotry(ins); var result = new BoolExpression(); if (exp.Col != null) { //简单类型 var col = model.Columns.First(p => p.ID == exp.Col.ID); result.Exp = fac.CreateBoolExpression(new Query.CompareCol() { Col = col, SelectedTableName = model.Table.ShowName }, QueryCache.GetCompareType(con, col.DataType).First(p => p.ID.ToString() == exp.CompareOp.ID), exp.ValueExp, exp.ValueFmt, exp.ParamName); } else if (exp.FirstExp != null) { //复杂类型 result = GetQueryExp(exp.FirstExp, model, con, ins); foreach (var sequence in exp.Sequences) { fac.AddBoolExpression( result, sequence.BoolOp, GetQueryExp(sequence.AddedExp, model, con, ins)); } } return(result); }
internal FragmentQuery(string label, BoolExpression fromVariable, IEnumerable <MemberPath> attrs, BoolExpression condition) { m_label = label; m_fromVariable = fromVariable; m_condition = condition; m_attributes = new HashSet <MemberPath>(attrs); }
internal static void EntityConfigurationToUserString( BoolExpression condition, StringBuilder builder, bool writeRoundTrippingMessage) { condition.AsUserString(builder, "PK", writeRoundTrippingMessage); }
private bool CheckEquivalence( FragmentQuery cQuery, FragmentQuery sQuery, BoolExpression inExtentCondition, out BoolExpression unsatisfiedConstraint) { FragmentQuery fragmentQuery1 = this._viewgenContext.RightFragmentQP.Difference(cQuery, sQuery); FragmentQuery fragmentQuery2 = this._viewgenContext.RightFragmentQP.Difference(sQuery, cQuery); FragmentQuery query1 = FragmentQuery.Create(BoolExpression.CreateAnd(fragmentQuery1.Condition, inExtentCondition)); FragmentQuery query2 = FragmentQuery.Create(BoolExpression.CreateAnd(fragmentQuery2.Condition, inExtentCondition)); unsatisfiedConstraint = (BoolExpression)null; bool flag1 = true; bool flag2 = true; if (this._viewgenContext.RightFragmentQP.IsSatisfiable(query1)) { unsatisfiedConstraint = query1.Condition; flag1 = false; } if (this._viewgenContext.RightFragmentQP.IsSatisfiable(query2)) { unsatisfiedConstraint = query2.Condition; flag2 = false; } if (flag1 && flag2) { return(true); } unsatisfiedConstraint.ExpensiveSimplify(); return(false); }
internal static BoolExpression PropagateCellConstantsToWhereClause( LeftCellWrapper wrapper, BoolExpression expression, Constant constant, MemberPath member, MemberMaps memberMaps) { MemberProjectedSlot mappedSlotForSmember = wrapper.GetCSideMappedSlotForSMember(member); if (mappedSlotForSmember == null) { return(expression); } NegatedConstant negatedConstant = constant as NegatedConstant; IEnumerable <Constant> domain = memberMaps.QueryDomainMap.GetDomain(mappedSlotForSmember.MemberPath); Set <Constant> set = new Set <Constant>(Constant.EqualityComparer); if (negatedConstant != null) { set.Unite(domain); set.Difference(negatedConstant.Elements); } else { set.Add(constant); } MemberRestriction memberRestriction = (MemberRestriction) new ScalarRestriction(mappedSlotForSmember.MemberPath, (IEnumerable <Constant>)set, domain); return(BoolExpression.CreateAnd(expression, BoolExpression.CreateLiteral((BoolLiteral)memberRestriction, memberMaps.QueryDomainMap))); }
public Then(BoolExpression condition, Action thenAction, Action elseAction, object cookie) { this.condition = condition; this.thenAction = thenAction; this.elseAction = elseAction; this.cookie = cookie; }
private void ExtractProperties( IEnumerable <PropertyMapping> properties, MemberPath cNode, List <ProjectedSlot> cSlots, ref BoolExpression cQueryWhereClause, MemberPath sRootExtent, List <ProjectedSlot> sSlots, ref BoolExpression sQueryWhereClause) { foreach (PropertyMapping property in properties) { ScalarPropertyMapping scalarPropertyMapping = property as ScalarPropertyMapping; ComplexPropertyMapping complexPropertyMapping = property as ComplexPropertyMapping; EndPropertyMapping endPropertyMapping = property as EndPropertyMapping; ConditionPropertyMapping conditionMap = property as ConditionPropertyMapping; if (scalarPropertyMapping != null) { MemberPath node1 = new MemberPath(cNode, (EdmMember)scalarPropertyMapping.Property); MemberPath node2 = new MemberPath(sRootExtent, (EdmMember)scalarPropertyMapping.Column); cSlots.Add((ProjectedSlot) new MemberProjectedSlot(node1)); sSlots.Add((ProjectedSlot) new MemberProjectedSlot(node2)); } if (complexPropertyMapping != null) { foreach (ComplexTypeMapping typeMapping in complexPropertyMapping.TypeMappings) { MemberPath memberPath = new MemberPath(cNode, (EdmMember)complexPropertyMapping.Property); Set <EdmType> set = new Set <EdmType>(); IEnumerable <EdmType> elements = Helpers.AsSuperTypeList <ComplexType, EdmType>((IEnumerable <ComplexType>)typeMapping.Types); set.AddRange(elements); foreach (EdmType isOfType in typeMapping.IsOfTypes) { set.AddRange(MetadataHelper.GetTypeAndSubtypesOf(isOfType, (ItemCollection)this.m_containerMapping.StorageMappingItemCollection.EdmItemCollection, false)); } BoolExpression literal = BoolExpression.CreateLiteral((BoolLiteral) new TypeRestriction(memberPath, (IEnumerable <EdmType>)set), (MemberDomainMap)null); cQueryWhereClause = BoolExpression.CreateAnd(cQueryWhereClause, literal); this.ExtractProperties((IEnumerable <PropertyMapping>)typeMapping.AllProperties, memberPath, cSlots, ref cQueryWhereClause, sRootExtent, sSlots, ref sQueryWhereClause); } } if (endPropertyMapping != null) { MemberPath cNode1 = new MemberPath(cNode, (EdmMember)endPropertyMapping.AssociationEnd); this.ExtractProperties((IEnumerable <PropertyMapping>)endPropertyMapping.PropertyMappings, cNode1, cSlots, ref cQueryWhereClause, sRootExtent, sSlots, ref sQueryWhereClause); } if (conditionMap != null) { if (conditionMap.Column != null) { BoolExpression conditionExpression = CellCreator.GetConditionExpression(sRootExtent, conditionMap); sQueryWhereClause = BoolExpression.CreateAnd(sQueryWhereClause, conditionExpression); } else { BoolExpression conditionExpression = CellCreator.GetConditionExpression(cNode, conditionMap); cQueryWhereClause = BoolExpression.CreateAnd(cQueryWhereClause, conditionExpression); } } } }
private static IEnumerable <IInstruction> GetBoolExpressionInstructions(this BoolExpression boolExpression) { if (boolExpression.Value) { return(Iconst_1Instruction.AsList()); } return(Iconst_0Instruction.AsList()); }
/// <summary> /// Creates a boolean slot for expression that comes from originalCellNum, i.e., /// the value of the slot is <paramref name="expr"/> and the name is "_from{<paramref name="originalCellNum"/>}", e.g., _from2 /// </summary> internal BooleanProjectedSlot(BoolExpression expr, CqlIdentifiers identifiers, int originalCellNum) { m_expr = expr; m_originalCell = new CellIdBoolean(identifiers, originalCellNum); Debug.Assert(!(expr.AsLiteral is CellIdBoolean) || BoolLiteral.EqualityComparer.Equals((CellIdBoolean)expr.AsLiteral, m_originalCell), "Cellid boolean for the slot and cell number disagree"); }
internal BooleanProjectedSlot( BoolExpression expr, CqlIdentifiers identifiers, int originalCellNum) { this.m_expr = expr; this.m_originalCell = new CellIdBoolean(identifiers, originalCellNum); }
public static FragmentQuery Create(BoolExpression fromVariable, CellQuery cellQuery) { BoolExpression whereClause = cellQuery.WhereClause; whereClause = whereClause.MakeCopy(); whereClause.ExpensiveSimplify(); return(new FragmentQuery(null /*label*/, fromVariable, new HashSet <MemberPath>(cellQuery.GetProjectedMembers()), whereClause)); }
public static FragmentQuery Create( BoolExpression fromVariable, CellQuery cellQuery) { BoolExpression condition = cellQuery.WhereClause.MakeCopy(); condition.ExpensiveSimplify(); return(new FragmentQuery((string)null, fromVariable, (IEnumerable <MemberPath>) new HashSet <MemberPath>(cellQuery.GetProjectedMembers()), condition)); }
internal override FragmentQuery Intersect(FragmentQuery q1, FragmentQuery q2) { HashSet <MemberPath> memberPathSet = new HashSet <MemberPath>((IEnumerable <MemberPath>)q1.Attributes); memberPathSet.IntersectWith((IEnumerable <MemberPath>)q2.Attributes); BoolExpression and = BoolExpression.CreateAnd(q1.Condition, q2.Condition); return(FragmentQuery.Create((IEnumerable <MemberPath>)memberPathSet, and)); }
internal override FragmentQuery Intersect(FragmentQuery q1, FragmentQuery q2) { var attributes = new HashSet <MemberPath>(q1.Attributes); attributes.IntersectWith(q2.Attributes); var condition = BoolExpression.CreateAnd(q1.Condition, q2.Condition); return(FragmentQuery.Create(attributes, condition)); }
private bool FindRewritingAndUsedViews( IEnumerable <MemberPath> attributes, BoolExpression whereClause, HashSet <FragmentQuery> outputUsedViews, out Tile <FragmentQuery> rewriting) { IEnumerable <MemberPath> notCoveredAttributes; return(this.FindRewritingAndUsedViews(attributes, whereClause, outputUsedViews, out rewriting, out notCoveredAttributes)); }
public static FragmentQuery Create( string label, RoleBoolean roleBoolean, CellQuery cellQuery) { BoolExpression condition = BoolExpression.CreateAnd(cellQuery.WhereClause.Create((BoolLiteral)roleBoolean), cellQuery.WhereClause).MakeCopy(); condition.ExpensiveSimplify(); return(new FragmentQuery(label, (BoolExpression)null, (IEnumerable <MemberPath>) new HashSet <MemberPath>(), condition)); }
private void CreateVariableConstraintsRecursion(EdmType edmType, MemberPath currentPath, MemberDomainMap domainMap, EdmItemCollection edmItemCollection) { // Add the types can member have, i.e., its type and its subtypes HashSet <EdmType> possibleTypes = new HashSet <EdmType>(); possibleTypes.UnionWith(MetadataHelper.GetTypeAndSubtypesOf(edmType, edmItemCollection, true)); foreach (EdmType possibleType in possibleTypes) { // determine type domain HashSet <EdmType> derivedTypes = new HashSet <EdmType>(); derivedTypes.UnionWith(MetadataHelper.GetTypeAndSubtypesOf(possibleType, edmItemCollection, false)); if (derivedTypes.Count != 0) { BoolExpression typeCondition = CreateIsOfTypeCondition(currentPath, derivedTypes, domainMap); BoolExpression typeConditionComplement = BoolExpression.CreateNot(typeCondition); if (false == typeConditionComplement.IsSatisfiable()) { continue; } StructuralType structuralType = (StructuralType)possibleType; foreach (EdmProperty childProperty in structuralType.GetDeclaredOnlyMembers <EdmProperty>()) { MemberPath childPath = new MemberPath(currentPath, childProperty); bool isScalar = MetadataHelper.IsNonRefSimpleMember(childProperty); if (domainMap.IsConditionMember(childPath) || domainMap.IsProjectedConditionMember(childPath)) { BoolExpression nullCondition; List <Constant> childDomain = new List <Constant>(domainMap.GetDomain(childPath)); if (isScalar) { nullCondition = BoolExpression.CreateLiteral(new ScalarRestriction(new MemberProjectedSlot(childPath), new Domain(ScalarConstant.Undefined, childDomain)), domainMap); } else { nullCondition = BoolExpression.CreateLiteral(new TypeRestriction(new MemberProjectedSlot(childPath), new Domain(TypeConstant.Undefined, childDomain)), domainMap); } // Properties not occuring in type are UNDEFINED AddEquivalence(typeConditionComplement.Tree, nullCondition.Tree); } // recurse into complex types if (false == isScalar) { CreateVariableConstraintsRecursion(childPath.EdmType, childPath, domainMap, edmItemCollection); } } } } }
public static FragmentQuery Create(string label, RoleBoolean roleBoolean, CellQuery cellQuery) { BoolExpression whereClause = cellQuery.WhereClause.Create(roleBoolean); whereClause = BoolExpression.CreateAnd(whereClause, cellQuery.WhereClause); //return new FragmentQuery(label, null /* fromVariable */, new HashSet<MemberPath>(cellQuery.GetProjectedMembers()), whereClause); // don't need any attributes whereClause = whereClause.MakeCopy(); whereClause.ExpensiveSimplify(); return(new FragmentQuery(label, null /* fromVariable */, new HashSet <MemberPath>(), whereClause)); }
internal static BoolExpression CreateMemberCondition( MemberPath path, Constant domainValue, MemberDomainMap domainMap) { if (domainValue is TypeConstant) { return(BoolExpression.CreateLiteral((BoolLiteral) new TypeRestriction(new MemberProjectedSlot(path), new Domain(domainValue, domainMap.GetDomain(path))), domainMap)); } return(BoolExpression.CreateLiteral((BoolLiteral) new ScalarRestriction(new MemberProjectedSlot(path), new Domain(domainValue, domainMap.GetDomain(path))), domainMap)); }
/// <summary> /// Creates an cql block representing the <paramref name="extent"/> (the FROM part). /// SELECT is given by <paramref name="slots"/>, WHERE by <paramref name="whereClause"/> and AS by <paramref name="blockAliasNum"/>. /// </summary> internal ExtentCqlBlock(EntitySetBase extent, CellQuery.SelectDistinct selectDistinct, SlotInfo[] slots, BoolExpression whereClause, CqlIdentifiers identifiers, int blockAliasNum) : base(slots, EmptyChildren, whereClause, identifiers, blockAliasNum) { m_extent = extent; m_nodeTableAlias = identifiers.GetBlockAlias(); m_selectDistinct = selectDistinct; }
private static List <BoolExpression> MergeBoolExpressions( CellQuery query1, CellQuery query2, BoolExpression conjunct1, BoolExpression conjunct2, CellTreeOpType opType) { List <BoolExpression> bools1 = query1.BoolVars; List <BoolExpression> bools2 = query2.BoolVars; if (!conjunct1.IsTrue) { bools1 = BoolExpression.AddConjunctionToBools(bools1, conjunct1); } if (!conjunct2.IsTrue) { bools2 = BoolExpression.AddConjunctionToBools(bools2, conjunct2); } List <BoolExpression> boolExpressionList = new List <BoolExpression>(); for (int index = 0; index < bools1.Count; ++index) { BoolExpression boolExpression = (BoolExpression)null; if (bools1[index] == null) { boolExpression = bools2[index]; } else if (bools2[index] == null) { boolExpression = bools1[index]; } else { switch (opType) { case CellTreeOpType.Union: boolExpression = BoolExpression.CreateOr(bools1[index], bools2[index]); break; case CellTreeOpType.IJ: boolExpression = BoolExpression.CreateAnd(bools1[index], bools2[index]); break; case CellTreeOpType.LASJ: boolExpression = BoolExpression.CreateAnd(bools1[index], BoolExpression.CreateNot(bools2[index])); break; } } boolExpression?.ExpensiveSimplify(); boolExpressionList.Add(boolExpression); } return(boolExpressionList); }
private bool IsSatisfiable(BoolExpression condition) { // instantiate conversion context for each check - gives better performance BoolExpression conditionUnderKB = condition.Create( new AndExpr <BoolDomainConstraint>(_kb.KbExpression, condition.Tree)); var context = IdentifierService <BoolDomainConstraint> .Instance.CreateConversionContext(); var converter = new Converter <BoolDomainConstraint>(conditionUnderKB.Tree, context); bool isSatisfiable = converter.Vertex.IsZero() == false; return(isSatisfiable); }
// effects: Given all the fields, just sets them. internal CellQuery( ProjectedSlot[] projectedSlots, BoolExpression whereClause, List<BoolExpression> boolExprs, SelectDistinct elimDupl, MemberPath rootMember) { m_boolExprs = boolExprs; m_projectedSlots = projectedSlots; m_whereClause = whereClause; m_originalWhereClause = whereClause; m_selectDistinct = elimDupl; m_extentMemberPath = rootMember; }
/// <summary> /// Given the generated <paramref name="view"/>, the <paramref name="caseStatements"/> for the multiconstant fields, /// the <paramref name="projectedSlotMap"/> that maps different paths of the entityset (for which the view is being generated) to slot indexes in the view, /// creates an object that is capable of generating the Cql for <paramref name="view"/>. /// </summary> internal CqlGenerator(CellTreeNode view, Dictionary<MemberPath, CaseStatement> caseStatements, CqlIdentifiers identifiers, MemberProjectionIndex projectedSlotMap, int numCellsInView, BoolExpression topLevelWhereClause, StorageMappingItemCollection mappingItemCollection) { m_view = view; m_caseStatements = caseStatements; m_projectedSlotMap = projectedSlotMap; m_numBools = numCellsInView; // We have that many booleans m_topLevelWhereClause = topLevelWhereClause; m_identifiers = identifiers; m_mappingItemCollection = mappingItemCollection; }
// requires: The CellConstantDomains in the OneOfConsts of the where // clause are partially done // effects: Given the domains of different variables in domainMap, // fixes the whereClause of this such that all the // CellConstantDomains in OneOfConsts are complete internal void UpdateWhereClause(MemberDomainMap domainMap) { var atoms = new List<BoolExpression>(); foreach (var atom in WhereClause.Atoms) { var literal = atom.AsLiteral; var restriction = literal as MemberRestriction; Debug.Assert(restriction != null, "All bool literals must be OneOfConst at this point"); // The oneOfConst needs to be fixed with the new possible values from the domainMap. var possibleValues = domainMap.GetDomain(restriction.RestrictedMemberSlot.MemberPath); var newOneOf = restriction.CreateCompleteMemberRestriction(possibleValues); // Prevent optimization of single constraint e.g: "300 in (300)" // But we want to optimize type constants e.g: "category in (Category)" // To prevent optimization of bool expressions we add a Sentinel OneOF var scalarConst = restriction as ScalarRestriction; var addSentinel = scalarConst != null && !scalarConst.Domain.Contains(Constant.Null) && !scalarConst.Domain.Contains(Constant.NotNull) && !scalarConst.Domain.Contains(Constant.Undefined); if (addSentinel) { domainMap.AddSentinel(newOneOf.RestrictedMemberSlot.MemberPath); } atoms.Add(BoolExpression.CreateLiteral(newOneOf, domainMap)); if (addSentinel) { domainMap.RemoveSentinel(newOneOf.RestrictedMemberSlot.MemberPath); } } // We create a new whereClause that has the memberDomainMap set if (atoms.Count > 0) { m_whereClause = BoolExpression.CreateAnd(atoms.ToArray()); } }
// effects: Creates a cell query with the given projection (slots), // from part (joinTreeRoot) and the predicate (whereClause) // Used for cell creation internal CellQuery(List<ProjectedSlot> slots, BoolExpression whereClause, MemberPath rootMember, SelectDistinct eliminateDuplicates) : this(slots.ToArray(), whereClause, new List<BoolExpression>(), eliminateDuplicates, rootMember) { }
private void AddUnrecoverableAttributesError( IEnumerable<MemberPath> attributes, BoolExpression domainAddedWhereClause, ErrorLog errorLog) { var builder = new StringBuilder(); var extentName = StringUtil.FormatInvariant("{0}", _extentPath); var tableString = Strings.ViewGen_Extent; var attributesString = StringUtil.ToCommaSeparatedString(GetTypeBasedMemberPathList(attributes)); builder.AppendLine(Strings.ViewGen_Cannot_Recover_Attributes(attributesString, tableString, extentName)); RewritingValidator.EntityConfigurationToUserString(domainAddedWhereClause, builder); var record = new ErrorLog.Record( ViewGenErrorCode.AttributesUnrecoverable, builder.ToString(), _context.AllWrappersForExtent, String.Empty); errorLog.AddEntry(record); }
MergeBoolExpressions(CellQuery query1, CellQuery query2, BoolExpression conjunct1, BoolExpression conjunct2, CellTreeOpType opType) { List<BoolExpression> bools1 = query1.BoolVars; List<BoolExpression> bools2 = query2.BoolVars; // Add conjuncts to both sets if needed if (false == conjunct1.IsTrue) { bools1 = BoolExpression.AddConjunctionToBools(bools1, conjunct1); } if (false == conjunct2.IsTrue) { bools2 = BoolExpression.AddConjunctionToBools(bools2, conjunct2); } // Perform merge Debug.Assert(bools1.Count == bools2.Count); List<BoolExpression> bools = new List<BoolExpression>(); // Both bools1[i] and bools2[i] be null for some of the i's. When // we merge two (leaf) cells (say), only one boolean each is set // in it; the rest are all nulls. If the SP/TM rules have been // applied, more than one boolean may be non-null in a cell query for (int i = 0; i < bools1.Count; i++) { BoolExpression merged = null; if (bools1[i] == null) { merged = bools2[i]; } else if (bools2[i] == null) { merged = bools1[i]; } else { if (opType == CellTreeOpType.IJ) { merged = BoolExpression.CreateAnd(bools1[i], bools2[i]); } else if (opType == CellTreeOpType.Union) { merged = BoolExpression.CreateOr(bools1[i], bools2[i]); } else if (opType == CellTreeOpType.LASJ) { merged = BoolExpression.CreateAnd(bools1[i], BoolExpression.CreateNot(bools2[i])); } else { Debug.Fail("No other operation expected for boolean merge"); } } if (merged != null) { merged.ExpensiveSimplify(); } bools.Add(merged); } return bools; }
// requires: "properties" corresponds to all the properties that are // inside cNode.Value, e.g., cNode corresponds to an extent Person, // properties contains all the properties inside Person (recursively) // effects: Given C-side and S-side Cell Query for a cell, generates // the projected slots on both sides corresponding to // properties. Also updates the C-side whereclause corresponding to // discriminator properties on the C-side, e.g, isHighPriority private void ExtractProperties( IEnumerable<StoragePropertyMapping> properties, MemberPath cNode, List<ProjectedSlot> cSlots, ref BoolExpression cQueryWhereClause, MemberPath sRootExtent, List<ProjectedSlot> sSlots, ref BoolExpression sQueryWhereClause) { // For each property mapping, we add an entry to the C and S cell queries foreach (var propMap in properties) { var scalarPropMap = propMap as StorageScalarPropertyMapping; var complexPropMap = propMap as StorageComplexPropertyMapping; var associationEndPropertypMap = propMap as StorageEndPropertyMapping; var conditionMap = propMap as StorageConditionPropertyMapping; Debug.Assert( scalarPropMap != null || complexPropMap != null || associationEndPropertypMap != null || conditionMap != null, "Unimplemented property mapping"); if (scalarPropMap != null) { Debug.Assert(scalarPropMap.ColumnProperty != null, "ColumnMember for a Scalar Property can not be null"); // Add an attribute node to node var cAttributeNode = new MemberPath(cNode, scalarPropMap.EdmProperty); // Add a column (attribute) node the sQuery // unlike the C side, there is no nesting. Hence we // did not need an internal node var sAttributeNode = new MemberPath(sRootExtent, scalarPropMap.ColumnProperty); cSlots.Add(new MemberProjectedSlot(cAttributeNode)); sSlots.Add(new MemberProjectedSlot(sAttributeNode)); } // Note: S-side constants are not allowed since they can cause // problems -- for example, if such a cell says 5 for the // third field, we cannot guarantee the fact that an // application may not set that field to 7 in the C-space // Check if the property mapping is for a complex types if (complexPropMap != null) { foreach (var complexTypeMap in complexPropMap.TypeMappings) { // Create a node for the complex type property and call recursively var complexMemberNode = new MemberPath(cNode, complexPropMap.EdmProperty); //Get the list of types that this type map represents var allTypes = new Set<EdmType>(); // Gather a set of all explicit types for an entity // type mapping in allTypes. var exactTypes = Helpers.AsSuperTypeList<ComplexType, EdmType>(complexTypeMap.Types); allTypes.AddRange(exactTypes); foreach (EdmType type in complexTypeMap.IsOfTypes) { allTypes.AddRange( MetadataHelper.GetTypeAndSubtypesOf( type, m_containerMapping.StorageMappingItemCollection.EdmItemCollection, false /*includeAbstractTypes*/)); } var complexInTypes = BoolExpression.CreateLiteral(new TypeRestriction(complexMemberNode, allTypes), null); cQueryWhereClause = BoolExpression.CreateAnd(cQueryWhereClause, complexInTypes); // Now extract the properties of the complex type // (which could have other complex types) ExtractProperties( complexTypeMap.AllProperties, complexMemberNode, cSlots, ref cQueryWhereClause, sRootExtent, sSlots, ref sQueryWhereClause); } } // Check if the property mapping is for an associaion if (associationEndPropertypMap != null) { // create join tree node representing this relation end var associationEndNode = new MemberPath(cNode, associationEndPropertypMap.EndMember); // call recursively ExtractProperties( associationEndPropertypMap.Properties, associationEndNode, cSlots, ref cQueryWhereClause, sRootExtent, sSlots, ref sQueryWhereClause); } //Check if the this is a condition and add it to the Where clause if (conditionMap != null) { if (conditionMap.ColumnProperty != null) { //Produce a Condition Expression for the Condition Map. var conditionExpression = GetConditionExpression(sRootExtent, conditionMap); //Add the condition expression to the exisiting S side Where clause using an "And" sQueryWhereClause = BoolExpression.CreateAnd(sQueryWhereClause, conditionExpression); } else { Debug.Assert(conditionMap.EdmProperty != null); //Produce a Condition Expression for the Condition Map. var conditionExpression = GetConditionExpression(cNode, conditionMap); //Add the condition expression to the exisiting C side Where clause using an "And" cQueryWhereClause = BoolExpression.CreateAnd(cQueryWhereClause, conditionExpression); } } } }
protected BinaryBoolExpression(BoolExpression lhs, BoolExpression rhs) { this.lhs=lhs; this.rhs=rhs; }
/// <summary> /// Adds an expression of the form "WHEN <paramref name="condition" /> THEN <paramref name="value" />". /// This operation is not allowed after the <see cref="Simplify" /> call. /// </summary> internal void AddWhenThen(BoolExpression condition, ProjectedSlot value) { Debug.Assert(!m_simplified, "Attempt to modify a simplified case statement"); DebugCheck.NotNull(value); condition.ExpensiveSimplify(); m_clauses.Add(new WhenThen(condition, value)); }
/// <summary> /// Creates WHEN condition THEN value. /// </summary> internal WhenThen(BoolExpression condition, ProjectedSlot value) { m_condition = condition; m_value = value; }
// make sure that we can find a rewriting for each possible entity shape appearing in an extent // Possible optimization for OfType view generation: // Cache "used views" for each (currentPath, domainValue) combination private void EnsureConfigurationIsFullyMapped( MemberPath currentPath, BoolExpression currentWhereClause, HashSet<FragmentQuery> outputUsedViews, ErrorLog errorLog) { foreach (var domainValue in GetDomain(currentPath)) { if (domainValue == Constant.Undefined) { continue; // no point in trying to recover a situation that can never happen } TraceVerbose("REWRITING FOR {0}={1}", currentPath, domainValue); // construct WHERE clause for this value var domainAddedWhereClause = CreateMemberCondition(currentPath, domainValue); // AND the current where clause to it var domainWhereClause = BoolExpression.CreateAnd(currentWhereClause, domainAddedWhereClause); // first check whether we can recover instances of this type - don't care about the attributes - to produce a helpful error message Tile<FragmentQuery> rewriting; if (false == FindRewritingAndUsedViews(_keyAttributes, domainWhereClause, outputUsedViews, out rewriting)) { if (!ErrorPatternMatcher.FindMappingErrors(_context, _domainMap, _errorLog)) { var builder = new StringBuilder(); var extentName = StringUtil.FormatInvariant("{0}", _extentPath); var whereClause = rewriting.Query.Condition; whereClause.ExpensiveSimplify(); if (whereClause.RepresentsAllTypeConditions) { var tableString = Strings.ViewGen_Extent; builder.AppendLine(Strings.ViewGen_Cannot_Recover_Types(tableString, extentName)); } else { var entitiesString = Strings.ViewGen_Entities; builder.AppendLine(Strings.ViewGen_Cannot_Disambiguate_MultiConstant(entitiesString, extentName)); } RewritingValidator.EntityConfigurationToUserString(whereClause, builder); var record = new ErrorLog.Record( ViewGenErrorCode.AmbiguousMultiConstants, builder.ToString(), _context.AllWrappersForExtent, String.Empty); errorLog.AddEntry(record); } } else { var typeConstant = domainValue as TypeConstant; if (typeConstant != null) { // we are enumerating types var edmType = typeConstant.EdmType; // If can recover the type, make sure can get all the necessary attributes (key is included for EntityTypes) var nonConditionalAttributes = GetNonConditionalScalarMembers(edmType, currentPath, _domainMap).Union( GetNonConditionalComplexMembers(edmType, currentPath, _domainMap)).ToList(); IEnumerable<MemberPath> notCoverdAttributes; if (nonConditionalAttributes.Count > 0 && !FindRewritingAndUsedViews( nonConditionalAttributes, domainWhereClause, outputUsedViews, out rewriting, out notCoverdAttributes)) { //Error: No mapping specified for some attributes // remove keys nonConditionalAttributes = new List<MemberPath>(nonConditionalAttributes.Where(a => !a.IsPartOfKey)); Debug.Assert(nonConditionalAttributes.Count > 0, "Must have caught key-only case earlier"); AddUnrecoverableAttributesError(notCoverdAttributes, domainAddedWhereClause, errorLog); } else { // recurse into complex members foreach (var complexMember in GetConditionalComplexMembers(edmType, currentPath, _domainMap)) { EnsureConfigurationIsFullyMapped(complexMember, domainWhereClause, outputUsedViews, errorLog); } // recurse into scalar members foreach (var scalarMember in GetConditionalScalarMembers(edmType, currentPath, _domainMap)) { EnsureConfigurationIsFullyMapped(scalarMember, domainWhereClause, outputUsedViews, errorLog); } } } } } }
public If(BoolExpression condition) { this.condition=condition; this.cookie=FuncBuilder.Instance.StartInflightUtterance("If requires an Endif"); }
public WithOptionalElse(BoolExpression condition, Action thenAction, Action elseAction, object cookie) : base(condition, thenAction, elseAction, cookie) { }
private IEnumerable<MemberRestriction> GetConjunctsFromWhereClause(BoolExpression whereClause) { foreach (var boolExpr in whereClause.Atoms) { if (boolExpr.IsTrue) { continue; } var result = boolExpr.AsLiteral as MemberRestriction; Debug.Assert(result != null, "Atom must be restriction"); yield return result; } }
// <summary> // Copy Constructor // </summary> internal CellQuery(CellQuery source) { m_basicCellRelation = source.m_basicCellRelation; m_boolExprs = source.m_boolExprs; m_selectDistinct = source.m_selectDistinct; m_extentMemberPath = source.m_extentMemberPath; m_originalWhereClause = source.m_originalWhereClause; m_projectedSlots = source.m_projectedSlots; m_whereClause = source.m_whereClause; }
// Find rewriting for query SELECT <attributes> WHERE <whereClause> FROM _extentPath private bool FindRewriting( IEnumerable<MemberPath> attributes, BoolExpression whereClause, out Tile<FragmentQuery> rewriting, out IEnumerable<MemberPath> notCoveredAttributes) { Tile<FragmentQuery> toFill = CreateTile(FragmentQuery.Create(attributes, whereClause)); Debug.Assert(toFill.Query.Attributes.Count > 0, "Query has no attributes?"); Tile<FragmentQuery> toAvoid = CreateTile(FragmentQuery.Create(_keyAttributes, BoolExpression.CreateNot(whereClause))); var isRelaxed = (_context.ViewTarget == ViewTarget.UpdateView); var found = RewriteQuery(toFill, toAvoid, out rewriting, out notCoveredAttributes, isRelaxed); Debug.Assert( !found || rewriting.GetNamedQueries().All(q => q != _trueViewSurrogate.Query), "TrueViewSurrogate should have been substituted"); return found; }
public While(BoolExpression condition) { this.condition=condition; this.cookie=FuncBuilder.Instance.StartInflightUtterance("While requires a Do"); }
// Generates the components used to assemble and validate the view: // (1) case statements // (2) top-level where clause // (3) used cells // (4) basic view CellTreeNode // (5) dictionary<MemberValue, CellTreeNode> for validation internal void GenerateViewComponents() { // make sure everything is mapped (for query views only) EnsureExtentIsFullyMapped(_usedViews); // (1) case statements GenerateCaseStatements(_domainMap.ConditionMembers(_extentPath.Extent), _usedViews); AddTrivialCaseStatementsForConditionMembers(); if (_usedViews.Count == 0 || _errorLog.Count > 0) { // can't continue: no view will be generated, further validation doesn't make sense Debug.Assert(_errorLog.Count > 0); ExceptionHelpers.ThrowMappingException(_errorLog, _config); } // (2) top-level where clause _topLevelWhereClause = GetTopLevelWhereClause(_usedViews); // some tracing if (_context.ViewTarget == ViewTarget.QueryView) { TraceVerbose("Used {0} views of {1} total for rewriting", _usedViews.Count, _views.Count); } PrintStatistics(_qp); // (3) construct the final _from variables _usedCells = RemapFromVariables(); // (4) construct basic view var basicViewGenerator = new BasicViewGenerator( _context.MemberMaps.ProjectedSlotMap, _usedCells, _domainQuery, _context, _domainMap, _errorLog, _config); _basicView = basicViewGenerator.CreateViewExpression(); // a top-level WHERE clause is needed only if the simplifiedView still contains extra tuples var noWhereClauseNeeded = _context.LeftFragmentQP.IsContainedIn(_basicView.LeftFragmentQuery, _domainQuery); if (noWhereClauseNeeded) { _topLevelWhereClause = BoolExpression.True; } if (_errorLog.Count > 0) { ExceptionHelpers.ThrowMappingException(_errorLog, _config); } }
internal CaseCqlBlock( SlotInfo[] slots, int caseSlot, CqlBlock child, BoolExpression whereClause, CqlIdentifiers identifiers, int blockAliasNum) : base(slots, new List<CqlBlock>(new[] { child }), whereClause, identifiers, blockAliasNum) { m_caseSlotInfo = slots[caseSlot]; }
// Find rewriting for query SELECT <attributes> WHERE <whereClause> FROM _extentPath // and add view appearing in rewriting to outputUsedViews private bool FindRewritingAndUsedViews( IEnumerable<MemberPath> attributes, BoolExpression whereClause, HashSet<FragmentQuery> outputUsedViews, out Tile<FragmentQuery> rewriting, out IEnumerable<MemberPath> notCoveredAttributes) { if (FindRewriting(attributes, whereClause, out rewriting, out notCoveredAttributes)) { outputUsedViews.UnionWith(rewriting.GetNamedQueries()); return true; } return false; }
// Modifies _caseStatements and _topLevelWhereClause private List<LeftCellWrapper> RemapFromVariables() { var usedCells = new List<LeftCellWrapper>(); // remap CellIdBooleans appearing in WHEN clauses and in topLevelWhereClause so the first used cell = 0, second = 1, etc. // This ordering is exploited in CQL generation var newNumber = 0; var literalRemap = new Dictionary<BoolLiteral, BoolLiteral>(BoolLiteral.EqualityIdentifierComparer); foreach (var leftCellWrapper in _context.AllWrappersForExtent) { if (_usedViews.Contains(leftCellWrapper.FragmentQuery)) { usedCells.Add(leftCellWrapper); var oldNumber = leftCellWrapper.OnlyInputCell.CellNumber; if (newNumber != oldNumber) { literalRemap[new CellIdBoolean(_identifiers, oldNumber)] = new CellIdBoolean(_identifiers, newNumber); } newNumber++; } } if (literalRemap.Count > 0) { // Remap _from literals in WHERE clause _topLevelWhereClause = _topLevelWhereClause.RemapLiterals(literalRemap); // Remap _from literals in case statements var newCaseStatements = new Dictionary<MemberPath, CaseStatement>(); foreach (var entry in _caseStatements) { var newCaseStatement = new CaseStatement(entry.Key); Debug.Assert(entry.Value.ElseValue == null); foreach (var clause in entry.Value.Clauses) { newCaseStatement.AddWhenThen(clause.Condition.RemapLiterals(literalRemap), clause.Value); } newCaseStatements[entry.Key] = newCaseStatement; } _caseStatements = newCaseStatements; } return usedCells; }
// Find rewriting for query SELECT <attributes> WHERE <whereClause> FROM _extentPath // and add view appearing in rewriting to outputUsedViews private bool FindRewritingAndUsedViews( IEnumerable<MemberPath> attributes, BoolExpression whereClause, HashSet<FragmentQuery> outputUsedViews, out Tile<FragmentQuery> rewriting) { IEnumerable<MemberPath> notCoveredAttributes; return FindRewritingAndUsedViews( attributes, whereClause, outputUsedViews, out rewriting, out notCoveredAttributes); }