public void RemoveBackwardEdges(EdgeKey myEdgeKey) { lock (_lockObj) { _BackwardEdges.Remove(myEdgeKey); } }
public void RemoveForwardEdges(EdgeKey myEdgeKey) { lock (_lockObj) { _ForwardEdges.Remove(myEdgeKey); } }
public void AddNodeAndBackwardEdge(LevelKey myPath, IVertex aVertex, EdgeKey backwardDirection, VertexInformation backwardDestination, IComparable EdgeWeight, IComparable NodeWeight) { lock (_Content) { var node = GenerateVertexInfoFromLevelKeyAndVertexID(aVertex.VertexTypeID, aVertex.VertexID); if (_Content.ContainsKey(myPath)) { //the level exists if (_Content[myPath].Nodes.ContainsKey(node)) { //Node exists _Content[myPath].Nodes[node].AddBackwardEdge(backwardDirection, backwardDestination, EdgeWeight); } else { //Node does not exist _Content[myPath].Nodes.Add(node, new ExpressionNode(aVertex, NodeWeight, node)); _Content[myPath].Nodes[node].AddBackwardEdge(backwardDirection, backwardDestination, EdgeWeight); } } else { HashSet <IExpressionEdge> backwardEdges = new HashSet <IExpressionEdge>() { new ExpressionEdge(backwardDestination, EdgeWeight, backwardDirection) }; _Content.Add(myPath, new ExpressionLevelEntry(myPath)); _Content[myPath].Nodes.Add(node, new ExpressionNode(aVertex, NodeWeight, node)); _Content[myPath].Nodes[node].AddBackwardEdge(backwardDirection, backwardDestination, EdgeWeight); } } }
public override int GetHashCode() { unchecked { return(((EdgeKey != null ? EdgeKey.GetHashCode() : 0) * 397) ^ (TargetVertexKey != null ? TargetVertexKey.GetHashCode() : 0)); } }
public void AddBackwardEdgesToNode(LevelKey myPath, ObjectUUID myObjectUUID, EdgeKey backwardDestination, Dictionary<ObjectUUID, ADBBaseObject> validUUIDs) { lock (_Content) { if (_Content.ContainsKey(myPath)) { //the level exists if (_Content[myPath].Nodes.ContainsKey(myObjectUUID)) { //Node exists _Content[myPath].Nodes[myObjectUUID].AddBackwardEdges(backwardDestination, validUUIDs); } else { //Node does not exist throw new GraphDBException(new Error_ExpressionGraphInternal(new System.Diagnostics.StackTrace(true), "The node does not exist in this LevelKey.")); } } else { //LevelKey does not exist throw new GraphDBException(new Error_ExpressionGraphInternal(new System.Diagnostics.StackTrace(true), "The LevelKey does not exist in this ExpressionLevel.")); } } }
public void TestEdgeKey() { EdgeKey first = new EdgeKey("x", "y"); EdgeKey second = new EdgeKey("x", "y"); Assert.AreEqual(first, second); Assert.AreEqual(first.GetHashCode(), second.GetHashCode()); }
/// <summary> /// This method adds a new EdgeKey to the IDNode /// </summary> /// <param name="myStartingType">The type that corresponds to the attribute.</param> /// <param name="tempTypeAttributeUUID">The attribute VertexID.</param> private void AddNewEdgeKey(IVertexType myStartingType, Int64 tempTypeAttributeUUID) { EdgeKey tempEdgeKey = new EdgeKey(myStartingType.ID, tempTypeAttributeUUID); _LastType = myStartingType; _Edges.Add(tempEdgeKey); }
public LevelKey(IEnumerable <EdgeKey> myEdgeKey, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken) { Edges = new List <EdgeKey>(); foreach (var aEdgeKey in myEdgeKey) { if (aEdgeKey.IsAttributeSet) { var vertexType = myGraphDB.GetVertexType <IVertexType> (mySecurityToken, myTransactionToken, new RequestGetVertexType(aEdgeKey.VertexTypeID), (stats, type) => type); var attribute = vertexType.GetAttributeDefinition(aEdgeKey.AttributeID); if (attribute != null && attribute.Kind != AttributeType.Property) { //so there is an edge Edges.Add(aEdgeKey); Level++; AddHashCodeFromSingleEdge(ref _hashcode, aEdgeKey); } else { if (Level == 0) { var newEdgeKey = new EdgeKey(aEdgeKey.VertexTypeID); Edges.Add(newEdgeKey); AddHashCodeFromSingleEdge(ref _hashcode, newEdgeKey); break; } else { break; } } } else { if (Level == 0) { Edges.Add(aEdgeKey); AddHashCodeFromSingleEdge(ref _hashcode, aEdgeKey); break; } else { break; } } } }
/// <summary> /// Adds a new BackwardEdge from the current DBObject to the destination attribute identified by <paramref name="myBackwardEdgeAttribute"/>. /// Do not forget to call Flush() after doing all changes! /// </summary> /// <param name="myBackwardEdgeAttribute">The destination type and attribute</param> /// <param name="myObjectReference">The destination DBObject</param> /// <returns></returns> public BulkInsertDBO AddBackwardEdge(EdgeKey myBackwardEdgeAttribute, ObjectUUID myObjectReference) { if (_BackwardEdge == null) _BackwardEdge = new BackwardEdgeStream(_DBObjectStream.ObjectLocation); _BackwardEdge.AddBackwardEdge(myBackwardEdgeAttribute, myObjectReference, _DBContext.DBObjectManager); BackwardEdgesCount++; return this; }
public void RemoveBackwardEdge(EdgeKey myEdgeKey, VertexInformation myObjectUUID) { lock (_lockObj) { var destEdges = from e in _BackwardEdges where e.Key.VertexTypeID == myEdgeKey.VertexTypeID select e.Key; foreach (var be in destEdges) { _BackwardEdges[be].RemoveWhere(exprEdge => exprEdge.Destination == myObjectUUID); } } }
public void RemoveForwardEdge(EdgeKey myEdgeKey, VertexInformation myObjectUUID) { lock (_lockObj) { if (!_ForwardEdges.ContainsKey(myEdgeKey)) { return; } _ForwardEdges[myEdgeKey].RemoveWhere(exprEdge => exprEdge.Destination == myObjectUUID); } }
static Edge GetEdge(Vector3 v0, Vector3 v1) { EdgeKey key = new EdgeKey(v0, v1); Edge edge; if (!edges.TryGetValue(key, out edge)) { edge = new Edge(key); edges.Add(key, edge); } return(edge); }
public LevelKey RemoveEdgeKey(EdgeKey myEdgeKey, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken) { var edgeList = new List <EdgeKey>(this.Edges); //edgeList.Remove(myEdgeKey); if (edgeList[edgeList.Count - 1] != myEdgeKey) { throw new InvalidLevelKeyOperationException(this, myEdgeKey, "-"); } return(new LevelKey(edgeList.Take(edgeList.Count - 1), myGraphDB, mySecurityToken, myTransactionToken)); }
public void TestCase() { Verticle v = new Verticle("v"); Verticle u = new Verticle("u"); Edge e = new Edge(v, u); Assert.AreSame(e.From, v); Assert.AreSame(e.To, u); EdgeKey edgeKey = e.GetKey(); Assert.AreEqual(edgeKey.from, v.Id, "v"); Assert.AreEqual(edgeKey.to, u.Id, "u"); }
public LevelKey(IEnumerable<EdgeKey> myEdgeKey, DBTypeManager myTypeManager) { _edges = new List<EdgeKey>(); foreach (var aEdgeKey in myEdgeKey) { if (aEdgeKey.AttrUUID != null && aEdgeKey.AttrUUID != UndefinedTypeAttribute.AttributeUUID) { var attribute = aEdgeKey.GetTypeAndAttributeInformation(myTypeManager).Item2; if (attribute.GetDBType(myTypeManager).IsUserDefined || attribute.IsBackwardEdge) { _edges.Add(aEdgeKey); _level++; AddHashCodeFromSingleEdge(ref _hashcode, aEdgeKey); } else { if (_level == 0) { var newEdgeKey = new EdgeKey(aEdgeKey.TypeUUID, null); _edges.Add(newEdgeKey); AddHashCodeFromSingleEdge(ref _hashcode, newEdgeKey); break; } else { break; } } } else { if (_level == 0) { _edges.Add(aEdgeKey); AddHashCodeFromSingleEdge(ref _hashcode, aEdgeKey); break; } else { break; } } } }
/// <summary> /// Finds all edges where the angle between adjacent triangle normal vectors. /// is larger than minimumAngle /// </summary> /// <param name="mesh"> /// A mesh geometry. /// </param> /// <param name="minimumAngle"> /// The minimum angle between the normal vectors of two adjacent triangles (degrees). /// </param> /// <returns> /// The edge indices. /// </returns> public static Int32Collection FindSharpEdges(this MeshGeometry3D mesh, double minimumAngle) { var edgeIndices = new Int32Collection(); var edgeNormals = new Dictionary <EdgeKey, Vector3D>(); for (var i = 0; i < mesh.TriangleIndices.Count / 3; i++) { var i0 = i * 3; var p0 = mesh.Positions[mesh.TriangleIndices[i0]]; var p1 = mesh.Positions[mesh.TriangleIndices[i0 + 1]]; var p2 = mesh.Positions[mesh.TriangleIndices[i0 + 2]]; var triangleNormal = SharedFunctions.CrossProduct(p1 - p0, p2 - p0); // Handle degenerated triangles. if (SharedFunctions.LengthSquared(ref triangleNormal) < 0.001f) { continue; } triangleNormal.Normalize(); for (var j = 0; j < 3; j++) { var index0 = mesh.TriangleIndices[i0 + j]; var index1 = mesh.TriangleIndices[i0 + (j + 1) % 3]; var position0 = SharedFunctions.ToVector3D(mesh.Positions[index0]); var position1 = SharedFunctions.ToVector3D(mesh.Positions[index1]); var edgeKey = new EdgeKey(position0, position1); var reverseEdgeKey = new EdgeKey(position1, position0); if (edgeNormals.TryGetValue(edgeKey, out var value) || edgeNormals.TryGetValue(reverseEdgeKey, out value)) { var rawDot = SharedFunctions.DotProduct(ref triangleNormal, ref value); // Acos returns NaN if rawDot > 1 or rawDot < -1 var dot = Math.Max(-1, Math.Min(rawDot, 1)); var angle = 180 / Math.PI * Math.Acos(dot); if (angle > minimumAngle) { edgeIndices.Add(index0); edgeIndices.Add(index1); } } else { edgeNormals.Add(edgeKey, triangleNormal); } } } return(edgeIndices); }
public void AddBackwardEdges(EdgeKey backwardDestination, Dictionary <VertexInformation, IComparable> validUUIDs) { lock (_lockObj) { if (_BackwardEdges.ContainsKey(backwardDestination)) { _BackwardEdges[backwardDestination].UnionWith(validUUIDs.Select(item => (IExpressionEdge)(new ExpressionEdge(item.Key, item.Value, backwardDestination)))); } else { _BackwardEdges.Add(backwardDestination, new HashSet <IExpressionEdge>(validUUIDs.Select(item => (IExpressionEdge)(new ExpressionEdge(item.Key, item.Value, backwardDestination))))); } } }
public void AddForwardEdges(EdgeKey forwardDestination, IEnumerable <IExpressionEdge> validEdges) { lock (_lockObj) { if (_ForwardEdges.ContainsKey(forwardDestination)) { _ForwardEdges[forwardDestination].UnionWith(validEdges); } else { _ForwardEdges.Add(forwardDestination, new HashSet <IExpressionEdge>(validEdges)); } } }
public void AddForwardEdge(EdgeKey ForwardEdge, VertexInformation destination, IComparable weight) { lock (_lockObj) { if (_ForwardEdges.ContainsKey(ForwardEdge)) { _ForwardEdges[ForwardEdge].Add(new ExpressionEdge(destination, weight, ForwardEdge)); } else { _ForwardEdges.Add(ForwardEdge, new HashSet <IExpressionEdge>() { new ExpressionEdge(destination, weight, ForwardEdge) }); } } }
public void AddBackwardEdge(EdgeKey backwardDestination, VertexInformation validUUIDs, IComparable edgeWeight) { lock (_lockObj) { var backwardEdges = new HashSet <IExpressionEdge>() { new ExpressionEdge(validUUIDs, edgeWeight, backwardDestination) }; if (_BackwardEdges.ContainsKey(backwardDestination)) { _BackwardEdges[backwardDestination].UnionWith(backwardEdges); } else { _BackwardEdges.Add(backwardDestination, backwardEdges); } } }
public void AddNodeAndBackwardEdge(LevelKey myPath, IVertex aVertex, EdgeKey backwardDirection, VertexInformation backwardDestination, IComparable EdgeWeight, IComparable NodeWeight) { lock (_Content) { var node = GenerateVertexInfoFromLevelKeyAndVertexID(aVertex.VertexTypeID, aVertex.VertexID); if (_Content.ContainsKey(myPath)) { //the level exists if (_Content[myPath].Nodes.ContainsKey(node)) { //Node exists _Content[myPath].Nodes[node].AddBackwardEdge(backwardDirection, backwardDestination, EdgeWeight); } else { //Node does not exist _Content[myPath].Nodes.Add(node, new ExpressionNode(aVertex, NodeWeight, node)); _Content[myPath].Nodes[node].AddBackwardEdge(backwardDirection, backwardDestination, EdgeWeight); } } else { HashSet<IExpressionEdge> backwardEdges = new HashSet<IExpressionEdge>() { new ExpressionEdge(backwardDestination, EdgeWeight, backwardDirection) }; _Content.Add(myPath, new ExpressionLevelEntry(myPath)); _Content[myPath].Nodes.Add(node, new ExpressionNode(aVertex, NodeWeight, node)); _Content[myPath].Nodes[node].AddBackwardEdge(backwardDirection, backwardDestination, EdgeWeight); } } }
public Graph GetGraph(int cnod) { var cEdgesNeeded = (int)(cnod * (cnod - 1) * _pctEdges); var cEdgesSoFar = 0; var setEdges = new HashSet <EdgeKey>(); var graph = new Graph(); graph.InsertVertices(cnod); while (cEdgesSoFar < cEdgesNeeded) { var ekey = new EdgeKey(_rnd.Next(cnod), _rnd.Next(cnod)); if (setEdges.Contains(ekey) || ekey.From == ekey.To) { continue; } graph.AddEdge(ekey.From, ekey.To); setEdges.Add(ekey); cEdgesSoFar++; } return(graph); }
public Graph GetGraph(int cnod) { int cEdgesNeeded = (int)(cnod * (cnod - 1) * _pctEdges); int cEdgesSoFar = 0; Set <EdgeKey> setEdges = new Set <EdgeKey>(); Graph graph = new Graph(); graph.InsertNodes(cnod); while (cEdgesSoFar < cEdgesNeeded) { EdgeKey ekey = new EdgeKey(_rnd.Next(cnod), _rnd.Next(cnod)); if (setEdges.Contains(ekey) || ekey.From == ekey.To) { continue; } graph.InsertEdge(ekey.From, ekey.To); setEdges.Add(ekey); cEdgesSoFar++; } return(graph); }
public LevelKey AddEdgeKey(EdgeKey myEdgeKey, IGraphDB myGraphDB, SecurityToken mySecurityToken, Int64 myTransactionToken) { // an empty level if (this.Edges == null) { return(new LevelKey(new List <EdgeKey> { myEdgeKey }, myGraphDB, mySecurityToken, myTransactionToken)); } var edgeList = new List <EdgeKey>(this.Edges); // if the first and only edge has a null attrUUID the new edge must have the same type!! if (edgeList.Count == 1 && !edgeList[0].IsAttributeSet) { if (edgeList[0].VertexTypeID != myEdgeKey.VertexTypeID) { throw new InvalidLevelKeyOperationException(this, myEdgeKey, "+"); } else { return(new LevelKey(new List <EdgeKey>() { myEdgeKey }, myGraphDB, mySecurityToken, myTransactionToken)); } } else { if (myEdgeKey.IsAttributeSet) { edgeList.Add(myEdgeKey); } return(new LevelKey(edgeList, myGraphDB, mySecurityToken, myTransactionToken)); } }
public EdgeList(EdgeKey myEdgeKey) : this(new List <EdgeKey>() { myEdgeKey }) { }
public LevelKey(IEnumerable<EdgeKey> myEdgeKey, IGraphDB myGraphDB, SecurityToken mySecurityToken, TransactionToken myTransactionToken) { Edges = new List<EdgeKey>(); foreach (var aEdgeKey in myEdgeKey) { if (aEdgeKey.IsAttributeSet) { var vertexType = myGraphDB.GetVertexType<IVertexType> (mySecurityToken, myTransactionToken, new RequestGetVertexType(aEdgeKey.VertexTypeID), (stats, type) => type); var attribute = vertexType.GetAttributeDefinition(aEdgeKey.AttributeID); if (attribute != null && attribute.Kind != AttributeType.Property) { //so there is an edge Edges.Add(aEdgeKey); Level++; AddHashCodeFromSingleEdge(ref _hashcode, aEdgeKey); } else { if (Level == 0) { var newEdgeKey = new EdgeKey(aEdgeKey.VertexTypeID); Edges.Add(newEdgeKey); AddHashCodeFromSingleEdge(ref _hashcode, newEdgeKey); break; } else { break; } } } else { if (Level == 0) { Edges.Add(aEdgeKey); AddHashCodeFromSingleEdge(ref _hashcode, aEdgeKey); break; } else { break; } } } }
public LevelKey RemoveEdgeKey(EdgeKey myEdgeKey, IGraphDB myGraphDB, SecurityToken mySecurityToken, TransactionToken myTransactionToken) { var edgeList = new List<EdgeKey>(this.Edges); //edgeList.Remove(myEdgeKey); if (edgeList[edgeList.Count - 1] != myEdgeKey) throw new InvalidLevelKeyOperationException(this, myEdgeKey, "-"); return new LevelKey(edgeList.Take(edgeList.Count - 1), myGraphDB, mySecurityToken, myTransactionToken); }
internal Exceptional SetBackwardEdges(GraphDBType aType, Dictionary<AttributeUUID, IObject> userdefinedAttributes, ObjectUUID reference, DBContext dbContext) { var returnVal = new Exceptional(); #region process attributes foreach (var aUserDefinedAttribute in userdefinedAttributes) { #region Data GraphDBType typeOFAttribute = null; TypeAttribute attributesOfType = null; #endregion #region get GraphType of Attribute //attributesOfType = aType.Attributes[aUserDefinedAttribute.Key]; attributesOfType = aType.GetTypeAttributeByUUID(aUserDefinedAttribute.Key); typeOFAttribute = dbContext.DBTypeManager.GetTypeByUUID(attributesOfType.DBTypeUUID); #endregion /* The DBO independent version */ var beEdge = new EdgeKey(aType.UUID, attributesOfType.UUID); var runMT = DBConstants.RunMT; runMT = false; if (runMT) { #region The parallel version /**/ /* The parallel version */ Parallel.ForEach(((IReferenceEdge)aUserDefinedAttribute.Value).GetAllReferenceIDs(), (uuid) => { var addExcept = dbContext.DBObjectManager.AddBackwardEdge(uuid, attributesOfType.DBTypeUUID, beEdge, reference); if (!addExcept.Success()) { returnVal.PushIExceptional(addExcept); } }); if (!returnVal.Success()) { return returnVal; } /**/ #endregion } else { #region Single thread foreach (var uuid in ((IReferenceEdge)aUserDefinedAttribute.Value).GetAllReferenceIDs()) { var addExcept = dbContext.DBObjectManager.AddBackwardEdge(uuid, attributesOfType.DBTypeUUID, beEdge, reference); if (addExcept.Failed()) { return new Exceptional(addExcept); } } #endregion } } #endregion return Exceptional.OK; }
public Error_InvalidLevelKeyOperation(LevelKey myLevelKey, EdgeKey myEdgeKey, String myOperation) { LevelKeyA = myLevelKey; EdgeKeyA = myEdgeKey; Operation = myOperation; }
protected override void InternalCompute() { // create condensated graph this.condensedGraph = new BidirectionalGraph < TGraph, CondensedEdge <TVertex, TEdge, TGraph> >(false); if (this.VisitedGraph.VertexCount == 0) { return; } // compute strongly connected components var components = new Dictionary <TVertex, int>(this.VisitedGraph.VertexCount); int componentCount = ComputeComponentCount(components); var cancelManager = this.Services.CancelManager; if (cancelManager.IsCancelling) { return; } // create list vertices var condensatedVertices = new Dictionary <int, TGraph>(componentCount); for (int i = 0; i < componentCount; ++i) { TGraph v = new TGraph(); condensatedVertices.Add(i, v); this.condensedGraph.AddVertex(v); } // addingvertices foreach (var v in this.VisitedGraph.Vertices) { condensatedVertices[components[v]].AddVertex(v); } if (cancelManager.IsCancelling) { return; } // condensated edges var condensatedEdges = new Dictionary <EdgeKey, CondensedEdge <TVertex, TEdge, TGraph> >(componentCount); // iterate over edges and condensate graph foreach (var edge in this.VisitedGraph.Edges) { // get component ids int sourceID = components[edge.Source]; int targetID = components[edge.Target]; // get vertices TGraph sources = condensatedVertices[sourceID]; if (sourceID == targetID) { sources.AddEdge(edge); continue; } var targets = condensatedVertices[targetID]; // at last add edge var edgeKey = new EdgeKey(sourceID, targetID); CondensedEdge <TVertex, TEdge, TGraph> condensatedEdge; if (!condensatedEdges.TryGetValue(edgeKey, out condensatedEdge)) { condensatedEdge = new CondensedEdge <TVertex, TEdge, TGraph>(sources, targets); condensatedEdges.Add(edgeKey, condensatedEdge); this.condensedGraph.AddEdge(condensatedEdge); } condensatedEdge.Edges.Add(edge); } }
/// <summary> /// Resolves an attribute /// </summary> /// <param name="attrDefinition">The TypeAttribute</param> /// <param name="attributeValue">The attribute value, either a AListReferenceEdgeType or ASingleEdgeType or a basic object (Int, String, ...)</param> /// <param name="myDepth">The current depth defined by a setting or in the select</param> /// <param name="currentLvl">The current level (for recursive resolve)</param> /// <returns>List<Vertex> for user defined list attributes; Vertex for reference attributes, Object for basic type values </returns> private object ResolveAttributeValue(TypeAttribute attrDefinition, object attributeValue, Int64 myDepth, EdgeList myEdgeList, DBObjectStream mySourceDBObject, String reference, Boolean myUsingGraph) { #region attributeValue is not a reference type just return the value if (!((attributeValue is ASetOfReferencesEdgeType) || (attributeValue is ASingleReferenceEdgeType))) { return attributeValue; } #endregion #region get typeOfAttribute var typeOfAttribute = attrDefinition.GetDBType(_DBContext.DBTypeManager); // For backwardEdges, the baseType is the type of the DBObjects! if (attrDefinition.TypeCharacteristics.IsBackwardEdge) typeOfAttribute = _DBContext.DBTypeManager.GetTypeAttributeByEdge(attrDefinition.BackwardEdgeDefinition).GetRelatedType(_DBContext.DBTypeManager); #endregion #region Get levelKey and UsingGraph if (!(attrDefinition is ASpecialTypeAttribute)) { if (myEdgeList.Level == 0) { myEdgeList = new EdgeList(new EdgeKey(attrDefinition.RelatedGraphDBTypeUUID, attrDefinition.UUID)); } else { myEdgeList += new EdgeKey(attrDefinition.RelatedGraphDBTypeUUID, attrDefinition.UUID); } } // at some deeper level we could get into graph independend results. From this time, we can use the GUID index rather than asking the graph all the time if (myUsingGraph) { myUsingGraph = _ExpressionGraph.IsGraphRelevant(new LevelKey(myEdgeList.Edges, _DBContext.DBTypeManager), mySourceDBObject); } #endregion if (attributeValue is ASetOfReferencesEdgeType) { #region SetReference attribute -> return new Edge IEnumerable<Vertex> resultList = null; var edge = ((ASetOfReferencesEdgeType)attributeValue); if (myUsingGraph) { var dbos = _ExpressionGraph.Select(new LevelKey(myEdgeList.Edges, _DBContext.DBTypeManager), mySourceDBObject, true); resultList = GetVertices(typeOfAttribute, edge, dbos, myDepth, myEdgeList, reference, myUsingGraph); } else { resultList = GetVertices(typeOfAttribute, edge, myDepth, myEdgeList, reference, myUsingGraph); } return new Edge(null, resultList, typeOfAttribute.Name); #endregion } else if (attributeValue is ASingleReferenceEdgeType) { #region Single reference attributeValue = new Edge(null, (attributeValue as ASingleReferenceEdgeType).GetVertex(a => LoadAndResolveVertex(a, typeOfAttribute, myDepth, myEdgeList, reference, myUsingGraph)) , typeOfAttribute.Name); return attributeValue; #endregion } else { throw new GraphDBException(new Error_NotImplemented(new System.Diagnostics.StackTrace(true))); } }
public Exceptional<TypeAttribute> CreateBackwardEdgeAttribute(BackwardEdgeDefinition myBackwardEdgeNode, GraphDBType myDBTypeStream, UInt16 beAttrCounter = 0) { var edgeType = GetTypeByName(myBackwardEdgeNode.TypeName); if (edgeType == null) return new Exceptional<TypeAttribute>(new Error_TypeDoesNotExist(myBackwardEdgeNode.TypeName)); var edgeAttribute = edgeType.GetTypeAttributeByName(myBackwardEdgeNode.TypeAttributeName); //error if the attribute does not exist #region if (edgeAttribute == null) { return new Exceptional<TypeAttribute>(new Error_AttributeIsNotDefined(edgeType.Name, myBackwardEdgeNode.TypeAttributeName)); } #endregion //error if the attribute does not represent non userdefined content #region if (!edgeAttribute.GetDBType(this).IsUserDefined) { return new Exceptional<TypeAttribute>(new Error_BackwardEdgesForNotReferenceAttributeTypesAreNotAllowed(myBackwardEdgeNode.TypeAttributeName)); } #endregion //invalid backwardEdge destination #region if (edgeAttribute.GetDBType(this) != myDBTypeStream) return new Exceptional<TypeAttribute>(new Error_BackwardEdgeDestinationIsInvalid(myDBTypeStream.Name, myBackwardEdgeNode.TypeAttributeName)); #endregion //error if there is already an be attribute on the to be changed type that points to the same destination #region var edgeKey = new EdgeKey(edgeType.UUID, edgeAttribute.UUID); if (myDBTypeStream.Attributes.Exists(aKV => aKV.Value.IsBackwardEdge && (aKV.Value.BackwardEdgeDefinition == edgeKey))) { return new Exceptional<TypeAttribute>(new Error_BackwardEdgeAlreadyExist(myDBTypeStream, edgeType.Name, edgeAttribute.Name)); } #endregion //error if the backwardEdge points to a backward edge #region var beDestinationAttribute = edgeKey.GetTypeAndAttributeInformation(this).Item2; if (beDestinationAttribute.IsBackwardEdge) return new Exceptional<TypeAttribute>(new Error_BackwardEdgeAlreadyExist(myDBTypeStream, edgeType.Name, edgeAttribute.Name)); #endregion var ta = new TypeAttribute(Convert.ToUInt16(beAttrCounter + DBConstants.DefaultBackwardEdgeIDStart)); ta.DBTypeUUID = DBBackwardEdgeType.UUID; ta.BackwardEdgeDefinition = edgeKey; ta.KindOfType = KindsOfType.SetOfReferences; ta.Name = myBackwardEdgeNode.AttributeName; ta.EdgeType = myBackwardEdgeNode.EdgeType.GetNewInstance(); ta.TypeCharacteristics.IsBackwardEdge = true; ta.RelatedGraphDBTypeUUID = myDBTypeStream.UUID; return new Exceptional<TypeAttribute>(ta); }
public void AddBackwardEdges(EdgeKey backwardDestination, Dictionary<VertexInformation, IComparable> validUUIDs) { lock (_lockObj) { if (_BackwardEdges.ContainsKey(backwardDestination)) { _BackwardEdges[backwardDestination].UnionWith(validUUIDs.Select(item => (IExpressionEdge)(new ExpressionEdge(item.Key, item.Value, backwardDestination)))); } else { _BackwardEdges.Add(backwardDestination, new HashSet<IExpressionEdge>(validUUIDs.Select(item => (IExpressionEdge)(new ExpressionEdge(item.Key, item.Value, backwardDestination))))); } } }
public void AddForwardEdges(EdgeKey forwardDestination, IEnumerable<IExpressionEdge> validEdges) { lock (_lockObj) { if (_ForwardEdges.ContainsKey(forwardDestination)) { _ForwardEdges[forwardDestination].UnionWith(validEdges); } else { _ForwardEdges.Add(forwardDestination, new HashSet<IExpressionEdge>(validEdges)); } } }
public void AddBackwardEdgesToNode(LevelKey myPath, VertexInformation myVertexInformation, EdgeKey backwardDestination, Dictionary <VertexInformation, IComparable> validUUIDs) { lock (_Content) { if (_Content.ContainsKey(myPath)) { //the level exists if (_Content[myPath].Nodes.ContainsKey(myVertexInformation)) { //Node exists _Content[myPath].Nodes[myVertexInformation].AddBackwardEdges(backwardDestination, validUUIDs); } else { //Node does not exist throw new ExpressionGraphInternalException("The node does not exist in this LevelKey."); } } else { //LevelKey does not exist throw new ExpressionGraphInternalException("The LevelKey does not exist in this ExpressionLevel."); } } }
public void AddForwardEdgeToNode(LevelKey levelKey, VertexInformation myVertexInformation, EdgeKey forwardDirection, VertexInformation destination, IComparable edgeWeight) { lock (_Content) { if (_Content.ContainsKey(levelKey)) { //the level exists if (_Content[levelKey].Nodes.ContainsKey(myVertexInformation)) { //Node exists _Content[levelKey].Nodes[myVertexInformation].AddForwardEdge(forwardDirection, destination, edgeWeight); } else { //Node does not exist throw new ExpressionGraphInternalException("The node does not exist in this LevelKey."); } } else { //LevelKey does not exist throw new ExpressionGraphInternalException("The LevelKey does not exist in this ExpressionLevel."); } } }
private Edge GetNotResolvedBackwardEdgeReferenceAttributeValue(DBObjectStream myDBObject, TypeAttribute myTypeAttribute, EdgeKey edgeKey, EdgeList currentEdgeList, Boolean myUsingGraph, DBContext _DBContext) { IObject attrValue = null; if (myUsingGraph) { var interestingLevelKey = new LevelKey((currentEdgeList + new EdgeKey(myTypeAttribute.RelatedGraphDBTypeUUID, myTypeAttribute.UUID)).Edges, _DBContext.DBTypeManager); attrValue = new EdgeTypeSetOfReferences(_ExpressionGraph.SelectUUIDs(interestingLevelKey, myDBObject), myTypeAttribute.DBTypeUUID); } else { var attrValueException = myDBObject.GetBackwardEdges(edgeKey, _DBContext, _DBContext.DBObjectCache, myTypeAttribute.GetDBType(_DBContext.DBTypeManager)); if (attrValueException.Failed()) { throw new GraphDBException(attrValueException.IErrors); } attrValue = attrValueException.Value; } if (attrValue == null) { return null; } else if (!(attrValue is IReferenceEdge)) { throw new GraphDBException(new Error_InvalidEdgeType(attrValue.GetType(), typeof(IReferenceEdge))); } var readouts = new List<Vertex>(); var typeName = _DBContext.DBTypeManager.GetTypeByUUID(edgeKey.TypeUUID).Name; foreach (var reference in (attrValue as IReferenceEdge).GetAllReferenceIDs()) { var specialAttributes = new Dictionary<string, object>(); specialAttributes.Add(SpecialTypeAttribute_UUID.AttributeName, reference); specialAttributes.Add(SpecialTypeAttribute_TYPE.AttributeName, typeName); readouts.Add(new Vertex(specialAttributes)); } return new Edge(null, readouts, _DBContext.DBTypeManager.GetTypeAttributeByEdge(edgeKey).GetDBType(_DBContext.DBTypeManager).Name); }
/// <summary> /// For framework use only. /// </summary> /// <param name="endpoints"></param> /// <returns></returns> public IReadOnlyList <PolicyNodeEdge> GetEdges(IReadOnlyList <Endpoint> endpoints) { // The algorithm here is designed to be preserve the order of the endpoints // while also being relatively simple. Preserving order is important. // First, build a dictionary of all possible HTTP method/CORS combinations // that exist in this list of endpoints. // // For now we're just building up the set of keys. We don't add any endpoints // to lists now because we don't want ordering problems. var allHttpMethods = new List <string>(); var edges = new Dictionary <EdgeKey, List <Endpoint> >(); for (var i = 0; i < endpoints.Count; i++) { var endpoint = endpoints[i]; var(httpMethods, acceptCorsPreFlight) = GetHttpMethods(endpoint); // If the action doesn't list HTTP methods then it supports all methods. // In this phase we use a sentinel value to represent the *other* HTTP method // a state that represents any HTTP method that doesn't have a match. if (httpMethods.Count == 0) { httpMethods = new[] { AnyMethod, }; } for (var j = 0; j < httpMethods.Count; j++) { // An endpoint that allows CORS reqests will match both CORS and non-CORS // so we model it as both. var httpMethod = httpMethods[j]; var key = new EdgeKey(httpMethod, acceptCorsPreFlight); if (!edges.ContainsKey(key)) { edges.Add(key, new List <Endpoint>()); } // An endpoint that allows CORS reqests will match both CORS and non-CORS // so we model it as both. if (acceptCorsPreFlight) { key = new EdgeKey(httpMethod, false); if (!edges.ContainsKey(key)) { edges.Add(key, new List <Endpoint>()); } } // Also if it's not the *any* method key, then track it. if (!string.Equals(AnyMethod, httpMethod, StringComparison.OrdinalIgnoreCase)) { if (!ContainsHttpMethod(allHttpMethods, httpMethod)) { allHttpMethods.Add(httpMethod); } } } } allHttpMethods.Sort(StringComparer.OrdinalIgnoreCase); // Now in a second loop, add endpoints to these lists. We've enumerated all of // the states, so we want to see which states this endpoint matches. for (var i = 0; i < endpoints.Count; i++) { var endpoint = endpoints[i]; var(httpMethods, acceptCorsPreFlight) = GetHttpMethods(endpoint); if (httpMethods.Count == 0) { // OK this means that this endpoint matches *all* HTTP methods. // So, loop and add it to all states. foreach (var kvp in edges) { if (acceptCorsPreFlight || !kvp.Key.IsCorsPreflightRequest) { kvp.Value.Add(endpoint); } } } else { // OK this endpoint matches specific methods. for (var j = 0; j < httpMethods.Count; j++) { var httpMethod = httpMethods[j]; var key = new EdgeKey(httpMethod, acceptCorsPreFlight); edges[key].Add(endpoint); // An endpoint that allows CORS reqests will match both CORS and non-CORS // so we model it as both. if (acceptCorsPreFlight) { key = new EdgeKey(httpMethod, false); edges[key].Add(endpoint); } } } } // Adds a very low priority endpoint that will reject the request with // a 405 if nothing else can handle this verb. This is only done if // no other actions exist that handle the 'all verbs'. // // The rationale for this is that we want to report a 405 if none of // the supported methods match, but we don't want to report a 405 in a // case where an application defines an endpoint that handles all verbs, but // a constraint rejects the request, or a complex segment fails to parse. We // consider a case like that a 'user input validation' failure rather than // a semantic violation of HTTP. // // This will make 405 much more likely in API-focused applications, and somewhat // unlikely in a traditional MVC application. That's good. // // We don't bother returning a 405 when the CORS preflight method doesn't exist. // The developer calling the API will see it as a CORS error, which is fine because // there isn't an endpoint to check for a CORS policy. if (!edges.TryGetValue(new EdgeKey(AnyMethod, false), out var matches)) { // Methods sorted for testability. var endpoint = CreateRejectionEndpoint(allHttpMethods); matches = new List <Endpoint>() { endpoint, }; edges[new EdgeKey(AnyMethod, false)] = matches; } var policyNodeEdges = new PolicyNodeEdge[edges.Count]; var index = 0; foreach (var kvp in edges) { policyNodeEdges[index++] = new PolicyNodeEdge(kvp.Key, kvp.Value); } return(policyNodeEdges); (IReadOnlyList <string> httpMethods, bool acceptCorsPreflight) GetHttpMethods(Endpoint e) { var metadata = e.Metadata.GetMetadata <IHttpMethodMetadata>(); return(metadata == null ? (Array.Empty <string>(), false) : (metadata.HttpMethods, metadata.AcceptCorsPreflight)); } }
/// <summary> /// This is the main function. It will check all selections on this type and will create the readouts /// </summary> /// <param name="dbos"></param> /// <param name="myResolutionDepth"></param> /// <param name="myTypeNode"></param> /// <param name="myLevelKey"></param> /// <param name="myUsingGraph">True if for all selects the graph will be asked for DBOs</param> /// <param name="myDBObjectCache"></param> /// <param name="mySessionToken"></param> /// <returns></returns> private IEnumerable<Vertex> ExamineVertex(long myResolutionDepth, String myReference, GraphDBType myReferencedDBType, EdgeList myLevelKey, bool myUsingGraph) { #region Get all selections and aggregates for this reference, type and level var _Selections = getAttributeSelections(myReference, myReferencedDBType, myLevelKey); var aggregates = getAttributeAggregates(myReference, myReferencedDBType, myLevelKey); #endregion if ( (_Selections.IsNotNullOrEmpty() && _Selections.All(s => s.IsReferenceToSkip(myLevelKey)) && aggregates.IsNotNullOrEmpty() && aggregates.All(a => a.IsReferenceToSkip(myLevelKey))) || (_Selections.IsNotNullOrEmpty() && _Selections.All(s => s.IsReferenceToSkip(myLevelKey)) && aggregates.IsNullOrEmpty()) ) { #region If there are only references in this level, we will skip this level (and add the attribute as placeholder) and step to the next one var Attributes = new Dictionary<String, Object>(); foreach (var _Selection in _Selections) { var edgeKey = new EdgeKey(_Selection.Element.RelatedGraphDBTypeUUID, _Selection.Element.UUID); Attributes.Add(_Selection.Alias, new Edge(null, ExamineVertex(myResolutionDepth, myReference, myReferencedDBType, myLevelKey + edgeKey, myUsingGraph), _Selection.Element.GetDBType(_DBContext.DBTypeManager).Name)); } yield return new Vertex(Attributes); #endregion } else { #region Otherwise load all dbos until this level and return them #region Get dbos enumerable of the first level - either from ExpressionGraph or via index IEnumerable<Exceptional<DBObjectStream>> dbos; if (myUsingGraph) { dbos = _ExpressionGraph.Select(new LevelKey(myLevelKey.Edges, _DBContext.DBTypeManager), null, true); } else // using GUID index { dbos = _DBContext.DBObjectCache.SelectDBObjectsForLevelKey(new LevelKey(myLevelKey.Edges, _DBContext.DBTypeManager), _DBContext); } #endregion if (aggregates.IsNotNullOrEmpty()) { foreach (var val in ExamineDBO_Aggregates(dbos, aggregates, _Selections, myReferencedDBType, myUsingGraph)) { if (val != null) { yield return val; } } } else if (_Groupings.IsNotNullOrEmpty()) { foreach (var val in ExamineDBO_Groupings(dbos, _Selections, myReferencedDBType)) { if (val != null) { yield return val; } } } else if (!_Selections.IsNullOrEmpty()) { Boolean isRefTypeVertex = myReferencedDBType.UUID.Equals(DBVertex.UUID); GraphDBType refType; #region Usually attribute selections foreach (var aDBObject in dbos) { if (aDBObject.Failed()) { // since we are in an yield we can do nothing else than throw a exception throw new GraphDBException(aDBObject.IErrors); } #region Create a readoutObject for this DBO and yield it: on failure throw an exception if (isRefTypeVertex) { refType = _DBContext.DBTypeManager.GetTypeByUUID(aDBObject.Value.TypeUUID); } else { refType = myReferencedDBType; } var Attributes = GetAllSelectedAttributesFromVertex(aDBObject.Value, refType, myResolutionDepth, myLevelKey, myReference, myUsingGraph); if (Attributes.IsNotNullOrEmpty()) { yield return new Vertex(Attributes); } //else //{ // // we found no attributes, so we return null because currently we do not want to add empty attribute readouts // yield return (Vertex)null; //} #endregion } #endregion } #endregion } }
/// <summary> /// Initializes a new instance of the InvalidEdgeListOperationException using an edge key. /// </summary> /// <param name="myEdgeList"></param> /// <param name="myEdgeKey"></param> /// <param name="myOperation"></param> /// <param name="innerException">The exception that is the cause of the current exception, this parameter can be NULL.</param> public InvalidEdgeListOperationException(EdgeList myEdgeList, EdgeKey myEdgeKey, string myOperation, Exception innerException = null) : base(innerException) { _EdgeList1 = myEdgeList; this._EdgeKey = myEdgeKey; this._Operation = myOperation; }
internal Exceptional AddBackwardEdge(ObjectUUID uuid, TypeUUID typeOfBESource, EdgeKey beEdgeKey, ObjectUUID reference) { //load the backward edge var loadExcept = _DBContext.DBObjectCache.LoadDBBackwardEdgeStream(typeOfBESource, uuid); // LoadBackwardEdge(beLocation); if (loadExcept.Failed()) { return new Exceptional(loadExcept); } loadExcept.Value.AddBackwardEdge(beEdgeKey, reference, this); if (loadExcept.Value.isNew) { return _IGraphFSSession.StoreFSObject(loadExcept.Value, true); } else { return loadExcept.Value.Save(); } }
private void AddHashCodeFromSingleEdge(ref int myHashCode, EdgeKey aEdge) { myHashCode += (int)(aEdge.GetHashCode() >> 32); }
protected override void InternalCompute() { // create condensated graph this.condensatedGraph = new BidirectionalGraph < TGraph, CondensatedEdge <TVertex, TEdge, TGraph> >(false); if (this.VisitedGraph.VertexCount == 0) { return; } // compute strongly connected components Dictionary <TVertex, int> components = new Dictionary <TVertex, int>(this.VisitedGraph.VertexCount); int componentCount; lock (this.SyncRoot) { if (this.StronglyConnected) { this.componentAlgorithm = new StronglyConnectedComponentsAlgorithm <TVertex, TEdge>(this.VisitedGraph, components); } else { this.componentAlgorithm = new WeaklyConnectedComponentsAlgorithm <TVertex, TEdge>(this.VisitedGraph, components); } } this.componentAlgorithm.Compute(); componentCount = this.componentAlgorithm.ComponentCount; lock (SyncRoot) { this.componentAlgorithm = null; } if (this.IsAborting) { return; } // create list vertices Dictionary <int, TGraph> condensatedVertices = new Dictionary <int, TGraph>(componentCount); for (int i = 0; i < componentCount; ++i) { if (this.IsAborting) { return; } TGraph v = new TGraph(); condensatedVertices.Add(i, v); this.condensatedGraph.AddVertex(v); } // addingvertices foreach (TVertex v in this.VisitedGraph.Vertices) { condensatedVertices[components[v]].AddVertex(v); } if (this.IsAborting) { return; } // condensated edges Dictionary <EdgeKey, CondensatedEdge <TVertex, TEdge, TGraph> > condensatedEdges = new Dictionary <EdgeKey, CondensatedEdge <TVertex, TEdge, TGraph> >(componentCount); // iterate over edges and condensate graph foreach (TEdge edge in this.VisitedGraph.Edges) { if (this.IsAborting) { return; } // get component ids int sourceID = components[edge.Source]; int targetID = components[edge.Target]; // get vertices TGraph sources = condensatedVertices[sourceID]; if (sourceID == targetID) { sources.AddEdge(edge); continue; } // TGraph targets = condensatedVertices[targetID]; // at last add edge EdgeKey edgeKey = new EdgeKey(sourceID, targetID); CondensatedEdge <TVertex, TEdge, TGraph> condensatedEdge; if (!condensatedEdges.TryGetValue(edgeKey, out condensatedEdge)) { condensatedEdge = new CondensatedEdge <TVertex, TEdge, TGraph>(sources, targets); condensatedEdges.Add(edgeKey, condensatedEdge); this.condensatedGraph.AddEdge(condensatedEdge); } condensatedEdge.Edges.Add(edge); } }
/// <summary> /// Constructor /// </summary> /// <param name="myDestination">The ExpressionNode that this edge is pointing to.</param> /// <param name="myWeight">The Weight of this edge.</param> /// <param name="myDirection">The direction (Type/Attribute) that this edge is pointing to.</param> public ExpressionEdge(VertexInformation myDestination, IComparable myWeight, EdgeKey myDirection) { _destination = myDestination; Weight = myWeight; _direction = myDirection; }
public LevelKey AddEdgeKey(EdgeKey myEdgeKey, IGraphDB myGraphDB, SecurityToken mySecurityToken, TransactionToken myTransactionToken) { // an empty level if (this.Edges == null) { return new LevelKey(new List<EdgeKey> { myEdgeKey }, myGraphDB, mySecurityToken, myTransactionToken); } var edgeList = new List<EdgeKey>(this.Edges); // if the first and only edge has a null attrUUID the new edge must have the same type!! if (edgeList.Count == 1 && !edgeList[0].IsAttributeSet) { if (edgeList[0].VertexTypeID != myEdgeKey.VertexTypeID) { throw new InvalidLevelKeyOperationException(this, myEdgeKey, "+"); } else { return new LevelKey(new List<EdgeKey>() { myEdgeKey }, myGraphDB, mySecurityToken, myTransactionToken); } } else { if (myEdgeKey.IsAttributeSet) { edgeList.Add(myEdgeKey); } return new LevelKey(edgeList, myGraphDB, mySecurityToken, myTransactionToken); } }
private void FillGraph(IVertex aDBObject, LevelKey myPath, int currentBackwardResolution, VertexInformation source, EdgeKey tempEdgeKey, Dictionary<VertexInformation, IComparable> validUUIDs) { lock (_Levels) { VertexInformation node = GenerateVertexInfoFromLevelKeyAndVertexID(aDBObject.VertexTypeID, aDBObject.VertexID); if (currentBackwardResolution == 0) { #region Top level //there is no need for forward edges, because we are in the maximum level AddEmptyLevel(myPath); if (!_Levels[myPath.Level].ExpressionLevels[myPath].Nodes.ContainsKey(node)) { _Levels[myPath.Level].ExpressionLevels[myPath].Nodes.Add(node, new ExpressionNode(aDBObject, null, node)); } _Levels[myPath.Level].AddBackwardEdgesToNode(myPath, node, GetCorrectBackwardEdge(myPath), validUUIDs); #endregion } else { #region Top level - 1 int desiredLevel = myPath.Level - currentBackwardResolution; LevelKey desiredLevelKey = new LevelKey(myPath.Edges.Take(desiredLevel), _iGraphDB, _securityToken, _transactionToken); AddEmptyLevel(desiredLevelKey); _Levels[desiredLevel].AddForwardEdgeToNode(desiredLevelKey, node, new EdgeKey(myPath.Edges[desiredLevel].VertexTypeID, myPath.Edges[desiredLevel].AttributeID), source, null); #endregion } } }
private LevelKey GetBackwardLevelKey(LevelKey mylevelKey, EdgeKey edgeKey) { if (mylevelKey.Level == 1) { return new LevelKey(new List<EdgeKey> { edgeKey }, _iGraphDB, _securityToken, _transactionToken); } else { List<EdgeKey> newEdges = new List<EdgeKey>(); newEdges.AddRange(mylevelKey.Edges.Take(mylevelKey.Level - 2)); newEdges.Add(edgeKey); return new LevelKey(newEdges, _iGraphDB, _securityToken, _transactionToken); } throw new NotImplementedException(); }
internal Exceptional SetBackwardEdges(Dictionary<AttributeUUID, IObject> userdefinedAttributes, ObjectUUID reference) { var returnVal = new Exceptional(); #region process attributes foreach (var aUserDefinedAttribute in userdefinedAttributes) { #region Data GraphDBType typeOFAttribute = null; TypeAttribute attributesOfType = null; #endregion #region get GraphType of Attribute //attributesOfType = _graphDBType.Attributes[aUserDefinedAttribute.Key]; attributesOfType = _graphDBType.GetTypeAttributeByUUID(aUserDefinedAttribute.Key); typeOFAttribute = _dbContext.DBTypeManager.GetTypeByUUID(attributesOfType.DBTypeUUID); #endregion /* The DBO independent version */ var beEdge = new EdgeKey(_graphDBType.UUID, attributesOfType.UUID); var runMT = DBConstants.RunMT; runMT = false; if (runMT) { #region The parallel version /**/ /* The parallel version */ Parallel.ForEach(((IReferenceEdge)aUserDefinedAttribute.Value).GetAllReferenceIDs(), (uuid) => { var addExcept = _dbContext.DBObjectManager.AddBackwardEdge(uuid, attributesOfType.DBTypeUUID, beEdge, reference); if (!addExcept.Success()) { returnVal.PushIExceptional(addExcept); } }); if (!returnVal.Success()) { return returnVal; } /**/ #endregion } else { #region Single thread foreach (var uuid in ((IReferenceEdge)aUserDefinedAttribute.Value).GetAllReferenceIDs()) { var addExcept = _dbContext.DBObjectManager.AddBackwardEdge(uuid, attributesOfType.DBTypeUUID, beEdge, reference); if (addExcept.Failed()) { return new Exceptional(addExcept); } } #endregion } } #endregion return Exceptional.OK; } private Exceptional AddMandatoryAttributes(DBContext myDBContext, GraphDBType myGraphDBType, ManipulationAttributes myManipulationAttributes) { Boolean mandatoryDefaults = (Boolean)myDBContext.DBSettingsManager.GetSettingValue((new SettingDefaultsOnMandatory()).ID, myDBContext, TypesSettingScope.TYPE, myGraphDBType).Value.Value; TypeAttribute typeAttr = null; GraphDBType typeOfAttr = null; var typeMandatoryAttribs = myGraphDBType.GetMandatoryAttributesUUIDs(myDBContext.DBTypeManager); if ((myManipulationAttributes.MandatoryAttributes.Count < typeMandatoryAttribs.Count()) && !mandatoryDefaults) return new Exceptional(new Error_MandatoryConstraintViolation(myGraphDBType.Name)); foreach (var attrib in typeMandatoryAttribs) { if (!myManipulationAttributes.MandatoryAttributes.Contains(attrib)) { //if we have mandatory attributes in _graphDBType but not in the current statement and USE_DEFAULTS_ON_MANDATORY is true then do this if (mandatoryDefaults) { typeAttr = myGraphDBType.GetTypeAttributeByUUID(attrib); if (typeAttr == null) return new Exceptional(new Error_AttributeIsNotDefined(myGraphDBType.Name, typeAttr.Name)); typeOfAttr = myDBContext.DBTypeManager.GetTypeByUUID(typeAttr.DBTypeUUID); IObject defaultValue = typeAttr.DefaultValue; if (defaultValue == null) defaultValue = typeAttr.GetDefaultValue(myDBContext); myManipulationAttributes.Attributes.Add(new TypeAndAttributeDefinition(typeAttr, typeOfAttr), defaultValue); } else { return new Exceptional(new Error_MandatoryConstraintViolation("Attribute \"" + myGraphDBType.GetTypeAttributeByUUID(attrib).Name + "\" of Type \"" + myGraphDBType.Name + "\" is mandatory.")); } } } return Exceptional.OK; } private Exceptional<Boolean> DeleteObjectReferences(ObjectUUID myObjectUUID, BackwardEdgeStream myObjectBackwardEdges) { foreach (var item in myObjectBackwardEdges) { var type = _dbContext.DBTypeManager.GetTypeByUUID(item.Key.TypeUUID); if (type == null) { return new Exceptional<Boolean>(new Error_TypeDoesNotExist("")); } foreach (var objID in item.Value.GetAllEdgeDestinations(_dbContext.DBObjectCache)) { if (objID.Failed()) { return new Exceptional<Boolean>(objID); } var attr = objID.Value.GetAttribute(item.Key.AttrUUID); if (attr is IReferenceEdge) { var removeResult = ((IReferenceEdge)attr).RemoveUUID(myObjectUUID); if (removeResult) { #region Sucessfully removed the single edge ref - so remove the attribute if (attr is ASingleReferenceEdgeType) { objID.Value.RemoveAttribute(item.Key.AttrUUID); } #endregion } else { return new Exceptional<bool>(new Error_NotImplemented(new System.Diagnostics.StackTrace(true))); } } var flushExcept = _dbContext.DBObjectManager.FlushDBObject(objID.Value); if (!flushExcept.Success()) return new Exceptional<bool>(flushExcept.IErrors.First()); } } return new Exceptional<bool>(true); } private Dictionary<TypeAndAttributeDefinition, IObject> ExtractDefinedAttributes(Dictionary<string, Tuple<TypeAttribute, IObject>> attrsForResult, DBTypeManager myTypeManager) { return attrsForResult.Where(item => !(item.Value.Item1 is UndefinedTypeAttribute)).ToDictionary(key => new TypeAndAttributeDefinition(key.Value.Item1, key.Value.Item1.GetDBType(myTypeManager)), value => value.Value.Item2); } private Dictionary<string, IObject> ExtractUndefindedAttributes(Dictionary<string, Tuple<TypeAttribute, IObject>> attrsForResult) { return attrsForResult.Where(item => (item.Value.Item1 is UndefinedTypeAttribute)).ToDictionary(key => key.Key, value => value.Value.Item2); } private AttributeUUID GetAttributesToCheckForUnique(AAttributeAssignOrUpdateOrRemove myAAttributeAssignOrUpdateOrRemove) { if (myAAttributeAssignOrUpdateOrRemove is AAttributeRemove) return null; if (myAAttributeAssignOrUpdateOrRemove.AttributeIDChain.IsUndefinedAttribute) { return null; } if (myAAttributeAssignOrUpdateOrRemove is AAttributeAssignOrUpdate) { return ((AAttributeAssignOrUpdate)myAAttributeAssignOrUpdateOrRemove).AttributeIDChain.LastAttribute.UUID; } if (myAAttributeAssignOrUpdateOrRemove is AttributeAssignOrUpdateList) return ((AttributeAssignOrUpdateList)myAAttributeAssignOrUpdateOrRemove).AttributeIDChain.LastAttribute.UUID; throw new GraphDBException(new Error_NotImplemented(new System.Diagnostics.StackTrace(true))); } /// <summary> /// Create a readout based on the passed <paramref name="attributes"/>, <paramref name="undefinedAttributes"/>, <paramref name="specialTypeAttributes"/> which are all optional /// </summary> /// <param name="myDBObjectStreamExceptional"></param> /// <param name="attributes"></param> /// <param name="undefinedAttributes"></param> /// <param name="specialTypeAttributes"></param> /// <returns></returns> private Exceptional<Vertex> GetManipulationResultSet(Exceptional<DBObjectStream> myDBObjectStreamExceptional, Dictionary<TypeAndAttributeDefinition, IObject> attributes = null, Dictionary<String, IObject> undefinedAttributes = null, Dictionary<ASpecialTypeAttribute, Object> specialTypeAttributes = null) { Vertex _Vertex = null; #region Return inserted attributes #region attributes if (!attributes.IsNullOrEmpty()) { _Vertex = new Vertex(attributes.ToDictionary(key => key.Key.Definition.Name, value => value.Value.GetReadoutValue())); } else { _Vertex = new Vertex(); } #endregion #region UndefinedAttributes if (!undefinedAttributes.IsNullOrEmpty()) { foreach (var undefAttr in undefinedAttributes) { _Vertex.AddAttribute(undefAttr.Key, undefAttr.Value.GetReadoutValue()); } } #endregion #region SpecialTypeAttributes if (!specialTypeAttributes.IsNullOrEmpty()) { foreach (var specAttr in specialTypeAttributes) { _Vertex.AddAttribute(specAttr.Key.Name, specAttr.Value); } } #endregion #region UUID if (!_Vertex.HasAttribute(SpecialTypeAttribute_UUID.AttributeName)) { var extractedValue = new SpecialTypeAttribute_UUID().ExtractValue(myDBObjectStreamExceptional.Value, _graphDBType, _dbContext); if (extractedValue.Failed()) { return new Exceptional<Vertex>(extractedValue); } _Vertex.AddAttribute(SpecialTypeAttribute_UUID.AttributeName, extractedValue.Value.GetReadoutValue()); } #endregion #region REVISION if (!_Vertex.HasAttribute(SpecialTypeAttribute_REVISION.AttributeName)) // If it was updated by SpecialTypeAttributes we do not need to add them again { var extractedValue = new SpecialTypeAttribute_REVISION().ExtractValue(myDBObjectStreamExceptional.Value, _graphDBType, _dbContext); if (extractedValue.Failed()) { return new Exceptional<Vertex>(extractedValue); } _Vertex.AddAttribute(SpecialTypeAttribute_REVISION.AttributeName, extractedValue.Value.GetReadoutValue()); } #endregion #endregion return new Exceptional<Vertex>(_Vertex); } /// <summary> /// Get attribute assignments for new DBObjects. /// </summary> /// <param name="myAttributeAssigns">The interesting ParseTreeNode.</param> /// <param name="typeManager">The TypeManager of the GraphDB.</param> /// <returns>A Dictionary of AttributeAssignments</returns> private Exceptional<ManipulationAttributes> GetRecursiveAttributes(List<AAttributeAssignOrUpdate> myAttributeAssigns, DBContext myDBContext, GraphDBType myGraphDBType) { #region Data var manipulationAttributes = new ManipulationAttributes(); var resultExcept = new Exceptional<ManipulationAttributes>(); if (myAttributeAssigns == null) { return new Exceptional<ManipulationAttributes>(manipulationAttributes); } TypeAttribute attr; ADBBaseObject typedAttributeValue; BasicType correspondingCSharpType; Warning_UndefinedAttribute undefAttrWarning = null; var typeMandatoryAttribs = myGraphDBType.GetMandatoryAttributesUUIDs(myDBContext.DBTypeManager); var setExcept = myDBContext.DBSettingsManager.GetSetting(SettingUndefAttrBehaviour.UUID, myDBContext, TypesSettingScope.DB); if (!setExcept.Success()) { return new Exceptional<ManipulationAttributes>(setExcept); } var undefAttrBehave = (SettingUndefAttrBehaviour)setExcept.Value; #endregion #region get Data #region proceed list foreach (var aAttributeAssign in myAttributeAssigns) { var validateResult = aAttributeAssign.AttributeIDChain.Validate(myDBContext, true); if (validateResult.Failed()) { return new Exceptional<ManipulationAttributes>(validateResult); } #region Undefined attributes - Refactor and add undefined logic into defined attribute AssignsOrUpdate System.Diagnostics.Debug.Assert(aAttributeAssign.AttributeIDChain != null); //in this case we have an undefined attribute if (aAttributeAssign.AttributeIDChain.IsUndefinedAttribute) { var UndefAttrName = aAttributeAssign.AttributeIDChain.UndefinedAttribute; switch (undefAttrBehave.Behaviour) { case UndefAttributeBehaviour.disallow: return new Exceptional<ManipulationAttributes>(new Error_UndefinedAttributes()); case UndefAttributeBehaviour.warn: resultExcept.PushIWarning(new Warning_UndefinedAttribute(aAttributeAssign.AttributeIDChain)); break; } if (aAttributeAssign is AttributeAssignOrUpdateList) { #region AttributeAssignCollection var colDefinition = (aAttributeAssign as AttributeAssignOrUpdateList).CollectionDefinition; EdgeTypeListOfBaseObjects valueList = new EdgeTypeListOfBaseObjects(); foreach (var tuple in colDefinition.TupleDefinition) { if (tuple.TypeOfValue == BasicType.Unknown) valueList.Add((tuple.Value as ValueDefinition).Value); else if (tuple.Value is ValueDefinition) valueList.Add((tuple.Value as ValueDefinition).Value); else return new Exceptional<ManipulationAttributes>(new Error_NotImplemented(new System.Diagnostics.StackTrace(true))); } if (colDefinition.CollectionType == CollectionType.Set) valueList.UnionWith(valueList); manipulationAttributes.UndefinedAttributes.Add(UndefAttrName, valueList); var undefAttr = new UndefinedAttributeDefinition() { AttributeName = UndefAttrName, AttributeValue = valueList }; var undefAttrAssign = new AttributeAssignOrUpdateUndefined((aAttributeAssign as AttributeAssignOrUpdateList).AttributeIDChain, undefAttr); manipulationAttributes.AttributeToUpdateOrAssign.Add(undefAttrAssign); #endregion } else if (aAttributeAssign is AttributeAssignOrUpdateValue) { #region AttributeAssignValue var value = GraphDBTypeMapper.GetBaseObjectFromCSharpType((aAttributeAssign as AttributeAssignOrUpdateValue).Value); manipulationAttributes.UndefinedAttributes.Add(UndefAttrName, value); var undefAttr = new UndefinedAttributeDefinition() { AttributeName = UndefAttrName, AttributeValue = value }; var undefAttrAssign = new AttributeAssignOrUpdateUndefined((aAttributeAssign as AttributeAssignOrUpdateValue).AttributeIDChain, undefAttr); manipulationAttributes.AttributeToUpdateOrAssign.Add(undefAttrAssign); #endregion } else if (aAttributeAssign is AttributeAssignOrUpdateSetRef) { return new Exceptional<ManipulationAttributes>(new Error_InvalidReferenceAssignmentOfUndefAttr()); } else { return new Exceptional<ManipulationAttributes>(new Error_InvalidUndefinedAttributeName()); } continue; } #endregion attr = aAttributeAssign.AttributeIDChain.LastAttribute; manipulationAttributes.AttributeToUpdateOrAssign.Add(aAttributeAssign); #region checks if (aAttributeAssign.AttributeIDChain.LastType != myGraphDBType) { return new Exceptional<ManipulationAttributes>(new Error_InvalidAttribute(aAttributeAssign.AttributeIDChain.ToString())); } if (attr.GetDBType(myDBContext.DBTypeManager).IsBackwardEdge) { return new Exceptional<ManipulationAttributes>(new Error_Logic("Adding values to BackwardEdges Attributes are not allowed! (" + attr.Name + ") is an BackwardEdge Attribute of GraphType \"" + myGraphDBType.Name + "\".")); } #endregion #region SpecialTypeAttribute if (attr is ASpecialTypeAttribute) { if (!(aAttributeAssign is AttributeAssignOrUpdateValue)) { return new Exceptional<ManipulationAttributes>(new Error_InvalidAttributeValue((attr as ASpecialTypeAttribute).Name, aAttributeAssign.ToString())); } manipulationAttributes.SpecialTypeAttributes.Add((attr as ASpecialTypeAttribute), (aAttributeAssign as AttributeAssignOrUpdateValue).Value); continue; } #endregion #region check & add if (aAttributeAssign.AttributeIDChain.Edges.Count > 1) { //in case of those statements: INSERT INTO Flower VALUES (Colors.Name = 'red') //Colors.Name is an IDNode with 2 Edges. This is not possible. return new Exceptional<ManipulationAttributes>(new Error_Logic("Invalid attribute assignment : " + aAttributeAssign.AttributeIDChain.ToString() + " = " + aAttributeAssign)); } if (aAttributeAssign is AttributeAssignOrUpdateList) { #region SetOfDBObjects #region Check, whether this is valid for SetOfDBObjects if (attr.KindOfType != KindsOfType.SetOfReferences) { if (attr.KindOfType != KindsOfType.ListOfNoneReferences) { if (attr.KindOfType != KindsOfType.SetOfNoneReferences) { return new Exceptional<ManipulationAttributes>(new Error_ReferenceAssignmentExpected(attr));//"Please use SETREF keyword instead of REF/REFERENCE or LISTOF.")); } } } #endregion #region list stuff #region process tuple #region process as list var collectionDefinition = ((AttributeAssignOrUpdateList)aAttributeAssign).CollectionDefinition; var dbType = attr.GetDBType(myDBContext.DBTypeManager); if (dbType.IsUserDefined) { #region List of references var uuids = collectionDefinition.GetEdge(attr, dbType, myDBContext); if (uuids.Failed()) { return new Exceptional<ManipulationAttributes>(uuids); } manipulationAttributes.Attributes.Add(new TypeAndAttributeDefinition(attr, dbType), uuids.Value); if (typeMandatoryAttribs.Contains(attr.UUID)) { manipulationAttributes.MandatoryAttributes.Add(attr.UUID); } #endregion } else { #region List of ADBBaseObjects (Integer, String, etc) var edge = (aAttributeAssign as AttributeAssignOrUpdateList).GetBasicList(myDBContext); if (edge.Failed()) { return new Exceptional<ManipulationAttributes>(edge); } // If the collection was declared as a SETOF insert if (collectionDefinition.CollectionType == CollectionType.Set) edge.Value.Distinction(); manipulationAttributes.Attributes.Add(new TypeAndAttributeDefinition(attr, attr.GetDBType(myDBContext.DBTypeManager)), edge.Value); if (typeMandatoryAttribs.Contains(attr.UUID)) { manipulationAttributes.MandatoryAttributes.Add(attr.UUID); } #endregion } #endregion #endregion #endregion #endregion } else if (aAttributeAssign is AttributeAssignOrUpdateSetRef) { #region reference var aSetRefNode = ((AttributeAssignOrUpdateSetRef)aAttributeAssign).SetRefDefinition; var singleedge = aSetRefNode.GetEdge(attr, myDBContext, attr.GetRelatedType(myDBContext.DBTypeManager)); if (singleedge.Failed()) { return new Exceptional<ManipulationAttributes>(singleedge); } if (attr.GetRelatedType(myDBContext.DBTypeManager).IsUserDefined) { //a list which carries elements of userdefined types consists of GUIDS manipulationAttributes.Attributes.Add(new TypeAndAttributeDefinition(attr, attr.GetDBType(myDBContext.DBTypeManager)), singleedge.Value); if (typeMandatoryAttribs.Contains(attr.UUID)) { manipulationAttributes.MandatoryAttributes.Add(attr.UUID); } } else { return new Exceptional<ManipulationAttributes>(new Error_UnknownDBError("Reference types cannot be basic types.")); } #endregion } else if (aAttributeAssign is AttributeAssignOrUpdateExpression) { #region Expression (aAttributeAssign as AttributeAssignOrUpdateExpression).BinaryExpressionDefinition.Validate(myDBContext); var value = (aAttributeAssign as AttributeAssignOrUpdateExpression).BinaryExpressionDefinition.ResultValue; if (value.Failed()) { return new Exceptional<ManipulationAttributes>(value.IErrors.First()); } if (value.Value is ValueDefinition) { #region AtomValue if (attr.KindOfType == KindsOfType.SetOfReferences || attr.KindOfType == KindsOfType.ListOfNoneReferences || attr.KindOfType == KindsOfType.SetOfNoneReferences) return new Exceptional<ManipulationAttributes>(new Error_InvalidTuple(aAttributeAssign.ToString())); if (!(value.Value as ValueDefinition).IsDefined) { (value.Value as ValueDefinition).ChangeType(attr.GetDBType(myDBContext.DBTypeManager).UUID); } var val = (value.Value as ValueDefinition).Value.Value; correspondingCSharpType = GraphDBTypeMapper.ConvertGraph2CSharp(attr, attr.GetDBType(myDBContext.DBTypeManager)); if (GraphDBTypeMapper.GetEmptyGraphObjectFromType(correspondingCSharpType).IsValidValue(val)) { typedAttributeValue = GraphDBTypeMapper.GetGraphObjectFromType(correspondingCSharpType, val); manipulationAttributes.Attributes.Add(new TypeAndAttributeDefinition(attr, attr.GetDBType(myDBContext.DBTypeManager)), typedAttributeValue); if (typeMandatoryAttribs.Contains(attr.UUID)) manipulationAttributes.MandatoryAttributes.Add(attr.UUID); } else { return new Exceptional<ManipulationAttributes>(new Error_InvalidAttributeValue(attr.Name, (aAttributeAssign as AttributeAssignOrUpdateValue).Value)); } #endregion } else // TupleValue! { #region TupleValue if (attr.KindOfType != KindsOfType.SetOfReferences) return new Exceptional<ManipulationAttributes>(new Error_InvalidTuple(aAttributeAssign.ToString())); if (!(attr.EdgeType is IBaseEdge)) return new Exceptional<ManipulationAttributes>(new Error_InvalidEdgeType(attr.EdgeType.GetType(), typeof(IBaseEdge))); correspondingCSharpType = GraphDBTypeMapper.ConvertGraph2CSharp(attr, attr.GetDBType(myDBContext.DBTypeManager)); if ((value.Value as TupleDefinition).TypeOfOperatorResult != correspondingCSharpType) return new Exceptional<ManipulationAttributes>(new Error_DataTypeDoesNotMatch(correspondingCSharpType.ToString(), (value.Value as TupleDefinition).TypeOfOperatorResult.ToString())); var edge = attr.EdgeType.GetNewInstance() as IBaseEdge; edge.AddRange((value.Value as TupleDefinition).Select(te => (te.Value as ValueDefinition).Value)); manipulationAttributes.Attributes.Add(new TypeAndAttributeDefinition(attr, attr.GetDBType(myDBContext.DBTypeManager)), edge as IBaseEdge); #endregion } #endregion } else if (aAttributeAssign is AttributeAssignOrUpdateValue) { #region Simple value var attrVal = aAttributeAssign as AttributeAssignOrUpdateValue; if (attr.KindOfType == KindsOfType.ListOfNoneReferences) return new Exceptional<ManipulationAttributes>(new Error_InvalidTuple(attrVal.ToString())); if (attr.KindOfType != KindsOfType.SingleNoneReference) { return new Exceptional<ManipulationAttributes>(new Error_InvalidAttributeKind(attr.KindOfType, KindsOfType.SingleNoneReference)); } correspondingCSharpType = GraphDBTypeMapper.ConvertGraph2CSharp(attr, attr.GetDBType(myDBContext.DBTypeManager)); if (GraphDBTypeMapper.GetEmptyGraphObjectFromType(correspondingCSharpType).IsValidValue(attrVal.Value)) { typedAttributeValue = GraphDBTypeMapper.GetGraphObjectFromType(correspondingCSharpType, attrVal.Value); manipulationAttributes.Attributes.Add(new TypeAndAttributeDefinition(attr, attr.GetDBType(myDBContext.DBTypeManager)), typedAttributeValue); if (typeMandatoryAttribs.Contains(attr.UUID)) manipulationAttributes.MandatoryAttributes.Add(attr.UUID); } else { return new Exceptional<ManipulationAttributes>(new Error_InvalidAttributeValue(attr.Name, attrVal.Value)); } #endregion } else { return new Exceptional<ManipulationAttributes>(new Error_NotImplemented(new System.Diagnostics.StackTrace(true))); } #endregion } #endregion #endregion resultExcept.Value = manipulationAttributes; return resultExcept; } /// <summary> /// Inserts into all indices that are affected if a DBObject is updated on a certain attibute /// </summary> /// <param name="dBObjectStream"></param> /// <param name="attributeUUID"></param> /// <param name="_dbContext"></param> /// <returns></returns> private Exceptional InsertDBObjectIntoIndex(DBObjectStream dBObjectStream, AttributeUUID attributeUUID) { foreach (var aType in _dbContext.DBTypeManager.GetAllParentTypes(_dbContext.DBTypeManager.GetTypeByUUID(dBObjectStream.TypeUUID), true, false)) { foreach (var aAttributeIdx in aType.GetAttributeIndices(_dbContext, attributeUUID)) { var result = aAttributeIdx.Insert(dBObjectStream, aType, _dbContext); if (result.Failed()) { return new Exceptional(result); } } } return new Exceptional(); } /// <summary> /// Removes index entries corresponding to a DBObject /// </summary> /// <param name="dBObjectStream"></param> /// <param name="attributeUUID"></param> /// <param name="_dbContext"></param> /// <returns></returns> private Exceptional RemoveDBObjectFromIndex(DBObjectStream dBObjectStream, AttributeUUID attributeUUID) { foreach (var aType in _dbContext.DBTypeManager.GetAllParentTypes(_dbContext.DBTypeManager.GetTypeByUUID(dBObjectStream.TypeUUID), true, false)) { foreach (var aAttributeIdx in aType.GetAttributeIndices(_dbContext, attributeUUID)) { var result = aAttributeIdx.Remove(dBObjectStream, aType, _dbContext); if (result.Failed()) { return new Exceptional(result); } } } return new Exceptional(); } private Exceptional RemoveUndefAttrs(IEnumerable<Exceptional<DBObjectStream>> myDBObjStream, List<String> myUndefAttrs) { #region delete undefined attributes foreach (var objects in myDBObjStream) { var undefAttrsStream = myUndefAttrs.Where(item => objects.Value.GetUndefinedAttributePayload(_dbContext.DBObjectManager).Value.ContainsKey(item)); foreach (var undefAttr in undefAttrsStream) { var removeExcept = _dbContext.DBObjectManager.RemoveUndefinedAttribute(undefAttr, objects.Value); if (removeExcept.Failed()) return new Exceptional(removeExcept); } } #endregion return Exceptional.OK; } /// <summary> /// setting the default value for the attribute /// </summary> /// <param name="myAttr">the attribute</param> /// <param name="myDBObjectCache">the object cache</param> /// <returns>true if the value was changed</returns> private Exceptional<Boolean> SetDefaultValue(TypeAttribute myAttr, Exceptional<DBObjectStream> myDBO) { if (myDBO.Success()) { IObject defaultValue = myAttr.DefaultValue; if (defaultValue == null) defaultValue = myAttr.GetDefaultValue(_dbContext); var alterExcept = myDBO.Value.AlterAttribute(myAttr.UUID, defaultValue); if (alterExcept.Failed()) return new Exceptional<Boolean>(alterExcept); if (!alterExcept.Value) { return new Exceptional<bool>(false); } } else { return new Exceptional<bool>(false); } return new Exceptional<bool>(true); } /// <summary> /// This is the update method which will change some <paramref name="myDBObjects"/> on behalf of the <paramref name="myListOfUpdates"/> /// </summary> /// <param name="myDBObjects">Some dbobjects</param> /// <param name="myListOfUpdates">The list of update tasks (assign, delete, etc)</param> /// <param name="dbObjectCache"></param> /// <returns></returns> private QueryResult Update(IEnumerable<Exceptional<DBObjectStream>> myDBObjects, IEnumerable<AAttributeAssignOrUpdateOrRemove> myListOfUpdates) { #region Data var queryResultContent = new List<Vertex>(); var queryResult = new QueryResult(); #endregion #region check for undefined attributes setting var undefAttrSetting = _dbContext.DBSettingsManager.GetSetting(SettingUndefAttrBehaviour.UUID, _dbContext, TypesSettingScope.DB); if (!undefAttrSetting.Success()) { return new QueryResult(undefAttrSetting); } var undefSettingVal = ((SettingUndefAttrBehaviour)undefAttrSetting.Value).Behaviour; #endregion #region Validate attributes var definedAttributeAssignments = new Dictionary<AttributeUUID, AAttributeAssignOrUpdate>(); foreach (var updateOrAssign in myListOfUpdates) { System.Diagnostics.Debug.Assert(updateOrAssign != null); if (!(updateOrAssign is AttributeRemove)) { var result = updateOrAssign.AttributeIDChain.Validate(_dbContext, true); if (result.Failed()) { return new QueryResult(result); } if (updateOrAssign.IsUndefinedAttributeAssign) { #region handle undefined attributes switch (undefSettingVal) { case UndefAttributeBehaviour.disallow: return new QueryResult(new Error_UndefinedAttributes()); case UndefAttributeBehaviour.warn: queryResult.PushIWarning(new Warning_UndefinedAttribute(updateOrAssign.AttributeIDChain)); break; } #endregion } else { //here a dictionary is used, because myListOfUpdates will be traversed many times now (maybe CachedEnumerator can be used instead) if (updateOrAssign is AAttributeAssignOrUpdate) definedAttributeAssignments[GetAttributesToCheckForUnique(updateOrAssign)] = updateOrAssign as AAttributeAssignOrUpdate; } } } #endregion #region check unique constraint if (definedAttributeAssignments.CountIsGreater(0)) { Exceptional<Boolean> CheckConstraint = null; IEnumerable<GraphDBType> parentTypes = _dbContext.DBTypeManager.GetAllParentTypes(_graphDBType, true, false); foreach (var entry in myDBObjects) { //here all attributes are listed, that will change their value var changingAttributes = (from CurrentAttribute in entry.Value.GetAttributes() join Update in definedAttributeAssignments on CurrentAttribute.Key equals Update.Key where !CurrentAttribute.Value.Equals(Update.Value.GetValueForAttribute(entry.Value, _dbContext, _graphDBType).Value) select new {Key = CurrentAttribute.Key, Value = CurrentAttribute.Value}).ToDictionary(x=>x.Key, x=>x.Value); CheckConstraint = _dbContext.DBIndexManager.CheckUniqueConstraint(_graphDBType, parentTypes, changingAttributes); if (CheckConstraint.Failed()) return new QueryResult(CheckConstraint.IErrors); } } #endregion #region regular update foreach (var aDBO in myDBObjects) { //key: attribute name //value: TypeAttribute, NewValue Dictionary<String, Tuple<TypeAttribute, IObject>> attrsForResult = new Dictionary<String, Tuple<TypeAttribute, IObject>>(); if (aDBO.Failed()) { return new QueryResult(aDBO); } #region data Boolean sthChanged = false; #endregion #region iterate tasks //Exceptional<Boolean> partialResult; foreach (var attributeUpdateOrAssign in myListOfUpdates) { var updateResult = attributeUpdateOrAssign.Update(_dbContext, aDBO.Value, _graphDBType); if (updateResult.Failed()) { return new QueryResult(updateResult); } if (updateResult.Value.Count > 0) { sthChanged = true; attrsForResult.AddRange(updateResult.Value); } } #endregion if (sthChanged) { var definedAttributes = ExtractDefinedAttributes(attrsForResult, _dbContext.DBTypeManager); #region update Idx foreach (var _AttributeIndex in _graphDBType.GetAllAttributeIndices(_dbContext)) { if(definedAttributes.Exists(item => _AttributeIndex.IndexKeyDefinition.IndexKeyAttributeUUIDs.Contains(item.Key.Definition.UUID))) { //execute update _AttributeIndex.Update(aDBO.Value, _graphDBType, _dbContext); } } #endregion #region update dbobjects on fs var flushResult = _dbContext.DBObjectManager.FlushDBObject(aDBO.Value); if (!flushResult.Success()) { return new QueryResult(flushResult); } #endregion var resultSet = GetManipulationResultSet(aDBO, undefinedAttributes: ExtractUndefindedAttributes(attrsForResult), attributes: definedAttributes); if (!resultSet.Success()) { /* what should happen now this should not break the update */ } queryResultContent.Add(resultSet.Value); } }
private LevelKey GetForwardLevelKey(LevelKey mylevelKey, EdgeKey edgeKey) { if (mylevelKey.Level == 0) { return new LevelKey(new List<EdgeKey> { edgeKey }, _iGraphDB, _securityToken, _transactionToken); } else { List<EdgeKey> newEdges = new List<EdgeKey>(); newEdges.AddRange(mylevelKey.Edges); newEdges.Add(edgeKey); return new LevelKey(newEdges, _iGraphDB, _securityToken, _transactionToken); } }
/// <inheritdoc /> protected override void InternalCompute() { // Create condensed graph CondensedGraph = new BidirectionalGraph <TGraph, CondensedEdge <TVertex, TEdge, TGraph> >(false); if (VisitedGraph.VertexCount == 0) { return; } // Compute strongly connected components var components = new Dictionary <TVertex, int>(VisitedGraph.VertexCount); int componentCount = ComputeComponentCount(components); ThrowIfCancellationRequested(); // Create vertices list var condensedVertices = new Dictionary <int, TGraph>(componentCount); for (int i = 0; i < componentCount; ++i) { var vertex = new TGraph(); condensedVertices.Add(i, vertex); CondensedGraph.AddVertex(vertex); } // Adding vertices foreach (TVertex vertex in VisitedGraph.Vertices) { condensedVertices[components[vertex]].AddVertex(vertex); } ThrowIfCancellationRequested(); // Condensed edges var condensedEdges = new Dictionary <EdgeKey, CondensedEdge <TVertex, TEdge, TGraph> >(componentCount); // Iterate over edges and condensate graph foreach (TEdge edge in VisitedGraph.Edges) { // Get component ids int sourceID = components[edge.Source]; int targetID = components[edge.Target]; // Get vertices TGraph sources = condensedVertices[sourceID]; if (sourceID == targetID) { sources.AddEdge(edge); continue; } // At last add edge var edgeKey = new EdgeKey(sourceID, targetID); if (!condensedEdges.TryGetValue(edgeKey, out CondensedEdge <TVertex, TEdge, TGraph> condensedEdge)) { TGraph targets = condensedVertices[targetID]; condensedEdge = new CondensedEdge <TVertex, TEdge, TGraph>(sources, targets); condensedEdges.Add(edgeKey, condensedEdge); CondensedGraph.AddEdge(condensedEdge); } condensedEdge.Edges.Add(edge); } }
private LevelKey GetForwardLevelKey(LevelKey mylevelKey, EdgeKey edgeKey, DBTypeManager myTypeManager) { if (mylevelKey.Level == 0) { return new LevelKey(new List<EdgeKey> { edgeKey }, myTypeManager); } else { List<EdgeKey> newEdges = new List<EdgeKey>(); newEdges.AddRange(mylevelKey.Edges); newEdges.Add(edgeKey); return new LevelKey(newEdges, myTypeManager); } }
public void RemoveForwardEdge(EdgeKey myEdgeKey, VertexInformation myObjectUUID) { lock (_lockObj) { if (!_ForwardEdges.ContainsKey(myEdgeKey)) return; _ForwardEdges[myEdgeKey].RemoveWhere(exprEdge => exprEdge.Destination == myObjectUUID); } }
public void AddBackwardEdge(EdgeKey backwardDestination, VertexInformation validUUIDs, IComparable edgeWeight) { lock (_lockObj) { var backwardEdges = new HashSet<IExpressionEdge>() { new ExpressionEdge(validUUIDs, edgeWeight, backwardDestination) }; if (_BackwardEdges.ContainsKey(backwardDestination)) { _BackwardEdges[backwardDestination].UnionWith(backwardEdges); } else { _BackwardEdges.Add(backwardDestination, backwardEdges); } } }
public void AddForwardEdge(EdgeKey ForwardEdge, VertexInformation destination, IComparable weight) { lock (_lockObj) { if (_ForwardEdges.ContainsKey(ForwardEdge)) { _ForwardEdges[ForwardEdge].Add(new ExpressionEdge(destination, weight, ForwardEdge)); } else { _ForwardEdges.Add(ForwardEdge, new HashSet<IExpressionEdge>() { new ExpressionEdge(destination, weight, ForwardEdge) }); } } }
/// <summary> /// This returns the TypeAttribute defined by an edge /// </summary> /// <param name="myEdgeKey">An EdgeKey containing the TypeUUID and AttributeUUID</param> /// <returns>TypeAttribute defined by an edge</returns> public TypeAttribute GetTypeAttributeByEdge(EdgeKey myEdgeKey) { return GetTypeByUUID(myEdgeKey.TypeUUID).GetTypeAttributeByUUID(myEdgeKey.AttrUUID); }
internal Exceptional AddBackwardEdge(ObjectUUID uuid, TypeUUID typeOfBESource, EdgeKey beEdgeKey, ObjectUUID reference) { //var beLocation = DBObjectStream.GetObjectLocation(_DBContext.DBTypeManager.GetTypeByUUID(typeOfBESource), uuid); var loadExcept = _DBContext.DBObjectCache.LoadDBBackwardEdgeStream(typeOfBESource, uuid); // LoadBackwardEdge(beLocation); if (loadExcept.Failed()) { return new Exceptional(loadExcept); } //EdgeKey tempKey = new EdgeKey(typeUUID, attributeUUID); loadExcept.Value.AddBackwardEdge(beEdgeKey, reference, this); if (loadExcept.Value.isNew) { return _IGraphFSSession.StoreFSObject(loadExcept.Value, true); } else { return loadExcept.Value.Save(); } }