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