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 manager;
9pub mod pool_factory;
10pub mod producer;
11pub mod query;
12pub mod session;
13pub(crate) mod utils;
14
15use std::sync::Arc;
16
17use camel_api::component_metadata::ComponentMetadata;
18use camel_api::datasource::DatasourceCatalog;
19use camel_component_api::CamelError;
20use camel_component_api::UriConfig;
21use camel_component_api::{Component, Endpoint};
22use sqlx::AnyPool;
23use tokio::sync::OnceCell;
24
25pub use bundle::SqlBundle;
26pub use config::{
27 PollStrategy, ProcessingStrategy, SqlEndpointConfig, SqlGlobalConfig, SqlOutputType,
28 TransactionMode,
29};
30pub use health::SqlHealthCheck;
31pub use manager::SqlTransactionManager;
32pub use session::SqlTxSession;
33
34type SharedPool = Arc<OnceCell<Arc<AnyPool>>>;
35
36pub struct SqlComponent {
37 config: Option<SqlGlobalConfig>,
38 catalog: Option<Arc<dyn DatasourceCatalog>>,
39}
40
41impl SqlComponent {
42 pub fn new() -> Self {
43 Self {
44 config: None,
45 catalog: None,
46 }
47 }
48
49 pub fn with_config(config: SqlGlobalConfig) -> Self {
50 Self {
51 config: Some(config),
52 catalog: None,
53 }
54 }
55
56 pub fn with_optional_config(config: Option<SqlGlobalConfig>) -> Self {
57 Self {
58 config,
59 catalog: None,
60 }
61 }
62
63 pub fn with_config_and_catalog(
64 config: SqlGlobalConfig,
65 catalog: Arc<dyn DatasourceCatalog>,
66 ) -> Self {
67 Self {
68 config: Some(config),
69 catalog: Some(catalog),
70 }
71 }
72
73 pub fn catalog(&self) -> Option<&Arc<dyn DatasourceCatalog>> {
74 self.catalog.as_ref()
75 }
76}
77
78impl Default for SqlComponent {
79 fn default() -> Self {
80 Self::new()
81 }
82}
83
84impl Component for SqlComponent {
85 fn scheme(&self) -> &str {
86 "sql"
87 }
88
89 fn metadata(&self) -> ComponentMetadata {
90 SqlEndpointConfig::metadata()
91 }
92
93 fn create_endpoint(
94 &self,
95 uri: &str,
96 ctx: &dyn camel_component_api::ComponentContext,
97 ) -> Result<Box<dyn Endpoint>, CamelError> {
98 let mut config = SqlEndpointConfig::from_uri(uri)?;
99 config.validate_transaction_mode(uri)?;
100
101 if config.datasource_name.is_some() && self.catalog.is_none() {
102 return Err(CamelError::Config(
103 "datasource parameter requires catalog — no datasource catalog configured".into(),
104 ));
105 }
106
107 if let Some(ref ds_name) = config.datasource_name
108 && let Some(ref catalog) = self.catalog
109 {
110 let ds_config = catalog.get_config(ds_name).ok_or_else(|| {
111 CamelError::Config(format!("datasource '{}' not found in catalog", ds_name))
112 })?;
113 config.db_url = ds_config.db_url;
114 }
115
116 if let Some(ref global_config) = self.config {
117 config.apply_defaults(global_config);
118 }
119 config.resolve_defaults();
120 let pool: SharedPool = Arc::new(OnceCell::new());
121 let health_check = SqlHealthCheck::new(
122 Arc::clone(&pool),
123 self.catalog.clone(),
124 config.datasource_name.clone(),
125 );
126 ctx.register_current_route_health_check(Arc::new(health_check));
127
128 if config.datasource_name.is_some()
129 && let Some(ref catalog) = self.catalog
130 {
131 Ok(Box::new(endpoint::SqlEndpoint::new_with_pool_and_catalog(
132 uri.to_string(),
133 config,
134 pool,
135 Arc::clone(catalog),
136 )))
137 } else {
138 Ok(Box::new(endpoint::SqlEndpoint::new_with_pool(
139 uri.to_string(),
140 config,
141 pool,
142 )))
143 }
144 }
145}
146
147#[cfg(test)]
148mod tests {
149 use super::*;
150 use camel_component_api::Component;
151 use camel_component_api::NoOpComponentContext;
152
153 #[test]
154 fn test_component_scheme() {
155 let c = SqlComponent::new();
156 assert_eq!(c.scheme(), "sql");
157 }
158
159 #[test]
160 fn test_component_metadata_nonempty() {
161 let c = SqlComponent::new();
162 let meta = c.metadata();
163 assert_eq!(meta.scheme, "sql");
164 assert!(!meta.description.is_empty());
165 assert!(
166 !meta.uri_options.is_empty(),
167 "uri_options must be non-empty"
168 );
169 let names: Vec<&str> = meta.uri_options.iter().map(|o| o.name.as_str()).collect();
170 assert!(
171 names.contains(&"db_url"),
172 "expected db_url in uri_options, got: {names:?}"
173 );
174 assert!(
175 names.contains(&"outputType"),
176 "expected outputType in uri_options, got: {names:?}"
177 );
178 let db_url_opt = meta
180 .uri_options
181 .iter()
182 .find(|o| o.name == "db_url")
183 .unwrap();
184 assert!(db_url_opt.secret, "db_url must be marked secret");
185 }
186
187 #[test]
188 fn test_config_uri_options_nonempty() {
189 let opts = SqlEndpointConfig::uri_options();
190 assert!(!opts.is_empty(), "uri_options() must be non-empty");
191 let names: Vec<&str> = opts.iter().map(|o| o.name.as_str()).collect();
192 assert!(names.contains(&"db_url"));
193 assert!(names.contains(&"delay"));
194 assert!(names.contains(&"batch"));
195 }
196
197 #[test]
198 fn test_config_metadata_capabilities() {
199 let meta = SqlEndpointConfig::metadata();
200 assert!(meta.capabilities.supports_producer);
201 assert!(meta.capabilities.supports_consumer);
202 assert!(!meta.capabilities.supports_polling_consumer);
203 assert!(!meta.capabilities.supports_streaming);
204 }
205
206 #[test]
207 fn test_component_creates_endpoint() {
208 let c = SqlComponent::new();
209 let ctx = NoOpComponentContext;
210 let ep = c.create_endpoint("sql:select 1?db_url=postgres://localhost/test", &ctx);
211 assert!(ep.is_ok());
212 }
213
214 #[test]
215 fn test_component_rejects_wrong_scheme() {
216 let c = SqlComponent::new();
217 let ctx = NoOpComponentContext;
218 let ep = c.create_endpoint("redis://localhost", &ctx);
219 assert!(ep.is_err());
220 }
221
222 #[test]
223 fn create_endpoint_rejects_managed_transaction_mode() {
224 let c = SqlComponent::new();
225 let ctx = NoOpComponentContext;
226 let Err(e) = c.create_endpoint(
227 "sql:select 1?db_url=postgres://user:s3cr3tpass@localhost/test&transactionMode=Managed",
228 &ctx,
229 ) else {
230 panic!("expected rejection");
231 };
232 let msg = e.to_string();
233 assert!(msg.contains("Managed"), "message must name Managed: {msg}");
234 assert!(msg.contains("rc-qv2iz"), "message must cite bd: {msg}");
235 assert!(
236 msg.contains("sql:select 1"),
237 "message must name the endpoint: {msg}"
238 );
239 assert!(
240 !msg.contains("s3cr3tpass"),
241 "message must redact credentials: {msg}"
242 );
243 }
244
245 #[test]
246 fn create_endpoint_accepts_auto_transaction_mode() {
247 let c = SqlComponent::new();
248 let ctx = NoOpComponentContext;
249 let result = c.create_endpoint(
250 "sql:select 1?db_url=postgres://localhost/test&transactionMode=Auto",
251 &ctx,
252 );
253 assert!(result.is_ok(), "Auto must be accepted");
254 }
255
256 #[test]
257 fn managed_reject_is_config_error_not_parse_error() {
258 let c = SqlComponent::new();
259 let ctx = NoOpComponentContext;
260 let Err(e) = c.create_endpoint(
261 "sql:select 1?db_url=postgres://localhost/test&transactionMode=Managed",
262 &ctx,
263 ) else {
264 panic!("expected rejection");
265 };
266 assert!(
267 matches!(e, CamelError::Config(_)),
268 "reject must be a Config error, got: {e:?}"
269 );
270 let msg = e.to_string();
271 assert!(
272 msg.contains("transactionMode=Auto"),
273 "message must state the workaround: {msg}"
274 );
275 assert!(
276 msg.contains("multi-statement"),
277 "message must state the workaround shape: {msg}"
278 );
279 }
280
281 #[test]
282 fn test_endpoint_uri() {
283 let c = SqlComponent::new();
284 let ctx = NoOpComponentContext;
285 let ep = c
286 .create_endpoint("sql:select 1?db_url=postgres://localhost/test", &ctx)
287 .unwrap();
288 assert_eq!(ep.uri(), "sql:select 1?db_url=postgres://localhost/test");
289 }
290
291 #[test]
292 fn test_component_with_global_config() {
293 let global = SqlGlobalConfig::default().with_max_connections(20);
294 let c = SqlComponent::with_config(global);
295 let ctx = NoOpComponentContext;
296 assert_eq!(c.scheme(), "sql");
298 let ep = c.create_endpoint("sql:select 1?db_url=postgres://localhost/test", &ctx);
299 assert!(ep.is_ok());
300 }
301
302 #[test]
303 fn test_global_config_applied_to_endpoint() {
304 let global = SqlGlobalConfig::default()
307 .with_max_connections(20)
308 .with_min_connections(3)
309 .with_idle_timeout_secs(600)
310 .with_max_lifetime_secs(3600);
311 let mut cfg =
312 config::SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test")
313 .unwrap();
314 cfg.apply_defaults(&global);
315 cfg.resolve_defaults();
316 assert_eq!(cfg.max_connections, Some(20));
317 assert_eq!(cfg.min_connections, Some(3));
318 assert_eq!(cfg.idle_timeout_secs, Some(600));
319 assert_eq!(cfg.max_lifetime_secs, Some(3600));
320 }
321
322 #[test]
323 fn test_uri_param_wins_over_global_config() {
324 let global = SqlGlobalConfig::default()
326 .with_max_connections(20)
327 .with_min_connections(3);
328 let mut cfg = config::SqlEndpointConfig::from_uri(
329 "sql:select 1?db_url=postgres://localhost/test&maxConnections=99&minConnections=7",
330 )
331 .unwrap();
332 cfg.apply_defaults(&global);
333 cfg.resolve_defaults();
334 assert_eq!(cfg.max_connections, Some(99)); assert_eq!(cfg.min_connections, Some(7)); }
337}