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