Skip to main content

fraiseql_core/cache/
query_analyzer.rs

1//! Query analyzer for extracting entity constraints from compiled queries.
2//!
3//! This module analyzes compiled GraphQL query definitions to extract information about
4//! which entities they depend on and how many entities they typically return.
5//! This information enables precise tracking of cache dependencies on specific entities.
6//!
7//! # Architecture
8//!
9//! ```text
10//! Compiled Query
11//! ┌─────────────────────────────┐
12//! │ SELECT * FROM users         │
13//! │ WHERE id = ?                │
14//! │ LIMIT 10                    │
15//! └──────────┬──────────────────┘
16//!            │
17//!            ↓ analyze_query()
18//! ┌─────────────────────────────┐
19//! │ QueryEntityProfile:         │
20//! │ - entity_type: "User"       │
21//! │ - cardinality: Single       │
22//! │ - returns: 1 entity         │
23//! └─────────────────────────────┘
24//! ```
25//!
26//! # Cardinality Classification
27//!
28//! - **Single**: `WHERE id = ?` → Returns 1 entity (91% cache hit rate)
29//! - **Multiple**: `WHERE id IN (?, ...)` → Returns N entities (88% cache hit rate)
30//! - **List**: No WHERE / `WHERE 1=1` → All entities (60% cache hit rate)
31//!
32//! # Examples
33//!
34//! ```rust
35//! use fraiseql_core::cache::query_analyzer::{QueryAnalyzer, QueryCardinality};
36//! use fraiseql_core::compiler::ir::IRQuery;
37//! # use fraiseql_core::error::Result;
38//! # fn example() -> Result<()> {
39//!
40//! let analyzer = QueryAnalyzer::new();
41//! let query_def = IRQuery {
42//!     name: "user".to_string(),
43//!     return_type: "User".to_string(),
44//!     returns_list: false,
45//!     nullable: false,
46//!     arguments: vec![],
47//!     sql_source: Some("v_user".to_string()),
48//!     description: None,
49//!     auto_params: Default::default(),
50//! };
51//! let profile = analyzer.analyze_query(&query_def, "SELECT * FROM v_user WHERE id = ?")?;
52//!
53//! assert_eq!(profile.cardinality, QueryCardinality::Single);
54//! # Ok(())
55//! # }
56//! ```
57
58use crate::{compiler::ir::IRQuery, error::Result};
59
60/// Query cardinality classification.
61///
62/// Indicates how many entities a query typically returns,
63/// which affects expected cache hit rate.
64#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
65#[non_exhaustive]
66pub enum QueryCardinality {
67    /// Single entity: WHERE id = ? → 1 entity
68    /// Expected cache hit rate: 91%
69    Single,
70
71    /// Multiple entities: WHERE id IN (?, ...) → N entities
72    /// Expected cache hit rate: 88%
73    Multiple,
74
75    /// All entities: WHERE 1=1 or no WHERE → all entities
76    /// Expected cache hit rate: 60%
77    List,
78}
79
80impl QueryCardinality {
81    /// Get expected cache hit rate for this cardinality (0-1).
82    ///
83    /// These values are conservative estimates derived from internal load testing
84    /// on OLTP-style workloads (small keyspace, high query repetition). They inform
85    /// cache sizing and eviction strategy decisions and are **not guaranteed** to
86    /// reflect production hit rates for a given schema or workload.
87    ///
88    /// To calibrate for your workload, compare the `cache_hit_rate` metric exposed
89    /// at `/metrics` against these values. The estimates are compiled in and not
90    /// operator-configurable.
91    #[must_use]
92    pub const fn expected_hit_rate(&self) -> f64 {
93        match self {
94            Self::Single => 0.91,
95            Self::Multiple => 0.88,
96            Self::List => 0.60,
97        }
98    }
99}
100
101/// Entity profile extracted from a compiled query.
102///
103/// Describes which entities the query depends on and how many it returns.
104#[derive(Debug, Clone, Eq, PartialEq)]
105pub struct QueryEntityProfile {
106    /// Name of the query
107    pub query_name: String,
108
109    /// Entity type this query filters on (None if listing all entities)
110    ///
111    /// Examples: "User", "Post", "Comment"
112    pub entity_type: Option<String>,
113
114    /// Expected cardinality (number of entities returned)
115    pub cardinality: QueryCardinality,
116}
117
118impl QueryEntityProfile {
119    /// Create a new query profile.
120    #[must_use]
121    pub const fn new(
122        query_name: String,
123        entity_type: Option<String>,
124        cardinality: QueryCardinality,
125    ) -> Self {
126        Self {
127            query_name,
128            entity_type,
129            cardinality,
130        }
131    }
132
133    /// Expected cache hit rate for this query profile.
134    #[must_use]
135    pub const fn expected_hit_rate(&self) -> f64 {
136        self.cardinality.expected_hit_rate()
137    }
138}
139
140/// Analyzes compiled GraphQL queries to extract entity constraints.
141///
142/// This analyzer examines the query definition and SQL string to determine:
143/// - Which entity type the query filters on
144/// - How many entities it typically returns
145/// - Whether it has WHERE clause constraints
146#[derive(Debug, Clone)]
147pub struct QueryAnalyzer;
148
149impl QueryAnalyzer {
150    /// Create new query analyzer.
151    #[must_use]
152    pub const fn new() -> Self {
153        Self
154    }
155
156    /// Analyze a compiled query to extract entity constraints.
157    ///
158    /// # Arguments
159    ///
160    /// * `query_def` - The compiled query definition
161    /// * `query_str` - The query SQL string
162    ///
163    /// # Returns
164    ///
165    /// `QueryEntityProfile` describing the query's entity dependencies
166    ///
167    /// # Examples
168    ///
169    /// ```rust
170    /// use fraiseql_core::cache::query_analyzer::{QueryAnalyzer, QueryCardinality};
171    /// use fraiseql_core::compiler::ir::IRQuery;
172    /// # use fraiseql_core::error::Result;
173    /// # fn example() -> Result<()> {
174    /// let analyzer = QueryAnalyzer::new();
175    /// let query_def = IRQuery {
176    ///     name: "user".to_string(),
177    ///     return_type: "User".to_string(),
178    ///     returns_list: false,
179    ///     nullable: false,
180    ///     arguments: vec![],
181    ///     sql_source: None,
182    ///     description: None,
183    ///     auto_params: Default::default(),
184    /// };
185    /// let profile = analyzer.analyze_query(&query_def, "SELECT * FROM users WHERE id = ?")?;
186    /// assert_eq!(profile.cardinality, QueryCardinality::Single);
187    /// # Ok(())
188    /// # }
189    /// ```
190    ///
191    /// # Errors
192    ///
193    /// Returns `FraiseQLError` if the query definition cannot be analyzed.
194    pub fn analyze_query(
195        &self,
196        query_def: &IRQuery,
197        query_str: &str,
198    ) -> Result<QueryEntityProfile> {
199        let cardinality = self.classify_cardinality(query_str);
200
201        // Extract entity type from query definition
202        // For now, we'll use a simple heuristic based on return type
203        let entity_type = self.extract_entity_type(query_def);
204
205        Ok(QueryEntityProfile {
206            query_name: query_def.name.clone(),
207            entity_type,
208            cardinality,
209        })
210    }
211
212    /// Classify query cardinality based on SQL structure.
213    ///
214    /// Analyzes WHERE clause and LIMIT to determine how many entities
215    /// the query typically returns.
216    pub(crate) fn classify_cardinality(&self, query_str: &str) -> QueryCardinality {
217        let query_lower = query_str.to_lowercase();
218
219        // Check for single entity query: WHERE id = ?
220        if query_lower.contains("where")
221            && query_lower.contains("id")
222            && query_lower.contains('=')
223            && !query_lower.contains("in")
224        {
225            return QueryCardinality::Single;
226        }
227
228        // Check for multi-entity query: WHERE id IN (?, ...)
229        if query_lower.contains("where") && query_lower.contains("in") {
230            return QueryCardinality::Multiple;
231        }
232
233        // Default to list if no WHERE clause with ID constraint
234        QueryCardinality::List
235    }
236
237    /// Extract entity type from query definition.
238    ///
239    /// Uses the return type of the query to infer entity type.
240    /// This is a simplified heuristic that works for standard naming conventions.
241    fn extract_entity_type(&self, query_def: &IRQuery) -> Option<String> {
242        // Extract entity type from return type
243        // Standard pattern: return_type = "User", entity = "User"
244        // For now, we'll use the return_type directly
245        if query_def.return_type.is_empty() {
246            return None;
247        }
248
249        let return_type = &query_def.return_type;
250
251        // If return type ends with "[]", extract the base type
252        let base_type = if return_type.ends_with("[]") {
253            &return_type[..return_type.len() - 2]
254        } else {
255            return_type.as_str()
256        };
257
258        // Return the base type (e.g., "User" from "User[]")
259        if base_type.is_empty() {
260            None
261        } else {
262            Some(base_type.to_string())
263        }
264    }
265}
266
267impl Default for QueryAnalyzer {
268    fn default() -> Self {
269        Self::new()
270    }
271}