camel_component_sql/
lib.rs1pub(crate) mod bind_kinds;
2pub mod bundle;
3pub mod config;
4pub mod consumer;
5pub mod endpoint;
6pub mod headers;
7pub mod health;
8pub mod pool_factory;
9pub mod producer;
10pub mod query;
11pub(crate) mod utils;
12
13use std::sync::Arc;
14
15use camel_api::component_metadata::ComponentMetadata;
16use camel_api::datasource::DatasourceCatalog;
17use camel_component_api::CamelError;
18use camel_component_api::UriConfig;
19use camel_component_api::{Component, Endpoint};
20use sqlx::AnyPool;
21use tokio::sync::OnceCell;
22
23pub use bundle::SqlBundle;
24pub use config::{
25 PollStrategy, ProcessingStrategy, SqlEndpointConfig, SqlGlobalConfig, SqlOutputType,
26 TransactionMode,
27};
28pub use health::SqlHealthCheck;
29
30type SharedPool = Arc<OnceCell<Arc<AnyPool>>>;
31
32pub struct SqlComponent {
33 config: Option<SqlGlobalConfig>,
34 catalog: Option<Arc<dyn DatasourceCatalog>>,
35}
36
37impl SqlComponent {
38 pub fn new() -> Self {
39 Self {
40 config: None,
41 catalog: None,
42 }
43 }
44
45 pub fn with_config(config: SqlGlobalConfig) -> Self {
46 Self {
47 config: Some(config),
48 catalog: None,
49 }
50 }
51
52 pub fn with_optional_config(config: Option<SqlGlobalConfig>) -> Self {
53 Self {
54 config,
55 catalog: None,
56 }
57 }
58
59 pub fn with_config_and_catalog(
60 config: SqlGlobalConfig,
61 catalog: Arc<dyn DatasourceCatalog>,
62 ) -> Self {
63 Self {
64 config: Some(config),
65 catalog: Some(catalog),
66 }
67 }
68
69 pub fn catalog(&self) -> Option<&Arc<dyn DatasourceCatalog>> {
70 self.catalog.as_ref()
71 }
72}
73
74impl Default for SqlComponent {
75 fn default() -> Self {
76 Self::new()
77 }
78}
79
80impl Component for SqlComponent {
81 fn scheme(&self) -> &str {
82 "sql"
83 }
84
85 fn metadata(&self) -> ComponentMetadata {
86 SqlEndpointConfig::metadata()
87 }
88
89 fn create_endpoint(
90 &self,
91 uri: &str,
92 ctx: &dyn camel_component_api::ComponentContext,
93 ) -> Result<Box<dyn Endpoint>, CamelError> {
94 let mut config = SqlEndpointConfig::from_uri(uri)?;
95
96 if config.datasource_name.is_some() && self.catalog.is_none() {
97 return Err(CamelError::Config(
98 "datasource parameter requires catalog — no datasource catalog configured".into(),
99 ));
100 }
101
102 if let Some(ref ds_name) = config.datasource_name
103 && let Some(ref catalog) = self.catalog
104 {
105 let ds_config = catalog.get_config(ds_name).ok_or_else(|| {
106 CamelError::Config(format!("datasource '{}' not found in catalog", ds_name))
107 })?;
108 config.db_url = ds_config.db_url;
109 }
110
111 if let Some(ref global_config) = self.config {
112 config.apply_defaults(global_config);
113 }
114 config.resolve_defaults();
115 let pool: SharedPool = Arc::new(OnceCell::new());
116 let health_check = SqlHealthCheck::new(
117 Arc::clone(&pool),
118 self.catalog.clone(),
119 config.datasource_name.clone(),
120 );
121 ctx.register_current_route_health_check(Arc::new(health_check));
122
123 if config.datasource_name.is_some()
124 && let Some(ref catalog) = self.catalog
125 {
126 Ok(Box::new(endpoint::SqlEndpoint::new_with_pool_and_catalog(
127 uri.to_string(),
128 config,
129 pool,
130 Arc::clone(catalog),
131 )))
132 } else {
133 Ok(Box::new(endpoint::SqlEndpoint::new_with_pool(
134 uri.to_string(),
135 config,
136 pool,
137 )))
138 }
139 }
140}
141
142#[cfg(test)]
143mod tests {
144 use super::*;
145 use camel_component_api::Component;
146 use camel_component_api::NoOpComponentContext;
147
148 #[test]
149 fn test_component_scheme() {
150 let c = SqlComponent::new();
151 assert_eq!(c.scheme(), "sql");
152 }
153
154 #[test]
155 fn test_component_metadata_nonempty() {
156 let c = SqlComponent::new();
157 let meta = c.metadata();
158 assert_eq!(meta.scheme, "sql");
159 assert!(!meta.description.is_empty());
160 assert!(
161 !meta.uri_options.is_empty(),
162 "uri_options must be non-empty"
163 );
164 let names: Vec<&str> = meta.uri_options.iter().map(|o| o.name.as_str()).collect();
165 assert!(
166 names.contains(&"db_url"),
167 "expected db_url in uri_options, got: {names:?}"
168 );
169 assert!(
170 names.contains(&"outputType"),
171 "expected outputType in uri_options, got: {names:?}"
172 );
173 let db_url_opt = meta
175 .uri_options
176 .iter()
177 .find(|o| o.name == "db_url")
178 .unwrap();
179 assert!(db_url_opt.secret, "db_url must be marked secret");
180 }
181
182 #[test]
183 fn test_config_uri_options_nonempty() {
184 let opts = SqlEndpointConfig::uri_options();
185 assert!(!opts.is_empty(), "uri_options() must be non-empty");
186 let names: Vec<&str> = opts.iter().map(|o| o.name.as_str()).collect();
187 assert!(names.contains(&"db_url"));
188 assert!(names.contains(&"delay"));
189 assert!(names.contains(&"batch"));
190 }
191
192 #[test]
193 fn test_config_metadata_capabilities() {
194 let meta = SqlEndpointConfig::metadata();
195 assert!(meta.capabilities.supports_producer);
196 assert!(meta.capabilities.supports_consumer);
197 assert!(!meta.capabilities.supports_polling_consumer);
198 assert!(!meta.capabilities.supports_streaming);
199 }
200
201 #[test]
202 fn test_component_creates_endpoint() {
203 let c = SqlComponent::new();
204 let ctx = NoOpComponentContext;
205 let ep = c.create_endpoint("sql:select 1?db_url=postgres://localhost/test", &ctx);
206 assert!(ep.is_ok());
207 }
208
209 #[test]
210 fn test_component_rejects_wrong_scheme() {
211 let c = SqlComponent::new();
212 let ctx = NoOpComponentContext;
213 let ep = c.create_endpoint("redis://localhost", &ctx);
214 assert!(ep.is_err());
215 }
216
217 #[test]
218 fn test_endpoint_uri() {
219 let c = SqlComponent::new();
220 let ctx = NoOpComponentContext;
221 let ep = c
222 .create_endpoint("sql:select 1?db_url=postgres://localhost/test", &ctx)
223 .unwrap();
224 assert_eq!(ep.uri(), "sql:select 1?db_url=postgres://localhost/test");
225 }
226
227 #[test]
228 fn test_component_with_global_config() {
229 let global = SqlGlobalConfig::default().with_max_connections(20);
230 let c = SqlComponent::with_config(global);
231 let ctx = NoOpComponentContext;
232 assert_eq!(c.scheme(), "sql");
234 let ep = c.create_endpoint("sql:select 1?db_url=postgres://localhost/test", &ctx);
235 assert!(ep.is_ok());
236 }
237
238 #[test]
239 fn test_global_config_applied_to_endpoint() {
240 let global = SqlGlobalConfig::default()
243 .with_max_connections(20)
244 .with_min_connections(3)
245 .with_idle_timeout_secs(600)
246 .with_max_lifetime_secs(3600);
247 let mut cfg =
248 config::SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test")
249 .unwrap();
250 cfg.apply_defaults(&global);
251 cfg.resolve_defaults();
252 assert_eq!(cfg.max_connections, Some(20));
253 assert_eq!(cfg.min_connections, Some(3));
254 assert_eq!(cfg.idle_timeout_secs, Some(600));
255 assert_eq!(cfg.max_lifetime_secs, Some(3600));
256 }
257
258 #[test]
259 fn test_uri_param_wins_over_global_config() {
260 let global = SqlGlobalConfig::default()
262 .with_max_connections(20)
263 .with_min_connections(3);
264 let mut cfg = config::SqlEndpointConfig::from_uri(
265 "sql:select 1?db_url=postgres://localhost/test&maxConnections=99&minConnections=7",
266 )
267 .unwrap();
268 cfg.apply_defaults(&global);
269 cfg.resolve_defaults();
270 assert_eq!(cfg.max_connections, Some(99)); assert_eq!(cfg.min_connections, Some(7)); }
273}