ParseRDFPatternMember() статический приватный Метод

Parses the given string to return an instance of pattern member
static private ParseRDFPatternMember ( String pMember ) : RDFPatternMember
pMember String
Результат RDFPatternMember
        /// <summary>
        /// Gets a graph corresponding to the query result
        /// </summary>
        public RDFGraph ToRDFGraph()
        {
            RDFGraph         result = new RDFGraph();
            RDFPatternMember subj   = null;
            RDFPatternMember pred   = null;
            RDFPatternMember obj    = null;

            //Iterate the datatable rows and generate the corresponding triples to be added to the result graph
            IEnumerator resultRows = this.ConstructResults.Rows.GetEnumerator();

            while (resultRows.MoveNext())
            {
                subj = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["?SUBJECT"].ToString());
                pred = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["?PREDICATE"].ToString());
                obj  = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["?OBJECT"].ToString());
                if (obj is RDFResource)
                {
                    result.AddTriple(new RDFTriple((RDFResource)subj, (RDFResource)pred, (RDFResource)obj));
                }
                else
                {
                    result.AddTriple(new RDFTriple((RDFResource)subj, (RDFResource)pred, (RDFLiteral)obj));
                }
            }

            return(result);
        }
        /// <summary>
        /// Gets a memory store corresponding to the query result
        /// </summary>
        public RDFMemoryStore ToRDFMemoryStore()
        {
            RDFMemoryStore   result = new RDFMemoryStore();
            RDFPatternMember ctx    = null;
            RDFPatternMember subj   = null;
            RDFPatternMember pred   = null;
            RDFPatternMember obj    = null;

            //Iterate the datatable rows and generate the corresponding triples to be added to the result memory store
            IEnumerator resultRows = this.DescribeResults.Rows.GetEnumerator();

            while (resultRows.MoveNext())
            {
                ctx = this.DescribeResults.Columns.Contains("?CONTEXT")
                        ? new RDFContext(RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["?CONTEXT"].ToString()).ToString())
                        : new RDFContext(RDFNamespaceRegister.DefaultNamespace.NamespaceUri);
                subj = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["?SUBJECT"].ToString());
                pred = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["?PREDICATE"].ToString());
                obj  = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)["?OBJECT"].ToString());
                if (obj is RDFResource)
                {
                    result.AddQuadruple(new RDFQuadruple((RDFContext)ctx, (RDFResource)subj, (RDFResource)pred, (RDFResource)obj));
                }
                else
                {
                    result.AddQuadruple(new RDFQuadruple((RDFContext)ctx, (RDFResource)subj, (RDFResource)pred, (RDFLiteral)obj));
                }
            }

            return(result);
        }
Пример #3
0
 /// <summary>
 /// Gets the row value for the aggregator as number
 /// </summary>
 internal Double GetRowValueAsNumber(DataRow tableRow)
 {
     try
     {
         if (!tableRow.IsNull(this.AggregatorVariable.VariableName))
         {
             RDFPatternMember rowAggregatorValue = RDFQueryUtilities.ParseRDFPatternMember(tableRow[this.AggregatorVariable.VariableName].ToString());
             //PlainLiteral: accepted only if numeric and non-languaged
             if (rowAggregatorValue is RDFPlainLiteral)
             {
                 if (String.IsNullOrEmpty(((RDFPlainLiteral)rowAggregatorValue).Language))
                 {
                     if (Double.TryParse(rowAggregatorValue.ToString(), NumberStyles.Float, CultureInfo.InvariantCulture, out Double doubleValue))
                     {
                         return(doubleValue);
                     }
                 }
             }
             //TypedLiteral: accepted only if numeric
             else if (rowAggregatorValue is RDFTypedLiteral)
             {
                 if (((RDFTypedLiteral)rowAggregatorValue).HasDecimalDatatype())
                 {
                     return(Double.Parse(((RDFTypedLiteral)rowAggregatorValue).Value, NumberStyles.Float, CultureInfo.InvariantCulture));
                 }
             }
         }
         return(Double.NaN);
     }
     catch (Exception ex)
     {
         RDFQueryEvents.RaiseSELECTQueryEvaluation(String.Format("Exception intercepted during evaluation of RDFAggregator '{0}' in method GetRowValueAsNumber: '{1}'", this, ex.Message));
         return(Double.NaN);
     }
 }
Пример #4
0
        /// <summary>
        /// Applies the filter on the given datarow
        /// </summary>
        internal override Boolean ApplyFilter(DataRow row, Boolean applyNegation)
        {
            var keepRow    = true;
            var leftValue  = this.LeftMember;
            var rightValue = this.RightMember;

            //In case LeftMember is a variable, try to get the value corresponding to its column; if column not found, the filter fails
            if (this.LeftMember     is RDFVariable)
            {
                if (row.Table.Columns.Contains(this.LeftMember.ToString()))
                {
                    leftValue = RDFQueryUtilities.ParseRDFPatternMember(row[this.LeftMember.ToString()].ToString());
                }
                else
                {
                    keepRow = false;
                }
            }

            //In case RightMember is a variable, try to get the value corresponding to its column; if column not found, the filter fails
            if (keepRow && this.RightMember is RDFVariable)
            {
                if (row.Table.Columns.Contains(this.RightMember.ToString()))
                {
                    rightValue = RDFQueryUtilities.ParseRDFPatternMember(row[this.RightMember.ToString()].ToString());
                }
                else
                {
                    keepRow = false;
                }
            }

            //Perform the comparison between leftValue and rightValue
            if (keepRow)
            {
                try {
                    var comparison = RDFQueryUtilities.CompareRDFPatternMembers(leftValue, rightValue);

                    //Type Error
                    if (comparison == -99)
                    {
                        keepRow = false;
                    }

                    //Type Correct
                    else
                    {
                        switch (this.ComparisonFlavor)
                        {
                        case RDFQueryEnums.RDFComparisonFlavors.LessThan:
                            keepRow = (comparison < 0);
                            break;

                        case RDFQueryEnums.RDFComparisonFlavors.LessOrEqualThan:
                            keepRow = (comparison <= 0);
                            break;

                        case RDFQueryEnums.RDFComparisonFlavors.EqualTo:
                            keepRow = (comparison == 0);
                            break;

                        case RDFQueryEnums.RDFComparisonFlavors.NotEqualTo:
                            keepRow = (comparison != 0);
                            break;

                        case RDFQueryEnums.RDFComparisonFlavors.GreaterOrEqualThan:
                            keepRow = (comparison >= 0);
                            break;

                        case RDFQueryEnums.RDFComparisonFlavors.GreaterThan:
                            keepRow = (comparison > 0);
                            break;
                        }
                    }
                }
                catch {
                    keepRow = false; //Type Error
                }
            }

            //Apply the eventual negation
            if (applyNegation)
            {
                keepRow = !keepRow;
            }

            return(keepRow);
        }
Пример #5
0
 internal override String ToString(List <RDFNamespace> prefixes)
 {
     return("FILTER ( DATATYPE(" + this.Variable + ") = " + RDFQueryUtilities.PrintRDFPatternMember(RDFQueryUtilities.ParseRDFPatternMember(RDFModelUtilities.GetDatatypeFromEnum(this.Datatype)), prefixes) + " )");
 }
Пример #6
0
        /// <summary>
        /// Prints the string representation of a pattern member
        /// </summary>
        internal static String PrintPatternMember(RDFPatternMember patternMember, List <RDFNamespace> prefixes)
        {
            if (patternMember != null)
            {
                #region Variable
                if (patternMember is RDFVariable)
                {
                    return(patternMember.ToString());
                }
                #endregion

                #region Resource/Context
                if (patternMember is RDFResource || patternMember is RDFContext)
                {
                    #region Blank
                    if (patternMember is RDFResource && ((RDFResource)patternMember).IsBlank)
                    {
                        return(patternMember.ToString().Replace("bnode:", "_:"));
                    }
                    #endregion

                    #region NonBlank
                    var abbreviatedPM = RDFQueryUtilities.AbbreviateRDFPatternMember(patternMember, prefixes);
                    if (abbreviatedPM.Item1)
                    {
                        return(abbreviatedPM.Item2);
                    }
                    else
                    {
                        return("<" + abbreviatedPM.Item2 + ">");
                    }
                    #endregion
                }
                #endregion

                #region Literal
                if (patternMember is RDFLiteral)
                {
                    #region PlainLiteral
                    if (patternMember is RDFPlainLiteral)
                    {
                        if (((RDFPlainLiteral)patternMember).Language != String.Empty)
                        {
                            return("\"" + ((RDFPlainLiteral)patternMember).Value + "\"@" + ((RDFPlainLiteral)patternMember).Language);
                        }
                        return("\"" + ((RDFPlainLiteral)patternMember).Value + "\"");
                    }
                    #endregion

                    #region TypedLiteral
                    else
                    {
                        var abbreviatedPM = RDFQueryUtilities.AbbreviateRDFPatternMember(RDFQueryUtilities.ParseRDFPatternMember(RDFModelUtilities.GetDatatypeFromEnum(((RDFTypedLiteral)patternMember).Datatype)), prefixes);
                        if (abbreviatedPM.Item1)
                        {
                            return("\"" + ((RDFTypedLiteral)patternMember).Value + "\"^^" + abbreviatedPM.Item2);
                        }
                        else
                        {
                            return("\"" + ((RDFTypedLiteral)patternMember).Value + "\"^^<" + abbreviatedPM.Item2 + ">");
                        }
                    }
                    #endregion
                }
                #endregion
            }
            return(null);
        }
Пример #7
0
        /// <summary>
        /// Writes the "SPARQL Query Results XML Format" stream corresponding to the SELECT query result
        /// </summary>
        public void ToSparqlXmlResult(Stream outputStream)
        {
            try {
                #region serialize
                using (XmlTextWriter sparqlWriter = new XmlTextWriter(outputStream, Encoding.UTF8)) {
                    XmlDocument sparqlDoc = new XmlDocument();
                    sparqlWriter.Formatting = Formatting.Indented;

                    #region xmlDecl
                    XmlDeclaration sparqlDecl = sparqlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
                    sparqlDoc.AppendChild(sparqlDecl);
                    #endregion

                    #region sparqlRoot
                    XmlNode      sparqlRoot       = sparqlDoc.CreateNode(XmlNodeType.Element, "sparql", null);
                    XmlAttribute sparqlRootNS     = sparqlDoc.CreateAttribute("xmlns");
                    XmlText      sparqlRootNSText = sparqlDoc.CreateTextNode("http://www.w3.org/2005/sparql-results#");
                    sparqlRootNS.AppendChild(sparqlRootNSText);
                    sparqlRoot.Attributes.Append(sparqlRootNS);

                    #region sparqlHead
                    XmlNode     sparqlHeadElement = sparqlDoc.CreateNode(XmlNodeType.Element, "head", null);
                    IEnumerator resultColumns     = this.SelectResults.Columns.GetEnumerator();
                    while (resultColumns.MoveNext())
                    {
                        XmlNode      variableElement = sparqlDoc.CreateNode(XmlNodeType.Element, "variable", null);
                        XmlAttribute varElName       = sparqlDoc.CreateAttribute("name");
                        XmlText      varElNameText   = sparqlDoc.CreateTextNode(resultColumns.Current.ToString());
                        varElName.AppendChild(varElNameText);
                        variableElement.Attributes.Append(varElName);
                        sparqlHeadElement.AppendChild(variableElement);
                    }
                    sparqlRoot.AppendChild(sparqlHeadElement);
                    #endregion

                    #region sparqlResults
                    XmlNode     sparqlResultsElement = sparqlDoc.CreateNode(XmlNodeType.Element, "results", null);
                    IEnumerator resultRows           = this.SelectResults.Rows.GetEnumerator();
                    while (resultRows.MoveNext())
                    {
                        resultColumns.Reset();
                        XmlNode resultElement = sparqlDoc.CreateNode(XmlNodeType.Element, "result", null);
                        while (resultColumns.MoveNext())
                        {
                            if (!((DataRow)resultRows.Current).IsNull(resultColumns.Current.ToString()))
                            {
                                XmlNode      bindingElement = sparqlDoc.CreateNode(XmlNodeType.Element, "binding", null);
                                XmlAttribute bindElName     = sparqlDoc.CreateAttribute("name");
                                XmlText      bindElNameText = sparqlDoc.CreateTextNode(resultColumns.Current.ToString());
                                bindElName.AppendChild(bindElNameText);
                                bindingElement.Attributes.Append(bindElName);

                                #region RDFTerm
                                RDFPatternMember rdfTerm = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)[resultColumns.Current.ToString()].ToString());
                                if (rdfTerm is RDFResource)
                                {
                                    if (rdfTerm.ToString().StartsWith("bnode:"))
                                    {
                                        XmlNode bnodeElement = sparqlDoc.CreateNode(XmlNodeType.Element, "bnode", null);
                                        XmlText bnodeElText  = sparqlDoc.CreateTextNode(rdfTerm.ToString());
                                        bnodeElement.AppendChild(bnodeElText);
                                        bindingElement.AppendChild(bnodeElement);
                                    }
                                    else
                                    {
                                        XmlNode uriElement = sparqlDoc.CreateNode(XmlNodeType.Element, "uri", null);
                                        XmlText uriElText  = sparqlDoc.CreateTextNode(rdfTerm.ToString());
                                        uriElement.AppendChild(uriElText);
                                        bindingElement.AppendChild(uriElement);
                                    }
                                }
                                else if (rdfTerm is RDFLiteral)
                                {
                                    XmlNode litElement = sparqlDoc.CreateNode(XmlNodeType.Element, "literal", null);
                                    if (rdfTerm is RDFPlainLiteral)
                                    {
                                        if (((RDFPlainLiteral)rdfTerm).Language != String.Empty)
                                        {
                                            XmlAttribute xmlLang     = sparqlDoc.CreateAttribute(RDFVocabulary.XML.PREFIX + ":lang", RDFVocabulary.XML.BASE_URI);
                                            XmlText      xmlLangText = sparqlDoc.CreateTextNode(((RDFPlainLiteral)rdfTerm).Language);
                                            xmlLang.AppendChild(xmlLangText);
                                            litElement.Attributes.Append(xmlLang);
                                        }
                                        XmlText plainLiteralText = sparqlDoc.CreateTextNode(RDFModelUtilities.EscapeControlCharsForXML(HttpUtility.HtmlDecode(((RDFLiteral)rdfTerm).Value)));
                                        litElement.AppendChild(plainLiteralText);
                                    }
                                    else
                                    {
                                        XmlAttribute datatype     = sparqlDoc.CreateAttribute("datatype");
                                        XmlText      datatypeText = sparqlDoc.CreateTextNode(RDFModelUtilities.GetDatatypeFromEnum(((RDFTypedLiteral)rdfTerm).Datatype));
                                        datatype.AppendChild(datatypeText);
                                        litElement.Attributes.Append(datatype);
                                        XmlText typedLiteralText = sparqlDoc.CreateTextNode(RDFModelUtilities.EscapeControlCharsForXML(HttpUtility.HtmlDecode(((RDFLiteral)rdfTerm).Value)));
                                        litElement.AppendChild(typedLiteralText);
                                    }
                                    bindingElement.AppendChild(litElement);
                                }
                                #endregion

                                resultElement.AppendChild(bindingElement);
                            }
                        }
                        sparqlResultsElement.AppendChild(resultElement);
                    }
                    sparqlRoot.AppendChild(sparqlResultsElement);
                    #endregion

                    sparqlDoc.AppendChild(sparqlRoot);
                    #endregion

                    sparqlDoc.Save(sparqlWriter);
                }
                #endregion
            }
            catch (Exception ex) {
                throw new RDFQueryException("Cannot serialize SPARQL XML RESULT because: " + ex.Message, ex);
            }
        }
Пример #8
0
        /// <summary>
        /// Applies the filter on the column corresponding to the pattern in the given datarow
        /// </summary>
        internal override Boolean ApplyFilter(DataRow row, Boolean applyNegation)
        {
            Boolean keepRow = false;
            EnumerableRowCollection <DataRow> patternResultsEnumerable = this.PatternResults?.AsEnumerable();

            if (patternResultsEnumerable?.Any() ?? false)
            {
                #region Disjoint Evaluation
                //In case of disjointess between the query and the filter's pattern, all solutions are compatible
                Boolean disjointSubject = this.Pattern.Subject is RDFVariable ?
                                          !row.Table.Columns.Contains(this.Pattern.Subject.ToString()) : true;
                Boolean disjointPredicate = this.Pattern.Predicate is RDFVariable ?
                                            !row.Table.Columns.Contains(this.Pattern.Predicate.ToString()) : true;
                Boolean disjointObject = this.Pattern.Object is RDFVariable ?
                                         !row.Table.Columns.Contains(this.Pattern.Object.ToString()) : true;
                if (disjointSubject && disjointPredicate && disjointObject)
                {
                    keepRow = true;
                }
                #endregion

                #region Non-Disjoint Evaluation
                else
                {
                    #region Subject
                    Boolean subjectCompared = false;
                    if (this.Pattern.Subject is RDFVariable &&
                        this.PatternResults.Columns.Contains(this.Pattern.Subject.ToString()) &&
                        row.Table.Columns.Contains(this.Pattern.Subject.ToString()))
                    {
                        //In case of emptiness the solution is compatible, otherwise proceed with comparison
                        if (!row.IsNull(this.Pattern.Subject.ToString()))
                        {
                            //Get subject filter's value for the given row
                            RDFPatternMember rowMember = RDFQueryUtilities.ParseRDFPatternMember(row[this.Pattern.Subject.ToString()].ToString());

                            //Apply subject filter on the pattern resultset
                            patternResultsEnumerable = patternResultsEnumerable.Where(x => RDFQueryUtilities.ParseRDFPatternMember(x.Field <String>(this.Pattern.Subject.ToString())).Equals(rowMember));
                        }
                        subjectCompared = true;
                    }
                    #endregion

                    #region Predicate
                    Boolean predicateCompared = false;
                    if (this.Pattern.Predicate is RDFVariable &&
                        this.PatternResults.Columns.Contains(this.Pattern.Predicate.ToString()) &&
                        row.Table.Columns.Contains(this.Pattern.Predicate.ToString()))
                    {
                        //In case of emptiness the solution is compatible, otherwise proceed with comparison
                        if (!row.IsNull(this.Pattern.Predicate.ToString()))
                        {
                            //Get predicate filter's value for the given row
                            RDFPatternMember rowMember = RDFQueryUtilities.ParseRDFPatternMember(row[this.Pattern.Predicate.ToString()].ToString());

                            //Apply predicate filter on the pattern resultset
                            patternResultsEnumerable = patternResultsEnumerable.Where(x => RDFQueryUtilities.ParseRDFPatternMember(x.Field <String>(this.Pattern.Predicate.ToString())).Equals(rowMember));
                        }
                        predicateCompared = true;
                    }
                    #endregion

                    #region Object
                    Boolean objectCompared = false;
                    if (this.Pattern.Object is RDFVariable &&
                        this.PatternResults.Columns.Contains(this.Pattern.Object.ToString()) &&
                        row.Table.Columns.Contains(this.Pattern.Object.ToString()))
                    {
                        //In case of emptiness the solution is compatible, otherwise proceed with comparison
                        if (!row.IsNull(this.Pattern.Object.ToString()))
                        {
                            //Get object filter's value for the given row
                            RDFPatternMember rowMember = RDFQueryUtilities.ParseRDFPatternMember(row[this.Pattern.Object.ToString()].ToString());

                            //Apply object filter on the pattern resultset
                            patternResultsEnumerable = patternResultsEnumerable.Where(x => RDFQueryUtilities.ParseRDFPatternMember(x.Field <String>(this.Pattern.Object.ToString())).Equals(rowMember));
                        }
                        objectCompared = true;
                    }
                    #endregion

                    #region Decision
                    //Verify filter's response on the pattern resultset
                    if ((subjectCompared || predicateCompared || objectCompared) && patternResultsEnumerable.ToList().Any())
                    {
                        keepRow = true;
                    }
                    #endregion
                }
                #endregion
            }

            //Apply the eventual negation
            if (applyNegation)
            {
                keepRow = !keepRow;
            }

            return(keepRow);
        }
Пример #9
0
        /// <summary>
        /// Fills the templates of the given query with data from the given result table
        /// </summary>
        internal static DataTable FillTemplates(RDFConstructQuery constructQuery, DataTable resultTable)
        {
            //Create the structure of the result datatable
            DataTable result = new DataTable("CONSTRUCT_RESULTS");

            result.Columns.Add("SUBJECT", Type.GetType("System.String"));
            result.Columns.Add("PREDICATE", Type.GetType("System.String"));
            result.Columns.Add("OBJECT", Type.GetType("System.String"));
            result.AcceptChanges();

            //Initialize working variables
            Dictionary <String, String> constructRow = new Dictionary <String, String>();

            constructRow.Add("SUBJECT", null);
            constructRow.Add("PREDICATE", null);
            constructRow.Add("OBJECT", null);

            //Iterate on the templates
            foreach (RDFPattern tp in constructQuery.Templates.Where(tp => tp.Variables.Count == 0 ||
                                                                     tp.Variables.TrueForAll(v => resultTable.Columns.Contains(v.ToString()))))
            {
                #region GROUND TEMPLATE
                //Check if the template is ground, so represents an explicit triple to be added as-is
                if (tp.Variables.Count == 0)
                {
                    constructRow["SUBJECT"]   = tp.Subject.ToString();
                    constructRow["PREDICATE"] = tp.Predicate.ToString();
                    constructRow["OBJECT"]    = tp.Object.ToString();
                    RDFQueryUtilities.AddRow(result, constructRow);
                    continue;
                }
                #endregion

                #region NON-GROUND TEMPLATE
                //Iterate the result datatable's rows to construct the triples of the current template
                IEnumerator rowsEnum = resultTable.Rows.GetEnumerator();
                while (rowsEnum.MoveNext())
                {
                    #region SUBJECT
                    //Subject of the template is a variable
                    if (tp.Subject is RDFVariable)
                    {
                        //Check if the template must be skipped, in order to not produce illegal triples
                        //Row contains an unbound value in position of the variable corresponding to the template subject
                        if (((DataRow)rowsEnum.Current).IsNull(tp.Subject.ToString()))
                        {
                            continue;
                        }

                        RDFPatternMember subj = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)rowsEnum.Current)[tp.Subject.ToString()].ToString());
                        //Row contains a literal in position of the variable corresponding to the template subject
                        if (subj is RDFLiteral)
                        {
                            continue;
                        }
                        //Row contains a resource in position of the variable corresponding to the template subject
                        constructRow["SUBJECT"] = subj.ToString();
                    }
                    //Subject of the template is a resource
                    else
                    {
                        constructRow["SUBJECT"] = tp.Subject.ToString();
                    }
                    #endregion

                    #region PREDICATE
                    //Predicate of the template is a variable
                    if (tp.Predicate is RDFVariable)
                    {
                        //Check if the template must be skipped, in order to not produce illegal triples
                        //Row contains an unbound value in position of the variable corresponding to the template predicate
                        if (((DataRow)rowsEnum.Current).IsNull(tp.Predicate.ToString()))
                        {
                            continue;
                        }
                        RDFPatternMember pred = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)rowsEnum.Current)[tp.Predicate.ToString()].ToString());
                        //Row contains a blank resource or a literal in position of the variable corresponding to the template predicate
                        if ((pred is RDFResource && ((RDFResource)pred).IsBlank) || pred is RDFLiteral)
                        {
                            continue;
                        }
                        //Row contains a non-blank resource in position of the variable corresponding to the template predicate
                        constructRow["PREDICATE"] = pred.ToString();
                    }
                    //Predicate of the template is a resource
                    else
                    {
                        constructRow["PREDICATE"] = tp.Predicate.ToString();
                    }
                    #endregion

                    #region OBJECT
                    //Object of the template is a variable
                    if (tp.Object is RDFVariable)
                    {
                        //Check if the template must be skipped, in order to not produce illegal triples
                        //Row contains an unbound value in position of the variable corresponding to the template object
                        if (((DataRow)rowsEnum.Current).IsNull(tp.Object.ToString()))
                        {
                            continue;
                        }
                        RDFPatternMember obj = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)rowsEnum.Current)[tp.Object.ToString()].ToString());
                        //Row contains a resource or a literal in position of the variable corresponding to the template object
                        constructRow["OBJECT"] = obj.ToString();
                    }
                    //Object of the template is a resource or a literal
                    else
                    {
                        constructRow["OBJECT"] = tp.Object.ToString();
                    }
                    #endregion

                    //Insert the triple into the final table
                    RDFQueryUtilities.AddRow(result, constructRow);
                }
                #endregion
            }

            return(result);
        }
Пример #10
0
        /// <summary>
        /// Applies the filter on the column corresponding to the pattern in the given datarow
        /// </summary>
        internal override Boolean ApplyFilter(DataRow row, Boolean applyNegation)
        {
            Boolean keepRow = false;
            EnumerableRowCollection <DataRow> patternResultsEnumerable = this.PatternResults?.AsEnumerable();

            if (patternResultsEnumerable?.Any() ?? false)
            {
                #region Evaluation

                #region Subject
                Boolean subjectCompared = false;
                if (this.Pattern.Subject is RDFVariable &&
                    this.PatternResults.Columns.Contains(this.Pattern.Subject.ToString()) &&
                    row.Table.Columns.Contains(this.Pattern.Subject.ToString()))
                {
                    //Get subject filter's value for the given row
                    RDFPatternMember rowMember = RDFQueryUtilities.ParseRDFPatternMember(row[this.Pattern.Subject.ToString()].ToString());

                    //Apply subject filter on the pattern resultset
                    patternResultsEnumerable = patternResultsEnumerable.Where(x => RDFQueryUtilities.ParseRDFPatternMember(x.Field <String>(this.Pattern.Subject.ToString())).Equals(rowMember));
                    subjectCompared          = true;
                }
                #endregion

                #region Predicate
                Boolean predicateCompared = false;
                if (this.Pattern.Predicate is RDFVariable &&
                    this.PatternResults.Columns.Contains(this.Pattern.Predicate.ToString()) &&
                    row.Table.Columns.Contains(this.Pattern.Predicate.ToString()))
                {
                    //Get predicate filter's value for the given row
                    RDFPatternMember rowMember = RDFQueryUtilities.ParseRDFPatternMember(row[this.Pattern.Predicate.ToString()].ToString());

                    //Apply predicate filter on the pattern resultset
                    patternResultsEnumerable = patternResultsEnumerable.Where(x => RDFQueryUtilities.ParseRDFPatternMember(x.Field <String>(this.Pattern.Predicate.ToString())).Equals(rowMember));
                    predicateCompared        = true;
                }
                #endregion

                #region Object
                Boolean objectCompared = false;
                if (this.Pattern.Object is RDFVariable &&
                    this.PatternResults.Columns.Contains(this.Pattern.Object.ToString()) &&
                    row.Table.Columns.Contains(this.Pattern.Object.ToString()))
                {
                    //Get object filter's value for the given row
                    RDFPatternMember rowMember = RDFQueryUtilities.ParseRDFPatternMember(row[this.Pattern.Object.ToString()].ToString());

                    //Apply object filter on the pattern resultset
                    patternResultsEnumerable = patternResultsEnumerable.Where(x => RDFQueryUtilities.ParseRDFPatternMember(x.Field <String>(this.Pattern.Object.ToString())).Equals(rowMember));
                    objectCompared           = true;
                }
                #endregion

                #endregion

                #region Decision
                //Verify filter's response on the pattern resultset
                if ((subjectCompared || predicateCompared || objectCompared) && patternResultsEnumerable.ToList().Any())
                {
                    keepRow = true;
                }
                #endregion
            }

            //Apply the eventual negation
            if (applyNegation)
            {
                keepRow = !keepRow;
            }

            return(keepRow);
        }
Пример #11
0
        /// <summary>
        /// Describes the terms of the given query with data from the given result table
        /// </summary>
        internal static DataTable DescribeTerms(RDFDescribeQuery describeQuery, Object graphOrStore, DataTable resultTable)
        {
            //Create the structure of the result datatable
            DataTable result = new DataTable("DESCRIBE_RESULTS");

            result.Columns.Add("SUBJECT", Type.GetType("System.String"));
            result.Columns.Add("PREDICATE", Type.GetType("System.String"));
            result.Columns.Add("OBJECT", Type.GetType("System.String"));
            result.AcceptChanges();

            //Query IS empty, so does not have pattern groups to fetch data from
            //(we can only proceed by searching for resources in the describe terms)
            if (describeQuery.IsEmpty)
            {
                //Iterate the describe terms of the query which are resources (variables are omitted, since useless)
                foreach (RDFPatternMember dt in describeQuery.DescribeTerms.Where(dterm => dterm is RDFResource))
                {
                    //Search on GRAPH
                    if (graphOrStore is RDFGraph)
                    {
                        //Search as RESOURCE (S-P-O)
                        RDFGraph desc = ((RDFGraph)graphOrStore).SelectTriplesBySubject((RDFResource)dt)
                                        .UnionWith(((RDFGraph)graphOrStore).SelectTriplesByPredicate((RDFResource)dt))
                                        .UnionWith(((RDFGraph)graphOrStore).SelectTriplesByObject((RDFResource)dt));
                        result.Merge(desc.ToDataTable(), true, MissingSchemaAction.Add);
                    }

                    //Search on STORE
                    else
                    {
                        //Search as RESOURCE (S-P-O)
                        RDFMemoryStore desc = ((RDFMemoryStore)((RDFMemoryStore)((RDFMemoryStore)((RDFStore)graphOrStore).SelectQuadruplesBySubject((RDFResource)dt))
                                                                .UnionWith(((RDFStore)graphOrStore).SelectQuadruplesByPredicate((RDFResource)dt)))
                                               .UnionWith(((RDFStore)graphOrStore).SelectQuadruplesByObject((RDFResource)dt)));
                        result.Merge(desc.ToDataTable(), true, MissingSchemaAction.Add);
                    }
                }
            }

            //Query IS NOT empty, so does have pattern groups to fetch data from
            else
            {
                //In case of a "Star" query, all the variables must be considered describe terms
                if (describeQuery.IsStar)
                {
                    describeQuery.PatternGroups.ForEach(pg =>
                                                        pg.Variables.ForEach(v => describeQuery.AddDescribeTerm(v))
                                                        );
                }

                //Iterate the describe terms of the query
                foreach (RDFPatternMember dt in describeQuery.DescribeTerms)
                {
                    //The describe term is a variable
                    if (dt is RDFVariable)
                    {
                        //Process the variable
                        if (resultTable.Columns.Contains(dt.ToString()))
                        {
                            //Iterate the results datatable's rows to retrieve terms to be described
                            IEnumerator rowsEnum = resultTable.Rows.GetEnumerator();
                            while (rowsEnum.MoveNext())
                            {
                                //Row contains a value in position of the variable corresponding to the describe term
                                if (!((DataRow)rowsEnum.Current).IsNull(dt.ToString()))
                                {
                                    //Retrieve the term to be described
                                    RDFPatternMember term = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)rowsEnum.Current)[dt.ToString()].ToString());

                                    //Search on GRAPH
                                    if (graphOrStore is RDFGraph)
                                    {
                                        //Search as RESOURCE (S-P-O)
                                        if (term is RDFResource)
                                        {
                                            RDFGraph desc = ((RDFGraph)graphOrStore).SelectTriplesBySubject((RDFResource)term)
                                                            .UnionWith(((RDFGraph)graphOrStore).SelectTriplesByPredicate((RDFResource)term))
                                                            .UnionWith(((RDFGraph)graphOrStore).SelectTriplesByObject((RDFResource)term));
                                            result.Merge(desc.ToDataTable(), true, MissingSchemaAction.Add);
                                        }
                                        //Search as LITERAL (L)
                                        else
                                        {
                                            RDFGraph desc = ((RDFGraph)graphOrStore).SelectTriplesByLiteral((RDFLiteral)term);
                                            result.Merge(desc.ToDataTable(), true, MissingSchemaAction.Add);
                                        }
                                    }

                                    //Search on STORE
                                    else
                                    {
                                        //Search as RESOURCE (S-P-O)
                                        if (term is RDFResource)
                                        {
                                            RDFMemoryStore desc = ((RDFMemoryStore)((RDFMemoryStore)((RDFMemoryStore)((RDFStore)graphOrStore).SelectQuadruplesBySubject((RDFResource)term))
                                                                                    .UnionWith(((RDFStore)graphOrStore).SelectQuadruplesByPredicate((RDFResource)term)))
                                                                   .UnionWith(((RDFStore)graphOrStore).SelectQuadruplesByObject((RDFResource)term)));
                                            result.Merge(desc.ToDataTable(), true, MissingSchemaAction.Add);
                                        }
                                        //Search as LITERAL (L)
                                        else
                                        {
                                            RDFMemoryStore desc = ((RDFMemoryStore)((RDFStore)graphOrStore).SelectQuadruplesByLiteral((RDFLiteral)term));
                                            result.Merge(desc.ToDataTable(), true, MissingSchemaAction.Add);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    //The describe term is a resource
                    else
                    {
                        //Search on GRAPH
                        if (graphOrStore is RDFGraph)
                        {
                            //Search as RESOURCE (S-P-O)
                            RDFGraph desc = ((RDFGraph)graphOrStore).SelectTriplesBySubject((RDFResource)dt)
                                            .UnionWith(((RDFGraph)graphOrStore).SelectTriplesByPredicate((RDFResource)dt))
                                            .UnionWith(((RDFGraph)graphOrStore).SelectTriplesByObject((RDFResource)dt));
                            result.Merge(desc.ToDataTable(), true, MissingSchemaAction.Add);
                        }

                        //Search on STORE
                        else
                        {
                            //Search as RESOURCE (S-P-O)
                            RDFMemoryStore desc = ((RDFMemoryStore)((RDFMemoryStore)((RDFMemoryStore)((RDFStore)graphOrStore).SelectQuadruplesBySubject((RDFResource)dt))
                                                                    .UnionWith(((RDFStore)graphOrStore).SelectQuadruplesByPredicate((RDFResource)dt)))
                                                   .UnionWith(((RDFStore)graphOrStore).SelectQuadruplesByObject((RDFResource)dt)));
                            result.Merge(desc.ToDataTable(), true, MissingSchemaAction.Add);
                        }
                    }
                }
            }

            return(result);
        }
 internal override string ToString(List <RDFNamespace> prefixes)
 => string.Concat(
     "FILTER ( DATATYPE(", this.Variable, ") = ",
     RDFQueryPrinter.PrintPatternMember(RDFQueryUtilities.ParseRDFPatternMember(RDFModelUtilities.GetDatatypeFromEnum(this.Datatype)), prefixes), " )");