Skip to main content

camel_component_sql/
endpoint.rs

1use std::sync::Arc;
2use tokio::sync::OnceCell;
3
4use camel_component_api::{BodyType, BoxProcessor, CamelError, RuntimeObservability};
5use camel_component_api::{Consumer, Endpoint, ProducerContext};
6use sqlx::AnyPool;
7
8use crate::config::SqlEndpointConfig;
9use crate::consumer::SqlConsumer;
10use crate::producer::SqlProducer;
11
12pub(crate) struct SqlEndpoint {
13    uri: String,
14    pub(crate) config: SqlEndpointConfig,
15    pub(crate) pool: Arc<OnceCell<AnyPool>>,
16}
17
18impl SqlEndpoint {
19    #[cfg(test)]
20    pub fn new(uri: String, config: SqlEndpointConfig) -> Self {
21        Self::new_with_pool(uri, config, Arc::new(OnceCell::new()))
22    }
23
24    pub fn new_with_pool(
25        uri: String,
26        config: SqlEndpointConfig,
27        pool: Arc<OnceCell<AnyPool>>,
28    ) -> Self {
29        Self { uri, config, pool }
30    }
31}
32
33impl Endpoint for SqlEndpoint {
34    fn uri(&self) -> &str {
35        &self.uri
36    }
37
38    fn create_producer(
39        &self,
40        rt: Arc<dyn RuntimeObservability>,
41        ctx: &ProducerContext,
42    ) -> Result<BoxProcessor, CamelError> {
43        let route_id = ctx.route_id().unwrap_or("unknown").to_string();
44        Ok(BoxProcessor::new(SqlProducer::new(
45            self.config.clone(),
46            Arc::clone(&self.pool),
47            rt,
48            route_id,
49        )))
50    }
51
52    fn create_consumer(
53        &self,
54        rt: Arc<dyn RuntimeObservability>,
55    ) -> Result<Box<dyn Consumer>, CamelError> {
56        Ok(Box::new(SqlConsumer::new(
57            self.config.clone(),
58            Arc::clone(&self.pool),
59            rt,
60        )))
61    }
62
63    fn body_contract(&self) -> Option<BodyType> {
64        if !self.config.use_message_body_for_sql {
65            return None;
66        }
67        if self.config.batch {
68            Some(BodyType::Json)
69        } else {
70            Some(BodyType::Text)
71        }
72    }
73}
74
75#[cfg(test)]
76mod tests {
77    use camel_component_api::test_support::PanicRuntimeObservability;
78    fn test_rt() -> std::sync::Arc<dyn camel_component_api::RuntimeObservability> {
79        std::sync::Arc::new(PanicRuntimeObservability)
80    }
81    use super::*;
82    use crate::config::SqlEndpointConfig;
83    use camel_component_api::Endpoint;
84    use camel_component_api::UriConfig;
85
86    fn make_endpoint(use_body: bool, batch: bool) -> SqlEndpoint {
87        let mut config =
88            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test")
89                .expect("valid SQL endpoint config");
90        config.use_message_body_for_sql = use_body;
91        config.batch = batch;
92
93        SqlEndpoint::new("sql:select 1".to_string(), config)
94    }
95
96    #[test]
97    fn body_contract_returns_some_text_when_body_mode_enabled_no_batch() {
98        let endpoint = make_endpoint(true, false);
99        assert_eq!(endpoint.body_contract(), Some(BodyType::Text));
100    }
101
102    #[test]
103    fn body_contract_returns_some_json_when_batch_mode_enabled() {
104        let endpoint = make_endpoint(true, true);
105        assert_eq!(endpoint.body_contract(), Some(BodyType::Json));
106    }
107
108    #[test]
109    fn body_contract_returns_none_when_body_mode_disabled() {
110        let endpoint = make_endpoint(false, false);
111        assert_eq!(endpoint.body_contract(), None);
112    }
113
114    #[test]
115    fn body_contract_returns_none_when_batch_without_body_mode() {
116        let endpoint = make_endpoint(false, true);
117        assert_eq!(endpoint.body_contract(), None);
118    }
119
120    #[test]
121    fn new_stores_uri_and_config() {
122        let config = SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test")
123            .expect("valid config");
124        let endpoint = SqlEndpoint::new("sql:select 1".to_string(), config.clone());
125        assert_eq!(endpoint.uri(), "sql:select 1");
126        assert_eq!(endpoint.config.db_url, "postgres://localhost/test");
127    }
128
129    #[test]
130    fn uri_returns_stored_uri() {
131        let endpoint = make_endpoint(false, false);
132        assert_eq!(endpoint.uri(), "sql:select 1");
133    }
134
135    #[test]
136    fn create_producer_returns_ok() {
137        let endpoint = make_endpoint(false, false);
138        let ctx = ProducerContext::new();
139        let result = endpoint.create_producer(test_rt(), &ctx);
140        assert!(result.is_ok());
141    }
142
143    #[test]
144    fn create_consumer_returns_ok() {
145        let endpoint = make_endpoint(false, false);
146        let result = endpoint.create_consumer(test_rt());
147        assert!(result.is_ok());
148    }
149
150    #[test]
151    fn pool_is_shared_via_arc() {
152        let config = SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test")
153            .expect("valid config");
154        let endpoint = SqlEndpoint::new("sql:select 1".to_string(), config);
155        let pool_ref1 = Arc::clone(&endpoint.pool);
156        let pool_ref2 = Arc::clone(&endpoint.pool);
157        assert!(Arc::ptr_eq(&pool_ref1, &pool_ref2));
158    }
159}