Skip to main content

camel_component_sql/
endpoint.rs

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