Skip to main content

camel_component_sql/
producer.rs

1use std::future::Future;
2use std::pin::Pin;
3use std::sync::Arc;
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::task::{Context, Poll};
6use std::time::Duration;
7
8use bytes::Bytes;
9use camel_api::datasource::DatasourceCatalog;
10use serde_json::json;
11use sqlx::AnyConnection;
12use sqlx::AnyPool;
13use sqlx::Either;
14use sqlx::Executor;
15use sqlx::SqlSafeStr;
16use sqlx::any::AnyRow;
17use sqlx::any::AnyTypeInfoKind;
18use sqlx::pool::PoolOptions;
19use tokio::sync::OnceCell;
20use tower::Service;
21use tracing::{debug, error, info, warn};
22
23use crate::bind_kinds::{
24    BindTarget, bind_batch_item, bind_single_item, bind_target_from_any_kind,
25    described_mode_eligible, hybrid_fallback_targets, scan_bind_targets,
26};
27use crate::config::{SqlEndpointConfig, SqlOutputType, enrich_db_url_with_ssl, redact_db_url};
28use crate::headers;
29use crate::query::{PreparedQuery, is_select_query, parse_query_template, resolve_params};
30use crate::utils::{fetch_error, is_retryable_sqlx_error, row_to_json};
31use camel_component_api::retry_async;
32use camel_component_api::{
33    Body, CamelError, Exchange, Message, RuntimeObservability, StreamBody, StreamMetadata,
34};
35
36#[derive(Clone)]
37pub struct SqlProducer {
38    pub(crate) config: SqlEndpointConfig,
39    pub(crate) pool: Arc<OnceCell<Arc<AnyPool>>>,
40    pub(crate) catalog: Option<Arc<dyn DatasourceCatalog>>,
41    pub(crate) stopped: Arc<AtomicBool>,
42    pub(crate) runtime: Arc<dyn RuntimeObservability>,
43    /// Route identifier for ADR-0012 (g) health/observability calls.
44    pub(crate) route_id: String,
45}
46
47impl SqlProducer {
48    pub fn new(
49        config: SqlEndpointConfig,
50        pool: Arc<OnceCell<Arc<AnyPool>>>,
51        catalog: Option<Arc<dyn DatasourceCatalog>>,
52        runtime: Arc<dyn RuntimeObservability>,
53        route_id: impl Into<String>,
54    ) -> Self {
55        Self {
56            config,
57            pool,
58            catalog,
59            stopped: Arc::new(AtomicBool::new(false)),
60            runtime,
61            route_id: route_id.into(),
62        }
63    }
64
65    pub fn stop(&self) {
66        self.stopped.store(true, Ordering::Relaxed);
67        // Close the pool asynchronously in the background with a timeout
68        if let Some(pool) = self.pool.get() {
69            let pool = pool.clone();
70            tokio::spawn(async move {
71                if tokio::time::timeout(Duration::from_secs(5), pool.close())
72                    .await
73                    .is_err()
74                {
75                    tracing::warn!("SQL producer pool did not close within 5s");
76                }
77            });
78        }
79    }
80
81    /// Resolves the query source based on priority:
82    /// 1. Header `CamelSql.Query` (only if `allow_dynamic_query=true`)
83    /// 2. Body (only if `allow_dynamic_query=true` AND `use_message_body_for_sql=true`)
84    /// 3. Config query
85    ///
86    /// H7: header/body are untrusted exchange data (ADR-0032). Sourcing the
87    /// query from them is full SQLi (incl. DDL). Both routes require the
88    /// explicit `allow_dynamic_query=true` opt-in.
89    pub(crate) fn resolve_query_source(exchange: &Exchange, config: &SqlEndpointConfig) -> String {
90        if config.allow_dynamic_query {
91            // Priority 1: Header
92            if let Some(query_value) = exchange.input.header(headers::QUERY)
93                && let Some(query_str) = query_value.as_str()
94            {
95                return query_str.to_string();
96            }
97
98            // Priority 2: Body (requires BOTH flags)
99            if config.use_message_body_for_sql
100                && let Some(body_text) = exchange.input.body.as_text()
101            {
102                return body_text.to_string();
103            }
104        }
105
106        // Priority 3: Config query
107        config.query.clone()
108    }
109
110    /// Health check: runs a simple `SELECT 1` query against the connection pool
111    /// to verify database connectivity.
112    ///
113    /// Returns `Ok(())` if the database is reachable, or an error with details
114    /// if the connection fails.
115    pub async fn check_connection(&self) -> Result<(), CamelError> {
116        let pool =
117            if let (Some(catalog), Some(ds_name)) = (&self.catalog, &self.config.datasource_name) {
118                let handle = catalog.get_pool(ds_name).await?;
119                let arc_pool: Arc<AnyPool> = handle.downcast()?;
120                // We don't cache this here — check_connection is a one-shot call
121                arc_pool
122            } else {
123                self.pool
124                    .get()
125                    .ok_or_else(|| {
126                        CamelError::ProcessorError("SQL connection pool not initialized".into())
127                    })?
128                    .clone()
129            };
130
131        debug!("Running health check: SELECT 1");
132        sqlx::query("SELECT 1").execute(&*pool).await.map_err(|e| {
133            warn!(error = %e, "SQL health check failed");
134            CamelError::ProcessorError(format!("SQL health check failed: {}", e))
135        })?;
136
137        debug!("SQL health check passed");
138        Ok(())
139    }
140}
141
142impl Service<Exchange> for SqlProducer {
143    type Response = Exchange;
144    type Error = CamelError;
145    type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
146
147    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
148        if self.stopped.load(Ordering::Relaxed) {
149            return Poll::Ready(Err(CamelError::ProcessorError(
150                "SQL producer stopped".into(),
151            )));
152        }
153        if let Some(pool) = self.pool.get()
154            && pool.is_closed()
155        {
156            return Poll::Ready(Err(CamelError::ProcessorError(
157                "SQL connection pool is closed".into(),
158            )));
159        }
160        Poll::Ready(Ok(()))
161    }
162
163    fn call(&mut self, mut exchange: Exchange) -> Self::Future {
164        let mut config = self.config.clone();
165        let pool_cell = Arc::clone(&self.pool);
166        let catalog = self.catalog.clone();
167        let runtime = Arc::clone(&self.runtime);
168        let route_id = self.route_id.clone();
169
170        Box::pin(async move {
171            // SQL-014: resolve file-based query before pool init, regardless of pool source
172            config.resolve_defaults();
173            config.resolve_file_query().await?;
174
175            // Get or initialize the connection pool
176            let pool: &Arc<AnyPool> = pool_cell
177                .get_or_try_init(|| async {
178                    // Catalog path: resolve shared pool from the datasource catalog
179                    let ds_name = config.datasource_name.clone();
180                    if let (Some(ref cat), Some(ref name)) = (catalog, ds_name) {
181                        let handle = cat.get_pool(name).await?;
182                        return handle.downcast::<AnyPool>();
183                    }
184
185                    let db_url = enrich_db_url_with_ssl(&config.db_url, &config)?;
186
187                    // Install all compiled-in sqlx drivers so AnyPool can resolve them.
188                    // This is idempotent; safe to call multiple times.
189                    sqlx::any::install_default_drivers();
190
191                    let max_conn = config.max_connections.ok_or_else(|| {
192                        CamelError::Config("max_connections not resolved for SQL pool".into())
193                    })?;
194                    let min_conn = config.min_connections.ok_or_else(|| {
195                        CamelError::Config("min_connections not resolved for SQL pool".into())
196                    })?;
197                    let idle_timeout = config.idle_timeout_secs.ok_or_else(|| {
198                        CamelError::Config("idle_timeout_secs not resolved for SQL pool".into())
199                    })?;
200                    let max_lifetime = config.max_lifetime_secs.ok_or_else(|| {
201                        CamelError::Config("max_lifetime_secs not resolved for SQL pool".into())
202                    })?;
203
204                    info!(
205                        db_url = %redact_db_url(&config.db_url),
206                        "SQL producer pool initializing"
207                    );
208                    let retry_policy = &config.retry;
209                    let pool = retry_async::<_, _, _, _, sqlx::Error>(
210                        retry_policy,
211                        "sql",
212                        "producer-pool-init",
213                        || {
214                            async {
215                                PoolOptions::new()
216                                    .max_connections(max_conn)
217                                    .min_connections(min_conn)
218                                    .idle_timeout(Duration::from_secs(idle_timeout))
219                                    .max_lifetime(Duration::from_secs(max_lifetime))
220                                    .connect(&db_url)
221                                    .await
222                            }
223                        },
224                        is_retryable_sqlx_error,
225                        Some(runtime.metrics().as_ref()),
226                    )
227                    .await
228                    .map_err(|e| {
229                        runtime.health().force_unhealthy_for_route(
230                            &route_id,
231                            "g:sql:producer-pool-init",
232                            &e.to_string(),
233                        );
234                        // log-policy: outside-contract
235                        error!(error = %e, db_url = %redact_db_url(&config.db_url), "Failed to connect to database");
236                        CamelError::EndpointCreationFailed(format!(
237                            "Failed to connect to database: {}",
238                            e
239                        ))
240                    })?;
241                    Ok(Arc::new(pool))
242                })
243                .await
244                .map_err(|e: CamelError| e.clone())?;
245
246            // Resolve query string
247            let query_str = Self::resolve_query_source(&exchange, &config);
248
249            // SQL-002: warn if Managed transaction mode requested
250            if config.transaction_mode == crate::config::TransactionMode::Managed {
251                warn!("transactionManager not yet implemented; using Auto mode");
252            }
253
254            debug!(
255                query = %query_str,
256                "executing SQL query"
257            );
258
259            // Execute based on mode
260            if config.batch {
261                // Batch mode: execute_batch handles its own template parsing per item
262                execute_batch(pool.as_ref(), &config, &mut exchange).await?;
263            } else if config.use_placeholder {
264                // Placeholder processing enabled (default): parse template, resolve params, apply header override
265                let template = parse_query_template(&query_str, config.placeholder)?;
266                let mut prepared = resolve_params(&template, &exchange, &config.in_separator)?;
267
268                // CamelSql.Parameters header override
269                if let Some(params_value) = exchange.input.header(headers::PARAMETERS) {
270                    if let Some(arr) = params_value.as_array() {
271                        if arr.len() != prepared.bindings.len() {
272                            warn!(
273                                expected = prepared.bindings.len(),
274                                got = arr.len(),
275                                header = headers::PARAMETERS,
276                                "Parameter count mismatch — SQL has {} placeholders but header provides {} values",
277                                prepared.bindings.len(),
278                                arr.len()
279                            );
280                        }
281                        debug!(
282                            "Overriding bindings from {} header with {} parameters",
283                            headers::PARAMETERS,
284                            arr.len()
285                        );
286                        prepared.bindings = arr.clone();
287                    } else {
288                        warn!(
289                            header = headers::PARAMETERS,
290                            "Header is present but not a JSON array — ignoring parameter override"
291                        );
292                    }
293                }
294
295                debug!(
296                    "Executing prepared SQL ({} bindings)",
297                    prepared.bindings.len()
298                );
299
300                if is_select_query(&prepared.sql) {
301                    execute_select(pool.as_ref(), &prepared, &config, &mut exchange).await?;
302                } else {
303                    execute_modify(pool.as_ref(), &prepared, &config, &mut exchange).await?;
304                }
305            } else {
306                // use_placeholder=false: execute query as-is without template parsing
307                debug!("Executing raw SQL (placeholder processing disabled)");
308                let prepared = PreparedQuery {
309                    sql: query_str,
310                    bindings: vec![],
311                };
312
313                if is_select_query(&prepared.sql) {
314                    execute_select(pool.as_ref(), &prepared, &config, &mut exchange).await?;
315                } else {
316                    execute_modify(pool.as_ref(), &prepared, &config, &mut exchange).await?;
317                }
318            }
319
320            Ok(exchange)
321        })
322    }
323}
324
325/// The bind plan for one single-mode statement (bd rc-mn139): which SQL
326/// text to execute, the per-position wire targets, and whether the
327/// statement may use the persistent cache.
328struct SingleBindPlan {
329    sql: String,
330    targets: Vec<Option<BindTarget>>,
331    persistent: bool,
332}
333
334/// Plans the binds for one single-mode statement on `conn` (the SAME
335/// pooled connection that will execute it — normalization must target
336/// the OIDs of the statement that actually runs, bd rc-mn139).
337async fn plan_single_binds(
338    conn: &mut AnyConnection,
339    sql: &str,
340    bindings: &[serde_json::Value],
341) -> Result<SingleBindPlan, CamelError> {
342    // Nothing to reinterpret: keep the default persistent path, with no
343    // probe round trip.
344    if bindings.is_empty() {
345        return Ok(SingleBindPlan {
346            sql: sql.to_string(),
347            targets: vec![],
348            persistent: true,
349        });
350    }
351
352    // Probe on a distinct SQL-text namespace: preparing with empty
353    // parameter types seeds a statement cache entry under the probed text,
354    // and for unmapped parameter types that entry is one no payload can
355    // satisfy. Keeping the probe on its own text keeps the user's SQL text
356    // namespace clean (mirrors the batch probe).
357    let probe_sql = format!("{sql} /* single-bind-kinds-probe */");
358    let described_kinds = match Executor::prepare_with(
359        &mut *conn,
360        sqlx::AssertSqlSafe(probe_sql).into_sql_str(),
361        &[],
362    )
363    .await
364    {
365        Ok(statement) => match statement.parameters {
366            // An empty type list cannot drive normalization.
367            Some(Either::Left(types)) if !types.is_empty() => Some(
368                types
369                    .iter()
370                    .map(|type_info| type_info.kind())
371                    .collect::<Vec<AnyTypeInfoKind>>(),
372            ),
373            _ => None,
374        },
375        // Metadata unavailable (e.g. NUMERIC columns have no Any mapping).
376        // Server and connection failures propagate unchanged.
377        Err(sqlx::Error::AnyDriverError(_)) => None,
378        Err(e) => {
379            // log-policy: handler-owned
380            // (category a: single-mode probe failure inside producer pipeline)
381            warn!("Single describe probe failed: {}", e);
382            return Err(CamelError::ProcessorError(format!(
383                "SQL query prepare failed: {e}"
384            )));
385        }
386    };
387
388    // The fallback alias is distinct from the probe alias on purpose: sqlx
389    // consults the SQL-text cache before the persistence flag, so a
390    // probe-seeded entry would otherwise be reused. Nothing is cached
391    // under the fallback text.
392    let fallback_sql = format!("{sql} /* single-bind-kinds-fallback */");
393
394    let Some(kinds) = described_kinds else {
395        return Ok(SingleBindPlan {
396            sql: fallback_sql,
397            targets: scan_bind_targets(&[bindings]),
398            persistent: false,
399        });
400    };
401
402    let described_targets = kinds
403        .iter()
404        .map(|kind| bind_target_from_any_kind(*kind))
405        .collect::<Vec<_>>();
406
407    if !described_mode_eligible(&kinds, bindings) {
408        // Hybrid fallback: keep every described numeric target so the
409        // checked guards still fire where the server described a numeric
410        // position; scan only the unresolved ones.
411        return Ok(SingleBindPlan {
412            sql: fallback_sql,
413            targets: hybrid_fallback_targets(&described_targets, bindings),
414            persistent: false,
415        });
416    }
417
418    // Describe with empty Parse parameter types so the server infers the
419    // parameter OIDs from the SQL text. On a cache hit the read-back
420    // parameters are the cached statement's actual OIDs — normalization
421    // targets those, so payloads always match the executed statement.
422    let statement = Executor::prepare_with(
423        &mut *conn,
424        sqlx::AssertSqlSafe(sql.to_string()).into_sql_str(),
425        &[],
426    )
427    .await
428    .map_err(|e| {
429        // log-policy: handler-owned
430        // (category a: single-mode described prepare failure inside producer pipeline)
431        warn!("Single describe failed: {}", e);
432        CamelError::ProcessorError(format!("SQL query prepare failed: {e}"))
433    })?;
434
435    let targets = match statement.parameters {
436        Some(Either::Left(types)) => types
437            .iter()
438            .map(|type_info| bind_target_from_any_kind(type_info.kind()))
439            .collect::<Vec<_>>(),
440        _ => scan_bind_targets(&[bindings]),
441    };
442
443    Ok(SingleBindPlan {
444        sql: sql.to_string(),
445        targets,
446        persistent: true,
447    })
448}
449
450/// Executes one single-mode SELECT on a pooled connection, planning the
451/// binds first (bd rc-mn139). Statements without bindings plan to the
452/// default persistent path with no probe and no binds.
453async fn fetch_single_rows(
454    pool: &AnyPool,
455    prepared: &PreparedQuery,
456) -> Result<Vec<AnyRow>, CamelError> {
457    let mut conn = pool
458        .acquire()
459        .await
460        .map_err(|e| fetch_error("Failed to acquire database connection", e))?;
461
462    let plan = plan_single_binds(&mut conn, &prepared.sql, &prepared.bindings).await?;
463    let query = sqlx::query(sqlx::AssertSqlSafe(plan.sql.as_str())).persistent(plan.persistent);
464    let query = bind_single_item(query, &prepared.bindings, &plan.targets)?;
465    query
466        .fetch_all(&mut *conn)
467        .await
468        .map_err(|e| fetch_error("SQL query failed", e))
469}
470
471/// Executes a SELECT query and populates the exchange body with results.
472async fn execute_select(
473    pool: &AnyPool,
474    prepared: &PreparedQuery,
475    config: &SqlEndpointConfig,
476    exchange: &mut Exchange,
477) -> Result<(), CamelError> {
478    match config.output_type {
479        SqlOutputType::SelectOne => {
480            // fetch_all and take first row
481            let rows = fetch_single_rows(pool, prepared).await?;
482
483            let count = rows.len();
484            debug!(rows = count, "SQL query completed");
485            let json_rows: Vec<serde_json::Value> = rows
486                .iter()
487                .map(row_to_json)
488                .collect::<Result<Vec<_>, _>>()?;
489
490            if let Some(first_row) = json_rows.into_iter().next() {
491                exchange.input.body = Body::Json(first_row);
492            } else {
493                exchange.input.body = Body::Empty;
494            }
495            debug!("SelectOne returned {} row", if count > 0 { 1 } else { 0 });
496            exchange
497                .input
498                .set_header(headers::ROW_COUNT, serde_json::json!(count));
499        }
500        SqlOutputType::SelectList => {
501            // fetch_all for list output
502            let rows = fetch_single_rows(pool, prepared).await?;
503
504            let count = rows.len();
505            debug!(rows = count, "SQL query completed");
506            let json_rows: Vec<serde_json::Value> = rows
507                .iter()
508                .map(row_to_json)
509                .collect::<Result<Vec<_>, _>>()?;
510
511            exchange.input.body = Body::Json(serde_json::Value::Array(json_rows));
512            debug!("SelectList returned {} rows", count);
513            exchange
514                .input
515                .set_header(headers::ROW_COUNT, serde_json::json!(count));
516        }
517        SqlOutputType::StreamList => {
518            // Use fetch() for true streaming - avoids loading all rows into memory
519            use futures::TryStreamExt;
520
521            let pool_clone = pool.clone();
522            let sql_str = prepared.sql.clone();
523            let bindings = prepared.bindings.clone();
524
525            // Build the stream that reads rows on demand and serializes to NDJSON bytes
526            let byte_stream = async_stream::try_stream! {
527                let mut conn = pool_clone
528                    .acquire()
529                    .await
530                    .map_err(|e| fetch_error("Failed to acquire database connection", e))?;
531
532                // Plan and execute against the SAME pooled connection so
533                // normalization targets the OIDs of the statement that
534                // actually runs (bd rc-mn139).
535                let plan = plan_single_binds(&mut conn, &sql_str, &bindings).await?;
536                let q = sqlx::query(sqlx::AssertSqlSafe(plan.sql.as_str()))
537                    .persistent(plan.persistent);
538                let q = bind_single_item(q, &bindings, &plan.targets)?;
539                let mut rows = q.fetch(&mut *conn);
540                while let Some(row) = rows
541                    .try_next()
542                    .await
543                    .map_err(|e| fetch_error("Query execution failed", e))?
544                {
545                    let json_val = row_to_json(&row)?;
546                    let mut bytes = serde_json::to_vec(&json_val)
547                        .map_err(|e| CamelError::ProcessorError(format!("JSON serialization failed: {}", e)))?;
548                    bytes.push(b'\n');
549                    yield Bytes::from(bytes);
550                }
551            };
552
553            exchange.input.body = Body::Stream(StreamBody {
554                stream: Arc::new(tokio::sync::Mutex::new(Some(Box::pin(byte_stream)))),
555                metadata: StreamMetadata {
556                    content_type: Some("application/x-ndjson".to_string()),
557                    size_hint: None,
558                    origin: None,
559                },
560            });
561            debug!("StreamList: created lazy stream (rows fetched on demand)");
562            // Note: ROW_COUNT not set for StreamList since row count is unknown until exhausted
563        }
564    }
565
566    Ok(())
567}
568
569/// Executes a modification query (INSERT/UPDATE/DELETE).
570async fn execute_modify(
571    pool: &AnyPool,
572    prepared: &PreparedQuery,
573    config: &SqlEndpointConfig,
574    exchange: &mut Exchange,
575) -> Result<(), CamelError> {
576    let mut conn = pool
577        .acquire()
578        .await
579        .map_err(|e| fetch_error("Failed to acquire database connection", e))?;
580
581    let plan = plan_single_binds(&mut conn, &prepared.sql, &prepared.bindings).await?;
582    let query = sqlx::query(sqlx::AssertSqlSafe(plan.sql.as_str())).persistent(plan.persistent);
583    let query = bind_single_item(query, &prepared.bindings, &plan.targets)?;
584    let result = query.execute(&mut *conn).await.map_err(|e| {
585        warn!(error = %e, "SQL query failed");
586        CamelError::ProcessorError(format!("Query execution failed: {}", e))
587    })?;
588
589    let rows_affected = result.rows_affected();
590
591    // Fix 4: Implement expected_update_count validation
592    if let Some(expected) = config.expected_update_count
593        && rows_affected as i64 != expected
594    {
595        warn!(expected, actual = rows_affected, "Row count mismatch");
596        return Err(CamelError::ProcessorError(format!(
597            "Expected {} rows affected, got {}",
598            expected, rows_affected
599        )));
600    }
601
602    exchange
603        .input
604        .set_header(headers::UPDATE_COUNT, serde_json::json!(rows_affected));
605
606    if config.noop {
607        // Preserve original body
608    } else {
609        exchange.input.body = Body::Json(json!({ "rowsAffected": rows_affected }));
610    }
611
612    debug!(rows = rows_affected, "SQL modify query completed");
613
614    Ok(())
615}
616
617/// Executes a batch of queries from a JSON array body.
618///
619/// Bind-kind safety (bd rc-fef4z): sqlx keys its statement cache by SQL text
620/// alone and fixes parameter OIDs at the first `Parse`, so a position that
621/// carries different Rust bind kinds across items silently reinterprets
622/// bits. Every position therefore binds exactly one wire encoding per
623/// statement: the server-described encoding when available, otherwise a
624/// per-batch scan (float wins) executed without statement caching.
625async fn execute_batch(
626    pool: &AnyPool,
627    config: &SqlEndpointConfig,
628    exchange: &mut Exchange,
629) -> Result<(), CamelError> {
630    // Body must be JSON array of arrays
631    let body_json = match &exchange.input.body {
632        Body::Json(val) => val,
633        _ => {
634            return Err(CamelError::ProcessorError(
635                "Batch mode requires body to be a JSON array of arrays".to_string(),
636            ));
637        }
638    };
639
640    let batch_data = body_json
641        .as_array()
642        .ok_or_else(|| {
643            CamelError::ProcessorError("Batch mode requires body to be a JSON array".to_string())
644        })?
645        .clone();
646
647    // Parse template from config query
648    let template = parse_query_template(&config.query, config.placeholder)?;
649
650    // Resolve every item up front so the fallback bind-kind scan sees the
651    // whole batch.
652    let mut prepared_items = Vec::with_capacity(batch_data.len());
653    for (batch_idx, params_array) in batch_data.iter().enumerate() {
654        // Each item must be an array of parameters
655        params_array.as_array().ok_or_else(|| {
656            CamelError::ProcessorError(format!(
657                "Batch item at index {} must be a JSON array of parameters",
658                batch_idx
659            ))
660        })?;
661
662        // Create a temporary exchange with the params as body for resolution
663        let temp_msg = Message::new(Body::Json(params_array.clone()));
664        let temp_exchange = Exchange::new(temp_msg);
665
666        prepared_items.push(resolve_params(
667            &template,
668            &temp_exchange,
669            &config.in_separator,
670        )?);
671    }
672
673    // Fallback targets: one bind kind per position across the batch, float wins.
674    let binding_rows: Vec<&[serde_json::Value]> = prepared_items
675        .iter()
676        .map(|prepared| prepared.bindings.as_slice())
677        .collect();
678    let scanned_targets = scan_bind_targets(&binding_rows);
679
680    // Fix 2: Batch operations must be wrapped in a transaction
681    let mut tx = pool.begin().await.map_err(|e| {
682        // log-policy: handler-owned
683        // (category a: tx begin failure inside producer pipeline)
684        warn!(error = %e, "Failed to begin transaction");
685        CamelError::ProcessorError(format!("Failed to begin transaction: {}", e))
686    })?;
687
688    // Probe the described parameter types once with the first item's SQL
689    // text. Described batches keep using the transaction connection (later
690    // items with the same text hit the statement cache for free).
691    let mut described_mode = true;
692    if let Some(first) = prepared_items.first() {
693        // Probe on a distinct SQL-text namespace: preparing with empty
694        // parameter types seeds a statement cache entry under the probed
695        // text, and for unmapped types (e.g. NUMERIC) that entry is one no
696        // payload can satisfy. Keeping the probe on its own text keeps the
697        // user's SQL text namespace clean.
698        let probe_sql = format!("{} /* batch-bind-kinds-probe */", first.sql);
699        described_mode = match Executor::prepare_with(
700            &mut *tx,
701            sqlx::AssertSqlSafe(probe_sql).into_sql_str(),
702            &[],
703        )
704        .await
705        {
706            Ok(statement) => match statement.parameters {
707                // Any-mapped parameter types are described-eligible: numeric
708                // kinds get bind targets, non-numeric kinds (text, bool,
709                // blob) keep the default JSON binding under their described
710                // OIDs. Unmapped kinds (e.g. NUMERIC) fail the probe itself.
711                // An empty type list cannot drive normalization.
712                Some(Either::Left(types)) => !types.is_empty(),
713                _ => false,
714            },
715            // Metadata unavailable (e.g. NUMERIC columns have no Any
716            // mapping). Server and connection failures propagate unchanged.
717            Err(sqlx::Error::AnyDriverError(_)) => false,
718            Err(e) => {
719                // log-policy: handler-owned
720                // (category a: batch probe failure inside producer pipeline)
721                warn!("Batch describe probe failed: {}", e);
722                return Err(CamelError::ProcessorError(format!(
723                    "Batch query prepare failed: {e}"
724                )));
725            }
726        };
727    }
728
729    let mut total_rows_affected: u64 = 0;
730
731    for (batch_idx, prepared) in prepared_items.iter().enumerate() {
732        let (mut query, targets) = if described_mode {
733            // Describe with empty Parse parameter types so the server infers
734            // the parameter OIDs from the SQL text. On a cache hit the
735            // read-back parameters are the cached statement's actual OIDs —
736            // normalization targets those, so payloads always match the
737            // executed statement.
738            let statement = Executor::prepare_with(
739                &mut *tx,
740                sqlx::AssertSqlSafe(prepared.sql.clone()).into_sql_str(),
741                &[],
742            )
743            .await
744            .map_err(|e| {
745                // log-policy: handler-owned
746                // (category a: batch describe failure inside producer pipeline)
747                warn!("Batch describe failed at index {}: {}", batch_idx, e);
748                CamelError::ProcessorError(format!("Batch query prepare failed: {e}"))
749            })?;
750            let query = sqlx::query(sqlx::AssertSqlSafe(prepared.sql.as_str()));
751            let targets = match statement.parameters {
752                Some(Either::Left(types)) => types
753                    .iter()
754                    .map(|type_info| bind_target_from_any_kind(type_info.kind()))
755                    .collect::<Vec<_>>(),
756                _ => scanned_targets.clone(),
757            };
758            (query, targets)
759        } else {
760            // Uncached fallback: execute a semantically identical alias text
761            // in its own cache namespace with persistent(false), so every
762            // item prepares an unnamed statement whose parameter types
763            // derive from the scan-normalized binds. Nothing is cached and
764            // nothing else uses this namespace, so no incompatible cached
765            // entry can be reused.
766            let fallback_sql = format!("{} /* batch-bind-kinds-fallback */", prepared.sql);
767            let query = sqlx::query(sqlx::AssertSqlSafe(fallback_sql.as_str())).persistent(false);
768            (query, scanned_targets.clone())
769        };
770
771        query = bind_batch_item(query, &prepared.bindings, &targets, batch_idx)?;
772
773        let result = query.execute(&mut *tx).await.map_err(|e| {
774            // log-policy: handler-owned
775            // (category a: batch query execution failure inside producer pipeline)
776            warn!("Batch query execution failed at index {}: {}", batch_idx, e);
777            CamelError::ProcessorError(format!("Batch query execution failed: {}", e))
778        })?;
779
780        // Validate expected_update_count per batch item
781        if let Some(expected) = config.expected_update_count
782            && result.rows_affected() as i64 != expected
783        {
784            // log-policy: handler-owned
785            // (category a: expected_update_count mismatch inside producer pipeline)
786            warn!(
787                "Batch item {}: expected {} rows affected, got {}",
788                batch_idx,
789                expected,
790                result.rows_affected()
791            );
792            return Err(CamelError::ProcessorError(format!(
793                "Batch item {}: expected {} rows affected, got {}",
794                batch_idx,
795                expected,
796                result.rows_affected()
797            )));
798        }
799
800        total_rows_affected += result.rows_affected();
801    }
802
803    // Commit the transaction
804    tx.commit().await.map_err(|e| {
805        // log-policy: handler-owned
806        // (category a: tx commit failure inside producer pipeline)
807        warn!(error = %e, "Failed to commit transaction");
808        CamelError::ProcessorError(format!("Failed to commit transaction: {}", e))
809    })?;
810
811    exchange.input.set_header(
812        headers::UPDATE_COUNT,
813        serde_json::json!(total_rows_affected),
814    );
815
816    debug!(
817        "Batch execution completed, total rows affected: {}",
818        total_rows_affected
819    );
820
821    Ok(())
822}
823
824#[cfg(test)]
825mod tests {
826    use super::*;
827    use crate::bind_kinds::bind_json_values;
828    use camel_api::MetricsCollector;
829    use camel_component_api::HealthCheckRegistry;
830    use camel_component_api::test_support::PanicRuntimeObservability;
831    fn test_rt() -> std::sync::Arc<dyn camel_component_api::RuntimeObservability> {
832        std::sync::Arc::new(PanicRuntimeObservability)
833    }
834    use camel_component_api::Message;
835    use camel_component_api::UriConfig;
836    use sqlx::any::AnyPoolOptions;
837    use std::sync::Arc;
838    use std::sync::Mutex;
839    use tokio::sync::OnceCell;
840
841    // ── Recording health fixture for ADR-0012 (g) tests ───────────────────
842
843    #[derive(Debug, Default)]
844    struct RecordingHealth {
845        forced: Mutex<Vec<(String, String, String)>>,
846    }
847
848    impl HealthCheckRegistry for RecordingHealth {
849        fn force_unhealthy_for_route(&self, route_id: &str, name: &str, reason: &str) {
850            self.forced.lock().unwrap().push((
851                route_id.to_string(),
852                name.to_string(),
853                reason.to_string(),
854            ));
855        }
856    }
857
858    struct NoopMetrics;
859
860    impl MetricsCollector for NoopMetrics {
861        fn record_exchange_duration(&self, _: &str, _: Duration) {}
862        fn increment_errors(&self, _: &str, _: &str) {}
863        fn increment_exchanges(&self, _: &str) {}
864        fn set_queue_depth(&self, _: &str, _: usize) {}
865        fn record_circuit_breaker_change(&self, _: &str, _: &str, _: &str) {}
866    }
867
868    struct RecordingRuntime {
869        health: Arc<RecordingHealth>,
870    }
871
872    impl RuntimeObservability for RecordingRuntime {
873        fn metrics(&self) -> Arc<dyn MetricsCollector> {
874            Arc::new(NoopMetrics)
875        }
876        fn health(&self) -> Arc<dyn HealthCheckRegistry> {
877            self.health.clone()
878        }
879    }
880
881    async fn sqlite_pool() -> AnyPool {
882        sqlx::any::install_default_drivers();
883        // Per-attempt deadline (lintwiden D4.3): a wedged pool connect
884        // must fail the helper instead of parking it.
885        tokio::time::timeout(
886            std::time::Duration::from_secs(10),
887            AnyPoolOptions::new()
888                .max_connections(1)
889                .connect("sqlite::memory:"),
890        )
891        .await
892        .expect("sqlite pool connect timed out after 10s")
893        .expect("sqlite pool")
894    }
895
896    async fn seed_items_table(pool: &AnyPool) {
897        sqlx::query(
898            "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT, done INTEGER DEFAULT 0)",
899        )
900        .execute(pool)
901        .await
902        .expect("create table");
903        sqlx::query("INSERT INTO items (id, name, done) VALUES (1, 'a', 0), (2, 'b', 0)")
904            .execute(pool)
905            .await
906            .expect("seed rows");
907    }
908
909    fn config() -> SqlEndpointConfig {
910        let mut c =
911            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
912        c.resolve_defaults();
913        c
914    }
915
916    #[test]
917    fn producer_clone_shares_pool() {
918        let p1 = SqlProducer::new(
919            config(),
920            Arc::new(OnceCell::new()),
921            None,
922            test_rt(),
923            "sql-producer-test-route",
924        );
925        let p2 = p1.clone();
926        assert!(Arc::ptr_eq(&p1.pool, &p2.pool));
927        assert!(Arc::ptr_eq(&p1.stopped, &p2.stopped));
928    }
929
930    #[test]
931    fn resolve_query_from_config() {
932        let config = config();
933        let ex = Exchange::new(Message::default());
934        let q = SqlProducer::resolve_query_source(&ex, &config);
935        assert_eq!(q, "select 1");
936    }
937
938    #[test]
939    fn resolve_query_from_header() {
940        let mut config = config();
941        config.allow_dynamic_query = true;
942        let mut msg = Message::default();
943        msg.set_header(headers::QUERY, serde_json::json!("select 2"));
944        let ex = Exchange::new(msg);
945        let q = SqlProducer::resolve_query_source(&ex, &config);
946        assert_eq!(q, "select 2");
947    }
948
949    #[test]
950    fn resolve_query_from_body() {
951        let mut config = config();
952        config.use_message_body_for_sql = true;
953        config.allow_dynamic_query = true;
954        let msg = Message::new(Body::Text("select 3".to_string()));
955        let ex = Exchange::new(msg);
956        let q = SqlProducer::resolve_query_source(&ex, &config);
957        assert_eq!(q, "select 3");
958    }
959
960    #[test]
961    fn resolve_query_header_priority_over_body() {
962        let mut config = config();
963        config.use_message_body_for_sql = true;
964        config.allow_dynamic_query = true;
965        let mut msg = Message::new(Body::Text("select from body".to_string()));
966        msg.set_header(headers::QUERY, serde_json::json!("select from header"));
967        let ex = Exchange::new(msg);
968        let q = SqlProducer::resolve_query_source(&ex, &config);
969        assert_eq!(q, "select from header");
970    }
971
972    #[test]
973    fn resolve_query_body_priority_over_config() {
974        let mut config = config();
975        config.use_message_body_for_sql = true;
976        config.allow_dynamic_query = true;
977        let msg = Message::new(Body::Text("select from body".to_string()));
978        let ex = Exchange::new(msg);
979        let q = SqlProducer::resolve_query_source(&ex, &config);
980        assert_eq!(q, "select from body");
981    }
982
983    // H7: dynamic queries from exchange data must be denied by default.
984    // The CamelSql.Query header and body are untrusted (ADR-0032). Reading
985    // them as a SQL source is a SQLi vector including DDL. Default is closed.
986    #[test]
987    fn dynamic_query_denied_by_default() {
988        let mut msg = Message::default();
989        msg.set_header(headers::QUERY, "DROP TABLE users; --");
990        let ex = Exchange::new(msg);
991
992        let mut config = config();
993        config.query = "SELECT 1".to_string();
994        // allow_dynamic_query defaults to false → header ignored
995
996        let q = SqlProducer::resolve_query_source(&ex, &config);
997        // Must return the config query, NOT the header
998        assert_eq!(q, "SELECT 1");
999    }
1000
1001    // H7: with explicit opt-in (allow_dynamic_query=true), header takes priority.
1002    #[test]
1003    fn dynamic_query_allowed_with_opt_in() {
1004        let mut msg = Message::default();
1005        msg.set_header(headers::QUERY, "SELECT 1 FROM users WHERE id = :#id");
1006        let ex = Exchange::new(msg);
1007
1008        let mut config = config();
1009        config.query = "SELECT 1".to_string();
1010        config.allow_dynamic_query = true;
1011
1012        let q = SqlProducer::resolve_query_source(&ex, &config);
1013        // With opt-in, header takes priority
1014        assert_eq!(q, "SELECT 1 FROM users WHERE id = :#id");
1015    }
1016
1017    #[test]
1018    fn bind_json_null() {
1019        let query = sqlx::query("SELECT ?");
1020        let values = vec![serde_json::Value::Null];
1021        let _bound = bind_json_values(query, &values);
1022        // Compilation test - ensure it binds
1023    }
1024
1025    #[test]
1026    fn bind_json_bool() {
1027        let query = sqlx::query("SELECT ?");
1028        let values = vec![serde_json::Value::Bool(true)];
1029        let _bound = bind_json_values(query, &values);
1030    }
1031
1032    #[test]
1033    fn bind_json_number_i64() {
1034        let query = sqlx::query("SELECT ?");
1035        let values = vec![serde_json::json!(42)];
1036        let _bound = bind_json_values(query, &values);
1037    }
1038
1039    #[test]
1040    fn bind_json_number_f64() {
1041        let query = sqlx::query("SELECT ?");
1042        let values = vec![serde_json::json!(std::f64::consts::PI)];
1043        let _bound = bind_json_values(query, &values);
1044    }
1045
1046    #[test]
1047    fn bind_json_string() {
1048        let query = sqlx::query("SELECT ?");
1049        let values = vec![serde_json::json!("hello world")];
1050        let _bound = bind_json_values(query, &values);
1051    }
1052
1053    #[test]
1054    fn bind_json_array() {
1055        let query = sqlx::query("SELECT ?");
1056        let values = vec![serde_json::json!([1, 2, 3])];
1057        let _bound = bind_json_values(query, &values);
1058    }
1059
1060    #[test]
1061    fn bind_json_object() {
1062        let query = sqlx::query("SELECT ?");
1063        let values = vec![serde_json::json!({"key": "value"})];
1064        let _bound = bind_json_values(query, &values);
1065    }
1066
1067    #[test]
1068    fn bind_multiple_values() {
1069        let query = sqlx::query("SELECT ?, ?, ?");
1070        let values = vec![
1071            serde_json::json!(1),
1072            serde_json::json!("test"),
1073            serde_json::Value::Null,
1074        ];
1075        let _bound = bind_json_values(query, &values);
1076    }
1077
1078    // Test for Fix 4: expected_update_count config field presence
1079    #[test]
1080    fn expected_update_count_validation() {
1081        // Test that expected_update_count is parsed from URI
1082        let config = SqlEndpointConfig::from_uri(
1083            "sql:update t set x=1?db_url=postgres://localhost/test&expectedUpdateCount=5",
1084        )
1085        .unwrap();
1086        assert_eq!(config.expected_update_count, Some(5));
1087
1088        // Test default (no expected_update_count)
1089        let config_default = self::config();
1090        assert_eq!(config_default.expected_update_count, None);
1091
1092        // Test negative value (should parse)
1093        let config_neg = SqlEndpointConfig::from_uri(
1094            "sql:update t set x=1?db_url=postgres://localhost/test&expectedUpdateCount=-1",
1095        )
1096        .unwrap();
1097        assert_eq!(config_neg.expected_update_count, Some(-1));
1098    }
1099
1100    // Test for Fix 3: parameters header override logic
1101    #[test]
1102    fn parameters_header_override_logic() {
1103        // Create a PreparedQuery manually
1104        let mut prepared = PreparedQuery {
1105            sql: "SELECT * FROM t WHERE id = $1".to_string(),
1106            bindings: vec![serde_json::json!(42)],
1107        };
1108
1109        // Simulate the header override logic
1110        let header_params = serde_json::json!([99, "extra"]);
1111        if let Some(arr) = header_params.as_array() {
1112            prepared.bindings = arr.clone();
1113        }
1114
1115        // Verify bindings were overridden
1116        assert_eq!(prepared.bindings.len(), 2);
1117        assert_eq!(prepared.bindings[0], serde_json::json!(99));
1118        assert_eq!(prepared.bindings[1], serde_json::json!("extra"));
1119
1120        // Test with non-array header (should not override)
1121        let mut prepared2 = PreparedQuery {
1122            sql: "SELECT * FROM t WHERE id = $1".to_string(),
1123            bindings: vec![serde_json::json!(42)],
1124        };
1125        let header_non_array = serde_json::json!({"not": "an array"});
1126        if let Some(arr) = header_non_array.as_array() {
1127            prepared2.bindings = arr.clone();
1128        }
1129        // Should remain unchanged
1130        assert_eq!(prepared2.bindings.len(), 1);
1131        assert_eq!(prepared2.bindings[0], serde_json::json!(42));
1132    }
1133
1134    #[tokio::test]
1135    async fn execute_select_one_sets_body_and_row_count() {
1136        let pool = sqlite_pool().await;
1137        seed_items_table(&pool).await;
1138
1139        let mut config = SqlEndpointConfig::from_uri(
1140            "sql:select id, name from items order by id?db_url=sqlite::memory:&outputType=SelectOne",
1141        )
1142        .unwrap();
1143        config.resolve_defaults();
1144
1145        let prepared = PreparedQuery {
1146            sql: "select id, name from items order by id".to_string(),
1147            bindings: vec![],
1148        };
1149        let mut exchange = Exchange::new(Message::default());
1150
1151        execute_select(&pool, &prepared, &config, &mut exchange)
1152            .await
1153            .expect("select one");
1154
1155        assert_eq!(exchange.input.header(headers::ROW_COUNT), Some(&json!(2)));
1156        assert_eq!(
1157            exchange.input.body,
1158            Body::Json(json!({"id": 1, "name": "a"}))
1159        );
1160    }
1161
1162    #[tokio::test]
1163    async fn execute_stream_list_materializes_ndjson() {
1164        let pool = sqlite_pool().await;
1165        seed_items_table(&pool).await;
1166
1167        let mut config = SqlEndpointConfig::from_uri(
1168            "sql:select id from items order by id?db_url=sqlite::memory:&outputType=StreamList",
1169        )
1170        .unwrap();
1171        config.resolve_defaults();
1172
1173        let prepared = PreparedQuery {
1174            sql: "select id from items order by id".to_string(),
1175            bindings: vec![],
1176        };
1177        let mut exchange = Exchange::new(Message::default());
1178
1179        execute_select(&pool, &prepared, &config, &mut exchange)
1180            .await
1181            .expect("stream list");
1182
1183        let bytes = exchange
1184            .input
1185            .body
1186            .clone()
1187            .into_bytes(1024)
1188            .await
1189            .expect("stream bytes");
1190        let text = String::from_utf8(bytes.to_vec()).expect("utf8");
1191        assert!(text.contains("{\"id\":1}"));
1192        assert!(text.contains("{\"id\":2}"));
1193        assert_eq!(exchange.input.header(headers::ROW_COUNT), None);
1194    }
1195
1196    #[tokio::test]
1197    async fn execute_modify_expected_update_count_mismatch_returns_error() {
1198        let pool = sqlite_pool().await;
1199        seed_items_table(&pool).await;
1200
1201        let mut config = SqlEndpointConfig::from_uri(
1202            "sql:update items set done=1 where id = #?db_url=sqlite::memory:&expectedUpdateCount=2",
1203        )
1204        .unwrap();
1205        config.resolve_defaults();
1206
1207        let prepared = PreparedQuery {
1208            sql: "update items set done=1 where id = $1".to_string(),
1209            bindings: vec![json!(1)],
1210        };
1211        let mut exchange = Exchange::new(Message::default());
1212
1213        let err = execute_modify(&pool, &prepared, &config, &mut exchange)
1214            .await
1215            .expect_err("must fail due expected row count mismatch");
1216        assert!(err.to_string().contains("Expected 2 rows affected, got 1"));
1217    }
1218
1219    #[tokio::test]
1220    async fn execute_batch_rollback_when_any_item_fails_expected_count() {
1221        let pool = sqlite_pool().await;
1222        seed_items_table(&pool).await;
1223
1224        let mut config = SqlEndpointConfig::from_uri(
1225            "sql:update items set done=1 where id = #?db_url=sqlite::memory:&batch=true&expectedUpdateCount=1",
1226        )
1227        .unwrap();
1228        config.resolve_defaults();
1229
1230        let mut exchange = Exchange::new(Message::new(Body::Json(json!([[1], [999]]))));
1231
1232        let err = execute_batch(&pool, &config, &mut exchange)
1233            .await
1234            .expect_err("second batch item should fail expectedUpdateCount");
1235        assert!(
1236            err.to_string()
1237                .contains("Batch item 1: expected 1 rows affected, got 0")
1238        );
1239
1240        let row = sqlx::query("select done from items where id = 1")
1241            .fetch_one(&pool)
1242            .await
1243            .expect("query row");
1244        let done: i64 = sqlx::Row::try_get(&row, 0).expect("done column");
1245        assert_eq!(done, 0, "transaction must rollback first update");
1246    }
1247
1248    // --- Phase B hardening tests ---
1249
1250    // SQL-001: Direct producer construction without resolve_defaults does not panic.
1251    // The producer defensively calls resolve_defaults() during pool init, so the pool
1252    // fields get resolved. This test verifies no panic occurs and the pool initializes.
1253    #[tokio::test]
1254    async fn producer_no_panic_without_prior_resolve_defaults() {
1255        // Create config without calling resolve_defaults() — pool fields are None
1256        let config = SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite::memory:").unwrap();
1257        assert!(config.max_connections.is_none());
1258
1259        let mut producer = SqlProducer::new(
1260            config,
1261            Arc::new(OnceCell::new()),
1262            None,
1263            // Noop runtime: pool-init retries now record per-attempt
1264            // telemetry by design, which the panic runtime would reject.
1265            std::sync::Arc::new(camel_component_api::test_support::NoopRuntimeObservability),
1266            "sql-producer-test-route",
1267        );
1268        let exchange = Exchange::new(Message::default());
1269
1270        // Should NOT panic — producer calls resolve_defaults() defensively
1271        let result = producer.call(exchange).await;
1272        assert!(
1273            result.is_ok(),
1274            "Producer should initialize pool without panic, got: {:?}",
1275            result
1276        );
1277    }
1278
1279    // SQL-001: Pool init returns CamelError::Config when pool params cannot be resolved
1280    #[tokio::test]
1281    async fn producer_pool_init_returns_config_error_for_invalid_db() {
1282        // Create config with an invalid db_url that will fail to connect.
1283        // Disable retry for this test — the purpose is to verify error handling
1284        // on a known-bad connect, not to exercise the retry loop.
1285        let mut config = SqlEndpointConfig::from_uri(
1286            "sql:select 1?db_url=postgres://nonexistent-host:5432/nonexistent_db&retryEnabled=false",
1287        )
1288        .unwrap();
1289        // Set pool params explicitly so resolve_defaults doesn't help with connection
1290        config.max_connections = Some(1);
1291        config.min_connections = Some(0);
1292        config.idle_timeout_secs = Some(300);
1293        config.max_lifetime_secs = Some(1800);
1294
1295        let health = Arc::new(RecordingHealth::default());
1296        let rt: Arc<dyn RuntimeObservability> = Arc::new(RecordingRuntime {
1297            health: health.clone(),
1298        });
1299        let mut producer = SqlProducer::new(
1300            config,
1301            Arc::new(OnceCell::new()),
1302            None,
1303            rt,
1304            "sql-producer-test-route",
1305        );
1306        let exchange = Exchange::new(Message::default());
1307
1308        let result = producer.call(exchange).await;
1309        assert!(result.is_err());
1310        // Error should be EndpointCreationFailed (connection error), not a panic
1311        let err_msg = result.unwrap_err().to_string();
1312        assert!(
1313            err_msg.contains("Failed to connect") || err_msg.contains("database"),
1314            "Expected connection error, got: {}",
1315            err_msg
1316        );
1317        // Verify force_unhealthy_for_route was also called
1318        let forced = health.forced.lock().unwrap();
1319        assert_eq!(
1320            forced.len(),
1321            1,
1322            "expected one force_unhealthy_for_route call"
1323        );
1324        assert_eq!(forced[0].0, "sql-producer-test-route");
1325        assert_eq!(forced[0].1, "g:sql:producer-pool-init");
1326    }
1327
1328    // SQL-007: poll_ready returns Ready (pool lazily initialized on first call)
1329    #[test]
1330    fn poll_ready_returns_ready_for_uninitialized_pool() {
1331        let config = {
1332            let mut c = SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite::memory:").unwrap();
1333            c.resolve_defaults();
1334            c
1335        };
1336        let mut producer = SqlProducer::new(
1337            config,
1338            Arc::new(OnceCell::new()),
1339            None,
1340            test_rt(),
1341            "sql-producer-test-route",
1342        );
1343        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1344        let result = producer.poll_ready(&mut cx);
1345        assert!(matches!(result, Poll::Ready(Ok(()))));
1346    }
1347
1348    // SQL-007: poll_ready returns error when stopped flag is set
1349    #[test]
1350    fn poll_ready_returns_error_when_stopped() {
1351        let config = {
1352            let mut c = SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite::memory:").unwrap();
1353            c.resolve_defaults();
1354            c
1355        };
1356        let mut producer = SqlProducer::new(
1357            config,
1358            Arc::new(OnceCell::new()),
1359            None,
1360            test_rt(),
1361            "sql-producer-test-route",
1362        );
1363        producer.stop();
1364        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1365        let result = producer.poll_ready(&mut cx);
1366        assert!(matches!(result, Poll::Ready(Err(_))));
1367        let err_msg = match result {
1368            Poll::Ready(Err(e)) => e.to_string(),
1369            _ => unreachable!(),
1370        };
1371        assert!(err_msg.contains("SQL producer stopped"));
1372    }
1373
1374    // SQL-007: poll_ready returns error when pool is closed
1375    #[tokio::test]
1376    async fn poll_ready_returns_error_when_pool_closed() {
1377        let pool = sqlite_pool().await;
1378        pool.close().await;
1379
1380        let config = {
1381            let mut c = SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite::memory:").unwrap();
1382            c.resolve_defaults();
1383            c
1384        };
1385        let pool_cell = Arc::new(OnceCell::new());
1386        pool_cell.set(Arc::new(pool)).unwrap();
1387
1388        let mut producer = SqlProducer::new(
1389            config,
1390            pool_cell,
1391            None,
1392            test_rt(),
1393            "sql-producer-test-route",
1394        );
1395        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1396        let result = producer.poll_ready(&mut cx);
1397        assert!(matches!(result, Poll::Ready(Err(_))));
1398        let err_msg = match result {
1399            Poll::Ready(Err(e)) => e.to_string(),
1400            _ => unreachable!(),
1401        };
1402        assert!(err_msg.contains("SQL connection pool is closed"));
1403    }
1404
1405    // SQL-007: poll_ready returns Ok for healthy initialized pool
1406    #[tokio::test]
1407    async fn poll_ready_returns_ok_for_healthy_pool() {
1408        let pool = sqlite_pool().await;
1409
1410        let config = {
1411            let mut c = SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite::memory:").unwrap();
1412            c.resolve_defaults();
1413            c
1414        };
1415        let pool_cell = Arc::new(OnceCell::new());
1416        pool_cell.set(Arc::new(pool)).unwrap();
1417
1418        let mut producer = SqlProducer::new(
1419            config,
1420            pool_cell,
1421            None,
1422            test_rt(),
1423            "sql-producer-test-route",
1424        );
1425        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1426        let result = producer.poll_ready(&mut cx);
1427        assert!(matches!(result, Poll::Ready(Ok(()))));
1428    }
1429
1430    // SQL-008: stop() closes the pool
1431    #[tokio::test]
1432    async fn test_sql_stop_closes_pool() {
1433        let pool = sqlite_pool().await;
1434
1435        let config = {
1436            let mut c = SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite::memory:").unwrap();
1437            c.resolve_defaults();
1438            c
1439        };
1440        let pool_cell = Arc::new(OnceCell::new());
1441        pool_cell.set(Arc::new(pool.clone())).unwrap();
1442
1443        let producer = SqlProducer::new(
1444            config,
1445            pool_cell.clone(),
1446            None,
1447            test_rt(),
1448            "sql-producer-test-route",
1449        );
1450        assert!(!pool.is_closed(), "Pool should be open before stop");
1451
1452        producer.stop();
1453
1454        // Allow background close task to complete
1455        tokio::time::sleep(Duration::from_millis(100)).await;
1456
1457        assert!(
1458            pool.is_closed(),
1459            "Pool should be closed after producer.stop()"
1460        );
1461
1462        // Subsequent poll_ready should fail
1463        let mut producer2 = SqlProducer::new(
1464            {
1465                let mut c =
1466                    SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite::memory:").unwrap();
1467                c.resolve_defaults();
1468                c
1469            },
1470            pool_cell.clone(),
1471            None,
1472            test_rt(),
1473            "sql-producer-test-route",
1474        );
1475        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1476        let result = producer2.poll_ready(&mut cx);
1477        assert!(
1478            matches!(result, Poll::Ready(Err(_))),
1479            "poll_ready should fail after pool closed"
1480        );
1481    }
1482
1483    // SQL-004: use_placeholder=false skips template parsing
1484    #[tokio::test]
1485    async fn use_placeholder_false_executes_raw_sql() {
1486        let pool = sqlite_pool().await;
1487        seed_items_table(&pool).await;
1488
1489        let mut config = SqlEndpointConfig::from_uri(
1490            "sql:select id, name from items order by id?db_url=sqlite::memory:&usePlaceholder=false",
1491        )
1492        .unwrap();
1493        config.resolve_defaults();
1494        assert!(!config.use_placeholder);
1495
1496        let mut producer = SqlProducer::new(
1497            config,
1498            Arc::new(OnceCell::new()),
1499            None,
1500            test_rt(),
1501            "sql-producer-test-route",
1502        );
1503        // Pre-initialize the pool so we don't hit the pool init path
1504        producer.pool.set(Arc::new(pool.clone())).unwrap();
1505
1506        let exchange = Exchange::new(Message::default());
1507        let result = producer.call(exchange).await;
1508        assert!(result.is_ok());
1509        let exchange = result.unwrap();
1510        // Should return results, not rowsAffected
1511        assert!(matches!(exchange.input.body, Body::Json(_)));
1512    }
1513
1514    // SQL-004: use_placeholder=true (default) processes placeholders normally
1515    #[tokio::test]
1516    async fn use_placeholder_true_processes_placeholders() {
1517        let pool = sqlite_pool().await;
1518        seed_items_table(&pool).await;
1519
1520        let mut config = SqlEndpointConfig::from_uri(
1521            "sql:select id, name from items where id = #?db_url=sqlite::memory:",
1522        )
1523        .unwrap();
1524        config.resolve_defaults();
1525        assert!(config.use_placeholder);
1526
1527        let mut producer = SqlProducer::new(
1528            config,
1529            Arc::new(OnceCell::new()),
1530            None,
1531            test_rt(),
1532            "sql-producer-test-route",
1533        );
1534        producer.pool.set(Arc::new(pool.clone())).unwrap();
1535
1536        let msg = Message::new(Body::Json(json!([1])));
1537        let exchange = Exchange::new(msg);
1538        let result = producer.call(exchange).await;
1539        assert!(result.is_ok());
1540    }
1541
1542    /// Regression: max_attempts=N → exactly N invocations (caught OpenSearch off-by-one 1f5c4c2a).
1543    /// Replicates the exact retry loop from SqlProducer::start() (producer.rs:161-185):
1544    ///   attempt starts at 0, incremented at top, should_retry(attempt), delay_for(attempt-1)
1545    #[tokio::test]
1546    async fn retry_loop_invokes_operation_exactly_max_attempts_times() {
1547        use camel_component_api::NetworkRetryPolicy;
1548        use std::sync::Arc;
1549        use std::sync::atomic::{AtomicU32, Ordering};
1550
1551        let policy = NetworkRetryPolicy {
1552            max_attempts: 3,
1553            initial_delay: Duration::from_millis(1),
1554            max_delay: Duration::from_millis(1),
1555            multiplier: 1.0,
1556            ..NetworkRetryPolicy::default()
1557        };
1558
1559        let calls = Arc::new(AtomicU32::new(0));
1560        let calls_clone = Arc::clone(&calls);
1561
1562        let mut attempt: u32 = 0;
1563        let _result: Result<(), ()> = tokio::time::timeout(Duration::from_secs(30), async {
1564            loop {
1565                attempt += 1;
1566                calls_clone.fetch_add(1, Ordering::SeqCst);
1567                let op_result: Result<(), ()> = Err(());
1568                match op_result {
1569                    Ok(v) => break Ok(v),
1570                    Err(_) if policy.should_retry(attempt) => {
1571                        let delay = policy.delay_for(attempt - 1);
1572                        tokio::time::sleep(delay).await;
1573                        continue;
1574                    }
1575                    Err(_) => break Err(()),
1576                }
1577            }
1578        })
1579        .await
1580        .expect("retry loop must finish within 30s");
1581
1582        assert_eq!(
1583            calls.load(Ordering::SeqCst),
1584            3,
1585            "max_attempts=3 must yield exactly 3 invocations"
1586        );
1587    }
1588
1589    // ── ADR-0012 (g) regression tests ──────────────────────────────────
1590
1591    /// Regression: producer pool init failure calls force_unhealthy_for_route
1592    /// with correct route_id + name "g:sql:producer-pool-init" + non-empty reason.
1593    #[tokio::test]
1594    async fn producer_pool_init_failure_calls_force_unhealthy_for_route() {
1595        let health = Arc::new(RecordingHealth::default());
1596        let rt: Arc<dyn RuntimeObservability> = Arc::new(RecordingRuntime {
1597            health: health.clone(),
1598        });
1599
1600        let mut config = SqlEndpointConfig::from_uri(
1601            "sql:select 1?db_url=postgres://nonexistent-host:5432/nonexistent_db&retryEnabled=false",
1602        )
1603        .unwrap();
1604        config.max_connections = Some(1);
1605        config.min_connections = Some(0);
1606        config.idle_timeout_secs = Some(300);
1607        config.max_lifetime_secs = Some(1800);
1608
1609        let mut producer = SqlProducer::new(
1610            config,
1611            Arc::new(OnceCell::new()),
1612            None,
1613            rt,
1614            "sql-producer-test-route",
1615        );
1616        let exchange = Exchange::new(Message::default());
1617
1618        let result = producer.call(exchange).await;
1619        assert!(result.is_err());
1620
1621        let forced = health.forced.lock().unwrap();
1622        assert_eq!(
1623            forced.len(),
1624            1,
1625            "expected one force_unhealthy_for_route call"
1626        );
1627        assert_eq!(forced[0].0, "sql-producer-test-route");
1628        assert_eq!(forced[0].1, "g:sql:producer-pool-init");
1629        assert!(!forced[0].2.is_empty(), "reason should be non-empty");
1630    }
1631
1632    // H7: from_uri must default allow_dynamic_query to false when the
1633    // URI does not include the allowDynamicQuery parameter.
1634    #[test]
1635    fn sql_allow_dynamic_query_defaults_false_from_uri() {
1636        let config =
1637            SqlEndpointConfig::from_uri("sql:query?datasource=mydb&query=SELECT+1").unwrap();
1638        assert!(!config.allow_dynamic_query);
1639    }
1640}