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    /// `file:` operands naming a registered embedded asset
737    /// (`camel-embedded:<asset path>` or its percent-encoded spelling) resolve
738    /// from the boot registry with zero filesystem access; an unregistered
739    /// reference never probes the host filesystem — the prefix is reserved (see
740    /// `camel-proto-compiler::embedded`). Only prefix-less values are read from
741    /// disk. The canonical spelling normally arrives through `from_uri`, whose
742    /// `parse_uri` percent-decodes the path exactly once; `resolve_ref` accepts
743    /// both spellings so a directly-placed `source_path` resolves either way.
744    ///
745    /// After this call, `self.query` contains the content (trimmed) and
746    /// `self.source_path` is retained so callers can still inspect the original
747    /// reference.
748    pub async fn resolve_file_query(&mut self) -> Result<(), CamelError> {
749        if let Some(file_path) = self.source_path.take() {
750            // Embedded references are resolved before any filesystem access.
751            // `camel-cli` registers sql assets at boot from digest-verified
752            // store entries, so a sealed artifact boots without materializing
753            // a file. The encoded spelling is private to
754            // `camel_component_api::embedded_assets`, so match it literally.
755            if file_path.starts_with(camel_component_api::embedded_assets::EMBEDDED_REF_PREFIX)
756                || file_path.starts_with(ENCODED_EMBEDDED_REF_PREFIX)
757            {
758                let Some(bytes) = camel_component_api::embedded_assets::resolve_ref(&file_path)
759                else {
760                    return Err(CamelError::Config(format!(
761                        "no embedded SQL file registered under '{file_path}'"
762                    )));
763                };
764                let contents = String::from_utf8(bytes.to_vec()).map_err(|e| {
765                    CamelError::Config(format!("Failed to read SQL file '{}': {}", file_path, e))
766                })?;
767                self.query = contents.trim().to_string();
768                self.source_path = Some(file_path);
769                return Ok(());
770            }
771
772            let contents = tokio::fs::read_to_string(&file_path).await.map_err(|e| {
773                CamelError::Config(format!("Failed to read SQL file '{}': {}", file_path, e))
774            })?;
775            self.query = contents.trim().to_string();
776            // Keep source_path as Some so tests can still verify the original path
777            self.source_path = Some(file_path);
778        }
779        Ok(())
780    }
781}
782
783/// Percent-encoded spelling of
784/// `camel_component_api::embedded_assets::EMBEDDED_REF_PREFIX`, which is
785/// private. A value carrying either spelling is resolved against the boot
786/// registry and never against the filesystem.
787const ENCODED_EMBEDDED_REF_PREFIX: &str = "camel-embedded%3A";
788
789struct SslParamMapping {
790    pg_key: &'static str,
791    mysql_key: &'static str,
792}
793
794const SSL_MAPPINGS: &[(&str, SslParamMapping)] = &[
795    (
796        "sslMode",
797        SslParamMapping {
798            pg_key: "sslmode",
799            mysql_key: "ssl-mode",
800        },
801    ),
802    (
803        "sslRootCert",
804        SslParamMapping {
805            pg_key: "sslrootcert",
806            mysql_key: "ssl-ca",
807        },
808    ),
809    (
810        "sslCert",
811        SslParamMapping {
812            pg_key: "sslcert",
813            mysql_key: "ssl-cert",
814        },
815    ),
816    (
817        "sslKey",
818        SslParamMapping {
819            pg_key: "sslkey",
820            mysql_key: "ssl-key",
821        },
822    ),
823];
824
825pub fn enrich_db_url_with_ssl(
826    db_url: &str,
827    config: &SqlEndpointConfig,
828) -> Result<String, CamelError> {
829    enrich_db_url_with_ssl_params(
830        db_url,
831        config.ssl_mode.as_deref(),
832        config.ssl_root_cert.as_deref(),
833        config.ssl_cert.as_deref(),
834        config.ssl_key.as_deref(),
835    )
836}
837
838pub(crate) fn enrich_db_url_with_ssl_params(
839    db_url: &str,
840    ssl_mode: Option<&str>,
841    ssl_root_cert: Option<&str>,
842    ssl_cert: Option<&str>,
843    ssl_key: Option<&str>,
844) -> Result<String, CamelError> {
845    let mut parsed = url::Url::parse(db_url).map_err(|e| {
846        CamelError::InvalidUri(format!(
847            "Cannot parse database URL for SSL enrichment: {}",
848            e
849        ))
850    })?;
851
852    let scheme = parsed.scheme();
853    if scheme.starts_with("sqlite") {
854        if ssl_mode.is_some() || ssl_root_cert.is_some() || ssl_cert.is_some() || ssl_key.is_some()
855        {
856            debug!(
857                "SSL options configured for SQLite database URL, but SQLite does not support SSL/TLS; ignoring sslMode/sslRootCert/sslCert/sslKey"
858            );
859        }
860        return Ok(db_url.to_string());
861    }
862
863    if scheme != "postgres" && scheme != "postgresql" && scheme != "mysql" {
864        return Ok(db_url.to_string());
865    }
866    let is_mysql = scheme == "mysql";
867
868    // Explicit URL sslmode/ssl-mode is operator intent and must not be
869    // overwritten by the per-driver default (ADR-0033).
870    let (driver_ssl_mode_key, default_ssl_mode) = if is_mysql {
871        ("ssl-mode", "prefer")
872    } else {
873        ("sslmode", "require")
874    };
875    let url_has_explicit_ssl_mode = parsed
876        .query_pairs()
877        .any(|(k, v)| k.as_ref() == driver_ssl_mode_key && !v.is_empty());
878    let effective_ssl_mode: Option<&str> = match ssl_mode {
879        Some(value) => Some(value),
880        None if url_has_explicit_ssl_mode => None,
881        None => Some(default_ssl_mode),
882    };
883
884    let ssl_params: Vec<(&str, &str)> = [
885        effective_ssl_mode.map(|value| ("sslMode", value)),
886        ssl_root_cert.map(|v| ("sslRootCert", v)),
887        ssl_cert.map(|v| ("sslCert", v)),
888        ssl_key.map(|v| ("sslKey", v)),
889    ]
890    .into_iter()
891    .flatten()
892    .collect();
893
894    let mut query_pairs = parsed.query_pairs().collect::<Vec<_>>();
895    for (camel_name, value) in &ssl_params {
896        if let Some((_, mapping)) = SSL_MAPPINGS.iter().find(|(name, _)| *name == *camel_name) {
897            let driver_key = if is_mysql {
898                mapping.mysql_key
899            } else {
900                mapping.pg_key
901            };
902
903            if let Some(pos) = query_pairs.iter().position(|(k, _)| k == driver_key) {
904                query_pairs[pos].1 = (*value).into();
905            } else {
906                query_pairs.push((driver_key.into(), (*value).into()));
907            }
908        }
909    }
910
911    // NOTE (bd rc-sa1zo): no connect_timeout is appended here. sqlx-postgres
912    // 0.9 does not read that URL key (it warns "ignoring unrecognized connect
913    // parameter" and drops it), so the historical connect_timeout=10 append
914    // never applied a TCP timeout. A stuck connect is bounded by the pool
915    // acquire_timeout instead (sqlx default 30 s, covers acquire + connect).
916
917    {
918        let mut serializer = url::form_urlencoded::Serializer::new(String::new());
919        for (k, v) in &query_pairs {
920            serializer.append_pair(k, v);
921        }
922        parsed.set_query(Some(&serializer.finish()));
923    }
924
925    Ok(parsed.to_string())
926}
927
928impl UriConfig for SqlEndpointConfig {
929    fn scheme() -> &'static str {
930        "sql"
931    }
932
933    fn from_uri(uri: &str) -> Result<Self, CamelError> {
934        let parts = parse_uri(uri)?;
935        Self::from_components(parts)
936    }
937
938    fn from_components(parts: UriComponents) -> Result<Self, CamelError> {
939        // Validate scheme
940        if parts.scheme != Self::scheme() {
941            return Err(CamelError::InvalidUri(format!(
942                "expected scheme '{}' but got '{}'",
943                Self::scheme(),
944                parts.scheme
945            )));
946        }
947
948        let params = &parts.params;
949
950        // Handle file: prefix for query
951        // SQL-014: defer file reading to async init path to avoid blocking I/O
952        // in the synchronous URI parsing path. Store the path; resolve_file_query()
953        // must be called during async initialization (producer pool init or consumer start).
954        let (query, source_path) = if parts.path.starts_with("file:") {
955            let file_path = parts.path.trim_start_matches("file:").to_string();
956            (String::new(), Some(file_path))
957        } else {
958            (parts.path.clone(), None)
959        };
960
961        // Optional parameter: db_url (required when datasource is not set)
962        let db_url = params.get("db_url").cloned().unwrap_or_default();
963
964        // Named datasource reference (from CamelConfig.datasources)
965        let datasource_name = params.get("datasource").cloned();
966
967        // Connection parameters - None when not set by URI param
968        let max_connections = params.get("maxConnections").and_then(|v| v.parse().ok());
969        let min_connections = params.get("minConnections").and_then(|v| v.parse().ok());
970        let idle_timeout_secs = params.get("idleTimeoutSecs").and_then(|v| v.parse().ok());
971        let max_lifetime_secs = params.get("maxLifetimeSecs").and_then(|v| v.parse().ok());
972
973        // Query parameters
974        let output_type = params
975            .get("outputType")
976            .map(|s| s.parse())
977            .transpose()?
978            .unwrap_or_default();
979        let placeholder = params
980            .get("placeholder")
981            .filter(|v| !v.is_empty())
982            .map(|v| {
983                if v.chars().count() != 1 {
984                    return Err(CamelError::InvalidUri(format!(
985                        "placeholder must be exactly one character, got '{}'",
986                        v
987                    )));
988                }
989                if !v.is_ascii() {
990                    return Err(CamelError::InvalidUri(
991                        "placeholder must be a single ASCII character".to_string(),
992                    ));
993                }
994                Ok(v.chars().next().unwrap()) // allow-unwrap
995            })
996            .transpose()?
997            .unwrap_or('#');
998        /// Parse a boolean URI parameter strictly.
999        ///
1000        /// Accepts only `"true"` or `"false"` (case-insensitive). Any other value
1001        /// returns `CamelError::InvalidUri` to prevent silent misconfiguration.
1002        fn parse_bool_param(name: &str, value: &str) -> Result<bool, CamelError> {
1003            if value.eq_ignore_ascii_case("true") {
1004                Ok(true)
1005            } else if value.eq_ignore_ascii_case("false") {
1006                Ok(false)
1007            } else {
1008                Err(CamelError::InvalidUri(format!(
1009                    "{} must be 'true' or 'false', got '{}'",
1010                    name, value
1011                )))
1012            }
1013        }
1014
1015        let use_placeholder = params
1016            .get("usePlaceholder")
1017            .map(|v| parse_bool_param("usePlaceholder", v))
1018            .transpose()?
1019            .unwrap_or(true);
1020        let noop = params
1021            .get("noop")
1022            .map(|v| parse_bool_param("noop", v))
1023            .transpose()?
1024            .unwrap_or(false);
1025        let in_separator = params
1026            .get("inSeparator")
1027            .map(|v| v.to_string())
1028            .unwrap_or_else(|| ", ".to_string());
1029        if in_separator.is_empty() {
1030            return Err(CamelError::InvalidUri(
1031                "inSeparator must not be empty".to_string(),
1032            ));
1033        }
1034
1035        // SQL-005: alwaysPopulateStatement
1036        let always_populate_statement = params
1037            .get("alwaysPopulateStatement")
1038            .map(|v| parse_bool_param("alwaysPopulateStatement", v))
1039            .transpose()?
1040            .unwrap_or(false);
1041
1042        // SQL-011: allowNamedParameters
1043        let allow_named_parameters = params
1044            .get("allowNamedParameters")
1045            .map(|v| parse_bool_param("allowNamedParameters", v))
1046            .transpose()?
1047            .unwrap_or(true);
1048
1049        // SQL-016: fetchSize
1050        let fetch_size = params.get("fetchSize").and_then(|v| v.parse().ok());
1051
1052        // SQL-002: transactionMode
1053        let transaction_mode = params
1054            .get("transactionMode")
1055            .map(|s| s.parse())
1056            .transpose()?
1057            .unwrap_or_default();
1058
1059        // Consumer parameters
1060        let delay_ms = params
1061            .get("delay")
1062            .and_then(|v| v.parse().ok())
1063            .unwrap_or(500);
1064        let initial_delay_ms = params
1065            .get("initialDelay")
1066            .and_then(|v| v.parse().ok())
1067            .unwrap_or(1000);
1068        let max_messages_per_poll = params
1069            .get("maxMessagesPerPoll")
1070            .and_then(|v| v.parse().ok());
1071        let on_consume = params.get("onConsume").cloned();
1072        let on_consume_failed = params.get("onConsumeFailed").cloned();
1073        let on_consume_batch_complete = params.get("onConsumeBatchComplete").cloned();
1074        let route_empty_result_set = params
1075            .get("routeEmptyResultSet")
1076            .map(|v| parse_bool_param("routeEmptyResultSet", v))
1077            .transpose()?
1078            .unwrap_or(false);
1079        let use_iterator = params
1080            .get("useIterator")
1081            .map(|v| parse_bool_param("useIterator", v))
1082            .transpose()?
1083            .unwrap_or(true);
1084        let expected_update_count = params
1085            .get("expectedUpdateCount")
1086            .and_then(|v| v.parse().ok());
1087        let break_batch_on_consume_fail = params
1088            .get("breakBatchOnConsumeFail")
1089            .map(|v| parse_bool_param("breakBatchOnConsumeFail", v))
1090            .transpose()?
1091            .unwrap_or(false);
1092        let bridge_error_handler = params
1093            .get("bridgeErrorHandler")
1094            .map(|v| parse_bool_param("bridgeErrorHandler", v))
1095            .transpose()?
1096            .unwrap_or(false);
1097
1098        // SQL-015: repeatCount
1099        let repeat_count = params.get("repeatCount").and_then(|v| v.parse().ok());
1100
1101        // SQL-020: breakOnEmpty
1102        let break_on_empty = params
1103            .get("breakOnEmpty")
1104            .map(|v| parse_bool_param("breakOnEmpty", v))
1105            .transpose()?
1106            .unwrap_or(false);
1107
1108        // SQL-017: processingStrategy
1109        let processing_strategy = params
1110            .get("processingStrategy")
1111            .map(|s| s.parse())
1112            .transpose()?
1113            .unwrap_or_default();
1114
1115        // SQL-018: pollStrategy
1116        let poll_strategy = params
1117            .get("pollStrategy")
1118            .map(|s| s.parse())
1119            .transpose()?
1120            .unwrap_or_default();
1121
1122        // Producer parameters
1123        let batch = params
1124            .get("batch")
1125            .map(|v| parse_bool_param("batch", v))
1126            .transpose()?
1127            .unwrap_or(false);
1128        let use_message_body_for_sql = params
1129            .get("useMessageBodyForSql")
1130            .map(|v| parse_bool_param("useMessageBodyForSql", v))
1131            .transpose()?
1132            .unwrap_or(false);
1133        let allow_dynamic_query = params
1134            .get("allowDynamicQuery")
1135            .map(|v| parse_bool_param("allowDynamicQuery", v))
1136            .transpose()?
1137            .unwrap_or(false);
1138        let ssl_mode = params.get("sslMode").cloned();
1139        let ssl_root_cert = params.get("sslRootCert").cloned();
1140        let ssl_cert = params.get("sslCert").cloned();
1141        let ssl_key = params.get("sslKey").cloned();
1142
1143        // Parse retry policy from URI params
1144        let mut retry = NetworkRetryPolicy::default();
1145        let mut retry_set_from_uri = false;
1146        if let Some(raw) = params.get("retryEnabled") {
1147            retry.enabled = raw.parse::<bool>().map_err(|_| {
1148                CamelError::InvalidUri(format!("retryEnabled must be a boolean, got '{raw}'"))
1149            })?;
1150            retry_set_from_uri = true;
1151        }
1152        if let Some(raw) = params.get("retryMaxAttempts") {
1153            retry.max_attempts = raw.parse::<u32>().map_err(|_| {
1154                CamelError::InvalidUri(format!("retryMaxAttempts must be a u32, got '{raw}'"))
1155            })?;
1156            retry_set_from_uri = true;
1157        }
1158        if let Some(raw) = params.get("retryInitialDelayMs") {
1159            retry.initial_delay = Duration::from_millis(raw.parse::<u64>().map_err(|_| {
1160                CamelError::InvalidUri(format!("retryInitialDelayMs must be a u64, got '{raw}'"))
1161            })?);
1162            retry_set_from_uri = true;
1163        }
1164        if let Some(raw) = params.get("retryMultiplier") {
1165            retry.multiplier = raw.parse::<f64>().map_err(|_| {
1166                CamelError::InvalidUri(format!("retryMultiplier must be a f64, got '{raw}'"))
1167            })?;
1168            retry_set_from_uri = true;
1169        }
1170        if let Some(raw) = params.get("retryMaxDelayMs") {
1171            retry.max_delay = Duration::from_millis(raw.parse::<u64>().map_err(|_| {
1172                CamelError::InvalidUri(format!("retryMaxDelayMs must be a u64, got '{raw}'"))
1173            })?);
1174            retry_set_from_uri = true;
1175        }
1176        if let Some(raw) = params.get("retryJitter") {
1177            retry.jitter_factor = raw.parse::<f64>().map_err(|_| {
1178                CamelError::InvalidUri(format!("retryJitter must be a f64, got '{raw}'"))
1179            })?;
1180            retry_set_from_uri = true;
1181        }
1182
1183        if datasource_name.is_none() && db_url.is_empty() {
1184            return Err(CamelError::Config(
1185                "either 'datasource' or 'db_url' parameter is required".to_string(),
1186            ));
1187        }
1188
1189        if datasource_name.is_some() && !db_url.is_empty() {
1190            return Err(CamelError::InvalidUri(
1191                "'db_url' not allowed with named datasource — use 'datasource' alone".to_string(),
1192            ));
1193        }
1194
1195        if datasource_name.is_some() {
1196            let overrides: Vec<&str> = {
1197                let mut v = Vec::new();
1198                if max_connections.is_some() {
1199                    v.push("maxConnections");
1200                }
1201                if min_connections.is_some() {
1202                    v.push("minConnections");
1203                }
1204                if idle_timeout_secs.is_some() {
1205                    v.push("idleTimeoutSecs");
1206                }
1207                if max_lifetime_secs.is_some() {
1208                    v.push("maxLifetimeSecs");
1209                }
1210                if ssl_mode.is_some() {
1211                    v.push("sslMode");
1212                }
1213                if ssl_root_cert.is_some() {
1214                    v.push("sslRootCert");
1215                }
1216                if ssl_cert.is_some() {
1217                    v.push("sslCert");
1218                }
1219                if ssl_key.is_some() {
1220                    v.push("sslKey");
1221                }
1222                v
1223            };
1224            if !overrides.is_empty() {
1225                return Err(CamelError::InvalidUri(format!(
1226                    "pool-affecting params not allowed with named datasource: {}",
1227                    overrides.join(", ")
1228                )));
1229            }
1230        }
1231
1232        Ok(Self {
1233            db_url,
1234            datasource_name,
1235            max_connections,
1236            min_connections,
1237            idle_timeout_secs,
1238            max_lifetime_secs,
1239            query,
1240            source_path,
1241            output_type,
1242            placeholder,
1243            use_placeholder,
1244            noop,
1245            in_separator,
1246            always_populate_statement,
1247            allow_named_parameters,
1248            fetch_size,
1249            transaction_mode,
1250            delay_ms,
1251            initial_delay_ms,
1252            max_messages_per_poll,
1253            on_consume,
1254            on_consume_failed,
1255            on_consume_batch_complete,
1256            route_empty_result_set,
1257            use_iterator,
1258            expected_update_count,
1259            break_batch_on_consume_fail,
1260            bridge_error_handler,
1261            repeat_count,
1262            break_on_empty,
1263            processing_strategy,
1264            poll_strategy,
1265            batch,
1266            use_message_body_for_sql,
1267            allow_dynamic_query,
1268            ssl_mode,
1269            ssl_root_cert,
1270            ssl_cert,
1271            ssl_key,
1272            retry,
1273            retry_set_from_uri,
1274        })
1275    }
1276}
1277
1278#[cfg(test)]
1279mod tests {
1280    use super::*;
1281    use camel_component_api::NetworkRetryPolicy;
1282
1283    #[test]
1284    fn config_defaults() {
1285        let mut c =
1286            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
1287        c.resolve_defaults();
1288        assert_eq!(c.query, "select 1");
1289        assert_eq!(c.db_url, "postgres://localhost/test");
1290        assert_eq!(c.max_connections, Some(5));
1291        assert_eq!(c.min_connections, Some(1));
1292        assert_eq!(c.idle_timeout_secs, Some(300));
1293        assert_eq!(c.max_lifetime_secs, Some(1800));
1294        assert_eq!(c.output_type, SqlOutputType::SelectList);
1295        assert_eq!(c.placeholder, '#');
1296        assert!(!c.noop);
1297        assert_eq!(c.in_separator, ", ");
1298        assert_eq!(c.delay_ms, 500);
1299        assert_eq!(c.initial_delay_ms, 1000);
1300        assert!(c.max_messages_per_poll.is_none());
1301        assert!(c.on_consume.is_none());
1302        assert!(c.on_consume_failed.is_none());
1303        assert!(c.on_consume_batch_complete.is_none());
1304        assert!(!c.route_empty_result_set);
1305        assert!(c.use_iterator);
1306        assert!(c.expected_update_count.is_none());
1307        assert!(!c.break_batch_on_consume_fail);
1308        assert!(!c.batch);
1309        assert!(!c.use_message_body_for_sql);
1310        assert!(!c.allow_dynamic_query);
1311        assert!(c.ssl_mode.is_none());
1312        assert!(c.ssl_root_cert.is_none());
1313        assert!(c.ssl_cert.is_none());
1314        assert!(c.ssl_key.is_none());
1315        // SQL-005/SQL-011/SQL-016/SQL-002/SQL-015/SQL-017/SQL-018 defaults
1316        assert!(!c.always_populate_statement);
1317        assert!(c.allow_named_parameters);
1318        assert!(c.fetch_size.is_none());
1319        assert_eq!(c.transaction_mode, TransactionMode::Auto);
1320        assert!(c.repeat_count.is_none());
1321        assert_eq!(c.processing_strategy, ProcessingStrategy::Direct);
1322        assert_eq!(c.poll_strategy, PollStrategy::Sequential);
1323    }
1324
1325    #[test]
1326    fn ssl_none_by_default() {
1327        let c =
1328            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
1329        assert!(c.ssl_mode.is_none());
1330        assert!(c.ssl_root_cert.is_none());
1331        assert!(c.ssl_cert.is_none());
1332        assert!(c.ssl_key.is_none());
1333    }
1334
1335    #[test]
1336    fn ssl_mode_from_uri() {
1337        let c = SqlEndpointConfig::from_uri(
1338            "sql:select 1?db_url=postgres://localhost/test&sslMode=require",
1339        )
1340        .unwrap();
1341        assert_eq!(c.ssl_mode, Some("require".to_string()));
1342        assert!(c.ssl_root_cert.is_none());
1343    }
1344
1345    #[test]
1346    fn ssl_all_params_from_uri() {
1347        let c = SqlEndpointConfig::from_uri(
1348            "sql:select 1?db_url=postgres://localhost/test&sslMode=require&sslRootCert=/ca.pem&sslCert=/cert.pem&sslKey=/key.pem",
1349        )
1350        .unwrap();
1351        assert_eq!(c.ssl_mode, Some("require".to_string()));
1352        assert_eq!(c.ssl_root_cert, Some("/ca.pem".to_string()));
1353        assert_eq!(c.ssl_cert, Some("/cert.pem".to_string()));
1354        assert_eq!(c.ssl_key, Some("/key.pem".to_string()));
1355    }
1356
1357    #[test]
1358    fn ssl_global_applied_to_endpoint() {
1359        let mut c =
1360            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
1361        let global = SqlGlobalConfig::default()
1362            .with_ssl_mode("require")
1363            .with_ssl_root_cert("/etc/ssl/ca.pem");
1364        c.apply_defaults(&global);
1365        assert_eq!(c.ssl_mode, Some("require".to_string()));
1366        assert_eq!(c.ssl_root_cert, Some("/etc/ssl/ca.pem".to_string()));
1367        assert!(c.ssl_cert.is_none());
1368        assert!(c.ssl_key.is_none());
1369    }
1370
1371    #[test]
1372    fn ssl_uri_overrides_global() {
1373        let mut c = SqlEndpointConfig::from_uri(
1374            "sql:select 1?db_url=postgres://localhost/test&sslMode=verify-full",
1375        )
1376        .unwrap();
1377        let global = SqlGlobalConfig::default().with_ssl_mode("require");
1378        c.apply_defaults(&global);
1379        assert_eq!(c.ssl_mode, Some("verify-full".to_string()));
1380    }
1381
1382    #[test]
1383    fn config_wrong_scheme() {
1384        assert!(SqlEndpointConfig::from_uri("redis://localhost:6379").is_err());
1385    }
1386
1387    #[test]
1388    fn config_missing_db_url() {
1389        assert!(SqlEndpointConfig::from_uri("sql:select 1").is_err());
1390    }
1391
1392    #[test]
1393    fn config_output_type_select_one() {
1394        let c = SqlEndpointConfig::from_uri(
1395            "sql:select 1?db_url=postgres://localhost/test&outputType=SelectOne",
1396        )
1397        .unwrap();
1398        assert_eq!(c.output_type, SqlOutputType::SelectOne);
1399    }
1400
1401    #[test]
1402    fn config_output_type_stream_list() {
1403        let c = SqlEndpointConfig::from_uri(
1404            "sql:select 1?db_url=postgres://localhost/test&outputType=StreamList",
1405        )
1406        .unwrap();
1407        assert_eq!(c.output_type, SqlOutputType::StreamList);
1408    }
1409
1410    #[test]
1411    fn in_separator_default() {
1412        let c =
1413            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
1414        assert_eq!(c.in_separator, ", ");
1415    }
1416
1417    #[test]
1418    fn in_separator_from_uri() {
1419        let c = SqlEndpointConfig::from_uri(
1420            "sql:select 1?db_url=postgres://localhost/test&inSeparator=;",
1421        )
1422        .unwrap();
1423        assert_eq!(c.in_separator, ";");
1424    }
1425
1426    #[test]
1427    fn in_separator_empty_rejected() {
1428        let result = SqlEndpointConfig::from_uri(
1429            "sql:select 1?db_url=postgres://localhost/test&inSeparator=",
1430        );
1431        assert!(result.is_err());
1432        let msg = format!("{:?}", result.unwrap_err());
1433        assert!(msg.contains("inSeparator") || msg.contains("empty"));
1434    }
1435
1436    #[test]
1437    fn config_consumer_options() {
1438        let c = SqlEndpointConfig::from_uri(
1439            "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"
1440        ).unwrap();
1441        assert_eq!(c.delay_ms, 2000);
1442        assert_eq!(c.initial_delay_ms, 500);
1443        assert_eq!(c.max_messages_per_poll, Some(10));
1444        assert_eq!(
1445            c.on_consume,
1446            Some("update t set done=true where id=:#id".to_string())
1447        );
1448        assert_eq!(
1449            c.on_consume_failed,
1450            Some("update t set failed=true where id=:#id".to_string())
1451        );
1452        assert_eq!(
1453            c.on_consume_batch_complete,
1454            Some("delete from t where done=true".to_string())
1455        );
1456        assert!(c.route_empty_result_set);
1457        assert!(!c.use_iterator);
1458        assert_eq!(c.expected_update_count, Some(1));
1459        assert!(c.break_batch_on_consume_fail);
1460        assert!(!c.bridge_error_handler);
1461    }
1462
1463    #[test]
1464    fn config_producer_options() {
1465        let c = SqlEndpointConfig::from_uri(
1466            "sql:insert into t values (#)?db_url=postgres://localhost/test&batch=true&useMessageBodyForSql=true&noop=true"
1467        ).unwrap();
1468        assert!(c.batch);
1469        assert!(c.use_message_body_for_sql);
1470        assert!(c.noop);
1471    }
1472
1473    #[test]
1474    fn config_pool_options() {
1475        let c = SqlEndpointConfig::from_uri(
1476            "sql:select 1?db_url=postgres://localhost/test&maxConnections=20&minConnections=3&idleTimeoutSecs=600&maxLifetimeSecs=3600"
1477        ).unwrap();
1478        assert_eq!(c.max_connections, Some(20));
1479        assert_eq!(c.min_connections, Some(3));
1480        assert_eq!(c.idle_timeout_secs, Some(600));
1481        assert_eq!(c.max_lifetime_secs, Some(3600));
1482    }
1483
1484    #[test]
1485    fn config_query_with_special_chars() {
1486        let c = SqlEndpointConfig::from_uri(
1487            "sql:select * from users where name = :#name and age > #?db_url=postgres://localhost/test",
1488        )
1489        .unwrap();
1490        assert_eq!(
1491            c.query,
1492            "select * from users where name = :#name and age > #"
1493        );
1494    }
1495
1496    #[test]
1497    fn output_type_from_str() {
1498        assert_eq!(
1499            "SelectList".parse::<SqlOutputType>().unwrap(),
1500            SqlOutputType::SelectList
1501        );
1502        assert_eq!(
1503            "SelectOne".parse::<SqlOutputType>().unwrap(),
1504            SqlOutputType::SelectOne
1505        );
1506        assert_eq!(
1507            "StreamList".parse::<SqlOutputType>().unwrap(),
1508            SqlOutputType::StreamList
1509        );
1510        assert!("Invalid".parse::<SqlOutputType>().is_err());
1511    }
1512
1513    // SQL-014: file-not-found is now detected during async resolve_file_query(), not from_uri
1514    #[tokio::test]
1515    async fn config_file_not_found() {
1516        let mut config = SqlEndpointConfig::from_uri(
1517            "sql:file:/nonexistent/path/query.sql?db_url=postgres://localhost/test",
1518        )
1519        .expect("from_uri should defer file reading");
1520        // from_uri no longer reads the file — source_path is set, query is empty
1521        assert_eq!(
1522            config.source_path,
1523            Some("/nonexistent/path/query.sql".to_string())
1524        );
1525        assert!(config.query.is_empty());
1526
1527        // Error occurs during async resolution
1528        let result = config.resolve_file_query().await;
1529        assert!(result.is_err());
1530        let msg = format!("{:?}", result.unwrap_err());
1531        assert!(msg.contains("Failed to read SQL file") || msg.contains("nonexistent"));
1532    }
1533
1534    // SQL-014: file query is now resolved asynchronously
1535    #[tokio::test]
1536    async fn config_file_query() {
1537        use std::io::Write;
1538        let unique_name = format!(
1539            "test_sql_query_{}.sql",
1540            std::time::SystemTime::now()
1541                .duration_since(std::time::UNIX_EPOCH)
1542                .unwrap_or_default()
1543                .as_nanos()
1544        );
1545        let mut tmp = std::env::temp_dir();
1546        tmp.push(unique_name);
1547        {
1548            let mut f = std::fs::File::create(&tmp).unwrap();
1549            writeln!(f, "SELECT * FROM users").unwrap();
1550        }
1551        let uri = format!(
1552            "sql:file:{}?db_url=postgres://localhost/test",
1553            tmp.display()
1554        );
1555        let mut c = SqlEndpointConfig::from_uri(&uri).unwrap();
1556        // query is empty until async resolution
1557        assert!(c.query.is_empty());
1558        assert_eq!(c.source_path, Some(tmp.to_string_lossy().into_owned()));
1559
1560        // Resolve asynchronously
1561        c.resolve_file_query()
1562            .await
1563            .expect("file query should resolve");
1564        assert_eq!(c.query, "SELECT * FROM users");
1565        std::fs::remove_file(&tmp).ok();
1566    }
1567
1568    // Sealed artifacts (mission 351): embedded SQL references resolve from the
1569    // process-global registry with zero filesystem access.
1570    #[test]
1571    fn encoded_embedded_prefix_literal_matches_registry_prefix() {
1572        assert_eq!(
1573            ENCODED_EMBEDDED_REF_PREFIX,
1574            camel_component_api::embedded_assets::EMBEDDED_REF_PREFIX.replace(':', "%3A")
1575        );
1576    }
1577
1578    #[tokio::test]
1579    async fn resolve_file_query_resolves_embedded_reference() {
1580        const KEY: &str = "assets/sql/fixture61.sql";
1581        camel_component_api::embedded_assets::register(KEY, b"SELECT 1".to_vec());
1582
1583        // The percent-encoded form travels through `parse_uri`, which decodes
1584        // the path exactly once, so the canonical spelling reaches the config.
1585        let mut from_uri = SqlEndpointConfig::from_uri(
1586            "sql:file:camel-embedded%3Aassets%2Fsql%2Ffixture61.sql?db_url=sqlite://memory",
1587        )
1588        .expect("from_uri should accept the encoded embedded reference");
1589        assert_eq!(
1590            from_uri.source_path.as_deref(),
1591            Some("camel-embedded:assets/sql/fixture61.sql"),
1592            "parse_uri decodes the encoded prefix once into the canonical spelling"
1593        );
1594        from_uri
1595            .resolve_file_query()
1596            .await
1597            .expect("registered embedded reference resolves");
1598        assert_eq!(from_uri.query, "SELECT 1");
1599
1600        // A directly-placed canonical spelling resolves identically.
1601        let mut direct = SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite://memory")
1602            .expect("plain config");
1603        direct.source_path = Some("camel-embedded:assets/sql/fixture61.sql".into());
1604        direct
1605            .resolve_file_query()
1606            .await
1607            .expect("canonical embedded reference resolves");
1608        assert_eq!(direct.query, "SELECT 1");
1609    }
1610
1611    #[tokio::test]
1612    async fn resolve_file_query_fails_closed_on_unknown_reference() {
1613        let mut config = SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite://memory")
1614            .expect("plain config");
1615        config.source_path = Some("camel-embedded:assets/sql/never-registered-61".into());
1616
1617        let err = config
1618            .resolve_file_query()
1619            .await
1620            .expect_err("unregistered embedded reference must fail closed");
1621        let message = err.to_string();
1622        assert!(
1623            message.contains("never-registered-61"),
1624            "error must name the reference, got: {message}"
1625        );
1626        assert!(
1627            message.contains("no embedded SQL file registered"),
1628            "error must be the typed embedded failure, got: {message}"
1629        );
1630    }
1631
1632    #[tokio::test]
1633    async fn resolve_file_query_rejects_non_utf8_embedded_bytes() {
1634        const KEY: &str = "assets/sql/bad62.sql";
1635        camel_component_api::embedded_assets::register(KEY, vec![0xFF, 0xFE]);
1636
1637        let mut config = SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite://memory")
1638            .expect("plain config");
1639        config.source_path = Some("camel-embedded:assets/sql/bad62.sql".into());
1640
1641        let err = config
1642            .resolve_file_query()
1643            .await
1644            .expect_err("non-UTF-8 embedded SQL bytes must be rejected");
1645        let message = err.to_string();
1646        assert!(
1647            message.contains("bad62.sql"),
1648            "error must name the reference, got: {message}"
1649        );
1650        assert!(
1651            message.contains("Failed to read SQL file"),
1652            "error must mirror the read-error wording, got: {message}"
1653        );
1654    }
1655
1656    #[tokio::test]
1657    async fn resolve_file_query_plain_file_unchanged() {
1658        use std::io::Write;
1659        let mut tmp = std::env::temp_dir();
1660        tmp.push(format!(
1661            "test_sql_plain61_{}.sql",
1662            std::time::SystemTime::now()
1663                .duration_since(std::time::UNIX_EPOCH)
1664                .unwrap_or_default()
1665                .as_nanos()
1666        ));
1667        {
1668            let mut f = std::fs::File::create(&tmp).expect("create temp sql file");
1669            writeln!(f, "SELECT 42 FROM plain61").expect("write temp sql file");
1670        }
1671        let mut config = SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite://memory")
1672            .expect("plain config");
1673        config.source_path = Some(tmp.to_string_lossy().into_owned());
1674
1675        config
1676            .resolve_file_query()
1677            .await
1678            .expect("plain file query still resolves");
1679        assert_eq!(config.query, "SELECT 42 FROM plain61");
1680        std::fs::remove_file(&tmp).ok();
1681    }
1682
1683    // New tests for config contract
1684    #[test]
1685    fn pool_fields_none_when_not_set() {
1686        let c =
1687            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
1688        assert_eq!(c.max_connections, None);
1689        assert_eq!(c.min_connections, None);
1690        assert_eq!(c.idle_timeout_secs, None);
1691        assert_eq!(c.max_lifetime_secs, None);
1692    }
1693
1694    #[test]
1695    fn apply_defaults_fills_none() {
1696        let mut c =
1697            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
1698        let global = SqlGlobalConfig {
1699            max_connections: 10,
1700            min_connections: 2,
1701            idle_timeout_secs: 600,
1702            max_lifetime_secs: 3600,
1703            ssl_mode: None,
1704            ssl_root_cert: None,
1705            ssl_cert: None,
1706            ssl_key: None,
1707            retry: NetworkRetryPolicy::default(),
1708        };
1709        c.apply_defaults(&global);
1710        assert_eq!(c.max_connections, Some(10));
1711        assert_eq!(c.min_connections, Some(2));
1712        assert_eq!(c.idle_timeout_secs, Some(600));
1713        assert_eq!(c.max_lifetime_secs, Some(3600));
1714        assert!(c.ssl_mode.is_none());
1715        assert!(c.ssl_root_cert.is_none());
1716        assert!(c.ssl_cert.is_none());
1717        assert!(c.ssl_key.is_none());
1718    }
1719
1720    #[test]
1721    fn apply_defaults_does_not_override() {
1722        let mut c = SqlEndpointConfig::from_uri(
1723            "sql:select 1?db_url=postgres://localhost/test&maxConnections=99&minConnections=5",
1724        )
1725        .unwrap();
1726        let global = SqlGlobalConfig {
1727            max_connections: 10,
1728            min_connections: 2,
1729            idle_timeout_secs: 600,
1730            max_lifetime_secs: 3600,
1731            ssl_mode: None,
1732            ssl_root_cert: None,
1733            ssl_cert: None,
1734            ssl_key: None,
1735            retry: NetworkRetryPolicy::default(),
1736        };
1737        c.apply_defaults(&global);
1738        // URI-set values should NOT be overridden
1739        assert_eq!(c.max_connections, Some(99));
1740        assert_eq!(c.min_connections, Some(5));
1741        // None fields should be filled from global
1742        assert_eq!(c.idle_timeout_secs, Some(600));
1743        assert_eq!(c.max_lifetime_secs, Some(3600));
1744    }
1745
1746    #[test]
1747    fn resolve_defaults_fills_remaining() {
1748        let mut c = SqlEndpointConfig::from_uri(
1749            "sql:select 1?db_url=postgres://localhost/test&maxConnections=7",
1750        )
1751        .unwrap();
1752        c.resolve_defaults();
1753        assert_eq!(c.max_connections, Some(7)); // from URI
1754        assert_eq!(c.min_connections, Some(1)); // from defaults
1755        assert_eq!(c.idle_timeout_secs, Some(300)); // from defaults
1756        assert_eq!(c.max_lifetime_secs, Some(1800)); // from defaults
1757    }
1758
1759    #[test]
1760    fn global_config_builder() {
1761        let c = SqlGlobalConfig::default()
1762            .with_max_connections(20)
1763            .with_min_connections(3)
1764            .with_idle_timeout_secs(600)
1765            .with_max_lifetime_secs(3600)
1766            .with_ssl_mode("require")
1767            .with_ssl_root_cert("/ca.pem")
1768            .with_ssl_cert("/cert.pem")
1769            .with_ssl_key("/key.pem");
1770        assert_eq!(c.max_connections, 20);
1771        assert_eq!(c.min_connections, 3);
1772        assert_eq!(c.idle_timeout_secs, 600);
1773        assert_eq!(c.max_lifetime_secs, 3600);
1774        assert_eq!(c.ssl_mode, Some("require".to_string()));
1775        assert_eq!(c.ssl_root_cert, Some("/ca.pem".to_string()));
1776        assert_eq!(c.ssl_cert, Some("/cert.pem".to_string()));
1777        assert_eq!(c.ssl_key, Some("/key.pem".to_string()));
1778    }
1779
1780    #[test]
1781    fn enrich_postgres_ssl_mode() {
1782        let mut c = SqlEndpointConfig::from_uri(
1783            "sql:select 1?db_url=postgres://localhost/test&sslMode=require",
1784        )
1785        .unwrap();
1786        c.resolve_defaults();
1787        let url = enrich_db_url_with_ssl(&c.db_url, &c).unwrap();
1788        assert!(url.contains("sslmode=require"), "got: {}", url);
1789    }
1790
1791    #[test]
1792    fn enrich_postgres_all_ssl() {
1793        let mut c = SqlEndpointConfig::from_uri(
1794            "sql:select 1?db_url=postgres://localhost/test&sslMode=require&sslRootCert=/ca.pem&sslCert=/cert.pem&sslKey=/key.pem",
1795        )
1796        .unwrap();
1797        c.resolve_defaults();
1798        let url = enrich_db_url_with_ssl(&c.db_url, &c).unwrap();
1799        assert!(url.contains("sslmode=require"), "got: {}", url);
1800        assert!(url.contains("sslrootcert="), "got: {}", url);
1801        assert!(url.contains("sslcert="), "got: {}", url);
1802        assert!(url.contains("sslkey="), "got: {}", url);
1803    }
1804
1805    #[test]
1806    fn enrich_mysql_ssl() {
1807        let mut c = SqlEndpointConfig::from_uri(
1808            "sql:select 1?db_url=mysql://localhost/test&sslMode=require",
1809        )
1810        .unwrap();
1811        c.resolve_defaults();
1812        let url = enrich_db_url_with_ssl(&c.db_url, &c).unwrap();
1813        assert!(url.contains("ssl-mode=require"), "got: {}", url);
1814    }
1815
1816    #[test]
1817    fn enrich_existing_query_params() {
1818        let mut c = SqlEndpointConfig::from_uri(
1819            "sql:select 1?db_url=postgres://localhost/test?existing=1&sslMode=require",
1820        )
1821        .unwrap();
1822        c.resolve_defaults();
1823        let url = enrich_db_url_with_ssl(&c.db_url, &c).unwrap();
1824        assert!(url.contains("existing=1"), "got: {}", url);
1825        assert!(url.contains("sslmode=require"), "got: {}", url);
1826    }
1827
1828    #[test]
1829    fn enrich_override_existing() {
1830        let mut c = SqlEndpointConfig::from_uri(
1831            "sql:select 1?db_url=postgres://localhost/test?sslmode=allow&sslMode=require",
1832        )
1833        .unwrap();
1834        c.resolve_defaults();
1835        let url = enrich_db_url_with_ssl(&c.db_url, &c).unwrap();
1836        assert!(url.contains("sslmode=require"), "got: {}", url);
1837        assert!(!url.contains("sslmode=allow"), "got: {}", url);
1838    }
1839
1840    #[test]
1841    fn enrich_applies_postgres_defaults() {
1842        let mut c =
1843            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
1844        c.resolve_defaults();
1845        let url = enrich_db_url_with_ssl(&c.db_url, &c).unwrap();
1846        // Default ssl_mode is applied at enrichment time. connect_timeout is
1847        // NOT appended: sqlx-postgres 0.9 does not read that URL key (bd rc-sa1zo).
1848        assert!(
1849            url.contains("sslmode=require"),
1850            "expected sslmode=require, got: {}",
1851            url
1852        );
1853        assert!(
1854            !url.contains("connect_timeout"),
1855            "connect_timeout must not be appended, got: {}",
1856            url
1857        );
1858    }
1859
1860    #[test]
1861    fn enrich_mysql_defaults_to_prefer() {
1862        let mut c =
1863            SqlEndpointConfig::from_uri("sql:select 1?db_url=mysql://localhost/test").unwrap();
1864        c.resolve_defaults();
1865        let url = enrich_db_url_with_ssl(&c.db_url, &c).unwrap();
1866        assert!(
1867            url.contains("ssl-mode=prefer"),
1868            "expected ssl-mode=prefer, got: {}",
1869            url
1870        );
1871        assert!(
1872            !url.contains("connect_timeout"),
1873            "connect_timeout must not be appended, got: {}",
1874            url
1875        );
1876    }
1877
1878    #[test]
1879    fn pg_url_sslmode_disable_preserved_when_config_absent() {
1880        let url = enrich_db_url_with_ssl_params(
1881            "postgres://localhost/test?sslmode=disable",
1882            None,
1883            None,
1884            None,
1885            None,
1886        )
1887        .unwrap();
1888        assert!(url.contains("sslmode=disable"), "got: {}", url);
1889        assert!(!url.contains("sslmode=require"), "got: {}", url);
1890        assert!(!url.contains("connect_timeout"), "got: {}", url);
1891    }
1892
1893    #[test]
1894    fn enrich_does_not_append_connect_timeout() {
1895        // Arrange: URL without connect_timeout, sslMode supplied via config
1896        // (bd rc-sa1zo: sqlx-postgres 0.9 does not read connect_timeout from
1897        // the URL; appending it only produces "ignoring unrecognized connect
1898        // parameter" warnings on every pool creation).
1899        // Act: enrich as usual.
1900        let url = enrich_db_url_with_ssl_params(
1901            "postgres://localhost/test",
1902            Some("require"),
1903            None,
1904            None,
1905            None,
1906        )
1907        .unwrap();
1908        // Assert: the fabricated key is gone, the SSL pair is still applied.
1909        assert!(
1910            !url.contains("connect_timeout"),
1911            "connect_timeout must not be appended, got: {}",
1912            url
1913        );
1914        assert!(
1915            url.contains("sslmode=require"),
1916            "expected sslmode=require, got: {}",
1917            url
1918        );
1919    }
1920
1921    #[test]
1922    fn pg_url_sslmode_require_and_verify_full_preserved_when_config_absent() {
1923        for mode in ["require", "verify-full"] {
1924            let url = enrich_db_url_with_ssl_params(
1925                &format!("postgres://localhost/test?sslmode={mode}"),
1926                None,
1927                None,
1928                None,
1929                None,
1930            )
1931            .unwrap();
1932            assert!(url.contains(&format!("sslmode={mode}")), "got: {}", url);
1933        }
1934    }
1935
1936    #[test]
1937    fn mysql_url_ssl_mode_disable_preserved_when_config_absent() {
1938        let url = enrich_db_url_with_ssl_params(
1939            "mysql://localhost/test?ssl-mode=disable",
1940            None,
1941            None,
1942            None,
1943            None,
1944        )
1945        .unwrap();
1946        assert!(url.contains("ssl-mode=disable"), "got: {}", url);
1947        assert!(!url.contains("ssl-mode=prefer"), "got: {}", url);
1948    }
1949
1950    #[test]
1951    fn config_overrides_url_mysql() {
1952        let url = enrich_db_url_with_ssl_params(
1953            "mysql://localhost/test?ssl-mode=disable",
1954            Some("require"),
1955            None,
1956            None,
1957            None,
1958        )
1959        .unwrap();
1960        assert!(url.contains("ssl-mode=require"), "got: {}", url);
1961        assert!(!url.contains("ssl-mode=disable"), "got: {}", url);
1962    }
1963
1964    #[test]
1965    fn enrich_preserves_explicit_connect_timeout() {
1966        let mut c = SqlEndpointConfig::from_uri(
1967            "sql:select 1?db_url=postgres://localhost/test?connect_timeout=5",
1968        )
1969        .unwrap();
1970        c.resolve_defaults();
1971        let url = enrich_db_url_with_ssl(&c.db_url, &c).unwrap();
1972        assert!(
1973            url.contains("connect_timeout=5"),
1974            "expected explicit connect_timeout=5 preserved, got: {}",
1975            url
1976        );
1977        assert!(
1978            url.contains("sslmode=require"),
1979            "expected sslmode=require, got: {}",
1980            url
1981        );
1982    }
1983
1984    #[test]
1985    fn enrich_url_encodes_paths() {
1986        let mut c = SqlEndpointConfig::from_uri(
1987            "sql:select 1?db_url=postgres://localhost/test&sslRootCert=/path/to/my%20cert.pem",
1988        )
1989        .unwrap();
1990        c.resolve_defaults();
1991        let url = enrich_db_url_with_ssl(&c.db_url, &c).unwrap();
1992        assert!(url.contains("sslrootcert="), "got: {}", url);
1993    }
1994
1995    #[test]
1996    fn enrich_unsupported_scheme_returns_unchanged() {
1997        let mut c = SqlEndpointConfig::from_uri(
1998            "sql:select 1?db_url=sqlite://localhost/test.db&sslMode=require",
1999        )
2000        .unwrap();
2001        c.resolve_defaults();
2002        let url = enrich_db_url_with_ssl(&c.db_url, &c).unwrap();
2003        assert_eq!(url, "sqlite://localhost/test.db");
2004    }
2005
2006    /// Pins both sides of the SQLite SSL-ignore diagnostic: it must stay
2007    /// below WARN (one env-driven config shared by SQLite and Postgres
2008    /// datasources must not warn on every boot) and it must still be emitted
2009    /// at DEBUG. `tracing-test` here is built with `no-env-filter`, so the
2010    /// subscriber captures every level; assert on the rendered level rather
2011    /// than on message presence alone.
2012    #[tracing_test::traced_test]
2013    #[test]
2014    fn sqlite_ssl_options_debug_not_warn() {
2015        let url = enrich_db_url_with_ssl_params(
2016            "sqlite://test.db?mode=rwc",
2017            Some("require"),
2018            None,
2019            None,
2020            None,
2021        )
2022        .expect("sqlite URL enrichment must succeed");
2023        assert_eq!(url, "sqlite://test.db?mode=rwc");
2024
2025        logs_assert(|lines| {
2026            let loud: Vec<&str> = lines
2027                .iter()
2028                .filter(|line| line.contains(" WARN ") || line.contains(" ERROR "))
2029                .copied()
2030                .collect();
2031            if !loud.is_empty() {
2032                return Err(format!(
2033                    "SQLite SSL enrichment must log nothing at WARN or above, got: {loud:?}"
2034                ));
2035            }
2036
2037            let diagnostic = lines.iter().any(|line| {
2038                line.contains(" DEBUG ") && line.contains("SQLite does not support SSL/TLS")
2039            });
2040            if diagnostic {
2041                Ok(())
2042            } else {
2043                Err("SQLite SSL enrichment must keep its ignore diagnostic at DEBUG level, but none was captured".to_string())
2044            }
2045        });
2046    }
2047
2048    #[test]
2049    fn enrich_invalid_url_returns_error() {
2050        let mut c = SqlEndpointConfig::from_uri(
2051            "sql:select 1?db_url=postgres://localhost/test&sslMode=require",
2052        )
2053        .unwrap();
2054        c.resolve_defaults();
2055        let result = enrich_db_url_with_ssl("://not-a-valid-url", &c);
2056        assert!(result.is_err());
2057    }
2058
2059    // --- Phase B hardening tests ---
2060
2061    // SQL-010: Debug output redacts credentials
2062    #[test]
2063    fn debug_redacts_db_url_with_password() {
2064        let c = SqlEndpointConfig::from_uri(
2065            "sql:select 1?db_url=postgres://user:secret123@localhost/test",
2066        )
2067        .unwrap();
2068        let debug_output = format!("{:?}", c);
2069        assert!(
2070            !debug_output.contains("secret123"),
2071            "Debug output must not contain password: {}",
2072            debug_output
2073        );
2074        assert!(
2075            debug_output.contains("***"),
2076            "Debug output must contain redacted marker: {}",
2077            debug_output
2078        );
2079    }
2080
2081    #[test]
2082    fn debug_redacts_ssl_key() {
2083        let c = SqlEndpointConfig::from_uri(
2084            "sql:select 1?db_url=postgres://localhost/test&sslKey=/secret/key.pem",
2085        )
2086        .unwrap();
2087        let debug_output = format!("{:?}", c);
2088        assert!(
2089            !debug_output.contains("/secret/key.pem"),
2090            "Debug output must not contain ssl_key path: {}",
2091            debug_output
2092        );
2093    }
2094
2095    #[test]
2096    fn debug_global_config_redacts_ssl_key() {
2097        let c = SqlGlobalConfig::default().with_ssl_key("/secret/key.pem");
2098        let debug_output = format!("{:?}", c);
2099        assert!(
2100            !debug_output.contains("/secret/key.pem"),
2101            "Debug output must not contain ssl_key path: {}",
2102            debug_output
2103        );
2104        assert!(
2105            debug_output.contains("***"),
2106            "Debug output must contain redacted marker: {}",
2107            debug_output
2108        );
2109    }
2110
2111    #[test]
2112    fn redact_db_url_with_credentials() {
2113        assert_eq!(
2114            redact_db_url("postgres://user:pass@host/db"),
2115            "postgres://***:***@host/db"
2116        );
2117    }
2118
2119    #[test]
2120    fn redact_db_url_without_credentials() {
2121        assert_eq!(redact_db_url("sqlite::memory:"), "sqlite::memory:");
2122    }
2123
2124    #[test]
2125    fn redact_db_url_invalid_returns_original() {
2126        assert_eq!(redact_db_url("not-a-url"), "not-a-url");
2127    }
2128
2129    #[test]
2130    fn redact_db_url_invalid_with_credentials_redacts() {
2131        // Port out of range (99999) makes url::Url::parse fail, but the raw
2132        // string carries userinfo. The Err branch must still redact it rather
2133        // than return the credential-bearing string verbatim (rc-7rup).
2134        let redacted = redact_db_url("postgres://user:secret@host:99999/db");
2135        assert!(
2136            !redacted.contains("secret"),
2137            "password must be redacted in unparseable URL: {redacted}"
2138        );
2139        assert!(
2140            !redacted.contains("user:secret"),
2141            "userinfo must be redacted: {redacted}"
2142        );
2143        assert!(
2144            !redacted.contains("user"),
2145            "username must be redacted: {redacted}"
2146        );
2147    }
2148
2149    #[test]
2150    fn redact_db_url_at_before_scheme_returns_original() {
2151        // `@` preceding `://` is not userinfo in a valid position; the
2152        // best-effort redactor leaves it unchanged (no false redaction).
2153        assert_eq!(redact_db_url("foo@bar://baz"), "foo@bar://baz");
2154    }
2155
2156    // SQL-004: usePlaceholder parsing
2157    #[test]
2158    fn use_placeholder_defaults_to_true() {
2159        let c =
2160            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
2161        assert!(c.use_placeholder);
2162    }
2163
2164    #[test]
2165    fn use_placeholder_false_from_uri() {
2166        let c = SqlEndpointConfig::from_uri(
2167            "sql:select 1?db_url=postgres://localhost/test&usePlaceholder=false",
2168        )
2169        .unwrap();
2170        assert!(!c.use_placeholder);
2171    }
2172
2173    #[test]
2174    fn use_placeholder_true_from_uri() {
2175        let c = SqlEndpointConfig::from_uri(
2176            "sql:select 1?db_url=postgres://localhost/test&usePlaceholder=true",
2177        )
2178        .unwrap();
2179        assert!(c.use_placeholder);
2180    }
2181
2182    // SQL-004: strict boolean parsing — invalid values rejected
2183    #[test]
2184    fn use_placeholder_rejects_invalid_value() {
2185        let result = SqlEndpointConfig::from_uri(
2186            "sql:select 1?db_url=postgres://localhost/test&usePlaceholder=1",
2187        );
2188        assert!(result.is_err());
2189        let msg = format!("{:?}", result.unwrap_err());
2190        assert!(msg.contains("usePlaceholder") && msg.contains("true") && msg.contains("false"));
2191    }
2192
2193    #[test]
2194    fn use_placeholder_rejects_typo_tru() {
2195        let result = SqlEndpointConfig::from_uri(
2196            "sql:select 1?db_url=postgres://localhost/test&usePlaceholder=tru",
2197        );
2198        assert!(result.is_err());
2199    }
2200
2201    #[test]
2202    fn use_placeholder_rejects_yes() {
2203        let result = SqlEndpointConfig::from_uri(
2204            "sql:select 1?db_url=postgres://localhost/test&usePlaceholder=yes",
2205        );
2206        assert!(result.is_err());
2207    }
2208
2209    #[test]
2210    fn noop_rejects_invalid_value() {
2211        let result =
2212            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test&noop=1");
2213        assert!(result.is_err());
2214        let msg = format!("{:?}", result.unwrap_err());
2215        assert!(msg.contains("noop"));
2216    }
2217
2218    #[test]
2219    fn batch_rejects_invalid_value() {
2220        let result =
2221            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test&batch=yes");
2222        assert!(result.is_err());
2223        let msg = format!("{:?}", result.unwrap_err());
2224        assert!(msg.contains("batch"));
2225    }
2226
2227    #[test]
2228    fn route_empty_result_set_rejects_invalid_value() {
2229        let result = SqlEndpointConfig::from_uri(
2230            "sql:select 1?db_url=postgres://localhost/test&routeEmptyResultSet=on",
2231        );
2232        assert!(result.is_err());
2233    }
2234
2235    #[test]
2236    fn use_iterator_rejects_invalid_value() {
2237        let result = SqlEndpointConfig::from_uri(
2238            "sql:select 1?db_url=postgres://localhost/test&useIterator=1",
2239        );
2240        assert!(result.is_err());
2241    }
2242
2243    #[test]
2244    fn break_batch_on_consume_fail_rejects_invalid_value() {
2245        let result = SqlEndpointConfig::from_uri(
2246            "sql:select 1?db_url=postgres://localhost/test&breakBatchOnConsumeFail=yes",
2247        );
2248        assert!(result.is_err());
2249    }
2250
2251    #[test]
2252    fn use_message_body_for_sql_rejects_invalid_value() {
2253        let result = SqlEndpointConfig::from_uri(
2254            "sql:select 1?db_url=postgres://localhost/test&useMessageBodyForSql=1",
2255        );
2256        assert!(result.is_err());
2257    }
2258
2259    // Case-insensitive true/false still works
2260    #[test]
2261    fn boolean_params_case_insensitive() {
2262        let c = SqlEndpointConfig::from_uri(
2263            "sql:select 1?db_url=postgres://localhost/test&usePlaceholder=TRUE&noop=FALSE&batch=True&useIterator=False&bridgeErrorHandler=TRUE",
2264        )
2265        .unwrap();
2266        assert!(c.use_placeholder);
2267        assert!(!c.noop);
2268        assert!(c.batch);
2269        assert!(!c.use_iterator);
2270        assert!(c.bridge_error_handler);
2271    }
2272
2273    // SQL-022: multi-char placeholder rejected
2274    #[test]
2275    fn multi_char_placeholder_rejected() {
2276        let result = SqlEndpointConfig::from_uri(
2277            "sql:select 1?db_url=postgres://localhost/test&placeholder=##",
2278        );
2279        assert!(result.is_err());
2280        let msg = format!("{:?}", result.unwrap_err());
2281        assert!(msg.contains("placeholder") && msg.contains("one character"));
2282    }
2283
2284    #[test]
2285    fn non_ascii_placeholder_rejected() {
2286        let result = SqlEndpointConfig::from_uri(
2287            "sql:select 1?db_url=postgres://localhost/test&placeholder=%C2%A2",
2288        );
2289        assert!(result.is_err());
2290    }
2291
2292    #[test]
2293    fn single_char_placeholder_accepted() {
2294        let c = SqlEndpointConfig::from_uri(
2295            "sql:select 1?db_url=postgres://localhost/test&placeholder=$",
2296        )
2297        .unwrap();
2298        assert_eq!(c.placeholder, '$');
2299    }
2300
2301    #[test]
2302    fn empty_placeholder_falls_back_to_default() {
2303        // Empty string is filtered out by the original logic — falls back to '#'
2304        let c = SqlEndpointConfig::from_uri(
2305            "sql:select 1?db_url=postgres://localhost/test&placeholder=",
2306        )
2307        .unwrap();
2308        assert_eq!(c.placeholder, '#');
2309    }
2310
2311    // SQL-014: file-based SQL config test (verifies async resolution and caching)
2312    #[tokio::test]
2313    async fn file_query_cached_in_config() {
2314        use std::io::Write;
2315        let unique_name = format!(
2316            "test_sql_cached_{}.sql",
2317            std::time::SystemTime::now()
2318                .duration_since(std::time::UNIX_EPOCH)
2319                .unwrap_or_default()
2320                .as_nanos()
2321        );
2322        let mut tmp = std::env::temp_dir();
2323        tmp.push(unique_name);
2324        {
2325            let mut f = std::fs::File::create(&tmp).unwrap();
2326            writeln!(f, "SELECT * FROM cached_test").unwrap();
2327        }
2328        let uri = format!(
2329            "sql:file:{}?db_url=postgres://localhost/test",
2330            tmp.display()
2331        );
2332        let mut c = SqlEndpointConfig::from_uri(&uri).unwrap();
2333        // Query is empty before async resolution
2334        assert!(c.query.is_empty());
2335        assert_eq!(c.source_path, Some(tmp.to_string_lossy().into_owned()));
2336
2337        // Resolve asynchronously — query is cached in config
2338        c.resolve_file_query()
2339            .await
2340            .expect("resolve should succeed");
2341        assert_eq!(c.query, "SELECT * FROM cached_test");
2342
2343        // Delete the file — config still has the query
2344        std::fs::remove_file(&tmp).ok();
2345        assert_eq!(c.query, "SELECT * FROM cached_test");
2346    }
2347
2348    // --- H-03 audit sweep tests ---
2349
2350    // SQL-005: alwaysPopulateStatement
2351    #[test]
2352    fn always_populate_statement_defaults_to_false() {
2353        let c =
2354            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
2355        assert!(!c.always_populate_statement);
2356    }
2357
2358    #[test]
2359    fn always_populate_statement_from_uri() {
2360        let c = SqlEndpointConfig::from_uri(
2361            "sql:select 1?db_url=postgres://localhost/test&alwaysPopulateStatement=true",
2362        )
2363        .unwrap();
2364        assert!(c.always_populate_statement);
2365    }
2366
2367    // SQL-011: allowNamedParameters
2368    #[test]
2369    fn allow_named_parameters_defaults_to_true() {
2370        let c =
2371            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
2372        assert!(c.allow_named_parameters);
2373    }
2374
2375    #[test]
2376    fn allow_named_parameters_false_from_uri() {
2377        let c = SqlEndpointConfig::from_uri(
2378            "sql:select 1?db_url=postgres://localhost/test&allowNamedParameters=false",
2379        )
2380        .unwrap();
2381        assert!(!c.allow_named_parameters);
2382    }
2383
2384    // SQL-016: fetchSize
2385    #[test]
2386    fn fetch_size_defaults_to_none() {
2387        let c =
2388            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
2389        assert!(c.fetch_size.is_none());
2390    }
2391
2392    #[test]
2393    fn fetch_size_from_uri() {
2394        let c = SqlEndpointConfig::from_uri(
2395            "sql:select 1?db_url=postgres://localhost/test&fetchSize=1000",
2396        )
2397        .unwrap();
2398        assert_eq!(c.fetch_size, Some(1000));
2399    }
2400
2401    // SQL-002: transactionMode
2402    #[test]
2403    fn transaction_mode_defaults_to_auto() {
2404        let c =
2405            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
2406        assert_eq!(c.transaction_mode, TransactionMode::Auto);
2407    }
2408
2409    #[test]
2410    fn transaction_mode_managed_from_uri() {
2411        let c = SqlEndpointConfig::from_uri(
2412            "sql:select 1?db_url=postgres://localhost/test&transactionMode=Managed",
2413        )
2414        .unwrap();
2415        assert_eq!(c.transaction_mode, TransactionMode::Managed);
2416    }
2417
2418    #[test]
2419    fn transaction_mode_invalid_rejected() {
2420        let result = SqlEndpointConfig::from_uri(
2421            "sql:select 1?db_url=postgres://localhost/test&transactionMode=Invalid",
2422        );
2423        assert!(result.is_err());
2424    }
2425
2426    // SQL-015: repeatCount
2427    #[test]
2428    fn repeat_count_defaults_to_none() {
2429        let c =
2430            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
2431        assert!(c.repeat_count.is_none());
2432    }
2433
2434    #[test]
2435    fn repeat_count_from_uri() {
2436        let c = SqlEndpointConfig::from_uri(
2437            "sql:select 1?db_url=postgres://localhost/test&repeatCount=10",
2438        )
2439        .unwrap();
2440        assert_eq!(c.repeat_count, Some(10));
2441    }
2442
2443    // SQL-020: breakOnEmpty
2444    #[test]
2445    fn break_on_empty_defaults_to_false() {
2446        let c =
2447            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
2448        assert!(!c.break_on_empty);
2449    }
2450
2451    #[test]
2452    fn break_on_empty_true_from_uri() {
2453        let c = SqlEndpointConfig::from_uri(
2454            "sql:select 1?db_url=postgres://localhost/test&breakOnEmpty=true",
2455        )
2456        .unwrap();
2457        assert!(c.break_on_empty);
2458    }
2459
2460    #[test]
2461    fn break_on_empty_explicit_false_from_uri() {
2462        let c = SqlEndpointConfig::from_uri(
2463            "sql:select 1?db_url=postgres://localhost/test&breakOnEmpty=false",
2464        )
2465        .unwrap();
2466        assert!(!c.break_on_empty);
2467    }
2468
2469    // SQL-017: processingStrategy
2470    #[test]
2471    fn processing_strategy_defaults_to_direct() {
2472        let c =
2473            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
2474        assert_eq!(c.processing_strategy, ProcessingStrategy::Direct);
2475    }
2476
2477    #[test]
2478    fn processing_strategy_scheduled_from_uri() {
2479        let c = SqlEndpointConfig::from_uri(
2480            "sql:select 1?db_url=postgres://localhost/test&processingStrategy=Scheduled",
2481        )
2482        .unwrap();
2483        assert_eq!(c.processing_strategy, ProcessingStrategy::Scheduled);
2484    }
2485
2486    #[test]
2487    fn processing_strategy_invalid_rejected() {
2488        let result = SqlEndpointConfig::from_uri(
2489            "sql:select 1?db_url=postgres://localhost/test&processingStrategy=Invalid",
2490        );
2491        assert!(result.is_err());
2492    }
2493
2494    // SQL-018: pollStrategy
2495    #[test]
2496    fn poll_strategy_defaults_to_sequential() {
2497        let c =
2498            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
2499        assert_eq!(c.poll_strategy, PollStrategy::Sequential);
2500    }
2501
2502    #[test]
2503    fn poll_strategy_burst_from_uri() {
2504        let c = SqlEndpointConfig::from_uri(
2505            "sql:select 1?db_url=postgres://localhost/test&pollStrategy=Burst",
2506        )
2507        .unwrap();
2508        assert_eq!(c.poll_strategy, PollStrategy::Burst);
2509    }
2510
2511    #[test]
2512    fn poll_strategy_invalid_rejected() {
2513        let result = SqlEndpointConfig::from_uri(
2514            "sql:select 1?db_url=postgres://localhost/test&pollStrategy=Invalid",
2515        );
2516        assert!(result.is_err());
2517    }
2518
2519    // ── RetryPolicy (rc-ddl) ──────────────────────────────────────────────
2520
2521    #[test]
2522    fn sql_endpoint_config_has_retry_policy() {
2523        let cfg = SqlEndpointConfig::from_uri(
2524            "sql:select 1?db_url=sqlite::memory:&retryMaxAttempts=3&retryInitialDelayMs=500",
2525        )
2526        .expect("parse");
2527        assert_eq!(cfg.retry.max_attempts, 3);
2528        assert_eq!(
2529            cfg.retry.initial_delay,
2530            std::time::Duration::from_millis(500)
2531        );
2532        assert!(cfg.retry.enabled);
2533    }
2534
2535    #[test]
2536    fn sql_endpoint_config_retry_defaults_when_unspecified() {
2537        let cfg =
2538            SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite::memory:").expect("parse");
2539        // When URI has no retry params, retry defaults to NetworkRetryPolicy::default()
2540        assert!(cfg.retry.enabled);
2541        assert_eq!(cfg.retry.max_attempts, 10); // default
2542    }
2543
2544    #[test]
2545    fn sql_global_config_has_retry_default() {
2546        let cfg = SqlGlobalConfig::default();
2547        assert!(cfg.retry.enabled);
2548    }
2549
2550    #[test]
2551    fn retry_policy_parse_full_uri_params() {
2552        let cfg = SqlEndpointConfig::from_uri(
2553            "sql:select 1?db_url=sqlite::memory:&retryEnabled=false&retryMaxAttempts=7&retryInitialDelayMs=1000&retryMultiplier=3.0&retryMaxDelayMs=60000&retryJitter=0.5",
2554        )
2555        .expect("parse");
2556        assert!(!cfg.retry.enabled);
2557        assert_eq!(cfg.retry.max_attempts, 7);
2558        assert_eq!(
2559            cfg.retry.initial_delay,
2560            std::time::Duration::from_millis(1000)
2561        );
2562        assert!((cfg.retry.multiplier - 3.0).abs() < f64::EPSILON);
2563        assert_eq!(cfg.retry.max_delay, std::time::Duration::from_millis(60000));
2564        assert!((cfg.retry.jitter_factor - 0.5).abs() < f64::EPSILON);
2565    }
2566
2567    #[test]
2568    fn retry_policy_from_uri_survives_apply_defaults_with_global() {
2569        let mut ep = SqlEndpointConfig::from_uri(
2570            "sql:select 1?db_url=sqlite::memory:&retryMaxAttempts=10&retryInitialDelayMs=500",
2571        )
2572        .expect("parse");
2573        let global = SqlGlobalConfig::default(); // global has default retry (max_attempts=10)
2574        ep.apply_defaults(&global);
2575        // URI values survive when retry_set_from_uri is true
2576        assert_eq!(ep.retry.max_attempts, 10);
2577        assert_eq!(
2578            ep.retry.initial_delay,
2579            std::time::Duration::from_millis(500)
2580        );
2581    }
2582
2583    #[test]
2584    fn retry_policy_falls_back_to_global_when_uri_has_no_retry_params() {
2585        let mut ep =
2586            SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite::memory:").expect("parse");
2587        let mut global = SqlGlobalConfig::default();
2588        global.retry.max_attempts = 7;
2589        ep.apply_defaults(&global);
2590        // When URI has no retry params, global fills the gap
2591        assert_eq!(ep.retry.max_attempts, 7);
2592    }
2593
2594    #[test]
2595    fn from_uri_with_datasource_name() {
2596        let cfg = SqlEndpointConfig::from_uri("sql:SELECT 1?datasource=orders").unwrap();
2597        assert_eq!(cfg.datasource_name.as_deref(), Some("orders"));
2598        assert!(cfg.db_url.is_empty());
2599    }
2600
2601    #[test]
2602    fn from_uri_with_datasource_and_behavior_override() {
2603        let cfg =
2604            SqlEndpointConfig::from_uri("sql:SELECT 1?datasource=orders&outputType=SelectOne")
2605                .unwrap();
2606        assert_eq!(cfg.datasource_name.as_deref(), Some("orders"));
2607    }
2608
2609    #[test]
2610    fn from_uri_datasource_rejects_pool_override() {
2611        let result =
2612            SqlEndpointConfig::from_uri("sql:SELECT 1?datasource=orders&maxConnections=50");
2613        assert!(result.is_err());
2614        let msg = result.unwrap_err().to_string();
2615        assert!(msg.contains("pool-affecting"));
2616    }
2617
2618    #[test]
2619    fn from_uri_neither_datasource_nor_db_url_is_error() {
2620        let result = SqlEndpointConfig::from_uri("sql:SELECT 1");
2621        assert!(result.is_err());
2622    }
2623
2624    #[test]
2625    fn from_uri_db_url_inline_still_works() {
2626        let cfg =
2627            SqlEndpointConfig::from_uri("sql:SELECT 1?db_url=postgres://localhost/test").unwrap();
2628        assert!(cfg.datasource_name.is_none());
2629        assert_eq!(cfg.db_url, "postgres://localhost/test");
2630    }
2631
2632    #[test]
2633    fn from_uri_datasource_rejects_ssl_mode() {
2634        let result = SqlEndpointConfig::from_uri("sql:SELECT 1?datasource=orders&sslMode=require");
2635        assert!(result.is_err());
2636        let msg = result.unwrap_err().to_string();
2637        assert!(msg.contains("pool-affecting"));
2638    }
2639
2640    #[test]
2641    fn from_uri_datasource_rejects_ssl_root_cert() {
2642        let result =
2643            SqlEndpointConfig::from_uri("sql:SELECT 1?datasource=orders&sslRootCert=/ca.pem");
2644        assert!(result.is_err());
2645    }
2646
2647    #[test]
2648    fn from_uri_datasource_rejects_db_url() {
2649        let result = SqlEndpointConfig::from_uri(
2650            "sql:SELECT 1?datasource=orders&db_url=postgres://evil:5432/pwned",
2651        );
2652        assert!(result.is_err());
2653        let msg = result.unwrap_err().to_string();
2654        assert!(msg.contains("db_url") && msg.contains("datasource"));
2655    }
2656}