Skip to main content

qualia_core_db/sparql_library/
sparql_endpoint.rs

1//! SPARQL HTTP Endpoint
2//!
3//! Provides HTTP endpoint for SPARQL queries (/sparql)
4
5use crate::sparql_ast::*;
6use crate::sparql_executor::*;
7use crate::sparql_library::serialisers::sparql_results::ResultFormatter;
8use crate::sparql_parser;
9use crate::sparql_planner::*;
10use crate::NQuin;
11
12/// SPARQL HTTP endpoint handler
13pub struct SparqlEndpoint<'a> {
14    quins: &'a [NQuin],
15}
16
17impl<'a> SparqlEndpoint<'a> {
18    /// Creates a default `SparqlEndpoint`.
19    pub fn new(quins: &'a [NQuin]) -> Self {
20        Self { quins }
21    }
22
23    /// Handle SPARQL query via HTTP
24    pub fn handle_query(&self, query: &str, format: &str) -> Result<String, String> {
25        // Parse query
26        let (sparql_query, ctx) = sparql_parser::parse_sparql(query)?;
27
28        // Plan query
29        let plan = QueryPlanner::plan(&sparql_query, &ctx)?;
30
31        // Execute query
32        let executor = QueryExecutor::new(&self.quins);
33        let results = executor.execute(&plan, &ctx)?;
34
35        // Format results
36        match format.to_lowercase().as_str() {
37            "xml" => {
38                let mut output = Vec::new();
39                let vars = match &sparql_query {
40                    SparqlQuery::Select(select) => {
41                        select.variables[..select.var_count as usize].to_vec()
42                    }
43                    _ => vec![],
44                };
45                ResultFormatter::format_xml(&mut output, &vars, &results, &ctx, None)
46                    .map_err(|e| e.to_string())?;
47                Ok(String::from_utf8(output).unwrap())
48            }
49            "json" => {
50                let mut output = Vec::new();
51                let vars = match &sparql_query {
52                    SparqlQuery::Select(select) => {
53                        select.variables[..select.var_count as usize].to_vec()
54                    }
55                    _ => vec![],
56                };
57                ResultFormatter::format_json(&mut output, &vars, &results, &ctx, None)
58                    .map_err(|e| e.to_string())?;
59                Ok(String::from_utf8(output).unwrap())
60            }
61            "tsv" => {
62                let mut output = Vec::new();
63                let vars = match &sparql_query {
64                    SparqlQuery::Select(select) => {
65                        select.variables[..select.var_count as usize].to_vec()
66                    }
67                    _ => vec![],
68                };
69                ResultFormatter::format_tsv(&mut output, &vars, &results, &ctx, None)
70                    .map_err(|e| e.to_string())?;
71                Ok(String::from_utf8(output).unwrap())
72            }
73            "csv" => {
74                let mut output = Vec::new();
75                let vars = match &sparql_query {
76                    SparqlQuery::Select(select) => {
77                        select.variables[..select.var_count as usize].to_vec()
78                    }
79                    _ => vec![],
80                };
81                ResultFormatter::format_csv(&mut output, &vars, &results, &ctx, None)
82                    .map_err(|e| e.to_string())?;
83                Ok(String::from_utf8(output).unwrap())
84            }
85            _ => Err("Unsupported format. Use: xml, json, tsv, or csv".to_string()),
86        }
87    }
88
89    /// Handle ASK query
90    pub fn handle_ask(&self, query: &str, format: &str) -> Result<String, String> {
91        let (sparql_query, ctx) = sparql_parser::parse_sparql(query)?;
92
93        let plan = QueryPlanner::plan(&sparql_query, &ctx)?;
94        let executor = QueryExecutor::new(&self.quins);
95        let has_results = executor.execute_ask(&plan, &ctx)?;
96
97        match format.to_lowercase().as_str() {
98            "xml" => {
99                let mut output = Vec::new();
100                ResultFormatter::format_ask_xml(&mut output, has_results)
101                    .map_err(|e| e.to_string())?;
102                Ok(String::from_utf8(output).unwrap())
103            }
104            "json" => {
105                let mut output = Vec::new();
106                ResultFormatter::format_ask_json(&mut output, has_results)
107                    .map_err(|e| e.to_string())?;
108                Ok(String::from_utf8(output).unwrap())
109            }
110            _ => Err("Unsupported format for ASK. Use: xml or json".to_string()),
111        }
112    }
113
114    /// Handle CONSTRUCT query
115    pub fn handle_construct(&self, query: &str, format: &str) -> Result<String, String> {
116        let (sparql_query, ctx) = sparql_parser::parse_sparql(query)?;
117
118        let template_pattern = match &sparql_query {
119            SparqlQuery::Construct(c) => c.template_pattern,
120            _ => return Err("Query is not a CONSTRUCT".to_string()),
121        };
122
123        let plan = QueryPlanner::plan(&sparql_query, &ctx)?;
124        let executor = QueryExecutor::new(&self.quins);
125        // Rows are the instantiated template triples (slots 0/1/2 = s/p/o).
126        let results = executor.execute_construct(&plan, &ctx, template_pattern)?;
127
128        match format.to_lowercase().as_str() {
129            "ntriples" => {
130                let mut output = Vec::new();
131                ResultFormatter::format_ntriples(&mut output, &results)
132                    .map_err(|e| e.to_string())?;
133                Ok(String::from_utf8(output).unwrap())
134            }
135            "xml" => {
136                let mut output = Vec::new();
137                // Use default variables for CONSTRUCT
138                let vars = vec![0u8, 1u8, 2u8]; // subject, predicate, object
139                ResultFormatter::format_xml(&mut output, &vars, &results, &ctx, None)
140                    .map_err(|e| e.to_string())?;
141                Ok(String::from_utf8(output).unwrap())
142            }
143            "json" => {
144                let mut output = Vec::new();
145                let vars = vec![0u8, 1u8, 2u8];
146                ResultFormatter::format_json(&mut output, &vars, &results, &ctx, None)
147                    .map_err(|e| e.to_string())?;
148                Ok(String::from_utf8(output).unwrap())
149            }
150            _ => Err("Unsupported format. Use: ntriples, xml, or json".to_string()),
151        }
152    }
153
154    /// Handle DESCRIBE query
155    pub fn handle_describe(&self, query: &str, format: &str) -> Result<String, String> {
156        let (sparql_query, ctx) = sparql_parser::parse_sparql(query)?;
157
158        let describe = match &sparql_query {
159            SparqlQuery::Describe(d) => *d,
160            _ => return Err("Query is not a DESCRIBE".to_string()),
161        };
162
163        let plan = QueryPlanner::plan(&sparql_query, &ctx)?;
164        let executor = QueryExecutor::new(&self.quins);
165        // Rows are the Concise Bounded Description triples (slots 0/1/2 = s/p/o).
166        let results = executor.execute_describe(&plan, &ctx, &describe)?;
167
168        match format.to_lowercase().as_str() {
169            "ntriples" => {
170                let mut output = Vec::new();
171                ResultFormatter::format_ntriples(&mut output, &results)
172                    .map_err(|e| e.to_string())?;
173                Ok(String::from_utf8(output).unwrap())
174            }
175            "xml" => {
176                let mut output = Vec::new();
177                let vars = match &sparql_query {
178                    SparqlQuery::Describe(describe) => {
179                        // Use first variable
180                        if describe.var_count > 0 {
181                            vec![describe.vars_or_ids[0] as VariableId]
182                        } else {
183                            vec![0]
184                        }
185                    }
186                    _ => vec![],
187                };
188                ResultFormatter::format_xml(&mut output, &vars, &results, &ctx, None)
189                    .map_err(|e| e.to_string())?;
190                Ok(String::from_utf8(output).unwrap())
191            }
192            "json" => {
193                let mut output = Vec::new();
194                let vars = match &sparql_query {
195                    SparqlQuery::Describe(describe) => {
196                        if describe.var_count > 0 {
197                            vec![describe.vars_or_ids[0] as VariableId]
198                        } else {
199                            vec![0]
200                        }
201                    }
202                    _ => vec![],
203                };
204                ResultFormatter::format_json(&mut output, &vars, &results, &ctx, None)
205                    .map_err(|e| e.to_string())?;
206                Ok(String::from_utf8(output).unwrap())
207            }
208            _ => Err("Unsupported format. Use: ntriples, xml, or json".to_string()),
209        }
210    }
211}
212
213/// SPARQL protocol handler
214pub struct SparqlProtocolHandler<'a> {
215    endpoint: SparqlEndpoint<'a>,
216}
217
218impl<'a> SparqlProtocolHandler<'a> {
219    /// Creates a default `SparqlProtocolHandler`.
220    pub fn new(quins: &'a [NQuin]) -> Self {
221        Self {
222            endpoint: SparqlEndpoint::new(quins),
223        }
224    }
225
226    /// Parse Content-Type header to determine format
227    pub fn parse_accept_header(accept: &str) -> String {
228        if accept.contains("application/sparql-results+xml") {
229            "xml".to_string()
230        } else if accept.contains("application/sparql-results+json") {
231            "json".to_string()
232        } else if accept.contains("text/tab-separated-values") {
233            "tsv".to_string()
234        } else if accept.contains("text/csv") {
235            "csv".to_string()
236        } else if accept.contains("application/n-triples") {
237            "ntriples".to_string()
238        } else if accept.contains("application/n-quads") {
239            "ntriples".to_string()
240        } else {
241            "json".to_string() // Default
242        }
243    }
244
245    /// Handle SPARQL protocol request
246    pub fn handle_request(
247        &self,
248        query: Option<&str>,
249        accept: Option<&str>,
250    ) -> Result<String, String> {
251        let query = query.ok_or("No query provided")?;
252        let format = accept
253            .map(|a| Self::parse_accept_header(a))
254            .unwrap_or_else(|| "json".to_string());
255
256        // Check query type and dispatch
257        let query_upper = query.trim().to_uppercase();
258
259        if query_upper.starts_with("ASK") {
260            self.endpoint.handle_ask(query, &format)
261        } else if query_upper.starts_with("CONSTRUCT") {
262            self.endpoint.handle_construct(query, &format)
263        } else if query_upper.starts_with("DESCRIBE") {
264            self.endpoint.handle_describe(query, &format)
265        } else {
266            // Default to SELECT
267            self.endpoint.handle_query(query, &format)
268        }
269    }
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275
276    #[test]
277    fn test_parse_accept_header() {
278        assert_eq!(
279            SparqlProtocolHandler::parse_accept_header("application/sparql-results+xml"),
280            "xml"
281        );
282        assert_eq!(
283            SparqlProtocolHandler::parse_accept_header("application/sparql-results+json"),
284            "json"
285        );
286        assert_eq!(
287            SparqlProtocolHandler::parse_accept_header("text/tab-separated-values"),
288            "tsv"
289        );
290        assert_eq!(
291            SparqlProtocolHandler::parse_accept_header("text/csv"),
292            "csv"
293        );
294        assert_eq!(
295            SparqlProtocolHandler::parse_accept_header("application/n-triples"),
296            "ntriples"
297        );
298        assert_eq!(
299            SparqlProtocolHandler::parse_accept_header("application/n-quads"),
300            "ntriples"
301        );
302    }
303}