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