Skip to main content

tulna_rs/isomorphism/
api.rs

1use crate::isomorphism::core::{IsomorphismQuery, QueryIsomorphism, QueryLanguage, Triple};
2use std::error::Error;
3
4/// High-level API for query isomorphism checking
5///
6/// This module provides a simple interface for checking if two queries are isomorphic,
7/// similar to the TypeScript implementation.
8pub struct QueryIsomorphismAPI;
9
10impl QueryIsomorphismAPI {
11    /// Check if two queries are isomorphic to each other.
12    ///
13    /// This function:
14    /// 1. Auto-detects the query language (SPARQL, RSPQL, or JanusQL)
15    /// 2. Parses both queries
16    /// 3. For streaming queries (RSPQL/JanusQL), checks if stream parameters match
17    /// 4. Checks if the Basic Graph Patterns (BGP) are isomorphic
18    ///
19    /// # Arguments
20    /// * `query_one` - The first query string
21    /// * `query_two` - The second query string
22    ///
23    /// # Returns
24    /// * `Ok(true)` - If the queries are isomorphic
25    /// * `Ok(false)` - If the queries are not isomorphic
26    /// * `Err` - If there was an error parsing the queries
27    ///
28    /// # Example
29    /// ```
30    /// use tulna_rs::isomorphism::api::QueryIsomorphismAPI;
31    ///
32    /// let query1 = "SELECT ?s ?p ?o WHERE { ?s ?p ?o }";
33    /// let query2 = "SELECT ?x ?y ?z WHERE { ?x ?y ?z }";
34    ///
35    /// let is_iso = QueryIsomorphismAPI::is_isomorphic(query1, query2).unwrap();
36    /// assert!(is_iso);
37    /// ```
38    pub fn is_isomorphic(query_one: &str, query_two: &str) -> Result<bool, Box<dyn Error>> {
39        QueryIsomorphism::is_isomorphic(query_one, query_two)
40    }
41
42    /// Parse a query and return its structured representation
43    ///
44    /// # Arguments
45    /// * `query` - The query string to parse
46    ///
47    /// # Returns
48    /// * `Ok(IsomorphismQuery)` - The parsed query structure
49    /// * `Err` - If there was an error parsing the query
50    pub fn parse_query(query: &str) -> Result<IsomorphismQuery, Box<dyn Error>> {
51        QueryIsomorphism::parse_query(query)
52    }
53
54    /// Detect the query language type
55    ///
56    /// # Arguments
57    /// * `query` - The query string to analyze
58    ///
59    /// # Returns
60    /// * `QueryLanguage` - The detected language (SPARQL, RSPQL, or JanusQL)
61    pub fn detect_query_language(query: &str) -> QueryLanguage {
62        QueryIsomorphism::detect_query_type(query)
63    }
64
65    /// Extract the Basic Graph Pattern from a query
66    ///
67    /// # Arguments
68    /// * `query` - The query string to extract BGP from
69    ///
70    /// # Returns
71    /// * `Ok(Vec<Triple>)` - The extracted BGP as a vector of triples
72    /// * `Err` - If there was an error parsing the query
73    pub fn extract_bgp(query: &str) -> Result<Vec<Triple>, Box<dyn Error>> {
74        QueryIsomorphism::generate_bgp_quads_from_query(query)
75    }
76
77    /// Check if two RSPQL queries have matching stream parameters
78    ///
79    /// # Arguments
80    /// * `query_one` - The first RSPQL query
81    /// * `query_two` - The second RSPQL query
82    ///
83    /// # Returns
84    /// * `Ok(true)` - If stream parameters match
85    /// * `Ok(false)` - If stream parameters don't match
86    /// * `Err` - If there was an error parsing the queries
87    pub fn check_stream_parameters(
88        query_one: &str,
89        query_two: &str,
90    ) -> Result<bool, Box<dyn Error>> {
91        let q1 = QueryIsomorphism::parse_query(query_one)?;
92        let q2 = QueryIsomorphism::parse_query(query_two)?;
93
94        Ok(q1.stream_name == q2.stream_name
95            && q1.width == q2.width
96            && q1.slide == q2.slide
97            && q1.offset == q2.offset
98            && q1.start == q2.start
99            && q1.end == q2.end)
100    }
101
102    /// Check if two queries have matching window names
103    ///
104    /// # Arguments
105    /// * `query_one` - The first query
106    /// * `query_two` - The second query
107    ///
108    /// # Returns
109    /// * `Ok(true)` - If window names match
110    /// * `Ok(false)` - If window names don't match
111    /// * `Err` - If there was an error parsing the queries
112    pub fn check_window_names(query_one: &str, query_two: &str) -> Result<bool, Box<dyn Error>> {
113        let q1 = QueryIsomorphism::parse_query(query_one)?;
114        let q2 = QueryIsomorphism::parse_query(query_two)?;
115
116        Ok(q1.window_name == q2.window_name)
117    }
118
119    /// Compare two queries and provide detailed information about their similarity
120    ///
121    /// # Arguments
122    /// * `query_one` - The first query
123    /// * `query_two` - The second query
124    ///
125    /// # Returns
126    /// * `Ok(QueryComparisonResult)` - Detailed comparison information
127    /// * `Err` - If there was an error parsing the queries
128    pub fn compare_queries(
129        query_one: &str,
130        query_two: &str,
131    ) -> Result<QueryComparisonResult, Box<dyn Error>> {
132        let q1 = QueryIsomorphism::parse_query(query_one)?;
133        let q2 = QueryIsomorphism::parse_query(query_two)?;
134
135        let same_language = q1.query_language == q2.query_language;
136        let same_stream_params = q1.stream_name == q2.stream_name
137            && q1.width == q2.width
138            && q1.slide == q2.slide
139            && q1.offset == q2.offset
140            && q1.start == q2.start
141            && q1.end == q2.end;
142        let same_window_name = q1.window_name == q2.window_name;
143        let same_bgp_size = q1.bgp.len() == q2.bgp.len();
144
145        // Check BGP isomorphism
146        let bgp_isomorphic = if same_bgp_size {
147            crate::isomorphism::graph_isomorphism::GraphIsomorphism::check_bgp_isomorphism(
148                &q1.bgp, &q2.bgp,
149            )
150            .unwrap_or(false)
151        } else {
152            false
153        };
154
155        let is_isomorphic = if q1.query_language != QueryLanguage::SPARQL
156            || q2.query_language != QueryLanguage::SPARQL
157        {
158            same_language && same_stream_params && same_window_name && bgp_isomorphic
159        } else {
160            same_language && bgp_isomorphic
161        };
162
163        Ok(QueryComparisonResult {
164            is_isomorphic,
165            same_language,
166            same_stream_params,
167            same_window_name,
168            same_bgp_size,
169            bgp_isomorphic,
170            query1_language: q1.query_language,
171            query2_language: q2.query_language,
172            query1_bgp_size: q1.bgp.len(),
173            query2_bgp_size: q2.bgp.len(),
174        })
175    }
176}
177
178/// Detailed comparison result between two queries
179#[derive(Debug, Clone)]
180pub struct QueryComparisonResult {
181    /// Whether the queries are isomorphic
182    pub is_isomorphic: bool,
183    /// Whether both queries use the same language
184    pub same_language: bool,
185    /// Whether stream parameters match (for RSPQL/JanusQL)
186    pub same_stream_params: bool,
187    /// Whether window names match
188    pub same_window_name: bool,
189    /// Whether BGP sizes match
190    pub same_bgp_size: bool,
191    /// Whether BGPs are isomorphic
192    pub bgp_isomorphic: bool,
193    /// Language of first query
194    pub query1_language: QueryLanguage,
195    /// Language of second query
196    pub query2_language: QueryLanguage,
197    /// BGP size of first query
198    pub query1_bgp_size: usize,
199    /// BGP size of second query
200    pub query2_bgp_size: usize,
201}
202
203impl QueryComparisonResult {
204    /// Get a human-readable summary of the comparison
205    pub fn summary(&self) -> String {
206        let mut lines = vec![
207            format!("Isomorphic: {}", self.is_isomorphic),
208            format!(
209                "Same Language: {} ({:?} vs {:?})",
210                self.same_language, self.query1_language, self.query2_language
211            ),
212            format!(
213                "Same BGP Size: {} ({} vs {})",
214                self.same_bgp_size, self.query1_bgp_size, self.query2_bgp_size
215            ),
216            format!("BGP Isomorphic: {}", self.bgp_isomorphic),
217        ];
218
219        if self.query1_language != QueryLanguage::SPARQL
220            || self.query2_language != QueryLanguage::SPARQL
221        {
222            lines.push(format!("Same Stream Params: {}", self.same_stream_params));
223            lines.push(format!("Same Window Name: {}", self.same_window_name));
224        }
225
226        lines.join("\n")
227    }
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    #[test]
235    fn test_sparql_isomorphism() {
236        let query1 = "SELECT ?s ?p ?o WHERE { ?s ?p ?o . }";
237        let query2 = "SELECT ?x ?y ?z WHERE { ?x ?y ?z . }";
238
239        let result = QueryIsomorphismAPI::is_isomorphic(query1, query2);
240        if let Err(e) = &result {
241            println!("Error checking isomorphism: {}", e);
242        }
243        assert!(result.is_ok());
244    }
245
246    #[test]
247    fn test_detect_language() {
248        let sparql = "SELECT ?s ?p ?o WHERE { ?s ?p ?o }";
249        assert_eq!(
250            QueryIsomorphismAPI::detect_query_language(sparql),
251            QueryLanguage::SPARQL
252        );
253    }
254
255    #[test]
256    fn test_extract_bgp() {
257        let query = "SELECT ?s ?p ?o WHERE { ?s ?p ?o . }";
258        let bgp = QueryIsomorphismAPI::extract_bgp(query);
259        if let Err(e) = &bgp {
260            println!("Error extracting BGP: {}", e);
261        }
262        assert!(bgp.is_ok());
263    }
264
265    #[test]
266    fn test_compare_queries() {
267        let query1 = "SELECT ?s ?p ?o WHERE { ?s ?p ?o . }";
268        let query2 = "SELECT ?x ?y ?z WHERE { ?x ?y ?z . }";
269
270        let result = QueryIsomorphismAPI::compare_queries(query1, query2);
271        if let Err(e) = &result {
272            println!("Error comparing queries: {}", e);
273        }
274        assert!(result.is_ok());
275
276        let comparison = result.unwrap();
277        assert!(comparison.same_language);
278        assert!(comparison.same_bgp_size);
279    }
280}