Skip to main content

camel_component_sql/
config.rs

1use std::str::FromStr;
2use std::time::Duration;
3
4use camel_api::component_metadata::{ComponentMetadata, UriOption};
5use camel_component_api::CamelError;
6use camel_component_api::NetworkRetryPolicy;
7use camel_component_api::{UriComponents, UriConfig, parse_uri};
8use tracing::debug;
9
10/// Redaction helper: returns `Some("***")` if the option is `Some`, otherwise `None`.
11fn redacted_opt(opt: &Option<String>) -> Option<&'static str> {
12    if opt.is_some() { Some("***") } else { None }
13}
14
15/// Redacts the user:password portion of a database URL for safe display.
16/// Returns `"scheme://***@host/db"` for URLs with userinfo, or the original URL otherwise.
17pub fn redact_db_url(db_url: &str) -> String {
18    match url::Url::parse(db_url) {
19        Ok(mut parsed) => {
20            if parsed.username().is_empty() && parsed.password().is_none() {
21                return db_url.to_string();
22            }
23            let _ = parsed.set_username("***");
24            let _ = parsed.set_password(Some("***"));
25            parsed.to_string()
26        }
27        Err(_) => {
28            // url::Url rejected the string, so structured redaction is
29            // impossible. Best-effort: if the raw string carries a userinfo
30            // separator (`@` after `://`), redact that segment rather than
31            // risk leaking credentials (rc-7rup). Strings without `@` carry
32            // no userinfo and are returned unchanged.
33            if let Some(scheme_end) = db_url.find("://") {
34                let after_scheme = &db_url[scheme_end + 3..];
35                if let Some(at) = after_scheme.find('@') {
36                    let scheme = &db_url[..scheme_end + 3];
37                    let host_part = &after_scheme[at + 1..];
38                    return format!("{scheme}***@{host_part}");
39                }
40            }
41            db_url.to_string()
42        }
43    }
44}
45
46/// Output type for SQL query results.
47#[derive(Debug, Clone, PartialEq, Default)]
48pub enum SqlOutputType {
49    /// Return all rows as a list.
50    #[default]
51    SelectList,
52    /// Return a single row (first result).
53    SelectOne,
54    /// Stream results as an async iterator.
55    StreamList,
56}
57
58impl FromStr for SqlOutputType {
59    type Err = CamelError;
60
61    fn from_str(s: &str) -> Result<Self, Self::Err> {
62        match s {
63            "SelectList" => Ok(SqlOutputType::SelectList),
64            "SelectOne" => Ok(SqlOutputType::SelectOne),
65            "StreamList" => Ok(SqlOutputType::StreamList),
66            _ => Err(CamelError::InvalidUri(format!(
67                "Unknown output type: {}",
68                s
69            ))),
70        }
71    }
72}
73
74/// Transaction mode for SQL operations.
75///
76/// - `Auto`: Each statement auto-commits (default, current behavior).
77/// - `Managed`: Explicit transaction boundaries (future; currently logs a warning
78///   and falls back to Auto).
79///
80// TODO(SQL-002): managed transaction mode — implement explicit transaction boundaries
81#[derive(Debug, Clone, PartialEq, Default)]
82pub enum TransactionMode {
83    /// Auto-commit each statement (default).
84    #[default]
85    Auto,
86    /// Managed transactions — not yet implemented.
87    Managed,
88}
89
90impl FromStr for TransactionMode {
91    type Err = CamelError;
92
93    fn from_str(s: &str) -> Result<Self, Self::Err> {
94        match s {
95            "Auto" => Ok(TransactionMode::Auto),
96            "Managed" => Ok(TransactionMode::Managed),
97            _ => Err(CamelError::InvalidUri(format!(
98                "Unknown transaction mode: {}. Expected 'Auto' or 'Managed'",
99                s
100            ))),
101        }
102    }
103}
104
105impl std::fmt::Display for TransactionMode {
106    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107        match self {
108            TransactionMode::Auto => write!(f, "Auto"),
109            TransactionMode::Managed => write!(f, "Managed"),
110        }
111    }
112}
113
114/// Processing strategy for SQL consumers.
115#[derive(Debug, Clone, PartialEq, Default)]
116pub enum ProcessingStrategy {
117    /// Process rows directly in the polling task (default).
118    #[default]
119    Direct,
120    /// Schedule processing via a separate task (deferred execution).
121    Scheduled,
122}
123
124impl FromStr for ProcessingStrategy {
125    type Err = CamelError;
126
127    fn from_str(s: &str) -> Result<Self, Self::Err> {
128        match s {
129            "Direct" => Ok(ProcessingStrategy::Direct),
130            "Scheduled" => Ok(ProcessingStrategy::Scheduled),
131            _ => Err(CamelError::InvalidUri(format!(
132                "Unknown processing strategy: {}. Expected 'Direct' or 'Scheduled'",
133                s
134            ))),
135        }
136    }
137}
138
139impl std::fmt::Display for ProcessingStrategy {
140    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
141        match self {
142            ProcessingStrategy::Direct => write!(f, "Direct"),
143            ProcessingStrategy::Scheduled => write!(f, "Scheduled"),
144        }
145    }
146}
147
148/// Poll strategy for SQL consumers.
149#[derive(Debug, Clone, PartialEq, Default)]
150pub enum PollStrategy {
151    /// Poll sequentially with delay between polls (default).
152    #[default]
153    Sequential,
154    /// Poll in bursts — execute multiple queries in rapid succession.
155    Burst,
156}
157
158impl FromStr for PollStrategy {
159    type Err = CamelError;
160
161    fn from_str(s: &str) -> Result<Self, Self::Err> {
162        match s {
163            "Sequential" => Ok(PollStrategy::Sequential),
164            "Burst" => Ok(PollStrategy::Burst),
165            _ => Err(CamelError::InvalidUri(format!(
166                "Unknown poll strategy: {}. Expected 'Sequential' or 'Burst'",
167                s
168            ))),
169        }
170    }
171}
172
173impl std::fmt::Display for PollStrategy {
174    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
175        match self {
176            PollStrategy::Sequential => write!(f, "Sequential"),
177            PollStrategy::Burst => write!(f, "Burst"),
178        }
179    }
180}
181
182/// Global configuration for SQL component.
183///
184/// This struct supports serde deserialization with defaults and builder methods.
185/// It holds pool configuration that can be applied as defaults to endpoints.
186///
187/// **Security note:** `Debug` implementation redacts sensitive fields (SSL key paths).
188#[derive(Clone, PartialEq, serde::Deserialize)]
189#[serde(default)]
190pub struct SqlGlobalConfig {
191    pub max_connections: u32,
192    pub min_connections: u32,
193    pub idle_timeout_secs: u64,
194    pub max_lifetime_secs: u64,
195    // SSL/TLS
196    pub ssl_mode: Option<String>,
197    pub ssl_root_cert: Option<String>,
198    pub ssl_cert: Option<String>,
199    pub ssl_key: Option<String>,
200    /// Retry policy for transient database connection failures.
201    #[serde(default)]
202    pub retry: NetworkRetryPolicy,
203}
204
205impl std::fmt::Debug for SqlGlobalConfig {
206    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
207        f.debug_struct("SqlGlobalConfig")
208            .field("max_connections", &self.max_connections)
209            .field("min_connections", &self.min_connections)
210            .field("idle_timeout_secs", &self.idle_timeout_secs)
211            .field("max_lifetime_secs", &self.max_lifetime_secs)
212            .field("ssl_mode", &self.ssl_mode)
213            .field("ssl_root_cert", &self.ssl_root_cert)
214            .field("ssl_cert", &self.ssl_cert)
215            .field("ssl_key", &redacted_opt(&self.ssl_key))
216            .field("retry", &self.retry)
217            .finish()
218    }
219}
220
221impl Default for SqlGlobalConfig {
222    fn default() -> Self {
223        Self {
224            max_connections: 5,
225            min_connections: 1,
226            idle_timeout_secs: 300,
227            max_lifetime_secs: 1800,
228            ssl_mode: None,
229            ssl_root_cert: None,
230            ssl_cert: None,
231            ssl_key: None,
232            retry: NetworkRetryPolicy::default(),
233        }
234    }
235}
236
237impl SqlGlobalConfig {
238    pub fn new() -> Self {
239        Self::default()
240    }
241
242    pub fn with_max_connections(mut self, value: u32) -> Self {
243        self.max_connections = value;
244        self
245    }
246
247    pub fn with_min_connections(mut self, value: u32) -> Self {
248        self.min_connections = value;
249        self
250    }
251
252    pub fn with_idle_timeout_secs(mut self, value: u64) -> Self {
253        self.idle_timeout_secs = value;
254        self
255    }
256
257    pub fn with_max_lifetime_secs(mut self, value: u64) -> Self {
258        self.max_lifetime_secs = value;
259        self
260    }
261
262    pub fn with_ssl_mode(mut self, value: impl Into<String>) -> Self {
263        self.ssl_mode = Some(value.into());
264        self
265    }
266
267    pub fn with_ssl_root_cert(mut self, value: impl Into<String>) -> Self {
268        self.ssl_root_cert = Some(value.into());
269        self
270    }
271
272    pub fn with_ssl_cert(mut self, value: impl Into<String>) -> Self {
273        self.ssl_cert = Some(value.into());
274        self
275    }
276
277    pub fn with_ssl_key(mut self, value: impl Into<String>) -> Self {
278        self.ssl_key = Some(value.into());
279        self
280    }
281
282    pub fn with_retry(mut self, value: NetworkRetryPolicy) -> Self {
283        self.retry = value;
284        self
285    }
286}
287
288/// Configuration for SQL component endpoints.
289///
290/// URI format: `sql:<query>?db_url=<url>&param1=val1&param2=val2`
291///
292/// The query can be inline SQL or a file reference with `file:` prefix:
293/// - `sql:SELECT * FROM users?db_url=...` - inline SQL
294/// - `sql:file:/path/to/query.sql?db_url=...` - read SQL from file
295///
296/// **Note on file-based queries (SQL-014):** When the query path starts with `file:`,
297/// the file is NOT read synchronously during `from_uri()`. Instead, the file path is
298/// stored in `source_path` and the query is resolved asynchronously via `resolve_file_query()`
299/// during async initialization (producer pool init or consumer start). This avoids
300/// blocking I/O in the synchronous URI parsing path.
301///
302/// **Security note:** `Debug` implementation redacts the `db_url` (which may contain credentials)
303/// and `ssl_key` path. Use `redact_db_url()` for safe logging of database URLs.
304#[derive(Clone)]
305pub struct SqlEndpointConfig {
306    // Connection
307    /// Database connection URL (optional when datasource_name is set).
308    pub db_url: String,
309    /// Named datasource reference (from CamelConfig.datasources).
310    pub datasource_name: Option<String>,
311    /// Maximum connections in the pool. None = use global default.
312    pub max_connections: Option<u32>,
313    /// Minimum connections in the pool. None = use global default.
314    pub min_connections: Option<u32>,
315    /// Idle timeout in seconds. None = use global default.
316    pub idle_timeout_secs: Option<u64>,
317    /// Maximum connection lifetime in seconds. None = use global default.
318    pub max_lifetime_secs: Option<u64>,
319
320    // Query
321    /// The SQL query (from URI path or file).
322    pub query: String,
323    /// Path to the file containing the SQL query (when using `file:` prefix).
324    pub source_path: Option<String>,
325    /// Output type for query results. Default: SelectList.
326    pub output_type: SqlOutputType,
327    /// Placeholder character for parameters. Default: '#'.
328    pub placeholder: char,
329    /// If true, process parameter placeholders in queries. Default: true.
330    pub use_placeholder: bool,
331    /// If true, don't execute the query (dry run). Default: false.
332    pub noop: bool,
333    /// Separator for IN clause expansion. Default: ", ".
334    pub in_separator: String,
335
336    // SQL-005: always populate statement even if body is null/empty
337    /// If true, always bind parameters even if the exchange body is null/empty
338    /// (uses empty defaults). Default: false.
339    pub always_populate_statement: bool,
340
341    // SQL-011: allow named parameters
342    /// If true, recognize `:name` style placeholders and map them from exchange
343    /// headers or body fields. Default: true.
344    pub allow_named_parameters: bool,
345
346    // SQL-016: fetch size hint
347    /// Fetch size hint for query results. None = driver default.
348    pub fetch_size: Option<u32>,
349
350    // SQL-002: transaction mode
351    /// Transaction mode for SQL operations. Default: Auto.
352    pub transaction_mode: TransactionMode,
353
354    // Consumer (polling)
355    /// Delay between polls in milliseconds. Default: 500.
356    pub delay_ms: u64,
357    /// Initial delay before first poll in milliseconds. Default: 1000.
358    pub initial_delay_ms: u64,
359    /// Maximum messages per poll.
360    pub max_messages_per_poll: Option<i32>,
361    /// SQL to execute after consuming each message.
362    pub on_consume: Option<String>,
363    /// SQL to execute if consumption fails.
364    pub on_consume_failed: Option<String>,
365    /// SQL to execute after consuming a batch.
366    pub on_consume_batch_complete: Option<String>,
367    /// Route empty result sets. Default: false.
368    pub route_empty_result_set: bool,
369    /// Use iterator for results. Default: true.
370    pub use_iterator: bool,
371    /// Expected number of rows affected.
372    pub expected_update_count: Option<i64>,
373    /// Break batch on consume failure. Default: false.
374    pub break_batch_on_consume_fail: bool,
375    /// Bridge poll errors into route error handling. Default: false.
376    pub bridge_error_handler: bool,
377
378    // SQL-015: repeat count for consumer polling
379    /// Maximum number of polls before the consumer stops. Omit (None) for infinite
380    /// polling. `0` = never poll (the consumer exits before its first poll); useful
381    /// for disabling a route via config without removing it. See also camel-timer's
382    /// `repeatCount`, which implements the same `0 = never` semantic.
383    pub repeat_count: Option<u32>,
384
385    // SQL-020: break on empty poll
386    /// When true, the consumer stops after a poll that returns zero rows
387    /// (SelectList mode only; ignored with a warning in StreamList mode).
388    /// Default: false.
389    pub break_on_empty: bool,
390
391    // SQL-017: processing strategy
392    /// Processing strategy for consumer. Default: Direct.
393    pub processing_strategy: ProcessingStrategy,
394
395    // SQL-018: poll strategy
396    /// Poll strategy for consumer. Default: Sequential.
397    pub poll_strategy: PollStrategy,
398
399    // Producer
400    /// Enable batch mode. Default: false.
401    pub batch: bool,
402    /// Use message body for SQL. Default: false.
403    pub use_message_body_for_sql: bool,
404    /// Allow queries to be sourced from exchange headers (`CamelSql.Query`) or body.
405    /// Default `false` — dynamic queries are SQLi risk. Set `true` for backward compat.
406    pub allow_dynamic_query: bool,
407
408    // SSL/TLS
409    /// SSL mode for the connection. None = use global default.
410    pub ssl_mode: Option<String>,
411    /// Path to SSL root certificate. None = use global default.
412    pub ssl_root_cert: Option<String>,
413    /// Path to SSL client certificate. None = use global default.
414    pub ssl_cert: Option<String>,
415    /// Path to SSL client key. None = use global default.
416    pub ssl_key: Option<String>,
417
418    /// Retry policy for transient database connection failures.
419    pub retry: NetworkRetryPolicy,
420
421    /// Whether `retry` was explicitly set via URI params. Used by
422    /// [`apply_defaults`] to decide whether URI values win over
423    /// the global config. Internal tracking flag, not serialized.
424    retry_set_from_uri: bool,
425}
426
427impl std::fmt::Debug for SqlEndpointConfig {
428    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
429        f.debug_struct("SqlEndpointConfig")
430            .field("db_url", &redact_db_url(&self.db_url))
431            .field("datasource_name", &self.datasource_name)
432            .field("max_connections", &self.max_connections)
433            .field("min_connections", &self.min_connections)
434            .field("idle_timeout_secs", &self.idle_timeout_secs)
435            .field("max_lifetime_secs", &self.max_lifetime_secs)
436            .field("query", &self.query)
437            .field("source_path", &self.source_path)
438            .field("output_type", &self.output_type)
439            .field("placeholder", &self.placeholder)
440            .field("use_placeholder", &self.use_placeholder)
441            .field("noop", &self.noop)
442            .field("in_separator", &self.in_separator)
443            .field("always_populate_statement", &self.always_populate_statement)
444            .field("allow_named_parameters", &self.allow_named_parameters)
445            .field("fetch_size", &self.fetch_size)
446            .field("transaction_mode", &self.transaction_mode)
447            .field("delay_ms", &self.delay_ms)
448            .field("initial_delay_ms", &self.initial_delay_ms)
449            .field("max_messages_per_poll", &self.max_messages_per_poll)
450            .field("on_consume", &self.on_consume)
451            .field("on_consume_failed", &self.on_consume_failed)
452            .field("on_consume_batch_complete", &self.on_consume_batch_complete)
453            .field("route_empty_result_set", &self.route_empty_result_set)
454            .field("use_iterator", &self.use_iterator)
455            .field("expected_update_count", &self.expected_update_count)
456            .field(
457                "break_batch_on_consume_fail",
458                &self.break_batch_on_consume_fail,
459            )
460            .field("bridge_error_handler", &self.bridge_error_handler)
461            .field("repeat_count", &self.repeat_count)
462            .field("break_on_empty", &self.break_on_empty)
463            .field("processing_strategy", &self.processing_strategy)
464            .field("poll_strategy", &self.poll_strategy)
465            .field("batch", &self.batch)
466            .field("use_message_body_for_sql", &self.use_message_body_for_sql)
467            .field("allow_dynamic_query", &self.allow_dynamic_query)
468            .field("ssl_mode", &self.ssl_mode)
469            .field("ssl_root_cert", &self.ssl_root_cert)
470            .field("ssl_cert", &self.ssl_cert)
471            .field("ssl_key", &redacted_opt(&self.ssl_key))
472            .field("retry", &self.retry)
473            .finish()
474    }
475}
476
477/// Private container for macro-derived `uri_options()` and `metadata()`.
478///
479/// Mirrors `SqlEndpointConfig`'s URI-parsed params exactly. `SqlEndpointConfig`
480/// holds extra non-URI fields (`retry`, `retry_set_from_uri`) and custom
481/// `from_uri` logic; metadata delegation targets this inner type.
482#[derive(Debug, Clone, UriConfig)]
483#[allow(dead_code)]
484#[uri_scheme = "sql"]
485#[uri_config(
486    skip_impl,
487    metadata(
488        scheme = "sql",
489        description = "Execute SQL against a configured datasource",
490        producer,
491        consumer
492    ),
493    crate = "camel_component_api"
494)]
495struct SqlUriConfig {
496    // ── Connection ──
497    #[uri_param(name = "db_url", desc = "Database connection URL", secret)]
498    pub db_url: Option<String>,
499    #[uri_param(
500        name = "datasource",
501        desc = "Named datasource reference (from CamelConfig.datasources)"
502    )]
503    pub datasource: Option<String>,
504    #[uri_param(name = "maxConnections", desc = "Maximum connections in the pool")]
505    pub max_connections: Option<u64>,
506    #[uri_param(name = "minConnections", desc = "Minimum connections in the pool")]
507    pub min_connections: Option<u64>,
508    #[uri_param(name = "idleTimeoutSecs", desc = "Idle timeout in seconds")]
509    pub idle_timeout_secs: Option<u64>,
510    #[uri_param(
511        name = "maxLifetimeSecs",
512        desc = "Maximum connection lifetime in seconds"
513    )]
514    pub max_lifetime_secs: Option<u64>,
515
516    // ── Query ──
517    #[uri_param(
518        name = "outputType",
519        kind = "enum:SelectList,SelectOne,StreamList",
520        default = "SelectList",
521        desc = "Output type for query results"
522    )]
523    pub output_type: Option<String>,
524    #[uri_param(
525        name = "placeholder",
526        default = "#",
527        desc = "Placeholder character for parameters"
528    )]
529    pub placeholder: Option<String>,
530    #[uri_param(
531        name = "usePlaceholder",
532        default = "true",
533        desc = "Process parameter placeholders in queries"
534    )]
535    pub use_placeholder: Option<bool>,
536    #[uri_param(
537        name = "noop",
538        default = "false",
539        desc = "Dry-run mode (don't execute the query)"
540    )]
541    pub noop: Option<bool>,
542    #[uri_param(
543        name = "inSeparator",
544        default = ", ",
545        desc = "Separator for IN clause expansion"
546    )]
547    pub in_separator: Option<String>,
548    #[uri_param(
549        name = "alwaysPopulateStatement",
550        default = "false",
551        desc = "Always bind parameters even if the exchange body is null or empty"
552    )]
553    pub always_populate_statement: Option<bool>,
554    #[uri_param(
555        name = "allowNamedParameters",
556        default = "true",
557        desc = "Recognize :name style placeholders from headers or body"
558    )]
559    pub allow_named_parameters: Option<bool>,
560    #[uri_param(name = "fetchSize", desc = "Fetch size hint for query results")]
561    pub fetch_size: Option<u64>,
562    #[uri_param(
563        name = "transactionMode",
564        kind = "enum:Auto,Managed",
565        default = "Auto",
566        desc = "Transaction mode for SQL operations"
567    )]
568    pub transaction_mode: Option<String>,
569
570    // ── Consumer ──
571    #[uri_param(
572        name = "delay",
573        default = "500",
574        desc = "Delay between polls in milliseconds"
575    )]
576    pub delay: Option<u64>,
577    #[uri_param(
578        name = "initialDelay",
579        default = "1000",
580        desc = "Initial delay before first poll in milliseconds"
581    )]
582    pub initial_delay: Option<u64>,
583    #[uri_param(name = "maxMessagesPerPoll", desc = "Maximum messages per poll")]
584    pub max_messages_per_poll: Option<u64>,
585    #[uri_param(
586        name = "onConsume",
587        desc = "SQL to execute after consuming each message"
588    )]
589    pub on_consume: Option<String>,
590    #[uri_param(name = "onConsumeFailed", desc = "SQL to execute if consumption fails")]
591    pub on_consume_failed: Option<String>,
592    #[uri_param(
593        name = "onConsumeBatchComplete",
594        desc = "SQL to execute after consuming a batch"
595    )]
596    pub on_consume_batch_complete: Option<String>,
597    #[uri_param(
598        name = "routeEmptyResultSet",
599        default = "false",
600        desc = "Route empty result sets"
601    )]
602    pub route_empty_result_set: Option<bool>,
603    #[uri_param(
604        name = "useIterator",
605        default = "true",
606        desc = "Use iterator for results"
607    )]
608    pub use_iterator: Option<bool>,
609    #[uri_param(
610        name = "expectedUpdateCount",
611        desc = "Expected number of rows affected"
612    )]
613    pub expected_update_count: Option<u64>,
614    #[uri_param(
615        name = "breakBatchOnConsumeFail",
616        default = "false",
617        desc = "Break batch on consume failure"
618    )]
619    pub break_batch_on_consume_fail: Option<bool>,
620    #[uri_param(
621        name = "bridgeErrorHandler",
622        default = "false",
623        desc = "Bridge poll errors into route error handling"
624    )]
625    pub bridge_error_handler: Option<bool>,
626    #[uri_param(
627        name = "repeatCount",
628        desc = "Maximum number of polls before the consumer stops"
629    )]
630    pub repeat_count: Option<u64>,
631    #[uri_param(
632        name = "breakOnEmpty",
633        default = "false",
634        desc = "Stop the consumer after a poll that returns zero rows"
635    )]
636    pub break_on_empty: Option<bool>,
637    #[uri_param(
638        name = "processingStrategy",
639        kind = "enum:Direct,Scheduled",
640        default = "Direct",
641        desc = "Processing strategy for the consumer"
642    )]
643    pub processing_strategy: Option<String>,
644    #[uri_param(
645        name = "pollStrategy",
646        kind = "enum:Sequential,Burst",
647        default = "Sequential",
648        desc = "Poll strategy for the consumer"
649    )]
650    pub poll_strategy: Option<String>,
651
652    // ── Producer ──
653    #[uri_param(name = "batch", default = "false", desc = "Enable batch mode")]
654    pub batch: Option<bool>,
655    #[uri_param(
656        name = "useMessageBodyForSql",
657        default = "false",
658        desc = "Use message body for SQL"
659    )]
660    pub use_message_body_for_sql: Option<bool>,
661    #[uri_param(
662        name = "allowDynamicQuery",
663        default = "false",
664        desc = "Allow queries to be sourced from exchange headers or body"
665    )]
666    pub allow_dynamic_query: Option<bool>,
667
668    // ── SSL ──
669    #[uri_param(name = "sslMode", desc = "SSL mode for the connection")]
670    pub ssl_mode: Option<String>,
671    #[uri_param(name = "sslRootCert", desc = "Path to SSL root certificate")]
672    pub ssl_root_cert: Option<String>,
673    #[uri_param(name = "sslCert", desc = "Path to SSL client certificate")]
674    pub ssl_cert: Option<String>,
675    #[uri_param(name = "sslKey", desc = "Path to SSL client key", secret)]
676    pub ssl_key: Option<String>,
677}
678
679impl SqlEndpointConfig {
680    /// Component metadata for the sql scheme, derived from
681    /// `#[uri_param]` annotations on `SqlUriConfig`.
682    pub fn metadata() -> ComponentMetadata {
683        SqlUriConfig::metadata()
684    }
685
686    /// Generated URI option definitions for the sql scheme,
687    /// derived from `#[uri_param]` annotations on `SqlUriConfig`.
688    pub fn uri_options() -> Vec<UriOption> {
689        SqlUriConfig::uri_options()
690    }
691
692    /// Apply defaults from global config, filling None fields without overriding.
693    pub fn apply_defaults(&mut self, defaults: &SqlGlobalConfig) {
694        if self.max_connections.is_none() {
695            self.max_connections = Some(defaults.max_connections);
696        }
697        if self.min_connections.is_none() {
698            self.min_connections = Some(defaults.min_connections);
699        }
700        if self.idle_timeout_secs.is_none() {
701            self.idle_timeout_secs = Some(defaults.idle_timeout_secs);
702        }
703        if self.max_lifetime_secs.is_none() {
704            self.max_lifetime_secs = Some(defaults.max_lifetime_secs);
705        }
706        if self.ssl_mode.is_none() {
707            self.ssl_mode = defaults.ssl_mode.clone();
708        }
709        if self.ssl_root_cert.is_none() {
710            self.ssl_root_cert = defaults.ssl_root_cert.clone();
711        }
712        if self.ssl_cert.is_none() {
713            self.ssl_cert = defaults.ssl_cert.clone();
714        }
715        if self.ssl_key.is_none() {
716            self.ssl_key = defaults.ssl_key.clone();
717        }
718        // retry: URI wins when set_from_uri, else global fills the gap
719        if !self.retry_set_from_uri {
720            self.retry = defaults.retry.clone();
721        }
722    }
723
724    /// Resolve any remaining None fields with built-in defaults.
725    pub fn resolve_defaults(&mut self) {
726        let defaults = SqlGlobalConfig::default();
727        self.apply_defaults(&defaults);
728    }
729
730    /// Asynchronously read the SQL query from the file referenced by `source_path`.
731    ///
732    /// This is the async replacement for the blocking `std::fs::read_to_string` that
733    /// was previously called in `from_uri()`. Must be invoked during async init
734    /// (producer pool init or consumer start) — never in a synchronous context.
735    ///
736    /// After this call, `self.query` contains the file content (trimmed) and
737    /// `self.source_path` is cleared to prevent re-reading.
738    pub async fn resolve_file_query(&mut self) -> Result<(), CamelError> {
739        if let Some(file_path) = self.source_path.take() {
740            let contents = tokio::fs::read_to_string(&file_path).await.map_err(|e| {
741                CamelError::Config(format!("Failed to read SQL file '{}': {}", file_path, e))
742            })?;
743            self.query = contents.trim().to_string();
744            // Keep source_path as Some so tests can still verify the original path
745            self.source_path = Some(file_path);
746        }
747        Ok(())
748    }
749}
750
751struct SslParamMapping {
752    pg_key: &'static str,
753    mysql_key: &'static str,
754}
755
756const SSL_MAPPINGS: &[(&str, SslParamMapping)] = &[
757    (
758        "sslMode",
759        SslParamMapping {
760            pg_key: "sslmode",
761            mysql_key: "ssl-mode",
762        },
763    ),
764    (
765        "sslRootCert",
766        SslParamMapping {
767            pg_key: "sslrootcert",
768            mysql_key: "ssl-ca",
769        },
770    ),
771    (
772        "sslCert",
773        SslParamMapping {
774            pg_key: "sslcert",
775            mysql_key: "ssl-cert",
776        },
777    ),
778    (
779        "sslKey",
780        SslParamMapping {
781            pg_key: "sslkey",
782            mysql_key: "ssl-key",
783        },
784    ),
785];
786
787pub fn enrich_db_url_with_ssl(
788    db_url: &str,
789    config: &SqlEndpointConfig,
790) -> Result<String, CamelError> {
791    enrich_db_url_with_ssl_params(
792        db_url,
793        config.ssl_mode.as_deref(),
794        config.ssl_root_cert.as_deref(),
795        config.ssl_cert.as_deref(),
796        config.ssl_key.as_deref(),
797    )
798}
799
800pub(crate) fn enrich_db_url_with_ssl_params(
801    db_url: &str,
802    ssl_mode: Option<&str>,
803    ssl_root_cert: Option<&str>,
804    ssl_cert: Option<&str>,
805    ssl_key: Option<&str>,
806) -> Result<String, CamelError> {
807    let mut parsed = url::Url::parse(db_url).map_err(|e| {
808        CamelError::InvalidUri(format!(
809            "Cannot parse database URL for SSL enrichment: {}",
810            e
811        ))
812    })?;
813
814    let scheme = parsed.scheme();
815    if scheme.starts_with("sqlite") {
816        if ssl_mode.is_some() || ssl_root_cert.is_some() || ssl_cert.is_some() || ssl_key.is_some()
817        {
818            debug!(
819                "SSL options configured for SQLite database URL, but SQLite does not support SSL/TLS; ignoring sslMode/sslRootCert/sslCert/sslKey"
820            );
821        }
822        return Ok(db_url.to_string());
823    }
824
825    if scheme != "postgres" && scheme != "postgresql" && scheme != "mysql" {
826        return Ok(db_url.to_string());
827    }
828    let is_mysql = scheme == "mysql";
829
830    // Explicit URL sslmode/ssl-mode is operator intent and must not be
831    // overwritten by the per-driver default (ADR-0033).
832    let (driver_ssl_mode_key, default_ssl_mode) = if is_mysql {
833        ("ssl-mode", "prefer")
834    } else {
835        ("sslmode", "require")
836    };
837    let url_has_explicit_ssl_mode = parsed
838        .query_pairs()
839        .any(|(k, v)| k.as_ref() == driver_ssl_mode_key && !v.is_empty());
840    let effective_ssl_mode: Option<&str> = match ssl_mode {
841        Some(value) => Some(value),
842        None if url_has_explicit_ssl_mode => None,
843        None => Some(default_ssl_mode),
844    };
845
846    let ssl_params: Vec<(&str, &str)> = [
847        effective_ssl_mode.map(|value| ("sslMode", value)),
848        ssl_root_cert.map(|v| ("sslRootCert", v)),
849        ssl_cert.map(|v| ("sslCert", v)),
850        ssl_key.map(|v| ("sslKey", v)),
851    ]
852    .into_iter()
853    .flatten()
854    .collect();
855
856    let mut query_pairs = parsed.query_pairs().collect::<Vec<_>>();
857    for (camel_name, value) in &ssl_params {
858        if let Some((_, mapping)) = SSL_MAPPINGS.iter().find(|(name, _)| *name == *camel_name) {
859            let driver_key = if is_mysql {
860                mapping.mysql_key
861            } else {
862                mapping.pg_key
863            };
864
865            if let Some(pos) = query_pairs.iter().position(|(k, _)| k == driver_key) {
866                query_pairs[pos].1 = (*value).into();
867            } else {
868                query_pairs.push((driver_key.into(), (*value).into()));
869            }
870        }
871    }
872
873    // Add TCP connect timeout (10s) if not already set.
874    // This is the sqlx URL-level connect_timeout, NOT the pool acquire_timeout.
875    if !query_pairs.iter().any(|(k, _)| k == "connect_timeout") {
876        query_pairs.push(("connect_timeout".into(), "10".into()));
877    }
878
879    {
880        let mut serializer = url::form_urlencoded::Serializer::new(String::new());
881        for (k, v) in &query_pairs {
882            serializer.append_pair(k, v);
883        }
884        parsed.set_query(Some(&serializer.finish()));
885    }
886
887    Ok(parsed.to_string())
888}
889
890impl UriConfig for SqlEndpointConfig {
891    fn scheme() -> &'static str {
892        "sql"
893    }
894
895    fn from_uri(uri: &str) -> Result<Self, CamelError> {
896        let parts = parse_uri(uri)?;
897        Self::from_components(parts)
898    }
899
900    fn from_components(parts: UriComponents) -> Result<Self, CamelError> {
901        // Validate scheme
902        if parts.scheme != Self::scheme() {
903            return Err(CamelError::InvalidUri(format!(
904                "expected scheme '{}' but got '{}'",
905                Self::scheme(),
906                parts.scheme
907            )));
908        }
909
910        let params = &parts.params;
911
912        // Handle file: prefix for query
913        // SQL-014: defer file reading to async init path to avoid blocking I/O
914        // in the synchronous URI parsing path. Store the path; resolve_file_query()
915        // must be called during async initialization (producer pool init or consumer start).
916        let (query, source_path) = if parts.path.starts_with("file:") {
917            let file_path = parts.path.trim_start_matches("file:").to_string();
918            (String::new(), Some(file_path))
919        } else {
920            (parts.path.clone(), None)
921        };
922
923        // Optional parameter: db_url (required when datasource is not set)
924        let db_url = params.get("db_url").cloned().unwrap_or_default();
925
926        // Named datasource reference (from CamelConfig.datasources)
927        let datasource_name = params.get("datasource").cloned();
928
929        // Connection parameters - None when not set by URI param
930        let max_connections = params.get("maxConnections").and_then(|v| v.parse().ok());
931        let min_connections = params.get("minConnections").and_then(|v| v.parse().ok());
932        let idle_timeout_secs = params.get("idleTimeoutSecs").and_then(|v| v.parse().ok());
933        let max_lifetime_secs = params.get("maxLifetimeSecs").and_then(|v| v.parse().ok());
934
935        // Query parameters
936        let output_type = params
937            .get("outputType")
938            .map(|s| s.parse())
939            .transpose()?
940            .unwrap_or_default();
941        let placeholder = params
942            .get("placeholder")
943            .filter(|v| !v.is_empty())
944            .map(|v| {
945                if v.chars().count() != 1 {
946                    return Err(CamelError::InvalidUri(format!(
947                        "placeholder must be exactly one character, got '{}'",
948                        v
949                    )));
950                }
951                if !v.is_ascii() {
952                    return Err(CamelError::InvalidUri(
953                        "placeholder must be a single ASCII character".to_string(),
954                    ));
955                }
956                Ok(v.chars().next().unwrap()) // allow-unwrap
957            })
958            .transpose()?
959            .unwrap_or('#');
960        /// Parse a boolean URI parameter strictly.
961        ///
962        /// Accepts only `"true"` or `"false"` (case-insensitive). Any other value
963        /// returns `CamelError::InvalidUri` to prevent silent misconfiguration.
964        fn parse_bool_param(name: &str, value: &str) -> Result<bool, CamelError> {
965            if value.eq_ignore_ascii_case("true") {
966                Ok(true)
967            } else if value.eq_ignore_ascii_case("false") {
968                Ok(false)
969            } else {
970                Err(CamelError::InvalidUri(format!(
971                    "{} must be 'true' or 'false', got '{}'",
972                    name, value
973                )))
974            }
975        }
976
977        let use_placeholder = params
978            .get("usePlaceholder")
979            .map(|v| parse_bool_param("usePlaceholder", v))
980            .transpose()?
981            .unwrap_or(true);
982        let noop = params
983            .get("noop")
984            .map(|v| parse_bool_param("noop", v))
985            .transpose()?
986            .unwrap_or(false);
987        let in_separator = params
988            .get("inSeparator")
989            .map(|v| v.to_string())
990            .unwrap_or_else(|| ", ".to_string());
991        if in_separator.is_empty() {
992            return Err(CamelError::InvalidUri(
993                "inSeparator must not be empty".to_string(),
994            ));
995        }
996
997        // SQL-005: alwaysPopulateStatement
998        let always_populate_statement = params
999            .get("alwaysPopulateStatement")
1000            .map(|v| parse_bool_param("alwaysPopulateStatement", v))
1001            .transpose()?
1002            .unwrap_or(false);
1003
1004        // SQL-011: allowNamedParameters
1005        let allow_named_parameters = params
1006            .get("allowNamedParameters")
1007            .map(|v| parse_bool_param("allowNamedParameters", v))
1008            .transpose()?
1009            .unwrap_or(true);
1010
1011        // SQL-016: fetchSize
1012        let fetch_size = params.get("fetchSize").and_then(|v| v.parse().ok());
1013
1014        // SQL-002: transactionMode
1015        let transaction_mode = params
1016            .get("transactionMode")
1017            .map(|s| s.parse())
1018            .transpose()?
1019            .unwrap_or_default();
1020
1021        // Consumer parameters
1022        let delay_ms = params
1023            .get("delay")
1024            .and_then(|v| v.parse().ok())
1025            .unwrap_or(500);
1026        let initial_delay_ms = params
1027            .get("initialDelay")
1028            .and_then(|v| v.parse().ok())
1029            .unwrap_or(1000);
1030        let max_messages_per_poll = params
1031            .get("maxMessagesPerPoll")
1032            .and_then(|v| v.parse().ok());
1033        let on_consume = params.get("onConsume").cloned();
1034        let on_consume_failed = params.get("onConsumeFailed").cloned();
1035        let on_consume_batch_complete = params.get("onConsumeBatchComplete").cloned();
1036        let route_empty_result_set = params
1037            .get("routeEmptyResultSet")
1038            .map(|v| parse_bool_param("routeEmptyResultSet", v))
1039            .transpose()?
1040            .unwrap_or(false);
1041        let use_iterator = params
1042            .get("useIterator")
1043            .map(|v| parse_bool_param("useIterator", v))
1044            .transpose()?
1045            .unwrap_or(true);
1046        let expected_update_count = params
1047            .get("expectedUpdateCount")
1048            .and_then(|v| v.parse().ok());
1049        let break_batch_on_consume_fail = params
1050            .get("breakBatchOnConsumeFail")
1051            .map(|v| parse_bool_param("breakBatchOnConsumeFail", v))
1052            .transpose()?
1053            .unwrap_or(false);
1054        let bridge_error_handler = params
1055            .get("bridgeErrorHandler")
1056            .map(|v| parse_bool_param("bridgeErrorHandler", v))
1057            .transpose()?
1058            .unwrap_or(false);
1059
1060        // SQL-015: repeatCount
1061        let repeat_count = params.get("repeatCount").and_then(|v| v.parse().ok());
1062
1063        // SQL-020: breakOnEmpty
1064        let break_on_empty = params
1065            .get("breakOnEmpty")
1066            .map(|v| parse_bool_param("breakOnEmpty", v))
1067            .transpose()?
1068            .unwrap_or(false);
1069
1070        // SQL-017: processingStrategy
1071        let processing_strategy = params
1072            .get("processingStrategy")
1073            .map(|s| s.parse())
1074            .transpose()?
1075            .unwrap_or_default();
1076
1077        // SQL-018: pollStrategy
1078        let poll_strategy = params
1079            .get("pollStrategy")
1080            .map(|s| s.parse())
1081            .transpose()?
1082            .unwrap_or_default();
1083
1084        // Producer parameters
1085        let batch = params
1086            .get("batch")
1087            .map(|v| parse_bool_param("batch", v))
1088            .transpose()?
1089            .unwrap_or(false);
1090        let use_message_body_for_sql = params
1091            .get("useMessageBodyForSql")
1092            .map(|v| parse_bool_param("useMessageBodyForSql", v))
1093            .transpose()?
1094            .unwrap_or(false);
1095        let allow_dynamic_query = params
1096            .get("allowDynamicQuery")
1097            .map(|v| parse_bool_param("allowDynamicQuery", v))
1098            .transpose()?
1099            .unwrap_or(false);
1100        let ssl_mode = params.get("sslMode").cloned();
1101        let ssl_root_cert = params.get("sslRootCert").cloned();
1102        let ssl_cert = params.get("sslCert").cloned();
1103        let ssl_key = params.get("sslKey").cloned();
1104
1105        // Parse retry policy from URI params
1106        let mut retry = NetworkRetryPolicy::default();
1107        let mut retry_set_from_uri = false;
1108        if let Some(raw) = params.get("retryEnabled") {
1109            retry.enabled = raw.parse::<bool>().map_err(|_| {
1110                CamelError::InvalidUri(format!("retryEnabled must be a boolean, got '{raw}'"))
1111            })?;
1112            retry_set_from_uri = true;
1113        }
1114        if let Some(raw) = params.get("retryMaxAttempts") {
1115            retry.max_attempts = raw.parse::<u32>().map_err(|_| {
1116                CamelError::InvalidUri(format!("retryMaxAttempts must be a u32, got '{raw}'"))
1117            })?;
1118            retry_set_from_uri = true;
1119        }
1120        if let Some(raw) = params.get("retryInitialDelayMs") {
1121            retry.initial_delay = Duration::from_millis(raw.parse::<u64>().map_err(|_| {
1122                CamelError::InvalidUri(format!("retryInitialDelayMs must be a u64, got '{raw}'"))
1123            })?);
1124            retry_set_from_uri = true;
1125        }
1126        if let Some(raw) = params.get("retryMultiplier") {
1127            retry.multiplier = raw.parse::<f64>().map_err(|_| {
1128                CamelError::InvalidUri(format!("retryMultiplier must be a f64, got '{raw}'"))
1129            })?;
1130            retry_set_from_uri = true;
1131        }
1132        if let Some(raw) = params.get("retryMaxDelayMs") {
1133            retry.max_delay = Duration::from_millis(raw.parse::<u64>().map_err(|_| {
1134                CamelError::InvalidUri(format!("retryMaxDelayMs must be a u64, got '{raw}'"))
1135            })?);
1136            retry_set_from_uri = true;
1137        }
1138        if let Some(raw) = params.get("retryJitter") {
1139            retry.jitter_factor = raw.parse::<f64>().map_err(|_| {
1140                CamelError::InvalidUri(format!("retryJitter must be a f64, got '{raw}'"))
1141            })?;
1142            retry_set_from_uri = true;
1143        }
1144
1145        if datasource_name.is_none() && db_url.is_empty() {
1146            return Err(CamelError::Config(
1147                "either 'datasource' or 'db_url' parameter is required".to_string(),
1148            ));
1149        }
1150
1151        if datasource_name.is_some() && !db_url.is_empty() {
1152            return Err(CamelError::InvalidUri(
1153                "'db_url' not allowed with named datasource — use 'datasource' alone".to_string(),
1154            ));
1155        }
1156
1157        if datasource_name.is_some() {
1158            let overrides: Vec<&str> = {
1159                let mut v = Vec::new();
1160                if max_connections.is_some() {
1161                    v.push("maxConnections");
1162                }
1163                if min_connections.is_some() {
1164                    v.push("minConnections");
1165                }
1166                if idle_timeout_secs.is_some() {
1167                    v.push("idleTimeoutSecs");
1168                }
1169                if max_lifetime_secs.is_some() {
1170                    v.push("maxLifetimeSecs");
1171                }
1172                if ssl_mode.is_some() {
1173                    v.push("sslMode");
1174                }
1175                if ssl_root_cert.is_some() {
1176                    v.push("sslRootCert");
1177                }
1178                if ssl_cert.is_some() {
1179                    v.push("sslCert");
1180                }
1181                if ssl_key.is_some() {
1182                    v.push("sslKey");
1183                }
1184                v
1185            };
1186            if !overrides.is_empty() {
1187                return Err(CamelError::InvalidUri(format!(
1188                    "pool-affecting params not allowed with named datasource: {}",
1189                    overrides.join(", ")
1190                )));
1191            }
1192        }
1193
1194        Ok(Self {
1195            db_url,
1196            datasource_name,
1197            max_connections,
1198            min_connections,
1199            idle_timeout_secs,
1200            max_lifetime_secs,
1201            query,
1202            source_path,
1203            output_type,
1204            placeholder,
1205            use_placeholder,
1206            noop,
1207            in_separator,
1208            always_populate_statement,
1209            allow_named_parameters,
1210            fetch_size,
1211            transaction_mode,
1212            delay_ms,
1213            initial_delay_ms,
1214            max_messages_per_poll,
1215            on_consume,
1216            on_consume_failed,
1217            on_consume_batch_complete,
1218            route_empty_result_set,
1219            use_iterator,
1220            expected_update_count,
1221            break_batch_on_consume_fail,
1222            bridge_error_handler,
1223            repeat_count,
1224            break_on_empty,
1225            processing_strategy,
1226            poll_strategy,
1227            batch,
1228            use_message_body_for_sql,
1229            allow_dynamic_query,
1230            ssl_mode,
1231            ssl_root_cert,
1232            ssl_cert,
1233            ssl_key,
1234            retry,
1235            retry_set_from_uri,
1236        })
1237    }
1238}
1239
1240#[cfg(test)]
1241mod tests {
1242    use super::*;
1243    use camel_component_api::NetworkRetryPolicy;
1244
1245    #[test]
1246    fn config_defaults() {
1247        let mut c =
1248            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
1249        c.resolve_defaults();
1250        assert_eq!(c.query, "select 1");
1251        assert_eq!(c.db_url, "postgres://localhost/test");
1252        assert_eq!(c.max_connections, Some(5));
1253        assert_eq!(c.min_connections, Some(1));
1254        assert_eq!(c.idle_timeout_secs, Some(300));
1255        assert_eq!(c.max_lifetime_secs, Some(1800));
1256        assert_eq!(c.output_type, SqlOutputType::SelectList);
1257        assert_eq!(c.placeholder, '#');
1258        assert!(!c.noop);
1259        assert_eq!(c.in_separator, ", ");
1260        assert_eq!(c.delay_ms, 500);
1261        assert_eq!(c.initial_delay_ms, 1000);
1262        assert!(c.max_messages_per_poll.is_none());
1263        assert!(c.on_consume.is_none());
1264        assert!(c.on_consume_failed.is_none());
1265        assert!(c.on_consume_batch_complete.is_none());
1266        assert!(!c.route_empty_result_set);
1267        assert!(c.use_iterator);
1268        assert!(c.expected_update_count.is_none());
1269        assert!(!c.break_batch_on_consume_fail);
1270        assert!(!c.batch);
1271        assert!(!c.use_message_body_for_sql);
1272        assert!(!c.allow_dynamic_query);
1273        assert!(c.ssl_mode.is_none());
1274        assert!(c.ssl_root_cert.is_none());
1275        assert!(c.ssl_cert.is_none());
1276        assert!(c.ssl_key.is_none());
1277        // SQL-005/SQL-011/SQL-016/SQL-002/SQL-015/SQL-017/SQL-018 defaults
1278        assert!(!c.always_populate_statement);
1279        assert!(c.allow_named_parameters);
1280        assert!(c.fetch_size.is_none());
1281        assert_eq!(c.transaction_mode, TransactionMode::Auto);
1282        assert!(c.repeat_count.is_none());
1283        assert_eq!(c.processing_strategy, ProcessingStrategy::Direct);
1284        assert_eq!(c.poll_strategy, PollStrategy::Sequential);
1285    }
1286
1287    #[test]
1288    fn ssl_none_by_default() {
1289        let c =
1290            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
1291        assert!(c.ssl_mode.is_none());
1292        assert!(c.ssl_root_cert.is_none());
1293        assert!(c.ssl_cert.is_none());
1294        assert!(c.ssl_key.is_none());
1295    }
1296
1297    #[test]
1298    fn ssl_mode_from_uri() {
1299        let c = SqlEndpointConfig::from_uri(
1300            "sql:select 1?db_url=postgres://localhost/test&sslMode=require",
1301        )
1302        .unwrap();
1303        assert_eq!(c.ssl_mode, Some("require".to_string()));
1304        assert!(c.ssl_root_cert.is_none());
1305    }
1306
1307    #[test]
1308    fn ssl_all_params_from_uri() {
1309        let c = SqlEndpointConfig::from_uri(
1310            "sql:select 1?db_url=postgres://localhost/test&sslMode=require&sslRootCert=/ca.pem&sslCert=/cert.pem&sslKey=/key.pem",
1311        )
1312        .unwrap();
1313        assert_eq!(c.ssl_mode, Some("require".to_string()));
1314        assert_eq!(c.ssl_root_cert, Some("/ca.pem".to_string()));
1315        assert_eq!(c.ssl_cert, Some("/cert.pem".to_string()));
1316        assert_eq!(c.ssl_key, Some("/key.pem".to_string()));
1317    }
1318
1319    #[test]
1320    fn ssl_global_applied_to_endpoint() {
1321        let mut c =
1322            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
1323        let global = SqlGlobalConfig::default()
1324            .with_ssl_mode("require")
1325            .with_ssl_root_cert("/etc/ssl/ca.pem");
1326        c.apply_defaults(&global);
1327        assert_eq!(c.ssl_mode, Some("require".to_string()));
1328        assert_eq!(c.ssl_root_cert, Some("/etc/ssl/ca.pem".to_string()));
1329        assert!(c.ssl_cert.is_none());
1330        assert!(c.ssl_key.is_none());
1331    }
1332
1333    #[test]
1334    fn ssl_uri_overrides_global() {
1335        let mut c = SqlEndpointConfig::from_uri(
1336            "sql:select 1?db_url=postgres://localhost/test&sslMode=verify-full",
1337        )
1338        .unwrap();
1339        let global = SqlGlobalConfig::default().with_ssl_mode("require");
1340        c.apply_defaults(&global);
1341        assert_eq!(c.ssl_mode, Some("verify-full".to_string()));
1342    }
1343
1344    #[test]
1345    fn config_wrong_scheme() {
1346        assert!(SqlEndpointConfig::from_uri("redis://localhost:6379").is_err());
1347    }
1348
1349    #[test]
1350    fn config_missing_db_url() {
1351        assert!(SqlEndpointConfig::from_uri("sql:select 1").is_err());
1352    }
1353
1354    #[test]
1355    fn config_output_type_select_one() {
1356        let c = SqlEndpointConfig::from_uri(
1357            "sql:select 1?db_url=postgres://localhost/test&outputType=SelectOne",
1358        )
1359        .unwrap();
1360        assert_eq!(c.output_type, SqlOutputType::SelectOne);
1361    }
1362
1363    #[test]
1364    fn config_output_type_stream_list() {
1365        let c = SqlEndpointConfig::from_uri(
1366            "sql:select 1?db_url=postgres://localhost/test&outputType=StreamList",
1367        )
1368        .unwrap();
1369        assert_eq!(c.output_type, SqlOutputType::StreamList);
1370    }
1371
1372    #[test]
1373    fn in_separator_default() {
1374        let c =
1375            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
1376        assert_eq!(c.in_separator, ", ");
1377    }
1378
1379    #[test]
1380    fn in_separator_from_uri() {
1381        let c = SqlEndpointConfig::from_uri(
1382            "sql:select 1?db_url=postgres://localhost/test&inSeparator=;",
1383        )
1384        .unwrap();
1385        assert_eq!(c.in_separator, ";");
1386    }
1387
1388    #[test]
1389    fn in_separator_empty_rejected() {
1390        let result = SqlEndpointConfig::from_uri(
1391            "sql:select 1?db_url=postgres://localhost/test&inSeparator=",
1392        );
1393        assert!(result.is_err());
1394        let msg = format!("{:?}", result.unwrap_err());
1395        assert!(msg.contains("inSeparator") || msg.contains("empty"));
1396    }
1397
1398    #[test]
1399    fn config_consumer_options() {
1400        let c = SqlEndpointConfig::from_uri(
1401            "sql:select * from t?db_url=postgres://localhost/test&delay=2000&initialDelay=500&maxMessagesPerPoll=10&onConsume=update t set done=true where id=:#id&onConsumeFailed=update t set failed=true where id=:#id&onConsumeBatchComplete=delete from t where done=true&routeEmptyResultSet=true&useIterator=false&expectedUpdateCount=1&breakBatchOnConsumeFail=true"
1402        ).unwrap();
1403        assert_eq!(c.delay_ms, 2000);
1404        assert_eq!(c.initial_delay_ms, 500);
1405        assert_eq!(c.max_messages_per_poll, Some(10));
1406        assert_eq!(
1407            c.on_consume,
1408            Some("update t set done=true where id=:#id".to_string())
1409        );
1410        assert_eq!(
1411            c.on_consume_failed,
1412            Some("update t set failed=true where id=:#id".to_string())
1413        );
1414        assert_eq!(
1415            c.on_consume_batch_complete,
1416            Some("delete from t where done=true".to_string())
1417        );
1418        assert!(c.route_empty_result_set);
1419        assert!(!c.use_iterator);
1420        assert_eq!(c.expected_update_count, Some(1));
1421        assert!(c.break_batch_on_consume_fail);
1422        assert!(!c.bridge_error_handler);
1423    }
1424
1425    #[test]
1426    fn config_producer_options() {
1427        let c = SqlEndpointConfig::from_uri(
1428            "sql:insert into t values (#)?db_url=postgres://localhost/test&batch=true&useMessageBodyForSql=true&noop=true"
1429        ).unwrap();
1430        assert!(c.batch);
1431        assert!(c.use_message_body_for_sql);
1432        assert!(c.noop);
1433    }
1434
1435    #[test]
1436    fn config_pool_options() {
1437        let c = SqlEndpointConfig::from_uri(
1438            "sql:select 1?db_url=postgres://localhost/test&maxConnections=20&minConnections=3&idleTimeoutSecs=600&maxLifetimeSecs=3600"
1439        ).unwrap();
1440        assert_eq!(c.max_connections, Some(20));
1441        assert_eq!(c.min_connections, Some(3));
1442        assert_eq!(c.idle_timeout_secs, Some(600));
1443        assert_eq!(c.max_lifetime_secs, Some(3600));
1444    }
1445
1446    #[test]
1447    fn config_query_with_special_chars() {
1448        let c = SqlEndpointConfig::from_uri(
1449            "sql:select * from users where name = :#name and age > #?db_url=postgres://localhost/test",
1450        )
1451        .unwrap();
1452        assert_eq!(
1453            c.query,
1454            "select * from users where name = :#name and age > #"
1455        );
1456    }
1457
1458    #[test]
1459    fn output_type_from_str() {
1460        assert_eq!(
1461            "SelectList".parse::<SqlOutputType>().unwrap(),
1462            SqlOutputType::SelectList
1463        );
1464        assert_eq!(
1465            "SelectOne".parse::<SqlOutputType>().unwrap(),
1466            SqlOutputType::SelectOne
1467        );
1468        assert_eq!(
1469            "StreamList".parse::<SqlOutputType>().unwrap(),
1470            SqlOutputType::StreamList
1471        );
1472        assert!("Invalid".parse::<SqlOutputType>().is_err());
1473    }
1474
1475    // SQL-014: file-not-found is now detected during async resolve_file_query(), not from_uri
1476    #[tokio::test]
1477    async fn config_file_not_found() {
1478        let mut config = SqlEndpointConfig::from_uri(
1479            "sql:file:/nonexistent/path/query.sql?db_url=postgres://localhost/test",
1480        )
1481        .expect("from_uri should defer file reading");
1482        // from_uri no longer reads the file — source_path is set, query is empty
1483        assert_eq!(
1484            config.source_path,
1485            Some("/nonexistent/path/query.sql".to_string())
1486        );
1487        assert!(config.query.is_empty());
1488
1489        // Error occurs during async resolution
1490        let result = config.resolve_file_query().await;
1491        assert!(result.is_err());
1492        let msg = format!("{:?}", result.unwrap_err());
1493        assert!(msg.contains("Failed to read SQL file") || msg.contains("nonexistent"));
1494    }
1495
1496    // SQL-014: file query is now resolved asynchronously
1497    #[tokio::test]
1498    async fn config_file_query() {
1499        use std::io::Write;
1500        let unique_name = format!(
1501            "test_sql_query_{}.sql",
1502            std::time::SystemTime::now()
1503                .duration_since(std::time::UNIX_EPOCH)
1504                .unwrap_or_default()
1505                .as_nanos()
1506        );
1507        let mut tmp = std::env::temp_dir();
1508        tmp.push(unique_name);
1509        {
1510            let mut f = std::fs::File::create(&tmp).unwrap();
1511            writeln!(f, "SELECT * FROM users").unwrap();
1512        }
1513        let uri = format!(
1514            "sql:file:{}?db_url=postgres://localhost/test",
1515            tmp.display()
1516        );
1517        let mut c = SqlEndpointConfig::from_uri(&uri).unwrap();
1518        // query is empty until async resolution
1519        assert!(c.query.is_empty());
1520        assert_eq!(c.source_path, Some(tmp.to_string_lossy().into_owned()));
1521
1522        // Resolve asynchronously
1523        c.resolve_file_query()
1524            .await
1525            .expect("file query should resolve");
1526        assert_eq!(c.query, "SELECT * FROM users");
1527        std::fs::remove_file(&tmp).ok();
1528    }
1529
1530    // New tests for config contract
1531    #[test]
1532    fn pool_fields_none_when_not_set() {
1533        let c =
1534            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
1535        assert_eq!(c.max_connections, None);
1536        assert_eq!(c.min_connections, None);
1537        assert_eq!(c.idle_timeout_secs, None);
1538        assert_eq!(c.max_lifetime_secs, None);
1539    }
1540
1541    #[test]
1542    fn apply_defaults_fills_none() {
1543        let mut c =
1544            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
1545        let global = SqlGlobalConfig {
1546            max_connections: 10,
1547            min_connections: 2,
1548            idle_timeout_secs: 600,
1549            max_lifetime_secs: 3600,
1550            ssl_mode: None,
1551            ssl_root_cert: None,
1552            ssl_cert: None,
1553            ssl_key: None,
1554            retry: NetworkRetryPolicy::default(),
1555        };
1556        c.apply_defaults(&global);
1557        assert_eq!(c.max_connections, Some(10));
1558        assert_eq!(c.min_connections, Some(2));
1559        assert_eq!(c.idle_timeout_secs, Some(600));
1560        assert_eq!(c.max_lifetime_secs, Some(3600));
1561        assert!(c.ssl_mode.is_none());
1562        assert!(c.ssl_root_cert.is_none());
1563        assert!(c.ssl_cert.is_none());
1564        assert!(c.ssl_key.is_none());
1565    }
1566
1567    #[test]
1568    fn apply_defaults_does_not_override() {
1569        let mut c = SqlEndpointConfig::from_uri(
1570            "sql:select 1?db_url=postgres://localhost/test&maxConnections=99&minConnections=5",
1571        )
1572        .unwrap();
1573        let global = SqlGlobalConfig {
1574            max_connections: 10,
1575            min_connections: 2,
1576            idle_timeout_secs: 600,
1577            max_lifetime_secs: 3600,
1578            ssl_mode: None,
1579            ssl_root_cert: None,
1580            ssl_cert: None,
1581            ssl_key: None,
1582            retry: NetworkRetryPolicy::default(),
1583        };
1584        c.apply_defaults(&global);
1585        // URI-set values should NOT be overridden
1586        assert_eq!(c.max_connections, Some(99));
1587        assert_eq!(c.min_connections, Some(5));
1588        // None fields should be filled from global
1589        assert_eq!(c.idle_timeout_secs, Some(600));
1590        assert_eq!(c.max_lifetime_secs, Some(3600));
1591    }
1592
1593    #[test]
1594    fn resolve_defaults_fills_remaining() {
1595        let mut c = SqlEndpointConfig::from_uri(
1596            "sql:select 1?db_url=postgres://localhost/test&maxConnections=7",
1597        )
1598        .unwrap();
1599        c.resolve_defaults();
1600        assert_eq!(c.max_connections, Some(7)); // from URI
1601        assert_eq!(c.min_connections, Some(1)); // from defaults
1602        assert_eq!(c.idle_timeout_secs, Some(300)); // from defaults
1603        assert_eq!(c.max_lifetime_secs, Some(1800)); // from defaults
1604    }
1605
1606    #[test]
1607    fn global_config_builder() {
1608        let c = SqlGlobalConfig::default()
1609            .with_max_connections(20)
1610            .with_min_connections(3)
1611            .with_idle_timeout_secs(600)
1612            .with_max_lifetime_secs(3600)
1613            .with_ssl_mode("require")
1614            .with_ssl_root_cert("/ca.pem")
1615            .with_ssl_cert("/cert.pem")
1616            .with_ssl_key("/key.pem");
1617        assert_eq!(c.max_connections, 20);
1618        assert_eq!(c.min_connections, 3);
1619        assert_eq!(c.idle_timeout_secs, 600);
1620        assert_eq!(c.max_lifetime_secs, 3600);
1621        assert_eq!(c.ssl_mode, Some("require".to_string()));
1622        assert_eq!(c.ssl_root_cert, Some("/ca.pem".to_string()));
1623        assert_eq!(c.ssl_cert, Some("/cert.pem".to_string()));
1624        assert_eq!(c.ssl_key, Some("/key.pem".to_string()));
1625    }
1626
1627    #[test]
1628    fn enrich_postgres_ssl_mode() {
1629        let mut c = SqlEndpointConfig::from_uri(
1630            "sql:select 1?db_url=postgres://localhost/test&sslMode=require",
1631        )
1632        .unwrap();
1633        c.resolve_defaults();
1634        let url = enrich_db_url_with_ssl(&c.db_url, &c).unwrap();
1635        assert!(url.contains("sslmode=require"), "got: {}", url);
1636    }
1637
1638    #[test]
1639    fn enrich_postgres_all_ssl() {
1640        let mut c = SqlEndpointConfig::from_uri(
1641            "sql:select 1?db_url=postgres://localhost/test&sslMode=require&sslRootCert=/ca.pem&sslCert=/cert.pem&sslKey=/key.pem",
1642        )
1643        .unwrap();
1644        c.resolve_defaults();
1645        let url = enrich_db_url_with_ssl(&c.db_url, &c).unwrap();
1646        assert!(url.contains("sslmode=require"), "got: {}", url);
1647        assert!(url.contains("sslrootcert="), "got: {}", url);
1648        assert!(url.contains("sslcert="), "got: {}", url);
1649        assert!(url.contains("sslkey="), "got: {}", url);
1650    }
1651
1652    #[test]
1653    fn enrich_mysql_ssl() {
1654        let mut c = SqlEndpointConfig::from_uri(
1655            "sql:select 1?db_url=mysql://localhost/test&sslMode=require",
1656        )
1657        .unwrap();
1658        c.resolve_defaults();
1659        let url = enrich_db_url_with_ssl(&c.db_url, &c).unwrap();
1660        assert!(url.contains("ssl-mode=require"), "got: {}", url);
1661    }
1662
1663    #[test]
1664    fn enrich_existing_query_params() {
1665        let mut c = SqlEndpointConfig::from_uri(
1666            "sql:select 1?db_url=postgres://localhost/test?existing=1&sslMode=require",
1667        )
1668        .unwrap();
1669        c.resolve_defaults();
1670        let url = enrich_db_url_with_ssl(&c.db_url, &c).unwrap();
1671        assert!(url.contains("existing=1"), "got: {}", url);
1672        assert!(url.contains("sslmode=require"), "got: {}", url);
1673    }
1674
1675    #[test]
1676    fn enrich_override_existing() {
1677        let mut c = SqlEndpointConfig::from_uri(
1678            "sql:select 1?db_url=postgres://localhost/test?sslmode=allow&sslMode=require",
1679        )
1680        .unwrap();
1681        c.resolve_defaults();
1682        let url = enrich_db_url_with_ssl(&c.db_url, &c).unwrap();
1683        assert!(url.contains("sslmode=require"), "got: {}", url);
1684        assert!(!url.contains("sslmode=allow"), "got: {}", url);
1685    }
1686
1687    #[test]
1688    fn enrich_applies_postgres_defaults() {
1689        let mut c =
1690            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
1691        c.resolve_defaults();
1692        let url = enrich_db_url_with_ssl(&c.db_url, &c).unwrap();
1693        // Default ssl_mode and connect_timeout are applied at enrichment time
1694        assert!(
1695            url.contains("sslmode=require"),
1696            "expected sslmode=require, got: {}",
1697            url
1698        );
1699        assert!(
1700            url.contains("connect_timeout=10"),
1701            "expected connect_timeout=10, got: {}",
1702            url
1703        );
1704    }
1705
1706    #[test]
1707    fn enrich_mysql_defaults_to_prefer() {
1708        let mut c =
1709            SqlEndpointConfig::from_uri("sql:select 1?db_url=mysql://localhost/test").unwrap();
1710        c.resolve_defaults();
1711        let url = enrich_db_url_with_ssl(&c.db_url, &c).unwrap();
1712        assert!(
1713            url.contains("ssl-mode=prefer"),
1714            "expected ssl-mode=prefer, got: {}",
1715            url
1716        );
1717        assert!(
1718            url.contains("connect_timeout=10"),
1719            "expected connect_timeout=10, got: {}",
1720            url
1721        );
1722    }
1723
1724    #[test]
1725    fn pg_url_sslmode_disable_preserved_when_config_absent() {
1726        let url = enrich_db_url_with_ssl_params(
1727            "postgres://localhost/test?sslmode=disable",
1728            None,
1729            None,
1730            None,
1731            None,
1732        )
1733        .unwrap();
1734        assert!(url.contains("sslmode=disable"), "got: {}", url);
1735        assert!(!url.contains("sslmode=require"), "got: {}", url);
1736        assert!(url.contains("connect_timeout=10"), "got: {}", url);
1737    }
1738
1739    #[test]
1740    fn pg_url_sslmode_require_and_verify_full_preserved_when_config_absent() {
1741        for mode in ["require", "verify-full"] {
1742            let url = enrich_db_url_with_ssl_params(
1743                &format!("postgres://localhost/test?sslmode={mode}"),
1744                None,
1745                None,
1746                None,
1747                None,
1748            )
1749            .unwrap();
1750            assert!(url.contains(&format!("sslmode={mode}")), "got: {}", url);
1751        }
1752    }
1753
1754    #[test]
1755    fn mysql_url_ssl_mode_disable_preserved_when_config_absent() {
1756        let url = enrich_db_url_with_ssl_params(
1757            "mysql://localhost/test?ssl-mode=disable",
1758            None,
1759            None,
1760            None,
1761            None,
1762        )
1763        .unwrap();
1764        assert!(url.contains("ssl-mode=disable"), "got: {}", url);
1765        assert!(!url.contains("ssl-mode=prefer"), "got: {}", url);
1766    }
1767
1768    #[test]
1769    fn config_overrides_url_mysql() {
1770        let url = enrich_db_url_with_ssl_params(
1771            "mysql://localhost/test?ssl-mode=disable",
1772            Some("require"),
1773            None,
1774            None,
1775            None,
1776        )
1777        .unwrap();
1778        assert!(url.contains("ssl-mode=require"), "got: {}", url);
1779        assert!(!url.contains("ssl-mode=disable"), "got: {}", url);
1780    }
1781
1782    #[test]
1783    fn enrich_preserves_explicit_connect_timeout() {
1784        let mut c = SqlEndpointConfig::from_uri(
1785            "sql:select 1?db_url=postgres://localhost/test?connect_timeout=5",
1786        )
1787        .unwrap();
1788        c.resolve_defaults();
1789        let url = enrich_db_url_with_ssl(&c.db_url, &c).unwrap();
1790        assert!(
1791            url.contains("connect_timeout=5"),
1792            "expected explicit connect_timeout=5 preserved, got: {}",
1793            url
1794        );
1795        assert!(
1796            url.contains("sslmode=require"),
1797            "expected sslmode=require, got: {}",
1798            url
1799        );
1800    }
1801
1802    #[test]
1803    fn enrich_url_encodes_paths() {
1804        let mut c = SqlEndpointConfig::from_uri(
1805            "sql:select 1?db_url=postgres://localhost/test&sslRootCert=/path/to/my%20cert.pem",
1806        )
1807        .unwrap();
1808        c.resolve_defaults();
1809        let url = enrich_db_url_with_ssl(&c.db_url, &c).unwrap();
1810        assert!(url.contains("sslrootcert="), "got: {}", url);
1811    }
1812
1813    #[test]
1814    fn enrich_unsupported_scheme_returns_unchanged() {
1815        let mut c = SqlEndpointConfig::from_uri(
1816            "sql:select 1?db_url=sqlite://localhost/test.db&sslMode=require",
1817        )
1818        .unwrap();
1819        c.resolve_defaults();
1820        let url = enrich_db_url_with_ssl(&c.db_url, &c).unwrap();
1821        assert_eq!(url, "sqlite://localhost/test.db");
1822    }
1823
1824    /// Pins both sides of the SQLite SSL-ignore diagnostic: it must stay
1825    /// below WARN (one env-driven config shared by SQLite and Postgres
1826    /// datasources must not warn on every boot) and it must still be emitted
1827    /// at DEBUG. `tracing-test` here is built with `no-env-filter`, so the
1828    /// subscriber captures every level; assert on the rendered level rather
1829    /// than on message presence alone.
1830    #[tracing_test::traced_test]
1831    #[test]
1832    fn sqlite_ssl_options_debug_not_warn() {
1833        let url = enrich_db_url_with_ssl_params(
1834            "sqlite://test.db?mode=rwc",
1835            Some("require"),
1836            None,
1837            None,
1838            None,
1839        )
1840        .expect("sqlite URL enrichment must succeed");
1841        assert_eq!(url, "sqlite://test.db?mode=rwc");
1842
1843        logs_assert(|lines| {
1844            let loud: Vec<&str> = lines
1845                .iter()
1846                .filter(|line| line.contains(" WARN ") || line.contains(" ERROR "))
1847                .copied()
1848                .collect();
1849            if !loud.is_empty() {
1850                return Err(format!(
1851                    "SQLite SSL enrichment must log nothing at WARN or above, got: {loud:?}"
1852                ));
1853            }
1854
1855            let diagnostic = lines.iter().any(|line| {
1856                line.contains(" DEBUG ") && line.contains("SQLite does not support SSL/TLS")
1857            });
1858            if diagnostic {
1859                Ok(())
1860            } else {
1861                Err("SQLite SSL enrichment must keep its ignore diagnostic at DEBUG level, but none was captured".to_string())
1862            }
1863        });
1864    }
1865
1866    #[test]
1867    fn enrich_invalid_url_returns_error() {
1868        let mut c = SqlEndpointConfig::from_uri(
1869            "sql:select 1?db_url=postgres://localhost/test&sslMode=require",
1870        )
1871        .unwrap();
1872        c.resolve_defaults();
1873        let result = enrich_db_url_with_ssl("://not-a-valid-url", &c);
1874        assert!(result.is_err());
1875    }
1876
1877    // --- Phase B hardening tests ---
1878
1879    // SQL-010: Debug output redacts credentials
1880    #[test]
1881    fn debug_redacts_db_url_with_password() {
1882        let c = SqlEndpointConfig::from_uri(
1883            "sql:select 1?db_url=postgres://user:secret123@localhost/test",
1884        )
1885        .unwrap();
1886        let debug_output = format!("{:?}", c);
1887        assert!(
1888            !debug_output.contains("secret123"),
1889            "Debug output must not contain password: {}",
1890            debug_output
1891        );
1892        assert!(
1893            debug_output.contains("***"),
1894            "Debug output must contain redacted marker: {}",
1895            debug_output
1896        );
1897    }
1898
1899    #[test]
1900    fn debug_redacts_ssl_key() {
1901        let c = SqlEndpointConfig::from_uri(
1902            "sql:select 1?db_url=postgres://localhost/test&sslKey=/secret/key.pem",
1903        )
1904        .unwrap();
1905        let debug_output = format!("{:?}", c);
1906        assert!(
1907            !debug_output.contains("/secret/key.pem"),
1908            "Debug output must not contain ssl_key path: {}",
1909            debug_output
1910        );
1911    }
1912
1913    #[test]
1914    fn debug_global_config_redacts_ssl_key() {
1915        let c = SqlGlobalConfig::default().with_ssl_key("/secret/key.pem");
1916        let debug_output = format!("{:?}", c);
1917        assert!(
1918            !debug_output.contains("/secret/key.pem"),
1919            "Debug output must not contain ssl_key path: {}",
1920            debug_output
1921        );
1922        assert!(
1923            debug_output.contains("***"),
1924            "Debug output must contain redacted marker: {}",
1925            debug_output
1926        );
1927    }
1928
1929    #[test]
1930    fn redact_db_url_with_credentials() {
1931        assert_eq!(
1932            redact_db_url("postgres://user:pass@host/db"),
1933            "postgres://***:***@host/db"
1934        );
1935    }
1936
1937    #[test]
1938    fn redact_db_url_without_credentials() {
1939        assert_eq!(redact_db_url("sqlite::memory:"), "sqlite::memory:");
1940    }
1941
1942    #[test]
1943    fn redact_db_url_invalid_returns_original() {
1944        assert_eq!(redact_db_url("not-a-url"), "not-a-url");
1945    }
1946
1947    #[test]
1948    fn redact_db_url_invalid_with_credentials_redacts() {
1949        // Port out of range (99999) makes url::Url::parse fail, but the raw
1950        // string carries userinfo. The Err branch must still redact it rather
1951        // than return the credential-bearing string verbatim (rc-7rup).
1952        let redacted = redact_db_url("postgres://user:secret@host:99999/db");
1953        assert!(
1954            !redacted.contains("secret"),
1955            "password must be redacted in unparseable URL: {redacted}"
1956        );
1957        assert!(
1958            !redacted.contains("user:secret"),
1959            "userinfo must be redacted: {redacted}"
1960        );
1961        assert!(
1962            !redacted.contains("user"),
1963            "username must be redacted: {redacted}"
1964        );
1965    }
1966
1967    #[test]
1968    fn redact_db_url_at_before_scheme_returns_original() {
1969        // `@` preceding `://` is not userinfo in a valid position; the
1970        // best-effort redactor leaves it unchanged (no false redaction).
1971        assert_eq!(redact_db_url("foo@bar://baz"), "foo@bar://baz");
1972    }
1973
1974    // SQL-004: usePlaceholder parsing
1975    #[test]
1976    fn use_placeholder_defaults_to_true() {
1977        let c =
1978            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
1979        assert!(c.use_placeholder);
1980    }
1981
1982    #[test]
1983    fn use_placeholder_false_from_uri() {
1984        let c = SqlEndpointConfig::from_uri(
1985            "sql:select 1?db_url=postgres://localhost/test&usePlaceholder=false",
1986        )
1987        .unwrap();
1988        assert!(!c.use_placeholder);
1989    }
1990
1991    #[test]
1992    fn use_placeholder_true_from_uri() {
1993        let c = SqlEndpointConfig::from_uri(
1994            "sql:select 1?db_url=postgres://localhost/test&usePlaceholder=true",
1995        )
1996        .unwrap();
1997        assert!(c.use_placeholder);
1998    }
1999
2000    // SQL-004: strict boolean parsing — invalid values rejected
2001    #[test]
2002    fn use_placeholder_rejects_invalid_value() {
2003        let result = SqlEndpointConfig::from_uri(
2004            "sql:select 1?db_url=postgres://localhost/test&usePlaceholder=1",
2005        );
2006        assert!(result.is_err());
2007        let msg = format!("{:?}", result.unwrap_err());
2008        assert!(msg.contains("usePlaceholder") && msg.contains("true") && msg.contains("false"));
2009    }
2010
2011    #[test]
2012    fn use_placeholder_rejects_typo_tru() {
2013        let result = SqlEndpointConfig::from_uri(
2014            "sql:select 1?db_url=postgres://localhost/test&usePlaceholder=tru",
2015        );
2016        assert!(result.is_err());
2017    }
2018
2019    #[test]
2020    fn use_placeholder_rejects_yes() {
2021        let result = SqlEndpointConfig::from_uri(
2022            "sql:select 1?db_url=postgres://localhost/test&usePlaceholder=yes",
2023        );
2024        assert!(result.is_err());
2025    }
2026
2027    #[test]
2028    fn noop_rejects_invalid_value() {
2029        let result =
2030            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test&noop=1");
2031        assert!(result.is_err());
2032        let msg = format!("{:?}", result.unwrap_err());
2033        assert!(msg.contains("noop"));
2034    }
2035
2036    #[test]
2037    fn batch_rejects_invalid_value() {
2038        let result =
2039            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test&batch=yes");
2040        assert!(result.is_err());
2041        let msg = format!("{:?}", result.unwrap_err());
2042        assert!(msg.contains("batch"));
2043    }
2044
2045    #[test]
2046    fn route_empty_result_set_rejects_invalid_value() {
2047        let result = SqlEndpointConfig::from_uri(
2048            "sql:select 1?db_url=postgres://localhost/test&routeEmptyResultSet=on",
2049        );
2050        assert!(result.is_err());
2051    }
2052
2053    #[test]
2054    fn use_iterator_rejects_invalid_value() {
2055        let result = SqlEndpointConfig::from_uri(
2056            "sql:select 1?db_url=postgres://localhost/test&useIterator=1",
2057        );
2058        assert!(result.is_err());
2059    }
2060
2061    #[test]
2062    fn break_batch_on_consume_fail_rejects_invalid_value() {
2063        let result = SqlEndpointConfig::from_uri(
2064            "sql:select 1?db_url=postgres://localhost/test&breakBatchOnConsumeFail=yes",
2065        );
2066        assert!(result.is_err());
2067    }
2068
2069    #[test]
2070    fn use_message_body_for_sql_rejects_invalid_value() {
2071        let result = SqlEndpointConfig::from_uri(
2072            "sql:select 1?db_url=postgres://localhost/test&useMessageBodyForSql=1",
2073        );
2074        assert!(result.is_err());
2075    }
2076
2077    // Case-insensitive true/false still works
2078    #[test]
2079    fn boolean_params_case_insensitive() {
2080        let c = SqlEndpointConfig::from_uri(
2081            "sql:select 1?db_url=postgres://localhost/test&usePlaceholder=TRUE&noop=FALSE&batch=True&useIterator=False&bridgeErrorHandler=TRUE",
2082        )
2083        .unwrap();
2084        assert!(c.use_placeholder);
2085        assert!(!c.noop);
2086        assert!(c.batch);
2087        assert!(!c.use_iterator);
2088        assert!(c.bridge_error_handler);
2089    }
2090
2091    // SQL-022: multi-char placeholder rejected
2092    #[test]
2093    fn multi_char_placeholder_rejected() {
2094        let result = SqlEndpointConfig::from_uri(
2095            "sql:select 1?db_url=postgres://localhost/test&placeholder=##",
2096        );
2097        assert!(result.is_err());
2098        let msg = format!("{:?}", result.unwrap_err());
2099        assert!(msg.contains("placeholder") && msg.contains("one character"));
2100    }
2101
2102    #[test]
2103    fn non_ascii_placeholder_rejected() {
2104        let result = SqlEndpointConfig::from_uri(
2105            "sql:select 1?db_url=postgres://localhost/test&placeholder=%C2%A2",
2106        );
2107        assert!(result.is_err());
2108    }
2109
2110    #[test]
2111    fn single_char_placeholder_accepted() {
2112        let c = SqlEndpointConfig::from_uri(
2113            "sql:select 1?db_url=postgres://localhost/test&placeholder=$",
2114        )
2115        .unwrap();
2116        assert_eq!(c.placeholder, '$');
2117    }
2118
2119    #[test]
2120    fn empty_placeholder_falls_back_to_default() {
2121        // Empty string is filtered out by the original logic — falls back to '#'
2122        let c = SqlEndpointConfig::from_uri(
2123            "sql:select 1?db_url=postgres://localhost/test&placeholder=",
2124        )
2125        .unwrap();
2126        assert_eq!(c.placeholder, '#');
2127    }
2128
2129    // SQL-014: file-based SQL config test (verifies async resolution and caching)
2130    #[tokio::test]
2131    async fn file_query_cached_in_config() {
2132        use std::io::Write;
2133        let unique_name = format!(
2134            "test_sql_cached_{}.sql",
2135            std::time::SystemTime::now()
2136                .duration_since(std::time::UNIX_EPOCH)
2137                .unwrap_or_default()
2138                .as_nanos()
2139        );
2140        let mut tmp = std::env::temp_dir();
2141        tmp.push(unique_name);
2142        {
2143            let mut f = std::fs::File::create(&tmp).unwrap();
2144            writeln!(f, "SELECT * FROM cached_test").unwrap();
2145        }
2146        let uri = format!(
2147            "sql:file:{}?db_url=postgres://localhost/test",
2148            tmp.display()
2149        );
2150        let mut c = SqlEndpointConfig::from_uri(&uri).unwrap();
2151        // Query is empty before async resolution
2152        assert!(c.query.is_empty());
2153        assert_eq!(c.source_path, Some(tmp.to_string_lossy().into_owned()));
2154
2155        // Resolve asynchronously — query is cached in config
2156        c.resolve_file_query()
2157            .await
2158            .expect("resolve should succeed");
2159        assert_eq!(c.query, "SELECT * FROM cached_test");
2160
2161        // Delete the file — config still has the query
2162        std::fs::remove_file(&tmp).ok();
2163        assert_eq!(c.query, "SELECT * FROM cached_test");
2164    }
2165
2166    // --- H-03 audit sweep tests ---
2167
2168    // SQL-005: alwaysPopulateStatement
2169    #[test]
2170    fn always_populate_statement_defaults_to_false() {
2171        let c =
2172            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
2173        assert!(!c.always_populate_statement);
2174    }
2175
2176    #[test]
2177    fn always_populate_statement_from_uri() {
2178        let c = SqlEndpointConfig::from_uri(
2179            "sql:select 1?db_url=postgres://localhost/test&alwaysPopulateStatement=true",
2180        )
2181        .unwrap();
2182        assert!(c.always_populate_statement);
2183    }
2184
2185    // SQL-011: allowNamedParameters
2186    #[test]
2187    fn allow_named_parameters_defaults_to_true() {
2188        let c =
2189            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
2190        assert!(c.allow_named_parameters);
2191    }
2192
2193    #[test]
2194    fn allow_named_parameters_false_from_uri() {
2195        let c = SqlEndpointConfig::from_uri(
2196            "sql:select 1?db_url=postgres://localhost/test&allowNamedParameters=false",
2197        )
2198        .unwrap();
2199        assert!(!c.allow_named_parameters);
2200    }
2201
2202    // SQL-016: fetchSize
2203    #[test]
2204    fn fetch_size_defaults_to_none() {
2205        let c =
2206            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
2207        assert!(c.fetch_size.is_none());
2208    }
2209
2210    #[test]
2211    fn fetch_size_from_uri() {
2212        let c = SqlEndpointConfig::from_uri(
2213            "sql:select 1?db_url=postgres://localhost/test&fetchSize=1000",
2214        )
2215        .unwrap();
2216        assert_eq!(c.fetch_size, Some(1000));
2217    }
2218
2219    // SQL-002: transactionMode
2220    #[test]
2221    fn transaction_mode_defaults_to_auto() {
2222        let c =
2223            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
2224        assert_eq!(c.transaction_mode, TransactionMode::Auto);
2225    }
2226
2227    #[test]
2228    fn transaction_mode_managed_from_uri() {
2229        let c = SqlEndpointConfig::from_uri(
2230            "sql:select 1?db_url=postgres://localhost/test&transactionMode=Managed",
2231        )
2232        .unwrap();
2233        assert_eq!(c.transaction_mode, TransactionMode::Managed);
2234    }
2235
2236    #[test]
2237    fn transaction_mode_invalid_rejected() {
2238        let result = SqlEndpointConfig::from_uri(
2239            "sql:select 1?db_url=postgres://localhost/test&transactionMode=Invalid",
2240        );
2241        assert!(result.is_err());
2242    }
2243
2244    // SQL-015: repeatCount
2245    #[test]
2246    fn repeat_count_defaults_to_none() {
2247        let c =
2248            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
2249        assert!(c.repeat_count.is_none());
2250    }
2251
2252    #[test]
2253    fn repeat_count_from_uri() {
2254        let c = SqlEndpointConfig::from_uri(
2255            "sql:select 1?db_url=postgres://localhost/test&repeatCount=10",
2256        )
2257        .unwrap();
2258        assert_eq!(c.repeat_count, Some(10));
2259    }
2260
2261    // SQL-020: breakOnEmpty
2262    #[test]
2263    fn break_on_empty_defaults_to_false() {
2264        let c =
2265            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
2266        assert!(!c.break_on_empty);
2267    }
2268
2269    #[test]
2270    fn break_on_empty_true_from_uri() {
2271        let c = SqlEndpointConfig::from_uri(
2272            "sql:select 1?db_url=postgres://localhost/test&breakOnEmpty=true",
2273        )
2274        .unwrap();
2275        assert!(c.break_on_empty);
2276    }
2277
2278    #[test]
2279    fn break_on_empty_explicit_false_from_uri() {
2280        let c = SqlEndpointConfig::from_uri(
2281            "sql:select 1?db_url=postgres://localhost/test&breakOnEmpty=false",
2282        )
2283        .unwrap();
2284        assert!(!c.break_on_empty);
2285    }
2286
2287    // SQL-017: processingStrategy
2288    #[test]
2289    fn processing_strategy_defaults_to_direct() {
2290        let c =
2291            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
2292        assert_eq!(c.processing_strategy, ProcessingStrategy::Direct);
2293    }
2294
2295    #[test]
2296    fn processing_strategy_scheduled_from_uri() {
2297        let c = SqlEndpointConfig::from_uri(
2298            "sql:select 1?db_url=postgres://localhost/test&processingStrategy=Scheduled",
2299        )
2300        .unwrap();
2301        assert_eq!(c.processing_strategy, ProcessingStrategy::Scheduled);
2302    }
2303
2304    #[test]
2305    fn processing_strategy_invalid_rejected() {
2306        let result = SqlEndpointConfig::from_uri(
2307            "sql:select 1?db_url=postgres://localhost/test&processingStrategy=Invalid",
2308        );
2309        assert!(result.is_err());
2310    }
2311
2312    // SQL-018: pollStrategy
2313    #[test]
2314    fn poll_strategy_defaults_to_sequential() {
2315        let c =
2316            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
2317        assert_eq!(c.poll_strategy, PollStrategy::Sequential);
2318    }
2319
2320    #[test]
2321    fn poll_strategy_burst_from_uri() {
2322        let c = SqlEndpointConfig::from_uri(
2323            "sql:select 1?db_url=postgres://localhost/test&pollStrategy=Burst",
2324        )
2325        .unwrap();
2326        assert_eq!(c.poll_strategy, PollStrategy::Burst);
2327    }
2328
2329    #[test]
2330    fn poll_strategy_invalid_rejected() {
2331        let result = SqlEndpointConfig::from_uri(
2332            "sql:select 1?db_url=postgres://localhost/test&pollStrategy=Invalid",
2333        );
2334        assert!(result.is_err());
2335    }
2336
2337    // ── RetryPolicy (rc-ddl) ──────────────────────────────────────────────
2338
2339    #[test]
2340    fn sql_endpoint_config_has_retry_policy() {
2341        let cfg = SqlEndpointConfig::from_uri(
2342            "sql:select 1?db_url=sqlite::memory:&retryMaxAttempts=3&retryInitialDelayMs=500",
2343        )
2344        .expect("parse");
2345        assert_eq!(cfg.retry.max_attempts, 3);
2346        assert_eq!(
2347            cfg.retry.initial_delay,
2348            std::time::Duration::from_millis(500)
2349        );
2350        assert!(cfg.retry.enabled);
2351    }
2352
2353    #[test]
2354    fn sql_endpoint_config_retry_defaults_when_unspecified() {
2355        let cfg =
2356            SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite::memory:").expect("parse");
2357        // When URI has no retry params, retry defaults to NetworkRetryPolicy::default()
2358        assert!(cfg.retry.enabled);
2359        assert_eq!(cfg.retry.max_attempts, 10); // default
2360    }
2361
2362    #[test]
2363    fn sql_global_config_has_retry_default() {
2364        let cfg = SqlGlobalConfig::default();
2365        assert!(cfg.retry.enabled);
2366    }
2367
2368    #[test]
2369    fn retry_policy_parse_full_uri_params() {
2370        let cfg = SqlEndpointConfig::from_uri(
2371            "sql:select 1?db_url=sqlite::memory:&retryEnabled=false&retryMaxAttempts=7&retryInitialDelayMs=1000&retryMultiplier=3.0&retryMaxDelayMs=60000&retryJitter=0.5",
2372        )
2373        .expect("parse");
2374        assert!(!cfg.retry.enabled);
2375        assert_eq!(cfg.retry.max_attempts, 7);
2376        assert_eq!(
2377            cfg.retry.initial_delay,
2378            std::time::Duration::from_millis(1000)
2379        );
2380        assert!((cfg.retry.multiplier - 3.0).abs() < f64::EPSILON);
2381        assert_eq!(cfg.retry.max_delay, std::time::Duration::from_millis(60000));
2382        assert!((cfg.retry.jitter_factor - 0.5).abs() < f64::EPSILON);
2383    }
2384
2385    #[test]
2386    fn retry_policy_from_uri_survives_apply_defaults_with_global() {
2387        let mut ep = SqlEndpointConfig::from_uri(
2388            "sql:select 1?db_url=sqlite::memory:&retryMaxAttempts=10&retryInitialDelayMs=500",
2389        )
2390        .expect("parse");
2391        let global = SqlGlobalConfig::default(); // global has default retry (max_attempts=10)
2392        ep.apply_defaults(&global);
2393        // URI values survive when retry_set_from_uri is true
2394        assert_eq!(ep.retry.max_attempts, 10);
2395        assert_eq!(
2396            ep.retry.initial_delay,
2397            std::time::Duration::from_millis(500)
2398        );
2399    }
2400
2401    #[test]
2402    fn retry_policy_falls_back_to_global_when_uri_has_no_retry_params() {
2403        let mut ep =
2404            SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite::memory:").expect("parse");
2405        let mut global = SqlGlobalConfig::default();
2406        global.retry.max_attempts = 7;
2407        ep.apply_defaults(&global);
2408        // When URI has no retry params, global fills the gap
2409        assert_eq!(ep.retry.max_attempts, 7);
2410    }
2411
2412    #[test]
2413    fn from_uri_with_datasource_name() {
2414        let cfg = SqlEndpointConfig::from_uri("sql:SELECT 1?datasource=orders").unwrap();
2415        assert_eq!(cfg.datasource_name.as_deref(), Some("orders"));
2416        assert!(cfg.db_url.is_empty());
2417    }
2418
2419    #[test]
2420    fn from_uri_with_datasource_and_behavior_override() {
2421        let cfg =
2422            SqlEndpointConfig::from_uri("sql:SELECT 1?datasource=orders&outputType=SelectOne")
2423                .unwrap();
2424        assert_eq!(cfg.datasource_name.as_deref(), Some("orders"));
2425    }
2426
2427    #[test]
2428    fn from_uri_datasource_rejects_pool_override() {
2429        let result =
2430            SqlEndpointConfig::from_uri("sql:SELECT 1?datasource=orders&maxConnections=50");
2431        assert!(result.is_err());
2432        let msg = result.unwrap_err().to_string();
2433        assert!(msg.contains("pool-affecting"));
2434    }
2435
2436    #[test]
2437    fn from_uri_neither_datasource_nor_db_url_is_error() {
2438        let result = SqlEndpointConfig::from_uri("sql:SELECT 1");
2439        assert!(result.is_err());
2440    }
2441
2442    #[test]
2443    fn from_uri_db_url_inline_still_works() {
2444        let cfg =
2445            SqlEndpointConfig::from_uri("sql:SELECT 1?db_url=postgres://localhost/test").unwrap();
2446        assert!(cfg.datasource_name.is_none());
2447        assert_eq!(cfg.db_url, "postgres://localhost/test");
2448    }
2449
2450    #[test]
2451    fn from_uri_datasource_rejects_ssl_mode() {
2452        let result = SqlEndpointConfig::from_uri("sql:SELECT 1?datasource=orders&sslMode=require");
2453        assert!(result.is_err());
2454        let msg = result.unwrap_err().to_string();
2455        assert!(msg.contains("pool-affecting"));
2456    }
2457
2458    #[test]
2459    fn from_uri_datasource_rejects_ssl_root_cert() {
2460        let result =
2461            SqlEndpointConfig::from_uri("sql:SELECT 1?datasource=orders&sslRootCert=/ca.pem");
2462        assert!(result.is_err());
2463    }
2464
2465    #[test]
2466    fn from_uri_datasource_rejects_db_url() {
2467        let result = SqlEndpointConfig::from_uri(
2468            "sql:SELECT 1?datasource=orders&db_url=postgres://evil:5432/pwned",
2469        );
2470        assert!(result.is_err());
2471        let msg = result.unwrap_err().to_string();
2472        assert!(msg.contains("db_url") && msg.contains("datasource"));
2473    }
2474}