camel-component-sql 0.68.0

SQL component for rust-camel (PostgreSQL, MySQL, SQLite via sqlx)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::task::{Context, Poll};
use std::time::Duration;

use bytes::Bytes;
use camel_api::datasource::DatasourceCatalog;
use serde_json::json;
use sqlx::Any;
use sqlx::AnyConnection;
use sqlx::AnyPool;
use sqlx::Either;
use sqlx::Executor;
use sqlx::SqlSafeStr;
use sqlx::any::AnyRow;
use sqlx::any::AnyTypeInfoKind;
use sqlx::pool::PoolConnection;
use sqlx::pool::PoolOptions;
use tokio::sync::OnceCell;
use tower::Service;
use tracing::{debug, error, info, warn};

use crate::bind_kinds::{
    BindTarget, bind_batch_item, bind_single_item, bind_target_from_any_kind,
    described_mode_eligible, hybrid_fallback_targets, scan_bind_targets,
};
use crate::config::{SqlEndpointConfig, SqlOutputType, enrich_db_url_with_ssl, redact_db_url};
use crate::headers;
use crate::query::{PreparedQuery, is_select_query, parse_query_template, resolve_params};
use crate::utils::{fetch_error, is_retryable_sqlx_error, row_to_json};
use camel_component_api::retry_async;
use camel_component_api::{
    Body, CamelError, Exchange, Message, RuntimeObservability, StreamBody, StreamMetadata,
};

#[derive(Clone)]
pub struct SqlProducer {
    pub(crate) config: SqlEndpointConfig,
    pub(crate) pool: Arc<OnceCell<Arc<AnyPool>>>,
    pub(crate) catalog: Option<Arc<dyn DatasourceCatalog>>,
    pub(crate) stopped: Arc<AtomicBool>,
    pub(crate) runtime: Arc<dyn RuntimeObservability>,
    /// Route identifier for ADR-0012 (g) health/observability calls.
    pub(crate) route_id: String,
}

impl SqlProducer {
    pub fn new(
        config: SqlEndpointConfig,
        pool: Arc<OnceCell<Arc<AnyPool>>>,
        catalog: Option<Arc<dyn DatasourceCatalog>>,
        runtime: Arc<dyn RuntimeObservability>,
        route_id: impl Into<String>,
    ) -> Self {
        Self {
            config,
            pool,
            catalog,
            stopped: Arc::new(AtomicBool::new(false)),
            runtime,
            route_id: route_id.into(),
        }
    }

    pub fn stop(&self) {
        self.stopped.store(true, Ordering::Relaxed);
        // Close the pool asynchronously in the background with a timeout
        if let Some(pool) = self.pool.get() {
            let pool = pool.clone();
            tokio::spawn(async move {
                if tokio::time::timeout(Duration::from_secs(5), pool.close())
                    .await
                    .is_err()
                {
                    tracing::warn!("SQL producer pool did not close within 5s");
                }
            });
        }
    }

    /// Resolves the query source based on priority:
    /// 1. Header `CamelSql.Query` (only if `allow_dynamic_query=true`)
    /// 2. Body (only if `allow_dynamic_query=true` AND `use_message_body_for_sql=true`)
    /// 3. Config query
    ///
    /// H7: header/body are untrusted exchange data (ADR-0032). Sourcing the
    /// query from them is full SQLi (incl. DDL). Both routes require the
    /// explicit `allow_dynamic_query=true` opt-in.
    pub(crate) fn resolve_query_source(exchange: &Exchange, config: &SqlEndpointConfig) -> String {
        if config.allow_dynamic_query {
            // Priority 1: Header
            if let Some(query_value) = exchange.input.header(headers::QUERY)
                && let Some(query_str) = query_value.as_str()
            {
                return query_str.to_string();
            }

            // Priority 2: Body (requires BOTH flags)
            if config.use_message_body_for_sql
                && let Some(body_text) = exchange.input.body.as_text()
            {
                return body_text.to_string();
            }
        }

        // Priority 3: Config query
        config.query.clone()
    }

    /// Health check: runs a simple `SELECT 1` query against the connection pool
    /// to verify database connectivity.
    ///
    /// Returns `Ok(())` if the database is reachable, or an error with details
    /// if the connection fails.
    pub async fn check_connection(&self) -> Result<(), CamelError> {
        let pool =
            if let (Some(catalog), Some(ds_name)) = (&self.catalog, &self.config.datasource_name) {
                let handle = catalog.get_pool(ds_name).await?;
                let arc_pool: Arc<AnyPool> = handle.downcast()?;
                // We don't cache this here — check_connection is a one-shot call
                arc_pool
            } else {
                self.pool
                    .get()
                    .ok_or_else(|| {
                        CamelError::ProcessorError("SQL connection pool not initialized".into())
                    })?
                    .clone()
            };

        debug!("Running health check: SELECT 1");
        sqlx::query("SELECT 1").execute(&*pool).await.map_err(|e| {
            warn!(error = %e, "SQL health check failed");
            CamelError::ProcessorError(format!("SQL health check failed: {}", e))
        })?;

        debug!("SQL health check passed");
        Ok(())
    }
}

impl Service<Exchange> for SqlProducer {
    type Response = Exchange;
    type Error = CamelError;
    type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;

    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        if self.stopped.load(Ordering::Relaxed) {
            return Poll::Ready(Err(CamelError::ProcessorError(
                "SQL producer stopped".into(),
            )));
        }
        if let Some(pool) = self.pool.get()
            && pool.is_closed()
        {
            return Poll::Ready(Err(CamelError::ProcessorError(
                "SQL connection pool is closed".into(),
            )));
        }
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, mut exchange: Exchange) -> Self::Future {
        let mut config = self.config.clone();
        let pool_cell = Arc::clone(&self.pool);
        let catalog = self.catalog.clone();
        let runtime = Arc::clone(&self.runtime);
        let route_id = self.route_id.clone();

        Box::pin(async move {
            // SQL-014: resolve file-based query before pool init, regardless of pool source
            config.resolve_defaults();
            config.resolve_file_query().await?;

            // Get or initialize the connection pool
            let pool: &Arc<AnyPool> = pool_cell
                .get_or_try_init(|| async {
                    // Catalog path: resolve shared pool from the datasource catalog
                    let ds_name = config.datasource_name.clone();
                    if let (Some(ref cat), Some(ref name)) = (catalog, ds_name) {
                        let handle = cat.get_pool(name).await?;
                        return handle.downcast::<AnyPool>();
                    }

                    let db_url = enrich_db_url_with_ssl(&config.db_url, &config)?;

                    // Install all compiled-in sqlx drivers so AnyPool can resolve them.
                    // This is idempotent; safe to call multiple times.
                    sqlx::any::install_default_drivers();

                    let max_conn = config.max_connections.ok_or_else(|| {
                        CamelError::Config("max_connections not resolved for SQL pool".into())
                    })?;
                    let min_conn = config.min_connections.ok_or_else(|| {
                        CamelError::Config("min_connections not resolved for SQL pool".into())
                    })?;
                    let idle_timeout = config.idle_timeout_secs.ok_or_else(|| {
                        CamelError::Config("idle_timeout_secs not resolved for SQL pool".into())
                    })?;
                    let max_lifetime = config.max_lifetime_secs.ok_or_else(|| {
                        CamelError::Config("max_lifetime_secs not resolved for SQL pool".into())
                    })?;

                    info!(
                        db_url = %redact_db_url(&config.db_url),
                        "SQL producer pool initializing"
                    );
                    let retry_policy = &config.retry;
                    let pool = retry_async::<_, _, _, _, sqlx::Error>(
                        retry_policy,
                        "sql",
                        "producer-pool-init",
                        || {
                            async {
                                PoolOptions::new()
                                    .max_connections(max_conn)
                                    .min_connections(min_conn)
                                    .idle_timeout(Duration::from_secs(idle_timeout))
                                    .max_lifetime(Duration::from_secs(max_lifetime))
                                    .connect(&db_url)
                                    .await
                            }
                        },
                        is_retryable_sqlx_error,
                        Some(runtime.metrics().as_ref()),
                    )
                    .await
                    .map_err(|e| {
                        runtime.health().force_unhealthy_for_route(
                            &route_id,
                            "g:sql:producer-pool-init",
                            &e.to_string(),
                        );
                        // log-policy: outside-contract
                        error!(error = %e, db_url = %redact_db_url(&config.db_url), "Failed to connect to database");
                        CamelError::EndpointCreationFailed(format!(
                            "Failed to connect to database: {}",
                            e
                        ))
                    })?;
                    Ok(Arc::new(pool))
                })
                .await
                .map_err(|e: CamelError| e.clone())?;

            // Resolve query string
            let query_str = Self::resolve_query_source(&exchange, &config);

            // SQL-002: warn if Managed transaction mode requested
            if config.transaction_mode == crate::config::TransactionMode::Managed {
                warn!("transactionManager not yet implemented; using Auto mode");
            }

            debug!(
                query = %query_str,
                "executing SQL query"
            );

            // Execute based on mode
            if config.batch {
                // Batch mode: execute_batch handles its own template parsing per item
                execute_batch(pool.as_ref(), &config, &mut exchange).await?;
            } else if config.use_placeholder {
                // Placeholder processing enabled (default): parse template, resolve params, apply header override
                let template = parse_query_template(&query_str, config.placeholder)?;
                let mut prepared = resolve_params(&template, &exchange, &config.in_separator)?;

                // CamelSql.Parameters header override
                if let Some(params_value) = exchange.input.header(headers::PARAMETERS) {
                    if let Some(arr) = params_value.as_array() {
                        if arr.len() != prepared.bindings.len() {
                            warn!(
                                expected = prepared.bindings.len(),
                                got = arr.len(),
                                header = headers::PARAMETERS,
                                "Parameter count mismatch — SQL has {} placeholders but header provides {} values",
                                prepared.bindings.len(),
                                arr.len()
                            );
                        }
                        debug!(
                            "Overriding bindings from {} header with {} parameters",
                            headers::PARAMETERS,
                            arr.len()
                        );
                        prepared.bindings = arr.clone();
                    } else {
                        warn!(
                            header = headers::PARAMETERS,
                            "Header is present but not a JSON array — ignoring parameter override"
                        );
                    }
                }

                debug!(
                    "Executing prepared SQL ({} bindings)",
                    prepared.bindings.len()
                );

                if is_select_query(&prepared.sql) {
                    execute_select(pool.as_ref(), &prepared, &config, &mut exchange).await?;
                } else {
                    execute_modify(pool.as_ref(), &prepared, &config, &mut exchange).await?;
                }
            } else {
                // use_placeholder=false: execute query as-is without template parsing
                debug!("Executing raw SQL (placeholder processing disabled)");
                let prepared = PreparedQuery {
                    sql: query_str,
                    bindings: vec![],
                };

                if is_select_query(&prepared.sql) {
                    execute_select(pool.as_ref(), &prepared, &config, &mut exchange).await?;
                } else {
                    execute_modify(pool.as_ref(), &prepared, &config, &mut exchange).await?;
                }
            }

            Ok(exchange)
        })
    }
}

/// The bind plan for one single-mode statement (bd rc-mn139): which SQL
/// text to execute, the per-position wire targets, and whether the
/// statement may use the persistent cache.
struct SingleBindPlan {
    sql: String,
    targets: Vec<Option<BindTarget>>,
    persistent: bool,
}

/// What to do with a pooled connection after a failed statement.
enum RollbackDisposition {
    /// Roll back and return the connection to the pool.
    Keep,
    /// Roll back, detach, and close the connection; never re-pool it.
    Discard,
}

/// SQLite's message when `ROLLBACK` runs with no transaction open: the
/// connection is known-clean, so it is safe to re-pool.
const SQLITE_NO_ACTIVE_TRANSACTION: &str = "cannot rollback - no transaction is active";

/// Classifies a driver error message into a rollback disposition.
///
/// Fail-closed: only the exact SQLite "no open transaction" message keeps
/// the connection. Anything else — including the same text wrapped in
/// driver context — discards it, because the connection state is unknown.
fn classify_db_message(msg: &str) -> RollbackDisposition {
    if msg == SQLITE_NO_ACTIVE_TRANSACTION {
        RollbackDisposition::Keep
    } else {
        RollbackDisposition::Discard
    }
}

/// Classifies a `ROLLBACK` failure into a rollback disposition.
fn classify_rollback_error(err: &sqlx::Error) -> RollbackDisposition {
    match err {
        sqlx::Error::Database(db) => classify_db_message(db.message()),
        sqlx::Error::AnyDriverError(inner) => match inner.downcast_ref::<sqlx::Error>() {
            Some(inner) => classify_rollback_error(inner),
            None => RollbackDisposition::Discard,
        },
        _ => RollbackDisposition::Discard,
    }
}

/// Owns a pooled connection whose state is unknown after a failed
/// statement. Dropping it while armed detaches the connection and closes
/// it instead of returning it to the pool; `disarm` gives it back so the
/// caller can re-pool it.
struct DiscardOnDrop(Option<PoolConnection<Any>>);

impl DiscardOnDrop {
    /// Releases the connection to the caller, which drops it back into the
    /// pool.
    fn disarm(mut self) -> PoolConnection<Any> {
        self.0.take().expect("guard disarmed twice") // allow-unwrap
    }

    /// Mutable access to the guarded connection.
    fn conn_mut(&mut self) -> &mut PoolConnection<Any> {
        self.0.as_mut().expect("guard used after disarm") // allow-unwrap
    }
}

impl Drop for DiscardOnDrop {
    fn drop(&mut self) {
        if let Some(conn) = self.0.take() {
            // Detach first so the pool never sees this connection again;
            // dropping the detached handle closes it.
            drop(conn.detach());
        }
    }
}

/// Rolls back a failed statement on `conn`, then either returns the
/// connection to the pool (benign rollback: nothing was open) or closes it
/// (unknown state). Always returns `original` unchanged.
async fn release_after_error(conn: PoolConnection<Any>, original: CamelError) -> CamelError {
    let mut guard = DiscardOnDrop(Some(conn));
    let rollback = sqlx::query(sqlx::AssertSqlSafe("ROLLBACK"))
        .execute(&mut **guard.conn_mut())
        .await;

    match rollback {
        Ok(_) => drop(guard.disarm()),
        Err(e) if matches!(classify_rollback_error(&e), RollbackDisposition::Keep) => {
            // log-policy: handler-owned
            // (category a: single-mode rollback failure inside producer pipeline)
            debug!(error = %e, "Rollback found no active transaction; keeping connection");
            drop(guard.disarm());
        }
        Err(e) => {
            // log-policy: handler-owned
            // (category a: single-mode rollback failure inside producer pipeline)
            warn!(error = %e, "Rollback failed; discarding connection with unknown state");
        }
    }

    original
}

/// Plans the binds for one single-mode statement on `conn` (the SAME
/// pooled connection that will execute it — normalization must target
/// the OIDs of the statement that actually runs, bd rc-mn139).
async fn plan_single_binds(
    conn: &mut AnyConnection,
    sql: &str,
    bindings: &[serde_json::Value],
) -> Result<SingleBindPlan, CamelError> {
    // Nothing to reinterpret: keep the default persistent path, with no
    // probe round trip.
    if bindings.is_empty() {
        return Ok(SingleBindPlan {
            sql: sql.to_string(),
            targets: vec![],
            persistent: true,
        });
    }

    // Probe on a distinct SQL-text namespace: preparing with empty
    // parameter types seeds a statement cache entry under the probed text,
    // and for unmapped parameter types that entry is one no payload can
    // satisfy. Keeping the probe on its own text keeps the user's SQL text
    // namespace clean (mirrors the batch probe).
    let probe_sql = format!("{sql} /* single-bind-kinds-probe */");
    let described_kinds = match Executor::prepare_with(
        &mut *conn,
        sqlx::AssertSqlSafe(probe_sql).into_sql_str(),
        &[],
    )
    .await
    {
        Ok(statement) => match statement.parameters {
            // An empty type list cannot drive normalization.
            Some(Either::Left(types)) if !types.is_empty() => Some(
                types
                    .iter()
                    .map(|type_info| type_info.kind())
                    .collect::<Vec<AnyTypeInfoKind>>(),
            ),
            _ => None,
        },
        // Metadata unavailable (e.g. NUMERIC columns have no Any mapping).
        // Server and connection failures propagate unchanged.
        Err(sqlx::Error::AnyDriverError(_)) => None,
        Err(e) => {
            // log-policy: handler-owned
            // (category a: single-mode probe failure inside producer pipeline)
            warn!("Single describe probe failed: {}", e);
            return Err(CamelError::ProcessorError(format!(
                "SQL query prepare failed: {e}"
            )));
        }
    };

    // The fallback alias is distinct from the probe alias on purpose: sqlx
    // consults the SQL-text cache before the persistence flag, so a
    // probe-seeded entry would otherwise be reused. Nothing is cached
    // under the fallback text.
    let fallback_sql = format!("{sql} /* single-bind-kinds-fallback */");

    let Some(kinds) = described_kinds else {
        return Ok(SingleBindPlan {
            sql: fallback_sql,
            targets: scan_bind_targets(&[bindings]),
            persistent: false,
        });
    };

    let described_targets = kinds
        .iter()
        .map(|kind| bind_target_from_any_kind(*kind))
        .collect::<Vec<_>>();

    if !described_mode_eligible(&kinds, bindings) {
        // Hybrid fallback: keep every described numeric target so the
        // checked guards still fire where the server described a numeric
        // position; scan only the unresolved ones.
        return Ok(SingleBindPlan {
            sql: fallback_sql,
            targets: hybrid_fallback_targets(&described_targets, bindings),
            persistent: false,
        });
    }

    // Describe with empty Parse parameter types so the server infers the
    // parameter OIDs from the SQL text. On a cache hit the read-back
    // parameters are the cached statement's actual OIDs — normalization
    // targets those, so payloads always match the executed statement.
    let statement = Executor::prepare_with(
        &mut *conn,
        sqlx::AssertSqlSafe(sql.to_string()).into_sql_str(),
        &[],
    )
    .await
    .map_err(|e| {
        // log-policy: handler-owned
        // (category a: single-mode described prepare failure inside producer pipeline)
        warn!("Single describe failed: {}", e);
        CamelError::ProcessorError(format!("SQL query prepare failed: {e}"))
    })?;

    let targets = match statement.parameters {
        Some(Either::Left(types)) => types
            .iter()
            .map(|type_info| bind_target_from_any_kind(type_info.kind()))
            .collect::<Vec<_>>(),
        _ => scan_bind_targets(&[bindings]),
    };

    Ok(SingleBindPlan {
        sql: sql.to_string(),
        targets,
        persistent: true,
    })
}

/// Executes one single-mode SELECT on a pooled connection, planning the
/// binds first (bd rc-mn139). Statements without bindings plan to the
/// default persistent path with no probe and no binds.
async fn fetch_single_rows(
    pool: &AnyPool,
    prepared: &PreparedQuery,
) -> Result<Vec<AnyRow>, CamelError> {
    let mut conn = pool
        .acquire()
        .await
        .map_err(|e| fetch_error("Failed to acquire database connection", e))?;

    let fetched = async {
        let plan = plan_single_binds(&mut conn, &prepared.sql, &prepared.bindings).await?;
        let query = sqlx::query(sqlx::AssertSqlSafe(plan.sql.as_str())).persistent(plan.persistent);
        let query = bind_single_item(query, &prepared.bindings, &plan.targets)?;
        query
            .fetch_all(&mut *conn)
            .await
            .map_err(|e| fetch_error("SQL query failed", e))
    }
    .await;

    match fetched {
        Ok(rows) => Ok(rows),
        Err(original) => Err(release_after_error(conn, original).await),
    }
}

/// Executes a SELECT query and populates the exchange body with results.
async fn execute_select(
    pool: &AnyPool,
    prepared: &PreparedQuery,
    config: &SqlEndpointConfig,
    exchange: &mut Exchange,
) -> Result<(), CamelError> {
    match config.output_type {
        SqlOutputType::SelectOne => {
            // fetch_all and take first row
            let rows = fetch_single_rows(pool, prepared).await?;

            let count = rows.len();
            debug!(rows = count, "SQL query completed");
            let json_rows: Vec<serde_json::Value> = rows
                .iter()
                .map(row_to_json)
                .collect::<Result<Vec<_>, _>>()?;

            if let Some(first_row) = json_rows.into_iter().next() {
                exchange.input.body = Body::Json(first_row);
            } else {
                exchange.input.body = Body::Empty;
            }
            debug!("SelectOne returned {} row", if count > 0 { 1 } else { 0 });
            exchange
                .input
                .set_header(headers::ROW_COUNT, serde_json::json!(count));
        }
        SqlOutputType::SelectList => {
            // fetch_all for list output
            let rows = fetch_single_rows(pool, prepared).await?;

            let count = rows.len();
            debug!(rows = count, "SQL query completed");
            let json_rows: Vec<serde_json::Value> = rows
                .iter()
                .map(row_to_json)
                .collect::<Result<Vec<_>, _>>()?;

            exchange.input.body = Body::Json(serde_json::Value::Array(json_rows));
            debug!("SelectList returned {} rows", count);
            exchange
                .input
                .set_header(headers::ROW_COUNT, serde_json::json!(count));
        }
        SqlOutputType::StreamList => {
            // Use fetch() for true streaming - avoids loading all rows into memory
            use futures::TryStreamExt;

            let pool_clone = pool.clone();
            let sql_str = prepared.sql.clone();
            let bindings = prepared.bindings.clone();

            // Build the stream that reads rows on demand and serializes to NDJSON bytes
            let byte_stream = async_stream::try_stream! {
                let mut conn = pool_clone
                    .acquire()
                    .await
                    .map_err(|e| fetch_error("Failed to acquire database connection", e))?;

                // Plan and execute against the SAME pooled connection so
                // normalization targets the OIDs of the statement that
                // actually runs (bd rc-mn139).
                let plan = match plan_single_binds(&mut conn, &sql_str, &bindings).await {
                    Ok(plan) => plan,
                    Err(original) => {
                        // `try_stream!` turns `?` into "yield the error and
                        // return", but the compiler still sees the `Ok` arm
                        // as reachable; that arm must diverge for the
                        // connection move to be accepted.
                        Err::<SingleBindPlan, CamelError>(
                            release_after_error(conn, original).await,
                        )?;
                        unreachable!("`release_after_error` always propagates the error")
                    }
                };
                let q = sqlx::query(sqlx::AssertSqlSafe(plan.sql.as_str()))
                    .persistent(plan.persistent);
                let q = match bind_single_item(q, &bindings, &plan.targets) {
                    Ok(q) => q,
                    Err(original) => {
                        Err::<_, CamelError>(release_after_error(conn, original).await)?;
                        unreachable!("`release_after_error` always propagates the error")
                    }
                };
                let mut rows = q.fetch(&mut *conn);
                let mut failure: Option<CamelError> = None;
                loop {
                    let row = match rows.try_next().await {
                        Ok(Some(row)) => row,
                        Ok(None) => break,
                        Err(e) => {
                            failure = Some(fetch_error("Query execution failed", e));
                            break;
                        }
                    };
                    let json_val = match row_to_json(&row) {
                        Ok(json_val) => json_val,
                        Err(original) => {
                            failure = Some(original);
                            break;
                        }
                    };
                    let mut bytes = match serde_json::to_vec(&json_val) {
                        Ok(bytes) => bytes,
                        Err(e) => {
                            failure = Some(CamelError::ProcessorError(format!(
                                "JSON serialization failed: {}",
                                e
                            )));
                            break;
                        }
                    };
                    bytes.push(b'\n');
                    yield Bytes::from(bytes);
                }
                // `rows` borrows the connection: end the borrow before
                // handing the connection to the rollback.
                drop(rows);
                if let Some(original) = failure {
                    Err::<(), CamelError>(release_after_error(conn, original).await)?;
                }
            };

            exchange.input.body = Body::Stream(StreamBody {
                stream: Arc::new(tokio::sync::Mutex::new(Some(Box::pin(byte_stream)))),
                metadata: StreamMetadata {
                    content_type: Some("application/x-ndjson".to_string()),
                    size_hint: None,
                    origin: None,
                },
            });
            debug!("StreamList: created lazy stream (rows fetched on demand)");
            // Note: ROW_COUNT not set for StreamList since row count is unknown until exhausted
        }
    }

    Ok(())
}

/// Executes a modification query (INSERT/UPDATE/DELETE).
async fn execute_modify(
    pool: &AnyPool,
    prepared: &PreparedQuery,
    config: &SqlEndpointConfig,
    exchange: &mut Exchange,
) -> Result<(), CamelError> {
    let mut conn = pool
        .acquire()
        .await
        .map_err(|e| fetch_error("Failed to acquire database connection", e))?;

    let executed = async {
        let plan = plan_single_binds(&mut conn, &prepared.sql, &prepared.bindings).await?;
        let query = sqlx::query(sqlx::AssertSqlSafe(plan.sql.as_str())).persistent(plan.persistent);
        let query = bind_single_item(query, &prepared.bindings, &plan.targets)?;
        query.execute(&mut *conn).await.map_err(|e| {
            warn!(error = %e, "SQL query failed");
            CamelError::ProcessorError(format!("Query execution failed: {}", e))
        })
    }
    .await;

    let result = match executed {
        Ok(result) => result,
        Err(original) => return Err(release_after_error(conn, original).await),
    };

    let rows_affected = result.rows_affected();

    // Fix 4: Implement expected_update_count validation
    if let Some(expected) = config.expected_update_count
        && rows_affected as i64 != expected
    {
        warn!(expected, actual = rows_affected, "Row count mismatch");
        let err = CamelError::ProcessorError(format!(
            "Expected {} rows affected, got {}",
            expected, rows_affected
        ));
        return Err(release_after_error(conn, err).await);
    }

    exchange
        .input
        .set_header(headers::UPDATE_COUNT, serde_json::json!(rows_affected));

    if config.noop {
        // Preserve original body
    } else {
        exchange.input.body = Body::Json(json!({ "rowsAffected": rows_affected }));
    }

    debug!(rows = rows_affected, "SQL modify query completed");

    Ok(())
}

/// Executes a batch of queries from a JSON array body.
///
/// Bind-kind safety (bd rc-fef4z): sqlx keys its statement cache by SQL text
/// alone and fixes parameter OIDs at the first `Parse`, so a position that
/// carries different Rust bind kinds across items silently reinterprets
/// bits. Every position therefore binds exactly one wire encoding per
/// statement: the server-described encoding when available, otherwise a
/// per-batch scan (float wins) executed without statement caching.
async fn execute_batch(
    pool: &AnyPool,
    config: &SqlEndpointConfig,
    exchange: &mut Exchange,
) -> Result<(), CamelError> {
    // Body must be JSON array of arrays
    let body_json = match &exchange.input.body {
        Body::Json(val) => val,
        _ => {
            return Err(CamelError::ProcessorError(
                "Batch mode requires body to be a JSON array of arrays".to_string(),
            ));
        }
    };

    let batch_data = body_json
        .as_array()
        .ok_or_else(|| {
            CamelError::ProcessorError("Batch mode requires body to be a JSON array".to_string())
        })?
        .clone();

    // Parse template from config query
    let template = parse_query_template(&config.query, config.placeholder)?;

    // Resolve every item up front so the fallback bind-kind scan sees the
    // whole batch.
    let mut prepared_items = Vec::with_capacity(batch_data.len());
    for (batch_idx, params_array) in batch_data.iter().enumerate() {
        // Each item must be an array of parameters
        params_array.as_array().ok_or_else(|| {
            CamelError::ProcessorError(format!(
                "Batch item at index {} must be a JSON array of parameters",
                batch_idx
            ))
        })?;

        // Create a temporary exchange with the params as body for resolution
        let temp_msg = Message::new(Body::Json(params_array.clone()));
        let temp_exchange = Exchange::new(temp_msg);

        prepared_items.push(resolve_params(
            &template,
            &temp_exchange,
            &config.in_separator,
        )?);
    }

    // Fallback targets: one bind kind per position across the batch, float wins.
    let binding_rows: Vec<&[serde_json::Value]> = prepared_items
        .iter()
        .map(|prepared| prepared.bindings.as_slice())
        .collect();
    let scanned_targets = scan_bind_targets(&binding_rows);

    // Fix 2: Batch operations must be wrapped in a transaction
    let mut tx = pool.begin().await.map_err(|e| {
        // log-policy: handler-owned
        // (category a: tx begin failure inside producer pipeline)
        warn!(error = %e, "Failed to begin transaction");
        CamelError::ProcessorError(format!("Failed to begin transaction: {}", e))
    })?;

    // Probe the described parameter types once with the first item's SQL
    // text. Described batches keep using the transaction connection (later
    // items with the same text hit the statement cache for free).
    let mut described_mode = true;
    if let Some(first) = prepared_items.first() {
        // Probe on a distinct SQL-text namespace: preparing with empty
        // parameter types seeds a statement cache entry under the probed
        // text, and for unmapped types (e.g. NUMERIC) that entry is one no
        // payload can satisfy. Keeping the probe on its own text keeps the
        // user's SQL text namespace clean.
        let probe_sql = format!("{} /* batch-bind-kinds-probe */", first.sql);
        described_mode = match Executor::prepare_with(
            &mut *tx,
            sqlx::AssertSqlSafe(probe_sql).into_sql_str(),
            &[],
        )
        .await
        {
            Ok(statement) => match statement.parameters {
                // Any-mapped parameter types are described-eligible: numeric
                // kinds get bind targets, non-numeric kinds (text, bool,
                // blob) keep the default JSON binding under their described
                // OIDs. Unmapped kinds (e.g. NUMERIC) fail the probe itself.
                // An empty type list cannot drive normalization.
                Some(Either::Left(types)) => !types.is_empty(),
                _ => false,
            },
            // Metadata unavailable (e.g. NUMERIC columns have no Any
            // mapping). Server and connection failures propagate unchanged.
            Err(sqlx::Error::AnyDriverError(_)) => false,
            Err(e) => {
                // log-policy: handler-owned
                // (category a: batch probe failure inside producer pipeline)
                warn!("Batch describe probe failed: {}", e);
                return Err(CamelError::ProcessorError(format!(
                    "Batch query prepare failed: {e}"
                )));
            }
        };
    }

    let mut total_rows_affected: u64 = 0;

    for (batch_idx, prepared) in prepared_items.iter().enumerate() {
        let (mut query, targets) = if described_mode {
            // Describe with empty Parse parameter types so the server infers
            // the parameter OIDs from the SQL text. On a cache hit the
            // read-back parameters are the cached statement's actual OIDs —
            // normalization targets those, so payloads always match the
            // executed statement.
            let statement = Executor::prepare_with(
                &mut *tx,
                sqlx::AssertSqlSafe(prepared.sql.clone()).into_sql_str(),
                &[],
            )
            .await
            .map_err(|e| {
                // log-policy: handler-owned
                // (category a: batch describe failure inside producer pipeline)
                warn!("Batch describe failed at index {}: {}", batch_idx, e);
                CamelError::ProcessorError(format!("Batch query prepare failed: {e}"))
            })?;
            let query = sqlx::query(sqlx::AssertSqlSafe(prepared.sql.as_str()));
            let targets = match statement.parameters {
                Some(Either::Left(types)) => types
                    .iter()
                    .map(|type_info| bind_target_from_any_kind(type_info.kind()))
                    .collect::<Vec<_>>(),
                _ => scanned_targets.clone(),
            };
            (query, targets)
        } else {
            // Uncached fallback: execute a semantically identical alias text
            // in its own cache namespace with persistent(false), so every
            // item prepares an unnamed statement whose parameter types
            // derive from the scan-normalized binds. Nothing is cached and
            // nothing else uses this namespace, so no incompatible cached
            // entry can be reused.
            let fallback_sql = format!("{} /* batch-bind-kinds-fallback */", prepared.sql);
            let query = sqlx::query(sqlx::AssertSqlSafe(fallback_sql.as_str())).persistent(false);
            (query, scanned_targets.clone())
        };

        query = bind_batch_item(query, &prepared.bindings, &targets, batch_idx)?;

        let result = query.execute(&mut *tx).await.map_err(|e| {
            // log-policy: handler-owned
            // (category a: batch query execution failure inside producer pipeline)
            warn!("Batch query execution failed at index {}: {}", batch_idx, e);
            CamelError::ProcessorError(format!("Batch query execution failed: {}", e))
        })?;

        // Validate expected_update_count per batch item
        if let Some(expected) = config.expected_update_count
            && result.rows_affected() as i64 != expected
        {
            // log-policy: handler-owned
            // (category a: expected_update_count mismatch inside producer pipeline)
            warn!(
                "Batch item {}: expected {} rows affected, got {}",
                batch_idx,
                expected,
                result.rows_affected()
            );
            return Err(CamelError::ProcessorError(format!(
                "Batch item {}: expected {} rows affected, got {}",
                batch_idx,
                expected,
                result.rows_affected()
            )));
        }

        total_rows_affected += result.rows_affected();
    }

    // Commit the transaction
    tx.commit().await.map_err(|e| {
        // log-policy: handler-owned
        // (category a: tx commit failure inside producer pipeline)
        warn!(error = %e, "Failed to commit transaction");
        CamelError::ProcessorError(format!("Failed to commit transaction: {}", e))
    })?;

    exchange.input.set_header(
        headers::UPDATE_COUNT,
        serde_json::json!(total_rows_affected),
    );

    debug!(
        "Batch execution completed, total rows affected: {}",
        total_rows_affected
    );

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bind_kinds::bind_json_values;
    use camel_api::MetricsCollector;
    use camel_component_api::HealthCheckRegistry;
    use camel_component_api::test_support::PanicRuntimeObservability;
    fn test_rt() -> std::sync::Arc<dyn camel_component_api::RuntimeObservability> {
        std::sync::Arc::new(PanicRuntimeObservability)
    }
    use camel_component_api::Message;
    use camel_component_api::UriConfig;
    use sqlx::any::AnyPoolOptions;
    use std::sync::Arc;
    use std::sync::Mutex;
    use tokio::sync::OnceCell;

    // ── Recording health fixture for ADR-0012 (g) tests ───────────────────

    #[derive(Debug, Default)]
    struct RecordingHealth {
        forced: Mutex<Vec<(String, String, String)>>,
    }

    impl HealthCheckRegistry for RecordingHealth {
        fn force_unhealthy_for_route(&self, route_id: &str, name: &str, reason: &str) {
            self.forced.lock().unwrap().push((
                route_id.to_string(),
                name.to_string(),
                reason.to_string(),
            ));
        }
    }

    struct NoopMetrics;

    impl MetricsCollector for NoopMetrics {
        fn record_exchange_duration(&self, _: &str, _: Duration) {}
        fn increment_errors(&self, _: &str, _: &str) {}
        fn increment_exchanges(&self, _: &str) {}
        fn set_queue_depth(&self, _: &str, _: usize) {}
        fn record_circuit_breaker_change(&self, _: &str, _: &str, _: &str) {}
    }

    struct RecordingRuntime {
        health: Arc<RecordingHealth>,
    }

    impl RuntimeObservability for RecordingRuntime {
        fn metrics(&self) -> Arc<dyn MetricsCollector> {
            Arc::new(NoopMetrics)
        }
        fn health(&self) -> Arc<dyn HealthCheckRegistry> {
            self.health.clone()
        }
    }

    async fn sqlite_pool() -> AnyPool {
        sqlx::any::install_default_drivers();
        // Per-attempt deadline (lintwiden D4.3): a wedged pool connect
        // must fail the helper instead of parking it.
        tokio::time::timeout(
            std::time::Duration::from_secs(10),
            AnyPoolOptions::new()
                .max_connections(1)
                .connect("sqlite::memory:"),
        )
        .await
        .expect("sqlite pool connect timed out after 10s")
        .expect("sqlite pool")
    }

    async fn seed_items_table(pool: &AnyPool) {
        sqlx::query(
            "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT, done INTEGER DEFAULT 0)",
        )
        .execute(pool)
        .await
        .expect("create table");
        sqlx::query("INSERT INTO items (id, name, done) VALUES (1, 'a', 0), (2, 'b', 0)")
            .execute(pool)
            .await
            .expect("seed rows");
    }

    fn config() -> SqlEndpointConfig {
        let mut c =
            SqlEndpointConfig::from_uri("sql:select 1?db_url=postgres://localhost/test").unwrap();
        c.resolve_defaults();
        c
    }

    #[test]
    fn producer_clone_shares_pool() {
        let p1 = SqlProducer::new(
            config(),
            Arc::new(OnceCell::new()),
            None,
            test_rt(),
            "sql-producer-test-route",
        );
        let p2 = p1.clone();
        assert!(Arc::ptr_eq(&p1.pool, &p2.pool));
        assert!(Arc::ptr_eq(&p1.stopped, &p2.stopped));
    }

    #[test]
    fn resolve_query_from_config() {
        let config = config();
        let ex = Exchange::new(Message::default());
        let q = SqlProducer::resolve_query_source(&ex, &config);
        assert_eq!(q, "select 1");
    }

    #[test]
    fn resolve_query_from_header() {
        let mut config = config();
        config.allow_dynamic_query = true;
        let mut msg = Message::default();
        msg.set_header(headers::QUERY, serde_json::json!("select 2"));
        let ex = Exchange::new(msg);
        let q = SqlProducer::resolve_query_source(&ex, &config);
        assert_eq!(q, "select 2");
    }

    #[test]
    fn resolve_query_from_body() {
        let mut config = config();
        config.use_message_body_for_sql = true;
        config.allow_dynamic_query = true;
        let msg = Message::new(Body::Text("select 3".to_string()));
        let ex = Exchange::new(msg);
        let q = SqlProducer::resolve_query_source(&ex, &config);
        assert_eq!(q, "select 3");
    }

    #[test]
    fn resolve_query_header_priority_over_body() {
        let mut config = config();
        config.use_message_body_for_sql = true;
        config.allow_dynamic_query = true;
        let mut msg = Message::new(Body::Text("select from body".to_string()));
        msg.set_header(headers::QUERY, serde_json::json!("select from header"));
        let ex = Exchange::new(msg);
        let q = SqlProducer::resolve_query_source(&ex, &config);
        assert_eq!(q, "select from header");
    }

    #[test]
    fn resolve_query_body_priority_over_config() {
        let mut config = config();
        config.use_message_body_for_sql = true;
        config.allow_dynamic_query = true;
        let msg = Message::new(Body::Text("select from body".to_string()));
        let ex = Exchange::new(msg);
        let q = SqlProducer::resolve_query_source(&ex, &config);
        assert_eq!(q, "select from body");
    }

    // H7: dynamic queries from exchange data must be denied by default.
    // The CamelSql.Query header and body are untrusted (ADR-0032). Reading
    // them as a SQL source is a SQLi vector including DDL. Default is closed.
    #[test]
    fn dynamic_query_denied_by_default() {
        let mut msg = Message::default();
        msg.set_header(headers::QUERY, "DROP TABLE users; --");
        let ex = Exchange::new(msg);

        let mut config = config();
        config.query = "SELECT 1".to_string();
        // allow_dynamic_query defaults to false → header ignored

        let q = SqlProducer::resolve_query_source(&ex, &config);
        // Must return the config query, NOT the header
        assert_eq!(q, "SELECT 1");
    }

    // H7: with explicit opt-in (allow_dynamic_query=true), header takes priority.
    #[test]
    fn dynamic_query_allowed_with_opt_in() {
        let mut msg = Message::default();
        msg.set_header(headers::QUERY, "SELECT 1 FROM users WHERE id = :#id");
        let ex = Exchange::new(msg);

        let mut config = config();
        config.query = "SELECT 1".to_string();
        config.allow_dynamic_query = true;

        let q = SqlProducer::resolve_query_source(&ex, &config);
        // With opt-in, header takes priority
        assert_eq!(q, "SELECT 1 FROM users WHERE id = :#id");
    }

    #[test]
    fn bind_json_null() {
        let query = sqlx::query("SELECT ?");
        let values = vec![serde_json::Value::Null];
        let _bound = bind_json_values(query, &values);
        // Compilation test - ensure it binds
    }

    #[test]
    fn bind_json_bool() {
        let query = sqlx::query("SELECT ?");
        let values = vec![serde_json::Value::Bool(true)];
        let _bound = bind_json_values(query, &values);
    }

    #[test]
    fn bind_json_number_i64() {
        let query = sqlx::query("SELECT ?");
        let values = vec![serde_json::json!(42)];
        let _bound = bind_json_values(query, &values);
    }

    #[test]
    fn bind_json_number_f64() {
        let query = sqlx::query("SELECT ?");
        let values = vec![serde_json::json!(std::f64::consts::PI)];
        let _bound = bind_json_values(query, &values);
    }

    #[test]
    fn bind_json_string() {
        let query = sqlx::query("SELECT ?");
        let values = vec![serde_json::json!("hello world")];
        let _bound = bind_json_values(query, &values);
    }

    #[test]
    fn bind_json_array() {
        let query = sqlx::query("SELECT ?");
        let values = vec![serde_json::json!([1, 2, 3])];
        let _bound = bind_json_values(query, &values);
    }

    #[test]
    fn bind_json_object() {
        let query = sqlx::query("SELECT ?");
        let values = vec![serde_json::json!({"key": "value"})];
        let _bound = bind_json_values(query, &values);
    }

    #[test]
    fn bind_multiple_values() {
        let query = sqlx::query("SELECT ?, ?, ?");
        let values = vec![
            serde_json::json!(1),
            serde_json::json!("test"),
            serde_json::Value::Null,
        ];
        let _bound = bind_json_values(query, &values);
    }

    // Test for Fix 4: expected_update_count config field presence
    #[test]
    fn expected_update_count_validation() {
        // Test that expected_update_count is parsed from URI
        let config = SqlEndpointConfig::from_uri(
            "sql:update t set x=1?db_url=postgres://localhost/test&expectedUpdateCount=5",
        )
        .unwrap();
        assert_eq!(config.expected_update_count, Some(5));

        // Test default (no expected_update_count)
        let config_default = self::config();
        assert_eq!(config_default.expected_update_count, None);

        // Test negative value (should parse)
        let config_neg = SqlEndpointConfig::from_uri(
            "sql:update t set x=1?db_url=postgres://localhost/test&expectedUpdateCount=-1",
        )
        .unwrap();
        assert_eq!(config_neg.expected_update_count, Some(-1));
    }

    // Test for Fix 3: parameters header override logic
    #[test]
    fn parameters_header_override_logic() {
        // Create a PreparedQuery manually
        let mut prepared = PreparedQuery {
            sql: "SELECT * FROM t WHERE id = $1".to_string(),
            bindings: vec![serde_json::json!(42)],
        };

        // Simulate the header override logic
        let header_params = serde_json::json!([99, "extra"]);
        if let Some(arr) = header_params.as_array() {
            prepared.bindings = arr.clone();
        }

        // Verify bindings were overridden
        assert_eq!(prepared.bindings.len(), 2);
        assert_eq!(prepared.bindings[0], serde_json::json!(99));
        assert_eq!(prepared.bindings[1], serde_json::json!("extra"));

        // Test with non-array header (should not override)
        let mut prepared2 = PreparedQuery {
            sql: "SELECT * FROM t WHERE id = $1".to_string(),
            bindings: vec![serde_json::json!(42)],
        };
        let header_non_array = serde_json::json!({"not": "an array"});
        if let Some(arr) = header_non_array.as_array() {
            prepared2.bindings = arr.clone();
        }
        // Should remain unchanged
        assert_eq!(prepared2.bindings.len(), 1);
        assert_eq!(prepared2.bindings[0], serde_json::json!(42));
    }

    #[tokio::test]
    async fn execute_select_one_sets_body_and_row_count() {
        let pool = sqlite_pool().await;
        seed_items_table(&pool).await;

        let mut config = SqlEndpointConfig::from_uri(
            "sql:select id, name from items order by id?db_url=sqlite::memory:&outputType=SelectOne",
        )
        .unwrap();
        config.resolve_defaults();

        let prepared = PreparedQuery {
            sql: "select id, name from items order by id".to_string(),
            bindings: vec![],
        };
        let mut exchange = Exchange::new(Message::default());

        execute_select(&pool, &prepared, &config, &mut exchange)
            .await
            .expect("select one");

        assert_eq!(exchange.input.header(headers::ROW_COUNT), Some(&json!(2)));
        assert_eq!(
            exchange.input.body,
            Body::Json(json!({"id": 1, "name": "a"}))
        );
    }

    #[tokio::test]
    async fn execute_stream_list_materializes_ndjson() {
        let pool = sqlite_pool().await;
        seed_items_table(&pool).await;

        let mut config = SqlEndpointConfig::from_uri(
            "sql:select id from items order by id?db_url=sqlite::memory:&outputType=StreamList",
        )
        .unwrap();
        config.resolve_defaults();

        let prepared = PreparedQuery {
            sql: "select id from items order by id".to_string(),
            bindings: vec![],
        };
        let mut exchange = Exchange::new(Message::default());

        execute_select(&pool, &prepared, &config, &mut exchange)
            .await
            .expect("stream list");

        let bytes = exchange
            .input
            .body
            .clone()
            .into_bytes(1024)
            .await
            .expect("stream bytes");
        let text = String::from_utf8(bytes.to_vec()).expect("utf8");
        assert!(text.contains("{\"id\":1}"));
        assert!(text.contains("{\"id\":2}"));
        assert_eq!(exchange.input.header(headers::ROW_COUNT), None);
    }

    // A mid-stream failure inside an explicit transaction must release the
    // connection (rolling the transaction back) so the pool stays usable.
    #[tokio::test]
    async fn stream_list_error_releases_connection_and_pool_stays_usable() {
        let pool = sqlite_pool().await;
        seed_items_table(&pool).await;

        let mut config = SqlEndpointConfig::from_uri(
            "sql:select id from items order by id?db_url=sqlite::memory:&outputType=StreamList",
        )
        .unwrap();
        config.resolve_defaults();

        let prepared = PreparedQuery {
            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(),
            bindings: vec![],
        };
        let mut exchange = Exchange::new(Message::default());

        // The stream is lazy: the SELECT itself succeeds.
        execute_select(&pool, &prepared, &config, &mut exchange)
            .await
            .expect("stream list");

        let err = exchange
            .input
            .body
            .clone()
            .into_bytes(1024)
            .await
            .expect_err("drain must fail on the duplicate INSERT");
        assert!(
            err.to_string().contains("UNIQUE"),
            "error must be preserved, got: {}",
            err
        );

        // The connection goes back to the pool.
        assert_eq!(pool.size(), 1, "connection must be kept in the pool");

        let mut select_config = SqlEndpointConfig::from_uri(
            "sql:select id from items order by id?db_url=sqlite::memory:&outputType=SelectList",
        )
        .unwrap();
        select_config.resolve_defaults();
        let select_prepared = PreparedQuery {
            sql: "select id from items order by id".to_string(),
            bindings: vec![],
        };
        let mut ex2 = Exchange::new(Message::default());

        tokio::time::timeout(
            Duration::from_secs(2),
            execute_select(&pool, &select_prepared, &select_config, &mut ex2),
        )
        .await
        .expect("follow-up select timed out on a poisoned connection")
        .expect("follow-up select failed on a poisoned connection");

        // The rolled-back row 9 is absent: only rows 1 and 2 remain.
        assert_eq!(ex2.input.header(headers::ROW_COUNT), Some(&json!(2)));
    }

    #[tokio::test]
    async fn execute_modify_expected_update_count_mismatch_returns_error() {
        let pool = sqlite_pool().await;
        seed_items_table(&pool).await;

        let mut config = SqlEndpointConfig::from_uri(
            "sql:update items set done=1 where id = #?db_url=sqlite::memory:&expectedUpdateCount=2",
        )
        .unwrap();
        config.resolve_defaults();

        let prepared = PreparedQuery {
            sql: "update items set done=1 where id = $1".to_string(),
            bindings: vec![json!(1)],
        };
        let mut exchange = Exchange::new(Message::default());

        let err = execute_modify(&pool, &prepared, &config, &mut exchange)
            .await
            .expect_err("must fail due expected row count mismatch");
        assert!(err.to_string().contains("Expected 2 rows affected, got 1"));
    }

    #[tokio::test]
    async fn execute_batch_rollback_when_any_item_fails_expected_count() {
        let pool = sqlite_pool().await;
        seed_items_table(&pool).await;

        let mut config = SqlEndpointConfig::from_uri(
            "sql:update items set done=1 where id = #?db_url=sqlite::memory:&batch=true&expectedUpdateCount=1",
        )
        .unwrap();
        config.resolve_defaults();

        let mut exchange = Exchange::new(Message::new(Body::Json(json!([[1], [999]]))));

        let err = execute_batch(&pool, &config, &mut exchange)
            .await
            .expect_err("second batch item should fail expectedUpdateCount");
        assert!(
            err.to_string()
                .contains("Batch item 1: expected 1 rows affected, got 0")
        );

        let row = sqlx::query("select done from items where id = 1")
            .fetch_one(&pool)
            .await
            .expect("query row");
        let done: i64 = sqlx::Row::try_get(&row, 0).expect("done column");
        assert_eq!(done, 0, "transaction must rollback first update");
    }

    // A multi-statement script that opens a transaction and then fails must
    // not leave that transaction open on the pooled connection.
    #[tokio::test]
    async fn failing_manual_begin_does_not_poison_the_pool() {
        let pool = sqlite_pool().await;
        seed_items_table(&pool).await;

        let mut config = SqlEndpointConfig::from_uri("sql:x?db_url=sqlite::memory:").unwrap();
        config.resolve_defaults();

        let prepared = PreparedQuery {
            sql: "BEGIN IMMEDIATE; INSERT INTO items (id,name) VALUES (9,'x'); INSERT INTO items (id,name) VALUES (9,'y'); COMMIT;".to_string(),
            bindings: vec![],
        };
        let mut exchange = Exchange::new(Message::default());

        let err = execute_modify(&pool, &prepared, &config, &mut exchange)
            .await
            .expect_err("duplicate id inside the open transaction must fail");
        assert!(!err.to_string().is_empty(), "error message must be present");

        let mut select_config = SqlEndpointConfig::from_uri(
            "sql:select id from items order by id?db_url=sqlite::memory:&outputType=SelectList",
        )
        .unwrap();
        select_config.resolve_defaults();
        let select_prepared = PreparedQuery {
            sql: "select id from items order by id".to_string(),
            bindings: vec![],
        };
        let mut ex2 = Exchange::new(Message::default());

        tokio::time::timeout(
            Duration::from_secs(2),
            execute_select(&pool, &select_prepared, &select_config, &mut ex2),
        )
        .await
        .expect("follow-up select timed out on a poisoned connection")
        .expect("follow-up select failed on a poisoned connection");

        // The rolled-back row 9 is absent: only rows 1 and 2 remain.
        assert_eq!(ex2.input.header(headers::ROW_COUNT), Some(&json!(2)));
    }

    // A failing statement outside any explicit transaction must keep its
    // error and leave the pool usable (connection returned, not discarded).
    #[tokio::test]
    async fn failed_statement_without_transaction_keeps_error_and_pool_usable() {
        let pool = sqlite_pool().await;
        seed_items_table(&pool).await;

        let mut config = SqlEndpointConfig::from_uri("sql:x?db_url=sqlite::memory:").unwrap();
        config.resolve_defaults();

        let prepared = PreparedQuery {
            sql: "INSERT INTO items (id,name) VALUES (1,'dup')".to_string(),
            bindings: vec![],
        };
        let mut exchange = Exchange::new(Message::default());

        let err = execute_modify(&pool, &prepared, &config, &mut exchange)
            .await
            .expect_err("duplicate primary key must fail");
        assert!(
            err.to_string().contains("Query execution failed"),
            "error must be preserved, got: {}",
            err
        );
        // Benign rollback: the connection goes back to the pool.
        assert_eq!(pool.size(), 1, "connection must be kept in the pool");

        let mut select_config = SqlEndpointConfig::from_uri(
            "sql:select id from items order by id?db_url=sqlite::memory:&outputType=SelectList",
        )
        .unwrap();
        select_config.resolve_defaults();
        let select_prepared = PreparedQuery {
            sql: "select id from items order by id".to_string(),
            bindings: vec![],
        };
        let mut ex2 = Exchange::new(Message::default());

        tokio::time::timeout(
            Duration::from_secs(2),
            execute_select(&pool, &select_prepared, &select_config, &mut ex2),
        )
        .await
        .expect("follow-up select timed out")
        .expect("follow-up select failed");

        assert_eq!(ex2.input.header(headers::ROW_COUNT), Some(&json!(2)));
    }

    // A failing SELECT must keep its error and leave the pool usable.
    #[tokio::test]
    async fn failing_select_keeps_error_and_pool_usable() {
        let pool = sqlite_pool().await;
        seed_items_table(&pool).await;

        let mut config =
            SqlEndpointConfig::from_uri("sql:x?db_url=sqlite::memory:&outputType=SelectList")
                .unwrap();
        config.resolve_defaults();

        let prepared = PreparedQuery {
            sql: "SELECT * FROM items_missing_table".to_string(),
            bindings: vec![],
        };
        let mut exchange = Exchange::new(Message::default());

        let err = execute_select(&pool, &prepared, &config, &mut exchange)
            .await
            .expect_err("missing table must fail");
        assert!(
            err.to_string().contains("Query execution failed"),
            "error must be preserved, got: {}",
            err
        );
        assert_eq!(pool.size(), 1, "connection must be kept in the pool");

        let select_prepared = PreparedQuery {
            sql: "select id from items order by id".to_string(),
            bindings: vec![],
        };
        let mut ex2 = Exchange::new(Message::default());

        tokio::time::timeout(
            Duration::from_secs(2),
            execute_select(&pool, &select_prepared, &config, &mut ex2),
        )
        .await
        .expect("follow-up select timed out")
        .expect("follow-up select failed");

        assert_eq!(ex2.input.header(headers::ROW_COUNT), Some(&json!(2)));
    }

    #[test]
    fn classify_db_message_is_fail_closed() {
        assert!(matches!(
            classify_db_message(SQLITE_NO_ACTIVE_TRANSACTION),
            RollbackDisposition::Keep
        ));
        assert!(matches!(
            classify_db_message("SQLITE_ERROR: cannot rollback - no transaction is active"),
            RollbackDisposition::Discard
        ));
        assert!(matches!(
            classify_db_message("cannot rollback - no transaction is active!!"),
            RollbackDisposition::Discard
        ));
        assert!(matches!(
            classify_db_message(""),
            RollbackDisposition::Discard
        ));
    }

    #[test]
    fn rollback_error_classifier_rejects_non_database_errors() {
        let err = sqlx::Error::Protocol(
            "cannot rollback - no transaction is active (context)".to_string(),
        );
        assert!(matches!(
            classify_rollback_error(&err),
            RollbackDisposition::Discard
        ));
    }

    #[tokio::test]
    async fn cleanup_guard_discards_when_armed_keeps_when_disarmed() {
        let pool = sqlite_pool().await;
        seed_items_table(&pool).await;

        // Bounded acquire (lint-unbounded-wait): a wedged pool must fail the test
        // instead of parking it.
        let conn = tokio::time::timeout(std::time::Duration::from_secs(10), pool.acquire())
            .await
            .expect("acquire timed out after 10s")
            .expect("acquire connection");
        let guard = DiscardOnDrop(Some(conn));
        drop(guard);
        assert_eq!(pool.size(), 0, "armed guard must discard the connection");

        let conn = tokio::time::timeout(std::time::Duration::from_secs(10), pool.acquire())
            .await
            .expect("acquire timed out after 10s")
            .expect("acquire connection");
        let guard = DiscardOnDrop(Some(conn));
        let conn = guard.disarm();
        drop(conn);
        assert_eq!(pool.size(), 1, "disarmed guard must keep the connection");
    }

    // --- Phase B hardening tests ---

    // SQL-001: Direct producer construction without resolve_defaults does not panic.
    // The producer defensively calls resolve_defaults() during pool init, so the pool
    // fields get resolved. This test verifies no panic occurs and the pool initializes.
    #[tokio::test]
    async fn producer_no_panic_without_prior_resolve_defaults() {
        // Create config without calling resolve_defaults() — pool fields are None
        let config = SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite::memory:").unwrap();
        assert!(config.max_connections.is_none());

        let mut producer = SqlProducer::new(
            config,
            Arc::new(OnceCell::new()),
            None,
            // Noop runtime: pool-init retries now record per-attempt
            // telemetry by design, which the panic runtime would reject.
            std::sync::Arc::new(camel_component_api::test_support::NoopRuntimeObservability),
            "sql-producer-test-route",
        );
        let exchange = Exchange::new(Message::default());

        // Should NOT panic — producer calls resolve_defaults() defensively
        let result = producer.call(exchange).await;
        assert!(
            result.is_ok(),
            "Producer should initialize pool without panic, got: {:?}",
            result
        );
    }

    // SQL-001: Pool init returns CamelError::Config when pool params cannot be resolved
    #[tokio::test]
    async fn producer_pool_init_returns_config_error_for_invalid_db() {
        // Create config with an invalid db_url that will fail to connect.
        // Disable retry for this test — the purpose is to verify error handling
        // on a known-bad connect, not to exercise the retry loop.
        let mut config = SqlEndpointConfig::from_uri(
            "sql:select 1?db_url=postgres://nonexistent-host:5432/nonexistent_db&retryEnabled=false",
        )
        .unwrap();
        // Set pool params explicitly so resolve_defaults doesn't help with connection
        config.max_connections = Some(1);
        config.min_connections = Some(0);
        config.idle_timeout_secs = Some(300);
        config.max_lifetime_secs = Some(1800);

        let health = Arc::new(RecordingHealth::default());
        let rt: Arc<dyn RuntimeObservability> = Arc::new(RecordingRuntime {
            health: health.clone(),
        });
        let mut producer = SqlProducer::new(
            config,
            Arc::new(OnceCell::new()),
            None,
            rt,
            "sql-producer-test-route",
        );
        let exchange = Exchange::new(Message::default());

        let result = producer.call(exchange).await;
        assert!(result.is_err());
        // Error should be EndpointCreationFailed (connection error), not a panic
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("Failed to connect") || err_msg.contains("database"),
            "Expected connection error, got: {}",
            err_msg
        );
        // Verify force_unhealthy_for_route was also called
        let forced = health.forced.lock().unwrap();
        assert_eq!(
            forced.len(),
            1,
            "expected one force_unhealthy_for_route call"
        );
        assert_eq!(forced[0].0, "sql-producer-test-route");
        assert_eq!(forced[0].1, "g:sql:producer-pool-init");
    }

    // SQL-007: poll_ready returns Ready (pool lazily initialized on first call)
    #[test]
    fn poll_ready_returns_ready_for_uninitialized_pool() {
        let config = {
            let mut c = SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite::memory:").unwrap();
            c.resolve_defaults();
            c
        };
        let mut producer = SqlProducer::new(
            config,
            Arc::new(OnceCell::new()),
            None,
            test_rt(),
            "sql-producer-test-route",
        );
        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
        let result = producer.poll_ready(&mut cx);
        assert!(matches!(result, Poll::Ready(Ok(()))));
    }

    // SQL-007: poll_ready returns error when stopped flag is set
    #[test]
    fn poll_ready_returns_error_when_stopped() {
        let config = {
            let mut c = SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite::memory:").unwrap();
            c.resolve_defaults();
            c
        };
        let mut producer = SqlProducer::new(
            config,
            Arc::new(OnceCell::new()),
            None,
            test_rt(),
            "sql-producer-test-route",
        );
        producer.stop();
        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
        let result = producer.poll_ready(&mut cx);
        assert!(matches!(result, Poll::Ready(Err(_))));
        let err_msg = match result {
            Poll::Ready(Err(e)) => e.to_string(),
            _ => unreachable!(),
        };
        assert!(err_msg.contains("SQL producer stopped"));
    }

    // SQL-007: poll_ready returns error when pool is closed
    #[tokio::test]
    async fn poll_ready_returns_error_when_pool_closed() {
        let pool = sqlite_pool().await;
        pool.close().await;

        let config = {
            let mut c = SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite::memory:").unwrap();
            c.resolve_defaults();
            c
        };
        let pool_cell = Arc::new(OnceCell::new());
        pool_cell.set(Arc::new(pool)).unwrap();

        let mut producer = SqlProducer::new(
            config,
            pool_cell,
            None,
            test_rt(),
            "sql-producer-test-route",
        );
        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
        let result = producer.poll_ready(&mut cx);
        assert!(matches!(result, Poll::Ready(Err(_))));
        let err_msg = match result {
            Poll::Ready(Err(e)) => e.to_string(),
            _ => unreachable!(),
        };
        assert!(err_msg.contains("SQL connection pool is closed"));
    }

    // SQL-007: poll_ready returns Ok for healthy initialized pool
    #[tokio::test]
    async fn poll_ready_returns_ok_for_healthy_pool() {
        let pool = sqlite_pool().await;

        let config = {
            let mut c = SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite::memory:").unwrap();
            c.resolve_defaults();
            c
        };
        let pool_cell = Arc::new(OnceCell::new());
        pool_cell.set(Arc::new(pool)).unwrap();

        let mut producer = SqlProducer::new(
            config,
            pool_cell,
            None,
            test_rt(),
            "sql-producer-test-route",
        );
        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
        let result = producer.poll_ready(&mut cx);
        assert!(matches!(result, Poll::Ready(Ok(()))));
    }

    // SQL-008: stop() closes the pool
    #[tokio::test]
    async fn test_sql_stop_closes_pool() {
        let pool = sqlite_pool().await;

        let config = {
            let mut c = SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite::memory:").unwrap();
            c.resolve_defaults();
            c
        };
        let pool_cell = Arc::new(OnceCell::new());
        pool_cell.set(Arc::new(pool.clone())).unwrap();

        let producer = SqlProducer::new(
            config,
            pool_cell.clone(),
            None,
            test_rt(),
            "sql-producer-test-route",
        );
        assert!(!pool.is_closed(), "Pool should be open before stop");

        producer.stop();

        // Allow background close task to complete
        tokio::time::sleep(Duration::from_millis(100)).await;

        assert!(
            pool.is_closed(),
            "Pool should be closed after producer.stop()"
        );

        // Subsequent poll_ready should fail
        let mut producer2 = SqlProducer::new(
            {
                let mut c =
                    SqlEndpointConfig::from_uri("sql:select 1?db_url=sqlite::memory:").unwrap();
                c.resolve_defaults();
                c
            },
            pool_cell.clone(),
            None,
            test_rt(),
            "sql-producer-test-route",
        );
        let mut cx = Context::from_waker(futures::task::noop_waker_ref());
        let result = producer2.poll_ready(&mut cx);
        assert!(
            matches!(result, Poll::Ready(Err(_))),
            "poll_ready should fail after pool closed"
        );
    }

    // SQL-004: use_placeholder=false skips template parsing
    #[tokio::test]
    async fn use_placeholder_false_executes_raw_sql() {
        let pool = sqlite_pool().await;
        seed_items_table(&pool).await;

        let mut config = SqlEndpointConfig::from_uri(
            "sql:select id, name from items order by id?db_url=sqlite::memory:&usePlaceholder=false",
        )
        .unwrap();
        config.resolve_defaults();
        assert!(!config.use_placeholder);

        let mut producer = SqlProducer::new(
            config,
            Arc::new(OnceCell::new()),
            None,
            test_rt(),
            "sql-producer-test-route",
        );
        // Pre-initialize the pool so we don't hit the pool init path
        producer.pool.set(Arc::new(pool.clone())).unwrap();

        let exchange = Exchange::new(Message::default());
        let result = producer.call(exchange).await;
        assert!(result.is_ok());
        let exchange = result.unwrap();
        // Should return results, not rowsAffected
        assert!(matches!(exchange.input.body, Body::Json(_)));
    }

    // SQL-004: use_placeholder=true (default) processes placeholders normally
    #[tokio::test]
    async fn use_placeholder_true_processes_placeholders() {
        let pool = sqlite_pool().await;
        seed_items_table(&pool).await;

        let mut config = SqlEndpointConfig::from_uri(
            "sql:select id, name from items where id = #?db_url=sqlite::memory:",
        )
        .unwrap();
        config.resolve_defaults();
        assert!(config.use_placeholder);

        let mut producer = SqlProducer::new(
            config,
            Arc::new(OnceCell::new()),
            None,
            test_rt(),
            "sql-producer-test-route",
        );
        producer.pool.set(Arc::new(pool.clone())).unwrap();

        let msg = Message::new(Body::Json(json!([1])));
        let exchange = Exchange::new(msg);
        let result = producer.call(exchange).await;
        assert!(result.is_ok());
    }

    /// Regression: max_attempts=N → exactly N invocations (caught OpenSearch off-by-one 1f5c4c2a).
    /// Replicates the exact retry loop from SqlProducer::start() (producer.rs:161-185):
    ///   attempt starts at 0, incremented at top, should_retry(attempt), delay_for(attempt-1)
    #[tokio::test]
    async fn retry_loop_invokes_operation_exactly_max_attempts_times() {
        use camel_component_api::NetworkRetryPolicy;
        use std::sync::Arc;
        use std::sync::atomic::{AtomicU32, Ordering};

        let policy = NetworkRetryPolicy {
            max_attempts: 3,
            initial_delay: Duration::from_millis(1),
            max_delay: Duration::from_millis(1),
            multiplier: 1.0,
            ..NetworkRetryPolicy::default()
        };

        let calls = Arc::new(AtomicU32::new(0));
        let calls_clone = Arc::clone(&calls);

        let mut attempt: u32 = 0;
        let _result: Result<(), ()> = tokio::time::timeout(Duration::from_secs(30), async {
            loop {
                attempt += 1;
                calls_clone.fetch_add(1, Ordering::SeqCst);
                let op_result: Result<(), ()> = Err(());
                match op_result {
                    Ok(v) => break Ok(v),
                    Err(_) if policy.should_retry(attempt) => {
                        let delay = policy.delay_for(attempt - 1);
                        tokio::time::sleep(delay).await;
                        continue;
                    }
                    Err(_) => break Err(()),
                }
            }
        })
        .await
        .expect("retry loop must finish within 30s");

        assert_eq!(
            calls.load(Ordering::SeqCst),
            3,
            "max_attempts=3 must yield exactly 3 invocations"
        );
    }

    // ── ADR-0012 (g) regression tests ──────────────────────────────────

    /// Regression: producer pool init failure calls force_unhealthy_for_route
    /// with correct route_id + name "g:sql:producer-pool-init" + non-empty reason.
    #[tokio::test]
    async fn producer_pool_init_failure_calls_force_unhealthy_for_route() {
        let health = Arc::new(RecordingHealth::default());
        let rt: Arc<dyn RuntimeObservability> = Arc::new(RecordingRuntime {
            health: health.clone(),
        });

        let mut config = SqlEndpointConfig::from_uri(
            "sql:select 1?db_url=postgres://nonexistent-host:5432/nonexistent_db&retryEnabled=false",
        )
        .unwrap();
        config.max_connections = Some(1);
        config.min_connections = Some(0);
        config.idle_timeout_secs = Some(300);
        config.max_lifetime_secs = Some(1800);

        let mut producer = SqlProducer::new(
            config,
            Arc::new(OnceCell::new()),
            None,
            rt,
            "sql-producer-test-route",
        );
        let exchange = Exchange::new(Message::default());

        let result = producer.call(exchange).await;
        assert!(result.is_err());

        let forced = health.forced.lock().unwrap();
        assert_eq!(
            forced.len(),
            1,
            "expected one force_unhealthy_for_route call"
        );
        assert_eq!(forced[0].0, "sql-producer-test-route");
        assert_eq!(forced[0].1, "g:sql:producer-pool-init");
        assert!(!forced[0].2.is_empty(), "reason should be non-empty");
    }

    // H7: from_uri must default allow_dynamic_query to false when the
    // URI does not include the allowDynamicQuery parameter.
    #[test]
    fn sql_allow_dynamic_query_defaults_false_from_uri() {
        let config =
            SqlEndpointConfig::from_uri("sql:query?datasource=mydb&query=SELECT+1").unwrap();
        assert!(!config.allow_dynamic_query);
    }
}