Skip to main content

fraiseql_core/runtime/
jsonb_strategy.rs

1//! JSONB field handling strategy selection
2//!
3//! Determines whether to project fields at database level or stream full JSONB
4
5use serde::Deserialize;
6
7/// Strategy for JSONB field handling
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
9#[non_exhaustive]
10pub enum JsonbStrategy {
11    /// Extract only requested fields using `jsonb_build_object/JSON_OBJECT`
12    #[default]
13    Project,
14    /// Stream full JSONB column, filter in application
15    Stream,
16}
17
18impl std::str::FromStr for JsonbStrategy {
19    type Err = String;
20
21    fn from_str(s: &str) -> Result<Self, Self::Err> {
22        match s.to_lowercase().as_str() {
23            "project" => Ok(JsonbStrategy::Project),
24            "stream" => Ok(JsonbStrategy::Stream),
25            other => {
26                Err(format!("Invalid JSONB strategy '{}', must be 'project' or 'stream'", other))
27            },
28        }
29    }
30}
31
32impl<'de> Deserialize<'de> for JsonbStrategy {
33    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
34    where
35        D: serde::Deserializer<'de>,
36    {
37        let s = String::deserialize(deserializer)?;
38        std::str::FromStr::from_str(&s).map_err(serde::de::Error::custom)
39    }
40}
41
42/// Configuration for JSONB optimization strategy
43#[derive(Debug, Clone)]
44pub struct JsonbOptimizationOptions {
45    /// Default strategy to use
46    pub default_strategy: JsonbStrategy,
47
48    /// Auto-switch threshold: if requesting >= this % of fields, use stream
49    pub auto_threshold_percent: u32,
50}
51
52impl Default for JsonbOptimizationOptions {
53    fn default() -> Self {
54        Self {
55            default_strategy:       JsonbStrategy::Project,
56            auto_threshold_percent: 80,
57        }
58    }
59}
60
61impl JsonbOptimizationOptions {
62    /// Choose strategy based on field count and configuration
63    #[must_use]
64    pub fn choose_strategy(&self, requested_fields: usize, total_fields: usize) -> JsonbStrategy {
65        if total_fields == 0 {
66            return self.default_strategy;
67        }
68
69        #[allow(clippy::cast_precision_loss)]
70        // Reason: field counts are small integers; f64 precision loss on usize is not material
71        let percent = (requested_fields as f64 / total_fields as f64) * 100.0;
72
73        if percent >= f64::from(self.auto_threshold_percent) {
74            JsonbStrategy::Stream
75        } else {
76            self.default_strategy
77        }
78    }
79}