예제 #1
0
파일: ToUNIXDate.cs 프로젝트: TheByte/sones
        public override Exceptional<FuncParameter> ExecFunc(DBContext dbContext, params FuncParameter[] myParams)
        {
            Exceptional<FuncParameter> result = new Exceptional<FuncParameter>();

            if (CallingObject is DBUInt64)
            {
                try
                {
                    var dtValue = new DateTime(System.Convert.ToInt64(((DBUInt64)CallingObject).Value));
                    result.Value = new FuncParameter(new DBInt64(dtValue.ToUnixTimeStamp()));
                }
                catch (Exception e)
                {
                    return new Exceptional<FuncParameter>(new Error_UnknownDBError(e.Message));
                }

                return result;
            }
            else if (CallingObject is DBDateTime)
            {
                result.Value = new FuncParameter(new DBInt64(((DateTime)((DBDateTime)CallingObject).Value).ToUnixTimeStamp()));
            }
            else
            {
                Debug.Assert(false); // this should never happen due to the ValidateWorkingBase method
                return new Exceptional<FuncParameter>(new Error_FunctionParameterTypeMismatch(typeof(DBDateTime), CallingObject.GetType()));
            }

            return result;
        }
예제 #2
0
        public override Exceptional<FuncParameter> ExecFunc(DBContext dbContext, params FuncParameter[] myParams)
        {
            var pResult = new Exceptional<FuncParameter>();

            // The edge we starting of (Friends)
            var typeAttribute = CallingAttribute;

            // Get the source Objects from the CallingObject, if this is not a reference this function is used in a wrong context and return a error
            IEnumerable<ObjectUUID> sourceDBOs = null;
            if (CallingObject is IReferenceEdge)
            {
                sourceDBOs = (CallingObject as ASetOfReferencesEdgeType).GetAllReferenceIDs();
            }
            else
            {
                throw new GraphDBException(new Error_InvalidEdgeType(CallingAttribute.EdgeType.GetType(), typeof(ASetOfReferencesEdgeType), typeof(ASingleReferenceEdgeType)));
            }

            // The destination DBObjects which are passed with the first parameter
            var destDBOs = (myParams[0].Value as DBEdge).GetDBObjects();
            if (destDBOs == null)
            {
                throw new GraphDBException(new Error_InvalidEdgeType(CallingAttribute.EdgeType.GetType(), typeof(ASetOfReferencesEdgeType), typeof(ASingleReferenceEdgeType)));
            }

            // The depth which is passed as the second parameter
            Int64 mayDepth = (myParams[1].Value as DBInt64).GetValue();

            // Call your own implementation of a path function and return the result, in this case it is a list of DB object (uuids)
            var resultOfPathFunction = new List<ObjectUUID>();

            pResult.Value = new FuncParameter(new EdgeTypeSetOfReferences(resultOfPathFunction, CallingAttribute.DBTypeUUID));

            return pResult;
        }
예제 #3
0
파일: TopFunc.cs 프로젝트: TheByte/sones
        public override Exceptional<FuncParameter> ExecFunc(DBContext dbContext, params FuncParameter[] myParams)
        {
            var pResult = new Exceptional<FuncParameter>();

            ulong numOfEntries = (myParams[0].Value as DBUInt64).GetValue();

            var retVal = (IEdgeType)(CallingObject as IListOrSetEdgeType).GetTopAsEdge(numOfEntries);
            pResult.Value = new FuncParameter(retVal, CallingAttribute);

            return pResult;
        }
예제 #4
0
        public override Exceptional<FuncParameter> ExecFunc(DBContext dbContext, params FuncParameter[] myParams)
        {
            var result = new Exceptional<FuncParameter>();

            if (!(CallingObject is EdgeTypeWeighted))
            {
                return result.PushIErrorT(new Error_FunctionParameterTypeMismatch(typeof(EdgeTypeWeighted), CallingObject.GetType()));
            }

            result.Value = new FuncParameter(((EdgeTypeWeighted)CallingObject).GetMaxWeight());

            return result;
        }
예제 #5
0
        /// <summary>
        /// Execute the removal of attribute indices
        /// <seealso cref=" AAlterTypeCommand"/>
        /// </summary>        
        public override Exceptional Execute(DBContext myDBContext, GraphDBType myGraphDBType)
        {
            var retExceptional = new Exceptional();

            foreach (var index in _IdxDropList)
            {
                var dropIdxExcept = myGraphDBType.RemoveIndex(index.Key, index.Value, myDBContext);

                if (!dropIdxExcept.Success())
                {
                    retExceptional.PushIExceptional(dropIdxExcept);
                }
            }

            return retExceptional;
        }
예제 #6
0
        public override Exceptional<FuncParameter> ExecFunc(DBContext dbContext, params FuncParameter[] myParams)
        {
            Exceptional<FuncParameter> result = new Exceptional<FuncParameter>();

            if (CallingObject != null)
            {
                if (CallingObject is DBInt64)
                {
                    result.Value = new FuncParameter(new DBDateTime(((Int64)((DBInt64)CallingObject).Value).FromUnixTimeStamp()));
                }
                else
                {
                    result = new Exceptional<FuncParameter>(new Error_FunctionParameterTypeMismatch(typeof(DBInt64), CallingObject.GetType()));
                }
            }
            else
                return new Exceptional<FuncParameter>(new Error_NotImplemented(new System.Diagnostics.StackTrace(true)));

            return result;
        }
예제 #7
0
        /// <summary>
        /// Executes the removal of certain myAttributes.
        /// <seealso cref=" AAlterTypeCommand"/>
        /// </summary>
        public override Exceptional Execute(DBContext myDBContext, GraphDBType myGraphDBType)
        {
            Exceptional result = new Exceptional();

            foreach (String aAttributeName in _ListOfAttributes)
            {
                var attr = myGraphDBType.GetTypeAttributeByName(aAttributeName);

                if (attr != null)
                {
                    var idxs = new List<Indices.AAttributeIndex>(myGraphDBType.GetAttributeIndices(myDBContext, attr.UUID));

                    foreach (var item in idxs)
                    {
                        var remIdxResult = myGraphDBType.RemoveIndex(item.IndexName, item.IndexEdition, myDBContext);

                        if (remIdxResult.Failed())
                        {
                            result.PushIExceptional(remIdxResult);
                        }
                    }
                }
                else
                {
                    result.PushIError(new Error_AttributeIsNotDefined(aAttributeName));
                    return result;
                }

                //Hack: remove myAttributes in DBObjects
                var aTempResult = myDBContext.DBTypeManager.RemoveAttributeFromType(myGraphDBType.Name, aAttributeName, myDBContext.DBTypeManager);

                if (aTempResult.Failed())
                {
                    result.PushIExceptional(aTempResult);
                    return result;
                }
            }

            return result;
        }
예제 #8
0
파일: InsertFunc.cs 프로젝트: TheByte/sones
        public override Exceptional<FuncParameter> ExecFunc(DBContext dbContext, params FuncParameter[] myParams)
        {
            var result = new Exceptional<FuncParameter>();

            if (!(CallingObject is ADBBaseObject))
            {
                return new Exceptional<FuncParameter>(new Errors.Error_InvalidFunctionParameter("CallingObject", "ADBBaseObject", CallingObject.GetType()));
            }

            var pos = (myParams[0].Value as DBInt32).GetValue();

            StringBuilder resString = new StringBuilder((CallingObject as ADBBaseObject).Value.ToString().Substring(0, pos));
            foreach (FuncParameter fp in myParams.Skip(1))
            {
                resString.Append((fp.Value as DBString).GetValue());
            }
            resString.Append((CallingObject as ADBBaseObject).Value.ToString().Substring(pos));

            result = new Exceptional<FuncParameter>(new FuncParameter(new DBString(resString.ToString())));

            return result;
        }
예제 #9
0
파일: CountFunc.cs 프로젝트: TheByte/sones
        public override Exceptional<FuncParameter> ExecFunc(DBContext dbContext, params FuncParameter[] myParams)
        {
            var pResult = new Exceptional<FuncParameter>();

            if (CallingObject is IListOrSetEdgeType)
            {
                pResult.Value = new FuncParameter(new DBUInt64(((IListOrSetEdgeType)CallingObject).Count()));
            }
            else if (CallingObject is ASingleReferenceEdgeType)
            {
                pResult.Value = new FuncParameter(new DBUInt64(1));
            }
            else if (CallingObject is IEnumerable<ObjectUUID>)
            {
                pResult.Value = new FuncParameter(new DBUInt64((CallingObject as IEnumerable<ObjectUUID>).LongCount()));
            }
            else
            {
                return pResult.PushIErrorT(new Error_FunctionParameterTypeMismatch(typeof(IEdgeType), CallingObject.GetType()));
            }

            return pResult;
        }
예제 #10
0
        /// <summary>
        /// Removes an attribute of the given type.
        /// </summary>
        /// <param name="targetClass">The target type.</param>
        /// <param name="myAttributeName">The attribute name, referencing the deprecated attribute.</param>
        /// <returns>True, if the attribute was successfully removed. Else, false.(it didnt exist)</returns>
        public Exceptional<ResultType> RemoveAttributeFromType(String targetClass, String attributeName, DBTypeManager myTypeManager)
        {
            #region INPUT EXCEPTIONS

            if (String.IsNullOrEmpty(targetClass))
                return new Exceptional<ResultType>(new Error_ArgumentNullOrEmpty(targetClass));

            if (String.IsNullOrEmpty(attributeName))
                return new Exceptional<ResultType>(new Error_ArgumentNullOrEmpty(attributeName));

            #endregion

            #region Data

            GraphDBType aType = GetTypeByName(targetClass);

            #endregion

            #region check if type exists

            if (aType == null)
                return new Exceptional<ResultType>(new Error_TypeDoesNotExist(targetClass));

            #endregion

            TypeAttribute Attribute = aType.GetTypeAttributeByName(attributeName);

            Exceptional<ResultType> retVal = null;

            if (Attribute != null)
            {
                //Check for other attributes that reference this one (i.e. as BackwardEdge)

                var referncedBy = GetBackwardReferencesForAttribute(Attribute);
                if (referncedBy.Count > 0)
                {
                    return new Exceptional<ResultType>(new Error_DropOfAttributeNotAllowed(Attribute.GetRelatedType(this).Name, attributeName, referncedBy.ToDictionary(key => key, value => value.GetRelatedType(this))));
                }

                if (Attribute.GetRelatedType(this) != aType)
                {
                    return new Exceptional<ResultType>(new Error_DropOfDerivedAttributeIsNotAllowed(Attribute.GetRelatedType(this).Name, attributeName));
                }
                retVal = RemoveAttributeOfType(aType, Attribute.UUID);
            }
            else
            {
                retVal = new Exceptional<ResultType>(new Error_AttributeIsNotDefined(attributeName));
            }

            return retVal;
        }
예제 #11
0
파일: DBObjectCache.cs 프로젝트: ipbi/sones
        /// <summary>
        /// Internal method for loading a DBObject from GraphFS.
        /// </summary>
        /// <param name="myType">The Type of the DBObjects as GraphType.</param>
        /// <param name="myObjectUUID">The UUID of the DBObject.</param>
        /// <returns>An DBObject</returns>
        private Exceptional<DBObjectStream> LoadDBObjectInternal(GraphDBType myType, ObjectUUID myObjectUUID)
        {
            var tempResult = _DBObjectManager.LoadDBObject(myType, myObjectUUID);

            #region Try all subTypes - as long as the Symlink alternativ does not work

            if (tempResult.Failed())
            {

                var exceptional = new Exceptional<DBObjectStream>(tempResult);

                #region Try sub types

                foreach (var type in _typeManager.GetAllSubtypes(myType, false))
                {
                    tempResult = LoadDBObjectInternal(type, myObjectUUID);
                    if (tempResult.Success())
                        break;
                    else
                        exceptional = new Exceptional<DBObjectStream>(tempResult);
                }

                #endregion

                if (tempResult.Failed())
                    return exceptional;
            }

            #endregion

            return tempResult;
        }
예제 #12
0
파일: DBObjectCache.cs 프로젝트: ipbi/sones
        private bool IsValidDBObjectForLevelKey(Exceptional<DBObjectStream> aDBO, LevelKey myLevelKey, GraphDBType typeOfDBO)
        {
            if (myLevelKey.Level == 0)
            {
                return true;
            }
            else
            {
                Boolean isValidDBO = false;

                EdgeKey backwardEdgeKey = myLevelKey.LastEdge;
                TypeAttribute currentAttribute = _typeManager.GetTypeByUUID(backwardEdgeKey.TypeUUID).GetTypeAttributeByUUID(backwardEdgeKey.AttrUUID);
                IEnumerable<Exceptional<DBObjectStream>> dbobjects = null;
                GraphDBType typeOfBackwardDBOs = null;

                if (currentAttribute.IsBackwardEdge)
                {
                    backwardEdgeKey = currentAttribute.BackwardEdgeDefinition;

                    currentAttribute = _typeManager.GetTypeByUUID(backwardEdgeKey.TypeUUID).GetTypeAttributeByUUID(backwardEdgeKey.AttrUUID);

                    typeOfBackwardDBOs = currentAttribute.GetDBType(_typeManager);

                    if (aDBO.Value.HasAttribute(backwardEdgeKey.AttrUUID, typeOfDBO))
                    {
                        dbobjects = GetReferenceObjects(aDBO.Value, currentAttribute, typeOfDBO, _typeManager);
                    }
                }
                else
                {
                    BackwardEdgeStream beStreamOfDBO = LoadDBBackwardEdgeStream(typeOfDBO, aDBO.Value.ObjectUUID).Value;

                    typeOfBackwardDBOs = _typeManager.GetTypeByUUID(backwardEdgeKey.TypeUUID);

                    if (beStreamOfDBO.ContainsBackwardEdge(backwardEdgeKey))
                    {
                        dbobjects = LoadListOfDBObjectStreams(typeOfBackwardDBOs, beStreamOfDBO.GetBackwardEdgeUUIDs(backwardEdgeKey));
                    }
                }

                if (dbobjects != null)
                {
                    LevelKey myLevelKeyPred = myLevelKey.GetPredecessorLevel(_typeManager);

                    foreach (var aBackwardDBO in dbobjects)
                    {
                        if (aBackwardDBO.Success())
                        {
                            if (IsValidDBObjectForLevelKey(aBackwardDBO, myLevelKeyPred, typeOfBackwardDBOs))
                            {
                                isValidDBO = true;
                                break;
                            }
                        }
                    }
                }
                else
                {
                    return false;
                }

                return isValidDBO;
            }
        }
예제 #13
0
        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);
                }
            }
예제 #14
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_graphDBType"></param>
        /// <param name="myAttributes">Pass null if you want to delete the whole object with all attributes</param>
        /// <param name="myListOfAffectedDBObjectUUIDs"></param>
        /// <param name="_dbContext"></param>
        /// <param name="myToken"></param>
        /// <param name="myDBObjectCache"></param>
        /// <returns></returns>
        public Exceptional<IEnumerable<Vertex>> DeleteDBObjects(GraphDBType myGraphDBType, List<TypeAttribute> myAttributes, IEnumerable<Exceptional<DBObjectStream>> myListOfAffectedDBObjects)
        {
            //some stuff for queryResult
            UInt64 deletionCounter = 0;

            foreach (var aDBO in myListOfAffectedDBObjects)
            {
                if (aDBO.Failed())
                {
                    return new Exceptional<IEnumerable<Vertex>>(new Error_LoadObject(aDBO.Value.ObjectLocation));
                }

                deletionCounter++;

                if (!myAttributes.IsNullOrEmpty())
                {

                    #region Delete some defined attributes

                    foreach (var Attr in myAttributes)
                    {
                        if (Attr.GetRelatedType(_dbContext.DBTypeManager).GetMandatoryAttributesUUIDs(_dbContext.DBTypeManager).Contains(Attr.UUID))
                        {

                            #region Attribute is mandatory - set default value

                            if ((Boolean)_dbContext.DBSettingsManager.GetSetting(SettingDefaultsOnMandatory.UUID, _dbContext, TypesSettingScope.TYPE, Attr.GetRelatedType(_dbContext.DBTypeManager)).Value.Value.Value)
                            {
                                //the attribute will be removed from the dbobject --> update index
                                var removeAttributefromIdxResult = RemoveDBObjectFromIndex(aDBO.Value, Attr.UUID);

                                if (removeAttributefromIdxResult.Failed())
                                {
                                    return new Exceptional<IEnumerable<Vertex>>(removeAttributefromIdxResult);
                                }

                                var defaultExcept = SetDefaultValue(Attr, aDBO);

                                if (defaultExcept.Failed())
                                    return new Exceptional<IEnumerable<Vertex>>(defaultExcept);

                                if (!defaultExcept.Value)
                                    return new Exceptional<IEnumerable<Vertex>>(new Error_UpdateAttributeValue(Attr));

                                #region update idx

                                //--> update index
                                var updateAttributefromIdxResult = InsertDBObjectIntoIndex(aDBO.Value, Attr.UUID);

                                if (updateAttributefromIdxResult.Failed())
                                {
                                    return new Exceptional<IEnumerable<Vertex>>(updateAttributefromIdxResult);
                                }

                                #endregion
                            }
                            else
                                return new Exceptional<IEnumerable<Vertex>>(new Error_MandatoryConstraintViolation(Attr.Name));

                            #endregion

                        }
                        else
                        {
                            //the attribute will be removed from the dbobject --> update index
                            var removeAttributefromIdxResult = RemoveDBObjectFromIndex(aDBO.Value, Attr.UUID);

                            if (removeAttributefromIdxResult.Failed())
                            {
                                return new Exceptional<IEnumerable<Vertex>>(removeAttributefromIdxResult);
                            }

                            if (!aDBO.Value.RemoveAttribute(Attr.UUID))
                            {
                                return new Exceptional<IEnumerable<Vertex>>(new Error_RemoveTypeAttribute(myGraphDBType, Attr));
                            }

                        }
                    }

                    var saveResult = aDBO.Value.Save();

                    if (!saveResult.Success())
                    {
                        return new Exceptional<IEnumerable<Vertex>>(saveResult);
                    }

                    #endregion

                }
                else
                {

                    #region Remove complete DBO

                    var objID = aDBO.Value.ObjectUUID;

                    var backwardEdgeLoadExcept = _dbContext.DBObjectManager.LoadBackwardEdge(aDBO.Value.ObjectLocation);

                    if (!backwardEdgeLoadExcept.Success())
                        return new Exceptional<IEnumerable<Vertex>>(backwardEdgeLoadExcept.IErrors.First());

                    var backwarEdges = backwardEdgeLoadExcept.Value;

                    var removeResult = _dbContext.DBObjectManager.RemoveDBObject(myGraphDBType, aDBO.Value, _dbContext.DBObjectCache, _dbContext.SessionSettings);

                    if (!removeResult.Success())
                    {
                        return new Exceptional<IEnumerable<Vertex>>(removeResult);
                    }

                    if (backwarEdges != null)
                    {
                        var delEdgeRefs = DeleteObjectReferences(objID, backwarEdges);

                        if (!delEdgeRefs.Success())
                            return new Exceptional<IEnumerable<Vertex>>(delEdgeRefs.IErrors.First());
                    }

                    #endregion

                }
            }

            if (deletionCounter == 0)
            {
                var result = new Exceptional<IEnumerable<Vertex>>(new List<Vertex>());
                return result.PushIWarningT(new Warning_NoObjectsToDelete());
            }

            return new Exceptional<IEnumerable<Vertex>>(new List<Vertex>());
        }
예제 #15
0
        private TypesOfBinaryExpression SetTypeOfBinaryExpression(Exceptional<DataContainer> leftData, Exceptional<DataContainer> rightData)
        {
            TypesOfBinaryExpression result;

            if (leftData.Value.IDChainDefinitions.Item1 != null && rightData.Value.IDChainDefinitions.Item1 != null)
            {
                result = TypesOfBinaryExpression.Complex;
            }
            else
            {
                if (leftData.Value.IDChainDefinitions.Item1 == null && rightData.Value.IDChainDefinitions.Item1 == null)
                {
                    result = TypesOfBinaryExpression.Atom;
                }
                else
                {
                    if (leftData.Value.IDChainDefinitions.Item1 != null)
                    {
                        result = TypesOfBinaryExpression.LeftComplex;
                    }
                    else
                    {
                        result = TypesOfBinaryExpression.RightComplex;
                    }
                }
            }

            return result;
        }
예제 #16
0
        /// <summary>
        /// Finds matching result corresponding to a binary expression.
        /// </summary>
        /// <param name="myLeftValueObject">The left value of a binary expression.</param>
        /// <param name="myRightValueObject">The right value of a binary expression.</param>
        /// <param name="currentTypeDefinitione"></param>
        /// <param name="dbContext">The TypeManager of the database.</param>
        /// <param name="typeOfBinExpr">The type of the binary expression.</param>
        /// <param name="associativity">The associativity of the binary expression.</param>
        /// <param name="referenceList"></param>
        /// <param name="queryCache">The per query DBObject/BackwardEdge cache.</param>
        /// <returns></returns>
        public override Exceptional<IExpressionGraph> TypeOperation(AExpressionDefinition myLeftValueObject, AExpressionDefinition myRightValueObject, DBContext dbContext, TypesOfBinaryExpression typeOfBinExpr, TypesOfAssociativity associativity, IExpressionGraph resultGr, Boolean aggregateAllowed = true)
        {
            #region Data

            //list of errors
            List<GraphDBError> errors = new List<GraphDBError>();

            //DataContainer for all data that is used by a binary expression/comparer
            Exceptional<DataContainer> data;

            //the index of the left attribute
            IEnumerable<Tuple<GraphDBType, AAttributeIndex>> leftIndex = null;

            //the index of the right attribute
            IEnumerable<Tuple<GraphDBType, AAttributeIndex>> rightIndex = null;

            #endregion

            #region extract data

            //data extraction with an eye on the type of the binary expression

            switch (typeOfBinExpr)
            {
                case TypesOfBinaryExpression.Atom:

                    //sth like 3 = 4
                    #region Get Atom data

                    //no further data has to be generated

                    //data = new DataContainer(null, new Tuple<Object, Object>(myLeftValueObject, myRightValueObject), null);
                    data = new Exceptional<DataContainer>();

                    #endregion

                    break;
                case TypesOfBinaryExpression.LeftComplex:

                    //sth like U.Age = 21
                    #region Get LeftComplex data

                    data = ExtractData(myLeftValueObject, myRightValueObject, ref typeOfBinExpr, dbContext.DBObjectCache, dbContext.SessionSettings, dbContext, aggregateAllowed);
                    if (!data.Success())
                    {
                        return new Exceptional<IExpressionGraph>(data);
                    }

                    #endregion

                    break;
                case TypesOfBinaryExpression.RightComplex:

                    //sth like 21 = U.Age
                    #region Get RightComplex data

                    data = ExtractData(myRightValueObject, myLeftValueObject, ref typeOfBinExpr, dbContext.DBObjectCache, dbContext.SessionSettings, dbContext, aggregateAllowed);
                    if (!data.Success())
                    {
                        return new Exceptional<IExpressionGraph>(data);
                    }

                    #endregion

                    break;
                case TypesOfBinaryExpression.Complex:

                    //sth like U.Age = F.Alter
                    #region Get Complex data

                    var leftData = ExtractData(myLeftValueObject, myRightValueObject, ref typeOfBinExpr, dbContext.DBObjectCache, dbContext.SessionSettings, dbContext, aggregateAllowed);
                    if (!leftData.Success())
                    {
                        return new Exceptional<IExpressionGraph>(leftData);
                    }

                    var rightData = ExtractData(myRightValueObject, myLeftValueObject, ref typeOfBinExpr, dbContext.DBObjectCache, dbContext.SessionSettings, dbContext, aggregateAllowed);
                    if (!rightData.Success())
                    {
                        return new Exceptional<IExpressionGraph>(rightData);
                    }

                    if (typeOfBinExpr == TypesOfBinaryExpression.Unknown)
                    {
                        typeOfBinExpr = SetTypeOfBinaryExpression(leftData, rightData);

                        switch (typeOfBinExpr)
                        {
                            case TypesOfBinaryExpression.Atom:

                                data = new Exceptional<DataContainer>(new DataContainer(new Tuple<IDChainDefinition, IDChainDefinition>(null, null), new Tuple<AExpressionDefinition, AExpressionDefinition>(leftData.Value.Operands.Item1, leftData.Value.Operands.Item1), new Tuple<AExpressionDefinition, AExpressionDefinition>(null, null)));

                                break;
                            case TypesOfBinaryExpression.LeftComplex:

                                data = new Exceptional<DataContainer>(new DataContainer(new Tuple<IDChainDefinition, IDChainDefinition>(leftData.Value.IDChainDefinitions.Item1, null), new Tuple<AExpressionDefinition, AExpressionDefinition>(rightData.Value.Operands.Item1, null), new Tuple<AExpressionDefinition, AExpressionDefinition>(null, null)));

                                break;
                            case TypesOfBinaryExpression.RightComplex:

                                data = new Exceptional<DataContainer>(new DataContainer(new Tuple<IDChainDefinition, IDChainDefinition>(rightData.Value.IDChainDefinitions.Item1, null), new Tuple<AExpressionDefinition, AExpressionDefinition>(leftData.Value.Operands.Item1, null), new Tuple<AExpressionDefinition, AExpressionDefinition>(null, null)));

                                break;
                            case TypesOfBinaryExpression.Complex:
                            case TypesOfBinaryExpression.Unknown:
                            default:

                                throw new GraphDBException(new Error_NotImplemented(new System.Diagnostics.StackTrace(true)));
                        }

                    }
                    else
                    {
                        data = new Exceptional<DataContainer>(JoinData(leftData.Value, rightData.Value));
                    }

                    #endregion

                    break;
                default:

                    throw new ArgumentException();
            }

            #region handle errors

            if (data.Failed())
            {
                return new Exceptional<IExpressionGraph>(data);
            }

            #endregion

            #endregion

            #region get indexes

            switch (typeOfBinExpr)
            {
                case TypesOfBinaryExpression.LeftComplex:

                    leftIndex = GetIndex(data.Value.IDChainDefinitions.Item1.LastAttribute, dbContext, data.Value.IDChainDefinitions.Item1.LastType, data.Value.Extraordinaries.Item1);

                    break;

                case TypesOfBinaryExpression.RightComplex:

                    //data.IdNodes.TupelElement1 is correct, because of correct handling in extract data (data.IdNodes.TupelElement2 should be null here)
                    rightIndex = GetIndex(data.Value.IDChainDefinitions.Item1.LastAttribute, dbContext, data.Value.IDChainDefinitions.Item1.LastType, data.Value.Extraordinaries.Item1);

                    break;

                case TypesOfBinaryExpression.Complex:

                    //both indexe have to be catched

                    leftIndex = GetIndex(data.Value.IDChainDefinitions.Item1.LastAttribute, dbContext, data.Value.IDChainDefinitions.Item1.LastType, data.Value.Extraordinaries.Item1);
                    rightIndex = GetIndex(data.Value.IDChainDefinitions.Item2.LastAttribute, dbContext, data.Value.IDChainDefinitions.Item2.LastType, data.Value.Extraordinaries.Item1);

                    break;
            }

            #endregion

            //time to compare some things
            Exceptional<Boolean> matchDataResult = null;

            if (IsValidIndexOperation(data.Value, dbContext, typeOfBinExpr))
            {
                #region match data

                switch (typeOfBinExpr)
                {
                    case TypesOfBinaryExpression.Atom:

                        #region Atom

                        //do nothing 3 = 3 (or 2 != 3) doesnt bother U

                        #endregion

                        break;

                    case TypesOfBinaryExpression.LeftComplex:

                        #region LeftComplex

                        matchDataResult = MatchData(data.Value, dbContext, dbContext.DBObjectCache, typeOfBinExpr, leftIndex, resultGr, dbContext.SessionSettings);

                        #endregion

                        break;

                    case TypesOfBinaryExpression.RightComplex:

                        #region RightComplex

                        matchDataResult = MatchData(data.Value, dbContext, dbContext.DBObjectCache, typeOfBinExpr, rightIndex, resultGr, dbContext.SessionSettings);

                        #endregion

                        break;

                    case TypesOfBinaryExpression.Complex:

                        #region Complex

                        matchDataResult = MatchComplexData(associativity, data.Value, dbContext, dbContext.DBObjectCache, typeOfBinExpr, leftIndex, rightIndex, ref errors, ref resultGr, dbContext.SessionSettings);

                        #endregion

                        break;
                }

                #endregion
            }
            else
            {
                return new Exceptional<IExpressionGraph>(new Error_InvalidBinaryExpression(this, data.Value.IDChainDefinitions, data.Value.Operands, typeOfBinExpr));
            }

            if (matchDataResult != null && matchDataResult.Failed())
                return new Exceptional<IExpressionGraph>(matchDataResult);
            else
                return new Exceptional<IExpressionGraph>(resultGr);
        }
예제 #17
0
        /// <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, DBContext dbContext)
        {
            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);
        }
예제 #18
0
        public Exceptional<QueryResult> AlterType(DBContext dbInnerContext, GraphDBType atype, AAlterTypeCommand alterTypeCommand)
        {
            var result = alterTypeCommand.Execute(dbInnerContext, atype);

            if (!result.Success())
            {
                var retVal = new Exceptional<QueryResult>(result);
                return retVal;
            }
            else
            {
                var resultReadout = alterTypeCommand.CreateVertex(dbInnerContext, atype);

                if (resultReadout != null)
                {
                    var retVal = new Exceptional<QueryResult>(new QueryResult(resultReadout));
                    retVal.PushIExceptional(result);

                    return retVal;
                }

                return new Exceptional<QueryResult>(result);
            }
        }
예제 #19
0
        public Exceptional GetContent(CompilerContext context, ParseTreeNode parseNode)
        {
            var retExceptional = new Exceptional();

            #region get Name

            _TypeName = parseNode.ChildNodes[0].Token.ValueString;

            #endregion

            #region get Extends

            if (parseNode.ChildNodes[1].HasChildNodes())
            {
                _Extends = parseNode.ChildNodes[1].ChildNodes[1].Token.ValueString;
            }
            else
            {
                //if there is no extend a Type is alwayse inheritated by GraphObject
                _Extends = DBVertex.Name;
            }

            #endregion

            #region get myAttributes

            if (parseNode.ChildNodes[2].HasChildNodes())
            {
                _Attributes = GetAttributeList(parseNode.ChildNodes[2].ChildNodes[1]);
            }

            #endregion

            #region get BackwardEdges

            if (parseNode.ChildNodes[3].HasChildNodes())
            {
                _BackwardEdgeInformation = (((BackwardEdgesNode)parseNode.ChildNodes[3].AstNode).BackwardEdgeInformation);
            }

            #endregion

            #region get Optional Unique

            if (((UniqueAttributesOptNode)parseNode.ChildNodes[4].AstNode).UniqueAttributes != null)
            {
                foreach (String uniqueAttr in ((UniqueAttributesOptNode)parseNode.ChildNodes[4].AstNode).UniqueAttributes)
                {
                    if (_Attributes.Any(a => a.Key.AttributeName == uniqueAttr))
                    {
                        var attr = (from a in _Attributes where a.Key.AttributeName == uniqueAttr select a).First();
                        attr.Key.AttributeType.TypeCharacteristics.IsUnique = true;
                    }
                    else
                    {
                        throw new GraphDBException(new Error_AttributeIsNotDefined(uniqueAttr));
                    }
                }
            }

            #endregion

            #region get Optional Mandatory

            if (((MandatoryOptNode)parseNode.ChildNodes[5].AstNode).MandatoryAttribs != null)
            {
                foreach (String mandAttr in ((MandatoryOptNode)parseNode.ChildNodes[5].AstNode).MandatoryAttribs)
                {
                    if (_Attributes.Any(a => a.Key.AttributeName == mandAttr))
                    {
                        var attr = (from a in _Attributes where a.Key.AttributeName == mandAttr select a).First();
                        attr.Key.AttributeType.TypeCharacteristics.IsMandatory = true;
                    }
                    else
                    {
                        throw new GraphDBException(new Error_AttributeIsNotDefined(mandAttr));
                    }
                }
            }

            #endregion

            #region Get Optional Indices

            if(parseNode.ChildNodes[6].HasChildNodes())
            {
                if (parseNode.ChildNodes[6].ChildNodes[0].HasChildNodes())
                {
                    var idxCreateNode = (IndexOnCreateTypeNode)parseNode.ChildNodes[6].ChildNodes[0].AstNode;
                    ParsingResult.PushIExceptional(idxCreateNode.ParsingResult);

                    _Indices = new List<IndexDefinition>();

                    foreach(var idx in idxCreateNode.ListOfIndexDefinitions)
                    {
                        _Indices.Add(idx);
                    }
                }
            }

            #endregion

            #region get Comment

            if (parseNode.ChildNodes[7].HasChildNodes())
            {
                _Comment = parseNode.ChildNodes[7].ChildNodes[2].Token.ValueString;
            }

            #endregion

            return retExceptional;
        }
예제 #20
0
        private Exceptional<ResultType> AddAttributeToDBObject(GraphDBType myTypeOfDBObject, ObjectUUID myUUID, AttributeUUID myAttributeUUID, IObject myAttributeValue)
        {
            //myGraphType is needed due to correctness concerning the attribute name

            #region Input exceptions

            if ((myTypeOfDBObject == null) || (myUUID == null) || (myAttributeUUID == null) || (myAttributeValue == null))
            {
                throw new ArgumentNullException();
            }

            #endregion

            #region Check GraphType for new Attribute

            TypeAttribute typeAttribute = myTypeOfDBObject.GetTypeAttributeByUUID(myAttributeUUID);

            if (typeAttribute == null)
            {
                //Todo: add notification here (the user has to be informed about the detailed circumstances)

                GraphDBError aError = new Error_AttributeIsNotDefined(myTypeOfDBObject.Name, myAttributeUUID.ToString());

                return new Exceptional<ResultType>(aError);
            }

            #endregion

            #region Data

            var objectLocation = new ObjectLocation(myTypeOfDBObject.ObjectLocation, DBConstants.DBObjectsLocation, myUUID.ToString());
            Exceptional<DBObjectStream> aNewDBObject;
            Exceptional<ResultType> result = new Exceptional<ResultType>();

            #endregion

            #region add attribute

            aNewDBObject = _DBContext.DBObjectManager.LoadDBObject(myTypeOfDBObject, myUUID);

            if (aNewDBObject.Failed())
            {
                result.PushIError(new Error_LoadObject(aNewDBObject.Value.ObjectLocation));
                return result;
            }

            result = aNewDBObject.Value.AddAttribute(typeAttribute.UUID, myAttributeValue);

            if (result.Failed())
                return result;

            try
            {
                _DBContext.DBObjectManager.FlushDBObject(aNewDBObject.Value);
            }
            catch (Exception ex)
            {
                result.PushIError(new Error_FlushObject(aNewDBObject.Value.ObjectLocation, ex));
                aNewDBObject.Value.RemoveAttribute(typeAttribute.UUID);
            }

            #endregion

            return result;
        }
예제 #21
0
        /// <summary>
        /// Add indices to a vertex
        /// <seealso cref=" AAlterTypeCommand"/>
        /// </summary>        
        public override Exceptional Execute(DBContext myDBContext, GraphDBType myGraphDBType)
        {
            var retExceptional = new Exceptional();

            foreach (var idxDef in _IdxDefinitionList)
            {

                var checkIdx = CheckIndexTypeReference(idxDef.IndexAttributeDefinitions, myGraphDBType);

                if (!checkIdx.Success())
                {
                    retExceptional.PushIExceptional(checkIdx);
                }
                else
                {
                    var result = myDBContext.DBIndexManager.CreateIndex(myDBContext, myGraphDBType.Name, idxDef.IndexName, idxDef.Edition, idxDef.IndexType, idxDef.IndexAttributeDefinitions);

                    if (!result.Success())
                    {
                        retExceptional.PushIExceptional(result);
                    }
                }

            }

            return retExceptional;
        }
예제 #22
0
        /// <summary>
        /// This will check the exceptional for errors. Depending on the SettingInvalidReferenceHandling an expcetion will be thrown or false will be return on any load error.
        /// </summary>
        /// <param name="dbStream"></param>
        /// <param name="myLevelKey"></param>
        /// <returns></returns>
        private Boolean CheckLoadedDBObjectStream(Exceptional<DBObjectStream> dbStream, GraphDBType myDBType, TypeAttribute myTypeAttribute = null)
        {

            SettingInvalidReferenceHandling invalidReferenceSetting = null;
            GraphDBType currentType = myDBType;

            if (dbStream.Failed())
            {
                #region error

                #region get setting

                if (invalidReferenceSetting == null)
                {
                    //currentType = _DBContext.DBTypeManager.GetTypeByUUID(myLevelKey.LastEdge.TypeUUID);

                    //if (myLevelKey.LastEdge.AttrUUID != null)
                    if (myTypeAttribute != null)
                    {
                        invalidReferenceSetting = (SettingInvalidReferenceHandling)_DBContext.DBSettingsManager.GetSetting(SettingInvalidReferenceHandling.UUID, _DBContext, TypesSettingScope.ATTRIBUTE, currentType, myTypeAttribute).Value; // currentType.GetTypeAttributeByUUID(myLevelKey.LastEdge.AttrUUID)).Value;
                    }
                    else
                    {
                        invalidReferenceSetting = (SettingInvalidReferenceHandling)_DBContext.DBSettingsManager.GetSetting(SettingInvalidReferenceHandling.UUID, _DBContext, TypesSettingScope.TYPE, currentType).Value;
                    }
                }

                #endregion

                switch (invalidReferenceSetting.Behaviour)
                {
                    case BehaviourOnInvalidReference.ignore:
                        #region ignore

                        return false;

                        #endregion
                    case BehaviourOnInvalidReference.log:

                    default:

                        throw new GraphDBException(new Error_NotImplemented(new System.Diagnostics.StackTrace()));
                }

                #endregion
            }

            return true;

        }
예제 #23
0
        public override Exceptional Execute(DBContext dbContext, GraphDBType graphDBType)
        {
            var listOfTypeAttrs = new List<TypeAttribute>();
            var retExcept = new Exceptional();

            foreach (var attr in _ListOfAttributes)
            {

                var typeAttr = graphDBType.GetTypeAttributeByName(attr);

                if (typeAttr == null)
                {
                    return new Exceptional(new Error_AttributeIsNotDefined(attr));
                }

                var attrType = dbContext.DBTypeManager.GetTypeByUUID(typeAttr.DBTypeUUID);

                if (attrType == null)
                    return new Exceptional(new Error_TypeDoesNotExist(""));

                if (attrType.IsUserDefined)
                    return new Exceptional(new Error_InvalidReferenceAssignmentOfUndefAttr());

                listOfTypeAttrs.Add(typeAttr);

            }

            var dbobjects = dbContext.DBObjectCache.SelectDBObjectsForLevelKey(new LevelKey(graphDBType, dbContext.DBTypeManager), dbContext);

            foreach (var item in dbobjects)
            {

                if (!item.Success())
                {
                    retExcept.PushIExceptional(item);
                }

                else
                {
                    foreach (var attr in listOfTypeAttrs)
                    {
                        if (item.Value.HasAttribute(attr.UUID, graphDBType))
                        {
                            var attrVal = item.Value.GetAttribute(attr.UUID);

                            var addExcept = item.Value.AddUndefinedAttribute(attr.Name, attrVal, dbContext.DBObjectManager);

                            if (!addExcept.Success())
                                retExcept.PushIExceptional(addExcept);

                            item.Value.RemoveAttribute(attr.UUID);

                            var saveExcept = dbContext.DBObjectManager.FlushDBObject(item.Value);

                            if (!saveExcept.Success())
                                retExcept.PushIExceptional(saveExcept);
                        }
                    }
                }
            }

            var indices = graphDBType.GetAllAttributeIndices();
            List<AAttributeIndex> idxToDelete = new List<AAttributeIndex>();

            //remove attributes from type
            foreach (var attr in listOfTypeAttrs)
            {

                foreach (var item in indices)
                {
                    var index = item.IndexKeyDefinition.IndexKeyAttributeUUIDs.Find(idx => idx == attr.UUID);

                    if (index != null && item.IndexKeyDefinition.IndexKeyAttributeUUIDs.Count == 1)
                    {
                        idxToDelete.Add(item);
                    }
                }

                //remove indices
                foreach (var idx in idxToDelete)
                {
                    var remExcept = graphDBType.RemoveIndex(idx.IndexName, idx.IndexEdition, dbContext.DBTypeManager);

                    if (!remExcept.Success())
                    {
                        retExcept.PushIExceptional(remExcept);
                    }
                }

                idxToDelete.Clear();
                graphDBType.RemoveAttribute(attr.UUID);

                var flushExcept = dbContext.DBTypeManager.FlushType(graphDBType);

                if (!flushExcept.Success())
                {
                    retExcept.PushIExceptional(flushExcept);
                }
            }

            return retExcept;
        }
예제 #24
0
        public override void AddNodesWithComplexRelation(Exceptional<DBObjectStream> leftDBObject, LevelKey leftLevelKey, Exceptional<DBObjectStream> rightDBObject, LevelKey rightLevelKey, DBObjectCache dbObjectCache, int backwardResolutiondepth)
        {
            lock (_Levels)
            {
                if ((AddNodeIfValid(leftDBObject.Value, leftLevelKey, 0, leftDBObject.Value.ObjectUUID, backwardResolutiondepth)) && (AddNodeIfValid(rightDBObject.Value, rightLevelKey, 0, rightDBObject.Value.ObjectUUID, backwardResolutiondepth)))
                {
                    //both nodes have been inserted correctly
                    //--> create a connection between both
                    _Levels[leftLevelKey.Level].ExpressionLevels[leftLevelKey].Nodes[leftDBObject.Value.ObjectUUID].AddComplexConnection(rightLevelKey, rightDBObject.Value.ObjectUUID);
                    _Levels[rightLevelKey.Level].ExpressionLevels[rightLevelKey].Nodes[rightDBObject.Value.ObjectUUID].AddComplexConnection(leftLevelKey, leftDBObject.Value.ObjectUUID);
                }
                else
                {
                    #region remove both nodes

                    if (ContainsLevelKey(leftLevelKey))
                    {
                        _Levels[leftLevelKey.Level].RemoveNode(leftLevelKey, leftDBObject.Value.ObjectUUID);
                    }
                    if (ContainsLevelKey(leftLevelKey))
                    {
                        _Levels[rightLevelKey.Level].RemoveNode(rightLevelKey, rightDBObject.Value.ObjectUUID);
                    }

                    #endregion
                }
            }
        }
예제 #25
0
        /// <summary>
        /// This method adds a bunch of new GraphTypeDefinitions (comes from a CREATE TYPE(S) statement) to the TypeManager.
        /// If a certain PType can't be added (because of some inheritance or 
        /// attribute errors), this method tries to add it in a second 
        /// step.
        /// </summary>
        /// <param name="TypeList">List of GraphType definitions that should 
        /// be added to the TypeManager</param>
        /// <returns>List of GraphError</returns>
        public Exceptional<QueryResult> AddBulkTypes(List<GraphDBTypeDefinition> TypeList, DBContext currentContext)
        {
            #region Input Exceptions

            if (TypeList == null)
            {
                return new Exceptional<QueryResult>(new QueryResult());
            }

            if (TypeList.Count.Equals(0))
            {
                return new Exceptional<QueryResult>(new QueryResult());
            }

            #endregion

            #region Data

            var errors = new List<GraphDBError>();
            List<GraphDBType> addedTypes = new List<GraphDBType>();
            List<AttributeUUID> uniqueAttrIDs = new List<AttributeUUID>();
            QueryResult result = new QueryResult();

            #endregion

            try
            {

                #region Create the types without attributes

                foreach (GraphDBTypeDefinition aTypeDef in TypeList)
                {

                    #region Input validation

                    if (String.IsNullOrEmpty(aTypeDef.Name))
                        return new Exceptional<QueryResult>(new Error_ArgumentNullOrEmpty("myTypeName"));

                    if (String.IsNullOrEmpty(aTypeDef.ParentType))
                        return new Exceptional<QueryResult>(new Error_ArgumentNullOrEmpty("myParentType"));

                    if (aTypeDef.Attributes == null)
                        return new Exceptional<QueryResult>(new Error_ArgumentNullOrEmpty("myAttributes"));

                    #endregion

                    GraphDBType thisType = GetTypeByName(aTypeDef.Name);

                    #region Check if the name of the type is already used

                    if (thisType != null)
                    {
                        return new Exceptional<QueryResult>(new Error_TypeAlreadyExist(aTypeDef.Name));
                    }

                    #endregion

                    GraphDBType parentType = GetTypeByName(aTypeDef.ParentType);
                    Dictionary<AttributeUUID, TypeAttribute> attributes = new Dictionary<AttributeUUID, TypeAttribute>();

                    #region objectDirectoryShards

                    var objectDirectoryShards = UInt16.Parse(currentContext.GraphAppSettings.Get<ObjectsDirectoryShardsSetting>());

                    #endregion

                    #region Add type

                    TypeUUID parentUUID = (parentType == null) ? null : parentType.UUID;

                    #region hack

                    GraphDBType _NewGraphType = new GraphDBType(null, new ObjectLocation(_DatabaseRootPath), aTypeDef.Name, parentUUID, attributes, true, aTypeDef.IsAbstract, aTypeDef.Comment, objectDirectoryShards);

                    #endregion

                    addedTypes.Add(_NewGraphType);

                    _UserDefinedTypes.Add(_NewGraphType.UUID, _NewGraphType);
                    _TypesNameLookUpTable.Add(_NewGraphType.Name, _NewGraphType);

                    #endregion

                }

                #endregion

                var backwardEdgesToBeAddedAfterwards = new Dictionary<GraphDBType, List<BackwardEdgeDefinition>>();

                #region Validate the previously added types and add the attributes and backwardEdges

                foreach (var aTypeDef in TypeList)
                {
                    GraphDBType aType = addedTypes.Where(item => item.Name == aTypeDef.Name).FirstOrDefault();

                    #region Check and set parent

                    GraphDBType parentType;

                    #region Verify base type existence

                    if (aType.ParentTypeUUID == null)
                    {
                        parentType = addedTypes.Where(item => item.Name == aTypeDef.ParentType).FirstOrDefault();
                        if (parentType == null)
                        {
                            RemoveRecentlyAddedTypes(addedTypes);
                            return new Exceptional<QueryResult>(new Error_ParentTypeDoesNotExist(aTypeDef.ParentType, aTypeDef.Name));
                        }
                        aType.SetParentTypeUUID(parentType.UUID);
                    }
                    else
                    {
                        parentType = aType.GetParentType(this);
                    }

                    #endregion

                    #region Verify that the type inherit DBReference

                    var parentTypeExcept = HasParentType(parentType.UUID, DBReference.UUID);

                    if (parentTypeExcept.Failed())
                    {
                        return new Exceptional<QueryResult>(parentTypeExcept);
                    }

                    if (!parentTypeExcept.Value)
                    {
                        RemoveRecentlyAddedTypes(addedTypes);
                        return new Exceptional<QueryResult>(new Error_InvalidBaseType(parentType.Name));
                    }

                    #endregion

                    #endregion

                    //add TypeAttributeLookuptable to current type
                    aType.AttributeLookupTable.AddRange(parentType.AttributeLookupTable);

                    #region check and set type of attributes

                    UInt16 attributeCounter = 0;

                    foreach (var attributeDef in aTypeDef.Attributes)
                    {
                        var attribute = attributeDef.Key.CreateTypeAttribute(currentContext, addedTypes, attributeCounter);
                        if (attribute.Failed())
                        {
                            return new Exceptional<QueryResult>(attribute);
                        }

                        if (attribute.Value.Name == aType.Name)
                        {
                            RemoveRecentlyAddedTypes(addedTypes);
                            return new Exceptional<QueryResult>(new Error_InvalidAttributeName("The attribute " + attribute.Value.Name + " can not be added, because it has the same name as its related type."));
                        }

                        GraphDBType attrType = GetTypeByName(attributeDef.Value);
                        if (attrType == null)
                        {
                            attrType = addedTypes.Where(item => item.Name == attributeDef.Value).FirstOrDefault();
                            if (attrType == null)
                            {
                                RemoveRecentlyAddedTypes(addedTypes);
                                return new Exceptional<QueryResult>(new Error_TypeDoesNotExist(attributeDef.Value));
                            }
                        }

                        attributeCounter++;

                        TypeAttribute newAttr = attribute.Value;

                        newAttr.DBTypeUUID = attrType.UUID;
                        newAttr.RelatedGraphDBTypeUUID = aType.UUID;

                        #region we had not defined a special EdgeType - for single reference attributes we need to set the EdgeTypeSingle NOW!

                        if (newAttr.KindOfType == KindsOfType.SingleReference && attrType.IsUserDefined && newAttr.EdgeType == null)
                            newAttr.EdgeType = new EdgeTypeSingleReference(null, newAttr.DBTypeUUID);

                        #endregion

                        #region Validate EdgeType in terms of List & Single

                        if (newAttr.KindOfType == KindsOfType.SingleReference && attrType.IsUserDefined && !(newAttr.EdgeType is ASingleReferenceEdgeType))
                        {
                            RemoveRecentlyAddedTypes(addedTypes);
                            return new Exceptional<QueryResult>(new Error_InvalidEdgeType(newAttr.EdgeType.GetType(), typeof(ASingleReferenceEdgeType)));
                        }
                        else if (newAttr.KindOfType == KindsOfType.SetOfReferences || newAttr.KindOfType == KindsOfType.SetOfNoneReferences)
                        {
                            if (attrType.IsUserDefined && !(newAttr.EdgeType is ASetOfReferencesEdgeType))
                            {
                                RemoveRecentlyAddedTypes(addedTypes);
                                return new Exceptional<QueryResult>(new Error_InvalidEdgeType(newAttr.EdgeType.GetType(), typeof(ASetOfReferencesEdgeType)));
                            }
                            else if (!attrType.IsUserDefined && !(newAttr.EdgeType is ASetOfBaseEdgeType))
                            {
                                RemoveRecentlyAddedTypes(addedTypes);
                                return new Exceptional<QueryResult>(new Error_InvalidEdgeType(newAttr.EdgeType.GetType(), typeof(AListOfBaseEdgeType)));
                            }
                        }

                        #endregion

                        aType.AddAttribute(newAttr, this, true);
                    }

                    #endregion

                    #region Set BackwardEdges

                    if (!aTypeDef.BackwardEdgeNodes.IsNullOrEmpty())
                    {
                        backwardEdgesToBeAddedAfterwards.Add(aType, aTypeDef.BackwardEdgeNodes);
                    }

                    #endregion
                }

                #endregion

                #region Add the BackwardEdges

                foreach (var beDefinition in backwardEdgesToBeAddedAfterwards)
                {
                    var aType = beDefinition.Key;
                    UInt16 beAttrCounter = 0;
                    foreach (var be in beDefinition.Value)
                    {

                        var bedgeAttribute = CreateBackwardEdgeAttribute(be, aType, beAttrCounter);

                        if (!bedgeAttribute.Success())
                        {
                            RemoveRecentlyAddedTypes(addedTypes);
                            return new Exceptional<QueryResult>(bedgeAttribute);
                        }

                        aType.AddAttribute(bedgeAttribute.Value, this, true);

                        beAttrCounter++;
                    }
                }

                #endregion

                #region Validate Attribute dependencies

                var _Vertices = new List<Vertex>();

                foreach (var _GraphDBType in addedTypes)
                {
                    foreach (var _GraphDBType2 in GetAllParentTypes(_GraphDBType, false, true))
                    {

                        var _MandatoryAttributes = _GraphDBType2.GetMandatoryAttributesUUIDs(this);
                        var _UniqueAttributes    = _GraphDBType2.GetAllUniqueAttributes(false, this);

                        foreach (var _TypeAttribute in _GraphDBType.Attributes.Values)
                        {

                            if (_GraphDBType2.GetTypeAttributeByName(_TypeAttribute.Name) != null)
                            {
                                // Todo: Use notification here
                                RemoveRecentlyAddedTypes(addedTypes);
                                return new Exceptional<QueryResult>(new Error_AttributeExistsInSupertype(_TypeAttribute.Name, _GraphDBType.Name));
                            }

                            #region unique and mandatory attributes

                            if (_TypeAttribute.TypeCharacteristics.IsUnique && !_UniqueAttributes.Contains(_TypeAttribute.UUID))
                            {
                                //if the attrbute has been marked unique and it is not contained in uniques of super types
                                if (!uniqueAttrIDs.Contains(_TypeAttribute.UUID))
                                {
                                    uniqueAttrIDs.Add(_TypeAttribute.UUID);
                                }
                            }

                            if (_TypeAttribute.TypeCharacteristics.IsMandatory && !_MandatoryAttributes.Contains(_TypeAttribute.UUID))
                            {
                                _GraphDBType.AddMandatoryAttribute(_TypeAttribute.UUID, this);
                            }

                            #endregion

                        }
                    }

                    //Add the unique attribute ids for the current type
                    var AddUniqueAttrExcept = _GraphDBType.AddUniqueAttributes(uniqueAttrIDs, currentContext);

                    if(AddUniqueAttrExcept.Failed())
                        return new Exceptional<QueryResult>(AddUniqueAttrExcept);

                    uniqueAttrIDs.Clear();
                }

                #endregion

                #region Create indices

                foreach (GraphDBType aType in addedTypes)
                {
                    #region Create userdefined Indices

                    var aTypeDef = TypeList.Where(item => item.Name == aType.Name).FirstOrDefault();

                    if (!aTypeDef.Indices.IsNullOrEmpty())
                    {
                        foreach (var index in aTypeDef.Indices)
                        {

                            if (!index.IndexAttributeDefinitions.All(node => !node.IndexAttribute.Validate(currentContext, false, aType).Failed()))
                            {
                                RemoveRecentlyAddedTypes(addedTypes);
                                return new Exceptional<QueryResult>(new Error_AttributeIsNotDefined(aType.Name, aType.Name));
                            }

                            var idxName = index.IndexName;
                            if (String.IsNullOrEmpty(index.IndexName))
                            {
                                idxName = index.IndexAttributeDefinitions.Aggregate(new StringBuilder(DBConstants.IndexKeyPrefix), (stringB, elem) => { stringB.Append(String.Concat(DBConstants.IndexKeySeperator, elem.IndexAttribute.LastAttribute.Name)); return stringB; }).ToString();
                            }

                            List<AttributeUUID> indexAttrs = new List<AttributeUUID>(index.IndexAttributeDefinitions.Select(node => node.IndexAttribute.LastAttribute.UUID));

                            foreach (var item in GetAllSubtypes(aType))
                            {
                                var CreateIdxExcept = item.CreateAttributeIndex(currentContext, idxName, indexAttrs, index.Edition, index.IndexType);

                                if (!CreateIdxExcept.Success())
                                    return new Exceptional<QueryResult>(CreateIdxExcept);
                            }
                        }
                    }

                    #endregion

                    //UUID index
                    var createIndexExcept = aType.CreateUUIDIndex(_DBContext, GetUUIDTypeAttribute().UUID);

                    if (!createIndexExcept.Success())
                    {
                        return new Exceptional<QueryResult>(createIndexExcept);
                    }

                    List<AttributeUUID> UniqueIDs = aType.GetAllUniqueAttributes(true, this);

                    if (UniqueIDs.Count() > 0)
                    {
                        var idxName = _DBContext.DBIndexManager.GetUniqueIndexName(UniqueIDs, aType); // UniqueIDs.Aggregate<AttributeUUID, String>("Idx", (result, item) => result = result + "_" + aType.GetTypeAttributeByUUID(item).Name);
                        var createIdxExcept = aType.CreateUniqueAttributeIndex(currentContext, idxName, UniqueIDs, DBConstants.UNIQUEATTRIBUTESINDEX);

                        if (!createIdxExcept.Success())
                            return new Exceptional<QueryResult>(createIdxExcept);
                    }
                }

                #endregion

                #region flush to fs

                foreach (var item in addedTypes)
                {
                    var createException = CreateTypeOnFS(item);

                    if (!createException.Success())
                        return new Exceptional<QueryResult>(createException);

                    #region get system attributes from type

                    var readOut = GetVertexForType(item);

                    if (!readOut.Success())
                        return new Exceptional<QueryResult>(readOut.IErrors.First());

                    _Vertices.Add(readOut.Value);

                    #endregion
                }

                result.Vertices = _Vertices;

                #endregion

            }
            catch (GraphDBException ee)
            {
                RemoveRecentlyAddedTypes(addedTypes);

                var _Exceptional = new Exceptional<QueryResult>();
                foreach (var _ex in ee.GraphDBErrors)
                    _Exceptional.PushIError(_ex);

                return _Exceptional;

            }
            catch (GraphDBWarningException ee)
            {
                RemoveRecentlyAddedTypes(addedTypes);
                return new Exceptional<QueryResult>(ee.GraphDBWarning);
            }
            catch (Exception e)
            //finally
            {
                //if (!succeeded)
                //{
                addedTypes.ForEach(item =>
                {
                    _UserDefinedTypes.Remove(item.UUID);
                    _TypesNameLookUpTable.Remove(item.Name);
                });
                //}

                return new Exceptional<QueryResult>(new Error_UnknownDBError(e));

            }

            return new Exceptional<QueryResult>(result);
        }
예제 #26
0
        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;
        }
예제 #27
0
        public override Exceptional Execute(DBContext dbContext, GraphDBType graphDBType)
        {
            var listOfTypeAttributes = new Dictionary<TypeAttribute, GraphDBType>();
            var retExcept = new Exceptional();
            var existingTypeAttributes = graphDBType.GetAllAttributes(dbContext);

            foreach (var attr in _ListOfAttributes)
            {
                var createExcept = attr.CreateTypeAttribute(dbContext);

                if (!createExcept.Success())
                {
                    retExcept.PushIExceptional(createExcept);
                }

                if (existingTypeAttributes.Exists(item => item.Name == createExcept.Value.Name))
                {
                    retExcept.PushIExceptional(new Exceptional(new Error_AttributeAlreadyExists(createExcept.Value.Name)));
                }

                var attrType = dbContext.DBTypeManager.GetTypeByName(attr.AttributeType.Name);

                if (attrType == null)
                {
                    retExcept.PushIExceptional(new Exceptional(new Error_TypeDoesNotExist(attr.AttributeType.Name)));
                    return retExcept;
                }

                if (attrType.IsUserDefined)
                {
                    retExcept.PushIExceptional(new Exceptional(new Error_InvalidReferenceAssignmentOfUndefAttr()));
                    return retExcept;
                }

                createExcept.Value.DBTypeUUID = attrType.UUID;
                createExcept.Value.RelatedGraphDBTypeUUID = graphDBType.UUID;

                graphDBType.AddAttribute(createExcept.Value, dbContext.DBTypeManager, true);

                var flushExcept = dbContext.DBTypeManager.FlushType(graphDBType);

                if (!flushExcept.Success())
                {
                    retExcept.PushIExceptional(flushExcept);
                }

                listOfTypeAttributes.Add(createExcept.Value, attrType);
            }

            var dbobjects = dbContext.DBObjectCache.SelectDBObjectsForLevelKey(new LevelKey(graphDBType, dbContext.DBTypeManager), dbContext);

            foreach (var item in dbobjects)
            {
                if (!item.Success())
                {
                    retExcept.PushIExceptional(item);
                }
                else
                {
                    var undefAttrExcept = item.Value.GetUndefinedAttributePayload(dbContext.DBObjectManager);

                    if (!undefAttrExcept.Success())
                    {
                        retExcept.PushIExceptional(undefAttrExcept);
                    }

                    foreach (var attr in listOfTypeAttributes)
                    {
                        IObject value;

                        if (undefAttrExcept.Value.TryGetValue(attr.Key.Name, out value))
                        {
                            var typeOfOperator = GraphDBTypeMapper.ConvertGraph2CSharp(attr.Value.Name);

                            if (GraphDBTypeMapper.IsAValidAttributeType(attr.Value, typeOfOperator, dbContext, value))
                            {
                                item.Value.AddAttribute(attr.Key.UUID, value);

                                var removeExcept = item.Value.RemoveUndefinedAttribute(attr.Key.Name, dbContext.DBObjectManager);

                                if (!removeExcept.Success())
                                {
                                    retExcept.PushIExceptional(removeExcept);
                                }

                                var flushExcept = dbContext.DBObjectManager.FlushDBObject(item.Value);

                                if (!flushExcept.Success())
                                {
                                    retExcept.PushIExceptional(flushExcept);
                                }
                            }
                            else
                            {
                                retExcept.PushIExceptional(new Exceptional(new Error_InvalidUndefAttrType(attr.Key.Name, attr.Value.Name)));
                            }
                        }
                    }
                }
            }

            return Exceptional.OK;
        }
예제 #28
0
        /// <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(DBContext myDBContext, Exceptional<DBObjectStream> myDBObjectStreamExceptional, GraphDBType myGraphDBType, 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, myGraphDBType, myDBContext);

                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, myGraphDBType, myDBContext);
                if (extractedValue.Failed())
                {
                    return new Exceptional<Vertex>(extractedValue);
                }
                _Vertex.AddAttribute(SpecialTypeAttribute_REVISION.AttributeName, extractedValue.Value.GetReadoutValue());

            }

            #endregion

            #endregion

            return new Exceptional<Vertex>(_Vertex);
        }
예제 #29
0
        public Exceptional<DBObjectStream> LoadDBObject(ObjectLocation myObjectLocation)
        {
            var _DBExceptional        = new Exceptional<DBObjectStream>();
            var _GetObjectExceptional = _IGraphFSSession.GetFSObject<DBObjectStream>(myObjectLocation, DBConstants.DBOBJECTSTREAM, null, null, 0, false);

            if (_GetObjectExceptional == null || _GetObjectExceptional.Failed() || _GetObjectExceptional.Value == null)
            {
                return _GetObjectExceptional.Convert<DBObjectStream>().PushIErrorT(new Error_LoadObject(myObjectLocation));
            }

            _DBExceptional.Value = _GetObjectExceptional.Value;
            return _DBExceptional;
        }
예제 #30
0
        /// <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:
                            if (undefAttrWarning == null)
                            {
                                undefAttrWarning = new Warning_UndefinedAttribute();
                            }

                            resultExcept.PushIWarning(undefAttrWarning);
                            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()));

                    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;
        }