/// <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); } }
/// <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); }
internal String ToString(List <RDFNamespace> prefixes) { return(RDFQueryUtilities.PrintRDFPatternMember(this.Start, prefixes) + " " + this.GetStepString(prefixes) + " " + RDFQueryUtilities.PrintRDFPatternMember(this.End, prefixes)); }
internal String ToString(List <RDFNamespace> prefixes) { String subj = RDFQueryUtilities.PrintRDFPatternMember(this.Subject, prefixes); String pred = RDFQueryUtilities.PrintRDFPatternMember(this.Predicate, prefixes); String obj = RDFQueryUtilities.PrintRDFPatternMember(this.Object, prefixes); //CSPO pattern if (this.Context != null) { String ctx = RDFQueryUtilities.PrintRDFPatternMember(this.Context, prefixes); if (this.IsOptional) { return("OPTIONAL { GRAPH " + ctx + " { " + subj + " " + pred + " " + obj + " } }"); } return("GRAPH " + ctx + " { " + subj + " " + pred + " " + obj + " }"); } //SPO pattern if (this.IsOptional) { return("OPTIONAL { " + subj + " " + pred + " " + obj + " }"); } return(subj + " " + pred + " " + obj); }
/// <summary> /// Gets the string representation of the path /// </summary> internal String GetStepString(List <RDFNamespace> prefixes) { var result = new StringBuilder(); #region Single Property if (this.Steps.Count == 1) { //InversePath (will swap start/end) if (this.Steps[0].IsInverseStep) { result.Append("^"); } var propPath = this.Steps[0].StepProperty; result.Append(RDFQueryUtilities.PrintRDFPatternMember(propPath, prefixes)); } #endregion #region Multiple Properties else { //Initialize printing Boolean openedParenthesis = false; //Iterate properties for (int i = 0; i < this.Steps.Count; i++) { //Alternative: generate union pattern if (this.Steps[i].StepFlavor == RDFQueryEnums.RDFPropertyPathStepFlavors.Alternative) { if (!openedParenthesis) { openedParenthesis = true; result.Append("("); } //InversePath (will swap start/end) if (this.Steps[i].IsInverseStep) { result.Append("^"); } var propPath = this.Steps[i].StepProperty; if (i < this.Steps.Count - 1) { result.Append(RDFQueryUtilities.PrintRDFPatternMember(propPath, prefixes)); result.Append((Char)this.Steps[i].StepFlavor); } else { result.Append(RDFQueryUtilities.PrintRDFPatternMember(propPath, prefixes)); result.Append(")"); } } //Sequence: generate pattern else { if (openedParenthesis) { result.Remove(result.Length - 1, 1); openedParenthesis = false; result.Append(")/"); } //InversePath (will swap start/end) if (this.Steps[i].IsInverseStep) { result.Append("^"); } var propPath = this.Steps[i].StepProperty; if (i < this.Steps.Count - 1) { result.Append(RDFQueryUtilities.PrintRDFPatternMember(propPath, prefixes)); result.Append((Char)this.Steps[i].StepFlavor); } else { result.Append(RDFQueryUtilities.PrintRDFPatternMember(propPath, prefixes)); } } } } #endregion return(result.ToString()); }
/// <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); }
/// <summary> /// Gives the string representation of the filter /// </summary> public override String ToString() { return("FILTER ( SAMETERM(" + this.Variable + ", " + RDFQueryUtilities.PrintRDFPatternMember(this.RDFTerm) + ") )"); }
/// <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); }
/// <summary> /// Prints the string representation of a SPARQL DESCRIBE query /// </summary> internal static String PrintDescribeQuery(RDFDescribeQuery describeQuery) { StringBuilder sb = new StringBuilder(); if (describeQuery != null) { #region PREFIXES if (describeQuery.Prefixes.Any()) { describeQuery.Prefixes.ForEach(pf => { sb.Append("PREFIX " + pf.NamespacePrefix + ": <" + pf.NamespaceUri + ">\n"); }); sb.Append("\n"); } #endregion #region HEADER #region BEGINDESCRIBE sb.Append("DESCRIBE"); #endregion #region TERMS if (describeQuery.DescribeTerms.Any()) { describeQuery.DescribeTerms.ForEach(dt => { sb.Append(" " + RDFQueryUtilities.PrintRDFPatternMember(dt, describeQuery.Prefixes)); }); } else { sb.Append(" *"); } sb.Append("\n"); #endregion #endregion #region BODY sb.Append("WHERE\n"); sb.Append("{\n"); #region MEMBERS Boolean printingUnion = false; List <RDFQueryMember> evaluableQueryMembers = describeQuery.GetEvaluableQueryMembers().ToList(); RDFQueryMember lastQueryMbr = evaluableQueryMembers.LastOrDefault(); foreach (var queryMember in evaluableQueryMembers) { #region PATTERNGROUPS if (queryMember is RDFPatternGroup) { //Current pattern group is set as UNION with the next one if (((RDFPatternGroup)queryMember).JoinAsUnion) { //Current pattern group IS NOT the last of the query //(so UNION keyword must be appended at last) if (!queryMember.Equals(lastQueryMbr)) { //Begin a new Union block if (!printingUnion) { printingUnion = true; sb.Append(" {\n"); } sb.Append(((RDFPatternGroup)queryMember).ToString(2, describeQuery.Prefixes) + " UNION\n"); } //Current pattern group IS the last of the query //(so UNION keyword must not be appended at last) else { //End the Union block if (printingUnion) { printingUnion = false; sb.Append(((RDFPatternGroup)queryMember).ToString(2, describeQuery.Prefixes)); sb.Append(" }"); sb.Append("\n"); } else { sb.Append(((RDFPatternGroup)queryMember).ToString(0, describeQuery.Prefixes)); } } } //Current pattern group is set as INTERSECT with the next one else { //End the Union block if (printingUnion) { printingUnion = false; sb.Append(((RDFPatternGroup)queryMember).ToString(2, describeQuery.Prefixes)); sb.Append(" }"); sb.Append("\n"); } else { sb.Append(((RDFPatternGroup)queryMember).ToString(0, describeQuery.Prefixes)); } } } #endregion #region SUBQUERY else if (queryMember is RDFQuery) { //Merge main query prefixes describeQuery.Prefixes.ForEach(pf1 => { if (!((RDFSelectQuery)queryMember).Prefixes.Any(pf2 => pf2.Equals(pf1))) { ((RDFSelectQuery)queryMember).AddPrefix(pf1); } }); //End the Union block if (printingUnion) { printingUnion = false; sb.Append(((RDFSelectQuery)queryMember).ToString()); sb.Append(" }"); sb.AppendLine(); } else { sb.Append(((RDFSelectQuery)queryMember).ToString()); } } #endregion } #endregion sb.Append("}\n"); #endregion #region FOOTER #region MODIFIERS List <RDFModifier> modifiers = describeQuery.GetModifiers().ToList(); // LIMIT/OFFSET if (modifiers.Any(mod => mod is RDFLimitModifier || mod is RDFOffsetModifier)) { modifiers.Where(mod => mod is RDFLimitModifier) .ToList() .ForEach(lim => { sb.Append("\n"); sb.Append(lim); }); modifiers.Where(mod => mod is RDFOffsetModifier) .ToList() .ForEach(off => { sb.Append("\n"); sb.Append(off); }); } #endregion #endregion } return(sb.ToString()); }
internal override string ToString(List <RDFNamespace> prefixes) => string.Concat( "FILTER ( DATATYPE(", this.Variable, ") = ", RDFQueryPrinter.PrintPatternMember(RDFQueryUtilities.ParseRDFPatternMember(RDFModelUtilities.GetDatatypeFromEnum(this.Datatype)), prefixes), " )");