hyperdb-api 0.1.0

Pure Rust API for Hyper database
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
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
// Copyright (c) 2026, Salesforce, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! High-performance bulk data inserter using COPY protocol.
//!
//! This module provides the `Inserter` struct for efficient bulk data insertion
//! into Hyper tables, along with the `IntoValue` trait for type-safe insertion.
//!
//! # Example
//!
//! ```no_run
//! # use hyperdb_api::{Inserter, Connection, CreateMode, Result};
//! # fn example(conn: &Connection, table_def: &hyperdb_api::TableDefinition) -> Result<()> {
//! let mut inserter = Inserter::new(&conn, &table_def)?;
//! for i in 0..10000i32 {
//!     inserter.add_row(&[&i, &format!("item {}", i), &(i as f64 * 1.5)])?;
//! }
//! inserter.execute()?;
//! # Ok(())
//! # }
//! ```

use std::time::Instant;

use hyperdb_api_core::client::client::CopyInWriter;
use hyperdb_api_core::protocol::copy;
use hyperdb_api_core::types::bytes::BytesMut;
use hyperdb_api_core::types::{Date, Interval, Numeric, OffsetTimestamp, Time, Timestamp};
use tracing::{debug, info};

use crate::catalog::Catalog;
use crate::connection::Connection;
use crate::error::{Error, Result};
use crate::table_definition::TableDefinition;

/// Initial buffer size (4 MB) to reduce early reallocations.
///
/// The COPY protocol sends data in chunks, and each chunk requires a
/// contiguous buffer. Starting at 4 MB avoids repeated reallocations
/// during the first chunk for typical workloads while keeping initial
/// memory allocation reasonable.
const INITIAL_BUFFER_SIZE: usize = 4 * 1024 * 1024;

/// Maximum buffer size per chunk before flushing to the server (16 MB).
///
/// This balances two competing concerns:
/// - **Throughput**: Larger chunks amortize per-chunk overhead (COPY header,
///   network round-trip). Below ~1 MB, per-chunk overhead becomes significant.
/// - **Memory**: The buffer must be fully materialized before sending. 16 MB
///   keeps resident memory bounded even when rows are wide.
///
/// The 16 MB value was chosen empirically — it lands on the flat part of
/// the throughput curve where further increases yield diminishing returns.
const CHUNK_SIZE_LIMIT: usize = 16 * 1024 * 1024;

/// Maximum rows per chunk before flushing to the server.
///
/// This is a secondary flush trigger alongside [`CHUNK_SIZE_LIMIT`]. For
/// narrow rows (few bytes each), the byte limit alone would accumulate
/// millions of rows before flushing, which delays server-side processing.
/// 64K rows ensures timely flushes regardless of row width and aligns with
/// the 64K chunk size used for query result streaming
/// ([`DEFAULT_BINARY_CHUNK_SIZE`](crate::result::DEFAULT_BINARY_CHUNK_SIZE)).
const CHUNK_ROW_LIMIT: usize = 64_000;

/// A high-performance bulk data inserter.
///
/// The `Inserter` efficiently inserts large amounts of data into a Hyper table
/// using the COPY protocol with `HyperBinary` format for optimal performance.
///
/// # Example
///
/// ```no_run
/// use hyperdb_api::{Connection, CreateMode, Catalog, TableDefinition, Inserter, SqlType, Result};
///
/// fn main() -> Result<()> {
///     let conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::CreateIfNotExists)?;
///
///     let table_def = TableDefinition::new("users")
///         .add_required_column("id", SqlType::int())
///         .add_nullable_column("name", SqlType::text());
///
///     Catalog::new(&conn).create_table(&table_def)?;
///
///     let mut inserter = Inserter::new(&conn, &table_def)?;
///
///     for i in 0..1000i32 {
///         inserter.add_row(&[&i, &format!("User {}", i)])?;
///     }
///
///     let rows = inserter.execute()?;
///     println!("Inserted {} rows", rows);
///     Ok(())
/// }
/// ```
#[derive(Debug)]
pub struct Inserter<'conn> {
    connection: &'conn Connection,
    table_def: TableDefinition,
    /// The current chunk being populated (delegates encoding).
    chunk: InsertChunk,
    /// Total rows inserted across all chunks.
    row_count: u64,
    /// Number of chunks sent.
    chunk_count: usize,
    /// Active COPY writer (lazily initialized on first write).
    writer: Option<CopyInWriter<'conn>>,
    /// Start time for timing the insert operation.
    start_time: Instant,
}

impl<'conn> Inserter<'conn> {
    /// Creates a new inserter for the given table.
    ///
    /// The underlying COPY session is started lazily on the first flush or
    /// execute, so construction is lightweight. However, the connection's
    /// transport is validated eagerly — using a gRPC connection will return
    /// an error immediately.
    ///
    /// # Errors
    ///
    /// - Returns [`Error::InvalidTableDefinition`] if `table_def` has zero
    ///   columns.
    /// - Returns [`Error::Other`] if `connection` is using gRPC transport
    ///   (COPY is TCP-only).
    pub fn new(connection: &'conn Connection, table_def: &TableDefinition) -> Result<Self> {
        if table_def.column_count() == 0 {
            return Err(Error::InvalidTableDefinition(
                "Table definition must have at least one column".into(),
            ));
        }

        // Fail fast: verify the connection supports COPY (TCP only)
        if connection.tcp_client().is_none() {
            return Err(Error::new(
                "Inserter requires a TCP connection. \
                 gRPC connections do not support COPY operations.",
            ));
        }

        Ok(Inserter {
            connection,
            table_def: table_def.clone(),
            chunk: InsertChunk::from_table_definition(table_def),
            row_count: 0,
            chunk_count: 0,
            writer: None,
            start_time: Instant::now(),
        })
    }

    /// Creates an inserter by querying the table schema from the database.
    ///
    /// This method queries the database to get the table definition automatically,
    /// which is useful when you want to insert into an existing table without
    /// manually specifying the schema.
    ///
    /// # Arguments
    ///
    /// * `connection` - The database connection.
    /// * `table_name` - The table name (can be a simple name, or "schema.table", etc.)
    ///
    /// # Errors
    ///
    /// Returns an error if the table doesn't exist or if the schema cannot be retrieved.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hyperdb_api::{Connection, CreateMode, Inserter, Result};
    ///
    /// fn main() -> Result<()> {
    ///     let conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::CreateIfNotExists)?;
    ///
    ///     // Create a table first
    ///     conn.execute_command("CREATE TABLE IF NOT EXISTS products (id INT NOT NULL, name TEXT, price DOUBLE PRECISION)")?;
    ///
    ///     // Create inserter by querying the schema directly from a string
    ///     let mut inserter = Inserter::from_table(&conn, "public.products")?;
    ///
    ///     // Now we can insert data without knowing the exact schema
    ///     inserter.add_row(&[&1i32, &"Widget", &19.99f64])?;
    ///     inserter.add_row(&[&2i32, &"Gadget", &29.99f64])?;
    ///
    ///     let rows = inserter.execute()?;
    ///     println!("Inserted {} rows", rows);
    ///     Ok(())
    /// }
    /// ```
    pub fn from_table<T>(connection: &'conn Connection, table_name: T) -> Result<Self>
    where
        T: TryInto<crate::TableName>,
        crate::Error: From<T::Error>,
    {
        let catalog = Catalog::new(connection);
        let table_def = catalog.get_table_definition(table_name)?;
        Self::new(connection, &table_def)
    }

    /// Creates an inserter with column mappings that allow SQL expressions.
    ///
    /// This method uses a temporary table and INSERT...SELECT to support
    /// column mappings with SQL expressions. Data is first inserted into
    /// a temporary staging table, then transformed using the mappings.
    ///
    /// # Arguments
    ///
    /// * `connection` - The database connection.
    /// * `inserter_def` - Defines the columns to be provided to the inserter (staging table).
    /// * `target_table` - The qualified name of the target table to insert into.
    ///   Use `TableDefinition::qualified_name()` for properly escaped names like `"schema"."table"`.
    /// * `mappings` - Column mappings defining how values are transformed.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hyperdb_api::{Connection, CreateMode, TableDefinition, ColumnMapping, Inserter, SqlType, Result};
    ///
    /// fn main() -> Result<()> {
    ///     let conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::CreateIfNotExists)?;
    ///
    ///     // Target table with computed columns
    ///     conn.execute_command(r#"
    ///         CREATE TABLE orders (
    ///             id INT NOT NULL,
    ///             product TEXT,
    ///             quantity INT,
    ///             price DOUBLE PRECISION,
    ///             total DOUBLE PRECISION,
    ///             created_at TIMESTAMP
    ///         )
    ///     "#)?;
    ///
    ///     // Inserter definition - what we provide
    ///     let inserter_def = TableDefinition::new("_stage")
    ///         .add_required_column("id", SqlType::int())
    ///         .add_nullable_column("product", SqlType::text())
    ///         .add_nullable_column("quantity", SqlType::int())
    ///         .add_nullable_column("price", SqlType::double());
    ///
    ///     // Column mappings - how values are transformed
    ///     let mappings = vec![
    ///         ColumnMapping::new("id"),
    ///         ColumnMapping::new("product"),
    ///         ColumnMapping::new("quantity"),
    ///         ColumnMapping::new("price"),
    ///         ColumnMapping::with_expression("total", "quantity * price"),
    ///         ColumnMapping::with_expression("created_at", "NOW()"),
    ///     ];
    ///
    ///     // For simple table names in the public schema, use quoted name
    ///     // For qualified names, use target_table_def.qualified_name()
    ///     let mut inserter = Inserter::with_column_mappings(&conn, &inserter_def, "orders", &mappings)?;
    ///
    ///     inserter.add_row(&[&1i32, &"Widget", &5i32, &10.0f64])?;
    ///     inserter.add_row(&[&2i32, &"Gadget", &3i32, &25.0f64])?;
    ///
    ///     let rows = inserter.execute()?;
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// - Returns an error if `target_table` fails to convert into a
    ///   [`TableName`](crate::TableName).
    /// - Returns [`Error::Client`] if creating the temporary staging table
    ///   fails on the server.
    /// - Returns the errors from [`Inserter::new`] for the staging table
    ///   (zero-column table definition, gRPC transport).
    pub fn with_column_mappings<T>(
        connection: &'conn Connection,
        inserter_def: &TableDefinition,
        target_table: T,
        mappings: &[ColumnMapping],
    ) -> Result<MappedInserter<'conn>>
    where
        T: TryInto<crate::TableName>,
        crate::Error: From<T::Error>,
    {
        MappedInserter::new(connection, inserter_def, target_table, mappings)
    }

    /// Returns the table definition.
    pub fn table_definition(&self) -> &TableDefinition {
        &self.table_def
    }

    /// Returns the number of columns.
    #[must_use]
    pub fn column_count(&self) -> usize {
        self.table_def.column_count()
    }

    /// Returns the number of complete rows buffered.
    #[must_use]
    pub fn row_count(&self) -> u64 {
        self.row_count
    }

    /// Adds a NULL value for the current column.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Other`] if the current row already has all columns
    /// supplied, or if the current column is marked `NOT NULL` in the table
    /// definition.
    #[inline]
    pub fn add_null(&mut self) -> Result<()> {
        self.chunk.add_null()
    }

    /// Adds a boolean value.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Other`] with message `"Too many columns in row"` if
    /// the current row already has all columns supplied.
    #[inline]
    pub fn add_bool(&mut self, value: bool) -> Result<()> {
        self.chunk.add_bool(value)
    }

    /// Adds an i16 value (SMALLINT).
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    #[inline]
    pub fn add_i16(&mut self, value: i16) -> Result<()> {
        self.chunk.add_i16(value)
    }

    /// Adds an i32 value (INT).
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    #[inline]
    pub fn add_i32(&mut self, value: i32) -> Result<()> {
        self.chunk.add_i32(value)
    }

    /// Adds an i64 value (BIGINT).
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    #[inline]
    pub fn add_i64(&mut self, value: i64) -> Result<()> {
        self.chunk.add_i64(value)
    }

    /// Adds an f32 value (REAL/FLOAT4).
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    #[inline]
    pub fn add_f32(&mut self, value: f32) -> Result<()> {
        self.chunk.add_f32(value)
    }

    /// Adds an f64 value (DOUBLE PRECISION/FLOAT8).
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    #[inline]
    pub fn add_f64(&mut self, value: f64) -> Result<()> {
        self.chunk.add_f64(value)
    }

    /// Adds a string value (TEXT/VARCHAR).
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    #[inline]
    pub fn add_str(&mut self, value: &str) -> Result<()> {
        self.chunk.add_str(value)
    }

    /// Adds a bytes value (BYTEA).
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    #[inline]
    pub fn add_bytes(&mut self, value: &[u8]) -> Result<()> {
        self.chunk.add_bytes(value)
    }

    /// Adds a 128-bit value (NUMERIC/INTERVAL).
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    #[inline]
    pub fn add_data128(&mut self, value: &[u8; 16]) -> Result<()> {
        self.chunk.add_data128(value)
    }

    /// Adds an optional value. If None, adds NULL.
    ///
    /// # Errors
    ///
    /// Propagates whatever `add_fn` or [`add_null`](Self::add_null) would
    /// return for the current row position.
    pub fn add_optional<T, F>(&mut self, value: Option<T>, add_fn: F) -> Result<()>
    where
        F: FnOnce(&mut Self, T) -> Result<()>,
    {
        match value {
            Some(v) => add_fn(self, v),
            None => self.add_null(),
        }
    }

    /// Ends the current row.
    ///
    /// Returns an error if the wrong number of columns were added.
    /// Automatically flushes the buffer if chunk limits are reached.
    ///
    /// # Errors
    ///
    /// - Returns [`Error::Other`] if fewer (or more) columns were supplied
    ///   than the table definition requires.
    /// - Returns any error from [`flush`](Self::flush) when an automatic
    ///   flush is triggered by reaching the chunk byte/row limit.
    pub fn end_row(&mut self) -> Result<()> {
        self.chunk.end_row()?;
        self.row_count += 1;

        // Auto-flush if we've reached chunk limits
        if self.chunk.should_flush() {
            self.flush()?;
        }

        Ok(())
    }

    /// Flushes the current buffer to the server.
    ///
    /// This sends all buffered rows as a chunk and resets the buffer.
    /// Called automatically when chunk limits are reached.
    ///
    /// # Errors
    ///
    /// - Returns [`Error::Other`] if the connection is using gRPC transport
    ///   (COPY is TCP-only) and no COPY session exists yet.
    /// - Returns [`Error::Client`] if the server rejects the `COPY IN` start
    ///   or the subsequent data send.
    /// - Returns [`Error::Io`] on transport-level I/O failures while writing
    ///   the chunk.
    pub fn flush(&mut self) -> Result<()> {
        if self.chunk.is_empty() {
            return Ok(());
        }

        let chunk_rows = self.chunk.row_count();
        let Some(buffer) = self.chunk.take() else {
            return Ok(());
        };

        // Ensure the COPY connection is started
        if self.writer.is_none() {
            let client = self.connection.tcp_client().ok_or_else(|| {
                crate::Error::new("Inserter requires a TCP connection. gRPC connections do not support COPY operations.")
            })?;
            let columns: Vec<&str> = self
                .table_def
                .columns
                .iter()
                .map(|c| c.name.as_str())
                .collect();
            let table_name = self.table_def.qualified_name();
            self.writer = Some(client.copy_in(&table_name, &columns)?);
        }

        // Write the chunk directly to the socket, avoiding a full-chunk memcpy
        // into the connection's write buffer. flush_stream ensures the data
        // reaches the server before we return.
        if let Some(ref mut writer) = self.writer {
            writer.send_direct(&buffer)?;
            writer.flush_stream()?;
        }

        debug!(
            target: "hyperdb_api",
            chunk = self.chunk_count,
            rows = chunk_rows,
            bytes = buffer.len(),
            "inserter-chunk"
        );

        self.chunk_count += 1;
        Ok(())
    }

    /// Adds a complete row of values.
    ///
    /// This is a convenience method that adds all column values at once
    /// using the `IntoValue` trait for type-safe insertion.
    ///
    /// # Arguments
    ///
    /// * `values` - A slice of values implementing `IntoValue`.
    ///
    /// # Errors
    ///
    /// Returns an error if the number of values doesn't match the column count,
    /// or if any value cannot be added.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hyperdb_api::{Connection, CreateMode, Catalog, TableDefinition, Inserter, SqlType, Result};
    ///
    /// fn main() -> Result<()> {
    ///     let conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::CreateIfNotExists)?;
    ///
    ///     let table_def = TableDefinition::new("users")
    ///         .add_required_column("id", SqlType::int())
    ///         .add_nullable_column("name", SqlType::text());
    ///
    ///     Catalog::new(&conn).create_table(&table_def)?;
    ///
    ///     let mut inserter = Inserter::new(&conn, &table_def)?;
    ///
    ///     // Add rows using IntoValue trait
    ///     inserter.add_row(&[&1i32, &"Alice"])?;
    ///     inserter.add_row(&[&2i32, &"Bob"])?;
    ///
    ///     // Option<T> can be used for nullable columns
    ///     inserter.add_row(&[&3i32, &None::<&str>])?;
    ///
    ///     let rows = inserter.execute()?;
    ///     Ok(())
    /// }
    /// ```
    pub fn add_row(&mut self, values: &[&dyn IntoValue]) -> Result<()> {
        let column_count = self.table_def.column_count();
        if values.len() != column_count {
            return Err(Error::new(format!(
                "Column count mismatch: expected {} columns but got {}",
                column_count,
                values.len()
            )));
        }

        for value in values {
            value.add_to_inserter(self)?;
        }

        self.end_row()?;
        Ok(())
    }

    /// Adds a Date value.
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    #[inline]
    pub fn add_date(&mut self, value: Date) -> Result<()> {
        self.chunk.add_date(value)
    }

    /// Adds a Time value.
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    #[inline]
    pub fn add_time(&mut self, value: Time) -> Result<()> {
        self.chunk.add_time(value)
    }

    /// Adds a Timestamp value.
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    #[inline]
    pub fn add_timestamp(&mut self, value: Timestamp) -> Result<()> {
        self.chunk.add_timestamp(value)
    }

    /// Adds an `OffsetTimestamp` (TIMESTAMP WITH TIME ZONE) value.
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    #[inline]
    pub fn add_offset_timestamp(&mut self, value: OffsetTimestamp) -> Result<()> {
        self.chunk.add_offset_timestamp(value)
    }

    /// Adds an Interval value.
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    #[inline]
    pub fn add_interval(&mut self, value: Interval) -> Result<()> {
        self.chunk.add_interval(value)
    }

    /// Adds a Numeric value.
    ///
    /// For NUMERIC(precision, scale) where precision ≤ [`Numeric::SMALL_NUMERIC_MAX_PRECISION`]
    /// (18), the value is stored as i64. For higher precision, 128-bit storage is used.
    ///
    /// # Errors
    ///
    /// Returns an error if the column's precision cannot be determined from the
    /// table definition. Ensure that NUMERIC columns are defined with explicit
    /// `SqlType` information including precision.
    pub fn add_numeric(&mut self, value: Numeric) -> Result<()> {
        let column_index = self.chunk.column_index();

        // Check the column's precision to determine storage format
        let precision = self
            .table_def
            .columns
            .get(column_index)
            .and_then(super::table_definition::ColumnDefinition::sql_type)
            .and_then(|t| t.precision())
            .ok_or_else(|| {
                let col_name = self
                    .table_def
                    .columns
                    .get(column_index)
                    .map_or("<unknown>", |c| c.name.as_str());
                Error::new(format!(
                    "Cannot determine numeric precision for column '{col_name}' at index {column_index}. \
                     Ensure the column is defined with explicit SqlType including precision.\n\n\
                     Example fix:\n  \
                     table_def.add_column_with_type(\"{col_name}\", SqlType::Numeric {{ precision: 10, scale: 2 }}, true);"
                ))
            })?;

        if precision <= Numeric::SMALL_NUMERIC_MAX_PRECISION {
            // Small numeric: stored as i64
            let unscaled = value.unscaled_value();
            let narrowed = i64::try_from(unscaled).map_err(|_| {
                Error::new(format!(
                    "Numeric value {unscaled} is out of range for i64 storage (precision {precision})"
                ))
            })?;
            self.chunk.add_i64(narrowed)
        } else {
            // Big numeric: stored as 128-bit
            self.chunk.add_data128(&value.to_packed())
        }
    }

    /// Executes the insert and commits all buffered rows.
    ///
    /// This sends any remaining buffered data and finishes the COPY operation.
    /// Returns the number of rows inserted.
    ///
    /// The inserter is single-use: calling `execute` a second time returns
    /// `Ok(0)` because the internal row counter has been reset and no further
    /// data has been added. To insert additional batches, create a new
    /// [`Inserter`].
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - There's an incomplete row (`column_index` != 0)
    /// - The COPY connection fails to start
    /// - Sending data fails
    pub fn execute(&mut self) -> Result<u64> {
        if self.chunk.column_index() != 0 {
            return Err(Error::new("Incomplete row at execute time"));
        }

        if self.row_count == 0 {
            return Ok(0);
        }

        // Ensure COPY connection exists before proceeding when we have rows
        if self.writer.is_none() {
            let client = self.connection.tcp_client().ok_or_else(|| {
                Error::new("Inserter requires a TCP connection. gRPC connections do not support COPY operations.")
            })?;
            let columns: Vec<&str> = self
                .table_def
                .columns
                .iter()
                .map(|c| c.name.as_str())
                .collect();
            let table_name = self.table_def.qualified_name();
            self.writer = Some(client.copy_in(&table_name, &columns)?);
        }

        // At this point, writer must exist since we have rows
        let writer = self
            .writer
            .as_mut()
            .ok_or_else(|| Error::new("Failed to initialize COPY connection for inserter"))?;

        // If we have buffered data that hasn't been sent yet
        if !self.chunk.is_empty() {
            writer.send(self.chunk.buffer())?;
        }

        // Write and send the COPY trailer
        let mut trailer_buf = BytesMut::with_capacity(2);
        copy::write_trailer(&mut trailer_buf);
        writer.send(&trailer_buf)?;

        // Finish the COPY operation
        let rows = self
            .writer
            .take()
            .map(hyperdb_api_core::client::CopyInWriter::finish)
            .transpose()?
            .unwrap_or(0);

        let duration_ms = u64::try_from(self.start_time.elapsed().as_millis()).unwrap_or(u64::MAX);
        info!(
            target: "hyperdb_api",
            rows,
            chunks = self.chunk_count,
            duration_ms,
            table = %self.table_def.qualified_name(),
            "inserter-end"
        );

        // Reset row counter so a stray second execute() call returns Ok(0)
        // instead of attempting another COPY trailer on a finished writer.
        self.row_count = 0;

        Ok(rows)
    }

    /// Cancels the insert and discards all buffered rows.
    pub fn cancel(&mut self) {
        // Drop the in-progress writer (if any). The Drop impl on CopyInWriter
        // sends a CopyFail to the server.
        self.writer = None;
        self.row_count = 0;
    }
}

// =============================================================================
// ColumnMapping
// =============================================================================

/// Defines how a column receives its value during insertion.
///
/// Column mappings allow you to:
/// - Insert values directly from the inserter stream
/// - Compute values using SQL expressions
/// - Use server-side functions like `NOW()` or `DEFAULT`
///
/// # Example
///
/// ```
/// use hyperdb_api::ColumnMapping;
///
/// // Simple column - insert value directly
/// let id_col = ColumnMapping::new("id");
///
/// // Column with expression - computed value
/// let created_at = ColumnMapping::with_expression("created_at", "NOW()");
/// let full_name = ColumnMapping::with_expression("full_name", "first_name || ' ' || last_name");
/// ```
#[derive(Debug, Clone)]
#[must_use = "ColumnMapping represents a column configuration that should not be discarded. Use it when defining inserter column mappings"]
pub struct ColumnMapping {
    /// The name of the target column.
    pub column_name: String,
    /// Optional SQL expression. If None, the value is inserted directly.
    pub expression: Option<String>,
}

impl ColumnMapping {
    /// Creates a column mapping for direct value insertion.
    ///
    /// The column will receive values directly from the inserter.
    pub fn new(column_name: impl Into<String>) -> Self {
        ColumnMapping {
            column_name: column_name.into(),
            expression: None,
        }
    }

    /// Creates a column mapping with a SQL expression.
    ///
    /// The column value will be computed using the given SQL expression.
    /// The expression can reference other columns or use SQL functions.
    ///
    /// # Arguments
    ///
    /// * `column_name` - The name of the target column.
    /// * `expression` - A SQL expression to compute the column value.
    ///
    /// # Example
    ///
    /// ```
    /// use hyperdb_api::ColumnMapping;
    ///
    /// // Use current timestamp
    /// let created = ColumnMapping::with_expression("created_at", "NOW()");
    ///
    /// // Compute from other columns
    /// let total = ColumnMapping::with_expression("total", "quantity * price");
    /// ```
    pub fn with_expression(column_name: impl Into<String>, expression: impl Into<String>) -> Self {
        ColumnMapping {
            column_name: column_name.into(),
            expression: Some(expression.into()),
        }
    }

    /// Returns the column name.
    #[must_use]
    pub fn column_name(&self) -> &str {
        &self.column_name
    }

    /// Returns the SQL expression, if any.
    #[must_use]
    pub fn expression(&self) -> Option<&str> {
        self.expression.as_deref()
    }

    /// Returns true if this is a direct value mapping (no expression).
    #[must_use]
    pub fn is_direct(&self) -> bool {
        self.expression.is_none()
    }

    /// Returns the select list item for this mapping.
    fn to_select_item(&self) -> String {
        match &self.expression {
            Some(expr) => format!("{} AS \"{}\"", expr, self.column_name.replace('"', "\"\"")),
            None => format!("\"{}\"", self.column_name.replace('"', "\"\"")),
        }
    }
}

// =============================================================================
// IntoValue Trait
// =============================================================================

/// Trait for types that can be inserted into a Hyper table.
///
/// This trait is implemented for common Rust types, allowing them to be
/// used with [`Inserter::add_row()`] for type-safe insertion.
///
/// # Supported Types
///
/// - Integers: `i16`, `i32`, `i64`
/// - Floats: `f32`, `f64`
/// - `bool`
/// - `&str`, `String`
/// - `Option<T>` where `T: IntoValue` (for nullable columns)
/// - Date/time types: `Date`, `Time`, `Timestamp`, `Interval`
/// - `Numeric`, `Geography`, `Oid`, `Vec<u8>` (bytes)
///
/// # Example
///
/// ```no_run
/// use hyperdb_api::{Connection, CreateMode, Catalog, TableDefinition, Inserter, IntoValue, SqlType, Result};
///
/// fn main() -> Result<()> {
///     let conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::CreateIfNotExists)?;
///
///     let table_def = TableDefinition::new("example")
///         .add_required_column("a", SqlType::int())
///         .add_nullable_column("b", SqlType::text())
///         .add_nullable_column("c", SqlType::double());
///     Catalog::new(&conn).create_table(&table_def)?;
///
///     let mut inserter = Inserter::new(&conn, &table_def)?;
///
///     // IntoValue allows adding rows with mixed types
///     inserter.add_row(&[&1i32, &"Alice", &Some(3.14f64)])?;
///     inserter.add_row(&[&2i32, &"Bob", &None::<f64>])?; // NULL value
///
///     inserter.execute()?;
///     Ok(())
/// }
/// ```
pub trait IntoValue {
    /// Adds this value to the inserter.
    ///
    /// # Errors
    ///
    /// Implementations call the matching `Inserter::add_*` method and
    /// forward its error — see [`Inserter::add_bool`] for the shared
    /// failure modes (too many columns, NULL into non-nullable, etc).
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()>;
}

// Implementations for basic types

impl IntoValue for bool {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_bool(*self)
    }
}

impl IntoValue for i16 {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_i16(*self)
    }
}

impl IntoValue for i32 {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_i32(*self)
    }
}

impl IntoValue for i64 {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_i64(*self)
    }
}

impl IntoValue for f32 {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_f32(*self)
    }
}

impl IntoValue for f64 {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_f64(*self)
    }
}

impl IntoValue for str {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_str(self)
    }
}

impl IntoValue for String {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_str(self)
    }
}

impl IntoValue for [u8] {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_bytes(self)
    }
}

impl IntoValue for Vec<u8> {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_bytes(self)
    }
}

// Hyper-specific types

impl IntoValue for Date {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_date(*self)
    }
}

impl IntoValue for Time {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_time(*self)
    }
}

impl IntoValue for Timestamp {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_timestamp(*self)
    }
}

impl IntoValue for OffsetTimestamp {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_offset_timestamp(*self)
    }
}

impl IntoValue for Interval {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_interval(*self)
    }
}

impl IntoValue for Numeric {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_numeric(*self)
    }
}

// Option<T> for nullable values
impl<T: IntoValue> IntoValue for Option<T> {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        match self {
            Some(value) => value.add_to_inserter(inserter),
            None => inserter.add_null(),
        }
    }
}

// Reference implementations for primitives

impl IntoValue for &bool {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_bool(**self)
    }
}

impl IntoValue for &i16 {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_i16(**self)
    }
}

impl IntoValue for &i32 {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_i32(**self)
    }
}

impl IntoValue for &i64 {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_i64(**self)
    }
}

impl IntoValue for &f32 {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_f32(**self)
    }
}

impl IntoValue for &f64 {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_f64(**self)
    }
}

impl IntoValue for &String {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_str(self)
    }
}

impl IntoValue for &str {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_str(self)
    }
}

impl IntoValue for &&str {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_str(self)
    }
}

impl IntoValue for &[u8] {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_bytes(self)
    }
}

impl IntoValue for &Date {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_date(**self)
    }
}

impl IntoValue for &Time {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_time(**self)
    }
}

impl IntoValue for &Timestamp {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_timestamp(**self)
    }
}

impl IntoValue for &OffsetTimestamp {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_offset_timestamp(**self)
    }
}

impl IntoValue for &Interval {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_interval(**self)
    }
}

impl IntoValue for &Numeric {
    fn add_to_inserter(&self, inserter: &mut Inserter<'_>) -> Result<()> {
        inserter.add_numeric(**self)
    }
}

// =============================================================================
// MappedInserter
// =============================================================================

/// An inserter that supports SQL expression mappings.
///
/// This inserter uses a staging table to support computed columns via
/// INSERT...SELECT with SQL expressions. It's created by
/// [`Inserter::with_column_mappings`].
#[derive(Debug)]
pub struct MappedInserter<'conn> {
    /// The underlying inserter for the staging table.
    inner: Inserter<'conn>,
    /// The target table name.
    target_table: crate::TableName,
    /// The column mappings.
    mappings: Vec<ColumnMapping>,
    /// The staging table name.
    staging_table: String,
}

impl<'conn> MappedInserter<'conn> {
    /// Creates a new mapped inserter.
    fn new<T>(
        connection: &'conn Connection,
        inserter_def: &TableDefinition,
        target_table: T,
        mappings: &[ColumnMapping],
    ) -> Result<Self>
    where
        T: TryInto<crate::TableName>,
        crate::Error: From<T::Error>,
    {
        let target_table = target_table.try_into()?;

        // Create a unique staging table name
        let staging_table = format!("_hyper_staging_{}", std::process::id());

        // Create the staging table definition (temporary)
        let mut staging_def = inserter_def.clone();
        staging_def.name.clone_from(&staging_table);

        // Create the staging table
        let create_sql = staging_def.to_create_sql(true)?;
        let create_temp = create_sql.replace("CREATE TABLE", "CREATE TEMPORARY TABLE");
        connection.execute_command(&create_temp)?;

        // Create the inner inserter for the staging table
        let inner = Inserter::new(connection, &staging_def)?;

        Ok(MappedInserter {
            inner,
            target_table,
            mappings: mappings.to_vec(),
            staging_table,
        })
    }

    /// Adds a row of values to the inserter.
    ///
    /// The values should correspond to the columns in the inserter definition,
    /// not the target table.
    ///
    /// # Errors
    ///
    /// Forwards the error from [`Inserter::add_row`].
    pub fn add_row(&mut self, values: &[&dyn IntoValue]) -> Result<()> {
        self.inner.add_row(values)
    }

    /// Adds a NULL value.
    ///
    /// # Errors
    ///
    /// Forwards the error from [`Inserter::add_null`].
    pub fn add_null(&mut self) -> Result<()> {
        self.inner.add_null()
    }

    /// Adds a boolean value.
    ///
    /// # Errors
    ///
    /// Forwards the error from [`Inserter::add_bool`].
    pub fn add_bool(&mut self, value: bool) -> Result<()> {
        self.inner.add_bool(value)
    }

    /// Adds an i16 value.
    ///
    /// # Errors
    ///
    /// Forwards the error from [`Inserter::add_i16`].
    pub fn add_i16(&mut self, value: i16) -> Result<()> {
        self.inner.add_i16(value)
    }

    /// Adds an i32 value.
    ///
    /// # Errors
    ///
    /// Forwards the error from [`Inserter::add_i32`].
    pub fn add_i32(&mut self, value: i32) -> Result<()> {
        self.inner.add_i32(value)
    }

    /// Adds an i64 value.
    ///
    /// # Errors
    ///
    /// Forwards the error from [`Inserter::add_i64`].
    pub fn add_i64(&mut self, value: i64) -> Result<()> {
        self.inner.add_i64(value)
    }

    /// Adds an f32 value.
    ///
    /// # Errors
    ///
    /// Forwards the error from [`Inserter::add_f32`].
    pub fn add_f32(&mut self, value: f32) -> Result<()> {
        self.inner.add_f32(value)
    }

    /// Adds an f64 value.
    ///
    /// # Errors
    ///
    /// Forwards the error from [`Inserter::add_f64`].
    pub fn add_f64(&mut self, value: f64) -> Result<()> {
        self.inner.add_f64(value)
    }

    /// Adds a string value.
    ///
    /// # Errors
    ///
    /// Forwards the error from [`Inserter::add_str`].
    pub fn add_str(&mut self, value: &str) -> Result<()> {
        self.inner.add_str(value)
    }

    /// Adds a bytes value.
    ///
    /// # Errors
    ///
    /// Forwards the error from [`Inserter::add_bytes`].
    pub fn add_bytes(&mut self, value: &[u8]) -> Result<()> {
        self.inner.add_bytes(value)
    }

    /// Ends the current row.
    ///
    /// # Errors
    ///
    /// Forwards the error from [`Inserter::end_row`].
    pub fn end_row(&mut self) -> Result<()> {
        self.inner.end_row()
    }

    /// Executes the insert with column mappings.
    ///
    /// This method:
    /// 1. Inserts all buffered rows into the staging table
    /// 2. Executes INSERT...SELECT from staging to target with mappings
    /// 3. Drops the staging table
    ///
    /// Returns the number of rows inserted into the target table.
    ///
    /// # Errors
    ///
    /// - Returns the error from the inner [`Inserter::execute`] if writing
    ///   the staging rows fails.
    /// - Returns [`Error::Client`] if the `INSERT ... SELECT` from staging
    ///   to the target table is rejected (e.g. a mapping expression fails
    ///   to evaluate).
    /// - Returns [`Error::Client`] if dropping the staging table fails.
    pub fn execute(&mut self) -> Result<u64> {
        let connection = self.inner.connection;
        let staging_table = self.staging_table.clone();

        // Insert data into staging table
        let _staging_rows = self.inner.execute()?;

        // Build the INSERT...SELECT statement
        use hyperdb_api_core::protocol::escape::SqlIdentifier;

        let target_columns: Vec<String> = self
            .mappings
            .iter()
            .map(|m| format!("{}", SqlIdentifier(&m.column_name)))
            .collect();

        let select_items: Vec<String> = self
            .mappings
            .iter()
            .map(ColumnMapping::to_select_item)
            .collect();

        let sql = format!(
            "INSERT INTO {} ({}) SELECT {} FROM {}",
            self.target_table,
            target_columns.join(", "),
            select_items.join(", "),
            SqlIdentifier(&staging_table),
        );

        // Execute the INSERT...SELECT (returns row count directly)
        let row_count = connection.execute_command(&sql)?;

        // Drop the staging table
        connection.execute_command(&format!(
            "DROP TABLE IF EXISTS {}",
            SqlIdentifier(&staging_table)
        ))?;

        // Return the number of rows inserted
        Ok(row_count)
    }

    /// Cancels the insert and drops the staging table.
    ///
    /// This method handles cleanup failures gracefully by logging warnings
    /// instead of returning errors. This prevents masking the original error
    /// that caused the cancellation.
    ///
    /// # Logging
    ///
    /// Cleanup failures are logged using the `tracing` crate at WARN level.
    /// If `tracing` is not initialized, errors are written to stderr.
    pub fn cancel(&mut self) {
        let connection = self.inner.connection;
        let staging_table = &self.staging_table;

        // Drop the staging table, but don't fail if cleanup fails
        // This avoids masking the original error that caused cancellation
        if let Err(e) = connection.execute_command(&format!(
            "DROP TABLE IF EXISTS \"{}\"",
            staging_table.replace('"', "\"\"")
        )) {
            // Log the cleanup failure for debugging
            // In production, consider using a logging framework like `tracing`
            eprintln!("Warning: Failed to drop staging table '{staging_table}' during cancel: {e}");
        }
    }
}

// =============================================================================
// InsertChunk - Thread-safe chunk for parallel encoding
// =============================================================================

/// A thread-safe chunk for encoding rows in parallel.
///
/// `InsertChunk` can be created and populated in any thread, then sent to a
/// [`ChunkSender`] for transmission. This enables parallel data encoding across
/// multiple worker threads while serializing the actual network sends.
///
/// # Example
///
/// ```no_run
/// use hyperdb_api::{InsertChunk, TableDefinition, SqlType, Result};
///
/// fn encode_chunk(table_def: &TableDefinition, start_id: i32) -> Result<InsertChunk> {
///     let mut chunk = InsertChunk::from_table_definition(table_def);
///     
///     for i in 0..1000 {
///         chunk.add_i32(start_id + i)?;
///         chunk.add_str(&format!("Item {}", start_id + i))?;
///         chunk.end_row()?;
///     }
///     
///     Ok(chunk)
/// }
/// ```
#[derive(Debug)]
pub struct InsertChunk {
    buffer: BytesMut,
    header_written: bool,
    column_index: usize,
    column_count: usize,
    row_count: usize,
    column_nullable: Vec<bool>,
}

// SAFETY: Every field of `InsertChunk` (`BytesMut`, `bool`, `usize`,
// `Vec<bool>`) is itself `Send`, and none of them hold raw pointers or
// thread-local state. The manual `unsafe impl` exists only because the
// auto-trait derivation is conservative for this struct's compilation context;
// the compound type has no `!Send` components.
unsafe impl Send for InsertChunk {}
// SAFETY: Same reasoning as the `Send` impl above — all fields are `Sync`
// and there is no interior mutability crossing a `&InsertChunk` boundary,
// so sharing `&InsertChunk` across threads is sound.
unsafe impl Sync for InsertChunk {}

impl InsertChunk {
    /// Creates a new empty chunk with the given schema.
    ///
    /// # Arguments
    ///
    /// * `column_count` - Number of columns per row
    /// * `column_nullable` - Whether each column is nullable
    #[must_use]
    pub fn new(column_count: usize, column_nullable: Vec<bool>) -> Self {
        debug_assert_eq!(column_count, column_nullable.len());
        InsertChunk {
            buffer: BytesMut::with_capacity(INITIAL_BUFFER_SIZE),
            header_written: false,
            column_index: 0,
            column_count,
            row_count: 0,
            column_nullable,
        }
    }

    /// Creates a chunk from a table definition.
    #[must_use]
    pub fn from_table_definition(table_def: &TableDefinition) -> Self {
        let column_nullable: Vec<bool> = table_def.columns.iter().map(|c| c.nullable).collect();
        Self::new(table_def.column_count(), column_nullable)
    }

    /// Returns the number of complete rows in this chunk.
    #[must_use]
    pub fn row_count(&self) -> usize {
        self.row_count
    }

    /// Returns the current buffer size in bytes.
    #[must_use]
    pub fn buffer_size(&self) -> usize {
        self.buffer.len()
    }

    /// Returns true if the chunk has reached size or row limits and should be sent.
    #[must_use]
    pub fn should_flush(&self) -> bool {
        self.row_count >= CHUNK_ROW_LIMIT || self.buffer.len() >= CHUNK_SIZE_LIMIT
    }

    /// Returns true if the chunk is empty (no rows).
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.row_count == 0
    }

    /// Takes the buffer, consuming the chunk data.
    ///
    /// Returns `None` if the chunk is empty. After calling this, the chunk
    /// can be reused by calling the add_* methods again.
    ///
    /// Note: The header flag is NOT reset - subsequent chunks from the same
    /// `InsertChunk` will NOT include the header (`HyperBinary` only needs one
    /// header per COPY stream).
    pub fn take(&mut self) -> Option<BytesMut> {
        if self.row_count == 0 {
            return None;
        }
        // Don't reset header_written - only first chunk should have header
        self.row_count = 0;
        Some(std::mem::take(&mut self.buffer))
    }

    /// Resets the chunk for reuse without reallocating.
    pub fn clear(&mut self) {
        self.buffer.clear();
        self.header_written = false;
        self.column_index = 0;
        self.row_count = 0;
    }

    #[allow(
        clippy::inline_always,
        reason = "hot-path numeric kernel; forced inlining measured to matter on this specific function"
    )]
    fn ensure_header(&mut self) {
        if !self.header_written {
            copy::write_header(&mut self.buffer);
            self.header_written = true;
        }
    }

    #[expect(
        clippy::inline_always,
        reason = "hot inner loop of the inserter; measured to matter for per-row throughput"
    )]
    #[inline(always)]
    fn current_column_nullable(&self) -> bool {
        *self.column_nullable.get(self.column_index).unwrap_or(&true)
    }

    /// Adds a NULL value for the current column.
    ///
    /// # Errors
    ///
    /// - Returns [`Error::Other`] with message `"Too many columns in row"`
    ///   if the current row already has all columns supplied.
    /// - Returns [`Error::Other`] with message
    ///   `"Cannot add NULL to non-nullable column"` if the current column
    ///   is `NOT NULL` in the schema.
    pub fn add_null(&mut self) -> Result<()> {
        if self.column_index >= self.column_count {
            return Err(Error::new("Too many columns in row"));
        }
        if !self.current_column_nullable() {
            return Err(Error::new("Cannot add NULL to non-nullable column"));
        }
        self.ensure_header();
        copy::write_null(&mut self.buffer);
        self.column_index += 1;
        Ok(())
    }

    /// Adds a boolean value.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Other`] with message `"Too many columns in row"` if
    /// the current row already has all columns supplied.
    pub fn add_bool(&mut self, value: bool) -> Result<()> {
        if self.column_index >= self.column_count {
            return Err(Error::new("Too many columns in row"));
        }
        self.ensure_header();
        let int_value = i8::from(value);
        if self.current_column_nullable() {
            copy::write_i8(&mut self.buffer, int_value);
        } else {
            copy::write_i8_not_null(&mut self.buffer, int_value);
        }
        self.column_index += 1;
        Ok(())
    }

    /// Adds an i16 value (SMALLINT).
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    pub fn add_i16(&mut self, value: i16) -> Result<()> {
        if self.column_index >= self.column_count {
            return Err(Error::new("Too many columns in row"));
        }
        self.ensure_header();
        if self.current_column_nullable() {
            copy::write_i16(&mut self.buffer, value);
        } else {
            copy::write_i16_not_null(&mut self.buffer, value);
        }
        self.column_index += 1;
        Ok(())
    }

    /// Adds an i32 value (INT).
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    pub fn add_i32(&mut self, value: i32) -> Result<()> {
        if self.column_index >= self.column_count {
            return Err(Error::new("Too many columns in row"));
        }
        self.ensure_header();
        if self.current_column_nullable() {
            copy::write_i32(&mut self.buffer, value);
        } else {
            copy::write_i32_not_null(&mut self.buffer, value);
        }
        self.column_index += 1;
        Ok(())
    }

    /// Adds an i64 value (BIGINT).
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    pub fn add_i64(&mut self, value: i64) -> Result<()> {
        if self.column_index >= self.column_count {
            return Err(Error::new("Too many columns in row"));
        }
        self.ensure_header();
        if self.current_column_nullable() {
            copy::write_i64(&mut self.buffer, value);
        } else {
            copy::write_i64_not_null(&mut self.buffer, value);
        }
        self.column_index += 1;
        Ok(())
    }

    /// Adds an f32 value (REAL/FLOAT4).
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    pub fn add_f32(&mut self, value: f32) -> Result<()> {
        if self.column_index >= self.column_count {
            return Err(Error::new("Too many columns in row"));
        }
        self.ensure_header();
        if self.current_column_nullable() {
            copy::write_f32(&mut self.buffer, value);
        } else {
            copy::write_f32_not_null(&mut self.buffer, value);
        }
        self.column_index += 1;
        Ok(())
    }

    /// Adds an f64 value (DOUBLE PRECISION/FLOAT8).
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    pub fn add_f64(&mut self, value: f64) -> Result<()> {
        if self.column_index >= self.column_count {
            return Err(Error::new("Too many columns in row"));
        }
        self.ensure_header();
        if self.current_column_nullable() {
            copy::write_f64(&mut self.buffer, value);
        } else {
            copy::write_f64_not_null(&mut self.buffer, value);
        }
        self.column_index += 1;
        Ok(())
    }

    /// Adds a string value (TEXT/VARCHAR).
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    pub fn add_str(&mut self, value: &str) -> Result<()> {
        self.add_bytes(value.as_bytes())
    }

    /// Adds a bytes value (BYTEA).
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    pub fn add_bytes(&mut self, value: &[u8]) -> Result<()> {
        if self.column_index >= self.column_count {
            return Err(Error::new("Too many columns in row"));
        }
        if value.len() > u32::MAX as usize {
            return Err(Error::new(format!(
                "Value length {} exceeds HyperBinary 4-byte length limit ({})",
                value.len(),
                u32::MAX
            )));
        }
        self.ensure_header();
        if self.current_column_nullable() {
            copy::write_varbinary(&mut self.buffer, value);
        } else {
            copy::write_varbinary_not_null(&mut self.buffer, value);
        }
        self.column_index += 1;
        Ok(())
    }

    /// Adds a 128-bit value (NUMERIC/INTERVAL).
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    pub fn add_data128(&mut self, value: &[u8; 16]) -> Result<()> {
        if self.column_index >= self.column_count {
            return Err(Error::new("Too many columns in row"));
        }
        self.ensure_header();
        if self.current_column_nullable() {
            copy::write_data128(&mut self.buffer, value);
        } else {
            copy::write_data128_not_null(&mut self.buffer, value);
        }
        self.column_index += 1;
        Ok(())
    }

    /// Adds a Date value.
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    pub fn add_date(&mut self, value: Date) -> Result<()> {
        if self.column_index >= self.column_count {
            return Err(Error::new("Too many columns in row"));
        }
        self.ensure_header();
        let julian_day = value.to_julian_day();
        if self.current_column_nullable() {
            copy::write_i32(&mut self.buffer, julian_day);
        } else {
            copy::write_i32_not_null(&mut self.buffer, julian_day);
        }
        self.column_index += 1;
        Ok(())
    }

    /// Adds a Time value.
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    pub fn add_time(&mut self, value: Time) -> Result<()> {
        if self.column_index >= self.column_count {
            return Err(Error::new("Too many columns in row"));
        }
        self.ensure_header();
        let micros = value.to_microseconds();
        if self.current_column_nullable() {
            copy::write_i64(&mut self.buffer, micros);
        } else {
            copy::write_i64_not_null(&mut self.buffer, micros);
        }
        self.column_index += 1;
        Ok(())
    }

    /// Adds a Timestamp value.
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    pub fn add_timestamp(&mut self, value: Timestamp) -> Result<()> {
        if self.column_index >= self.column_count {
            return Err(Error::new("Too many columns in row"));
        }
        self.ensure_header();
        let micros = value.to_microseconds();
        if self.current_column_nullable() {
            copy::write_i64(&mut self.buffer, micros);
        } else {
            copy::write_i64_not_null(&mut self.buffer, micros);
        }
        self.column_index += 1;
        Ok(())
    }

    /// Adds an `OffsetTimestamp` (TIMESTAMP WITH TIME ZONE) value.
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    pub fn add_offset_timestamp(&mut self, value: OffsetTimestamp) -> Result<()> {
        if self.column_index >= self.column_count {
            return Err(Error::new("Too many columns in row"));
        }
        self.ensure_header();
        let micros = value.to_microseconds_utc();
        if self.current_column_nullable() {
            copy::write_i64(&mut self.buffer, micros);
        } else {
            copy::write_i64_not_null(&mut self.buffer, micros);
        }
        self.column_index += 1;
        Ok(())
    }

    /// Adds an Interval value.
    ///
    /// # Errors
    ///
    /// See [`add_bool`](Self::add_bool).
    pub fn add_interval(&mut self, value: Interval) -> Result<()> {
        if self.column_index >= self.column_count {
            return Err(Error::new("Too many columns in row"));
        }
        self.ensure_header();
        let packed = value.to_packed();
        if self.current_column_nullable() {
            copy::write_data128(&mut self.buffer, &packed);
        } else {
            copy::write_data128_not_null(&mut self.buffer, &packed);
        }
        self.column_index += 1;
        Ok(())
    }

    /// Ends the current row.
    ///
    /// Returns an error if the wrong number of columns were added.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Other`] if fewer (or more) columns were supplied
    /// for this row than the chunk's column count.
    pub fn end_row(&mut self) -> Result<()> {
        if self.column_index != self.column_count {
            return Err(Error::new(format!(
                "Expected {} columns, got {}",
                self.column_count, self.column_index
            )));
        }
        self.column_index = 0;
        self.row_count += 1;
        Ok(())
    }

    /// Returns the current column index (for checking incomplete rows).
    #[must_use]
    pub fn column_index(&self) -> usize {
        self.column_index
    }

    /// Returns a reference to the internal buffer.
    pub(crate) fn buffer(&self) -> &BytesMut {
        &self.buffer
    }
}

// =============================================================================
// ChunkSender - Mutex-protected sender for InsertChunks
// =============================================================================

use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::Mutex;

/// A thread-safe sender for [`InsertChunk`]s.
///
/// `ChunkSender` manages the COPY protocol connection and ensures that only one
/// chunk is sent at a time. Multiple threads can call `send_chunk()` concurrently;
/// the mutex ensures serialized access.
///
/// # Example
///
/// ```no_run
/// use hyperdb_api::{Catalog, Connection, CreateMode, ChunkSender, InsertChunk, TableDefinition, SqlType, Result};
/// use std::sync::mpsc;
/// use std::thread;
///
/// fn main() -> Result<()> {
///     let conn = Connection::connect("localhost:7483", "test.hyper", CreateMode::CreateIfNotExists)?;
///     
///     let table_def = TableDefinition::new("products")
///         .add_required_column("id", SqlType::int())
///         .add_nullable_column("name", SqlType::text());
///     
///     Catalog::new(&conn).create_table(&table_def)?;
///     
///     let sender = ChunkSender::new(&conn, &table_def)?;
///     let (tx, rx) = mpsc::channel::<InsertChunk>();
///     
///     // Worker thread
///     let table_def_clone = table_def.clone();
///     let handle = thread::spawn(move || {
///         let mut chunk = InsertChunk::from_table_definition(&table_def_clone);
///         for i in 0..1000i32 {
///             chunk.add_i32(i).unwrap();
///             chunk.add_str(&format!("Product {}", i)).unwrap();
///             chunk.end_row().unwrap();
///         }
///         tx.send(chunk).unwrap();
///     });
///     
///     // Receive and send chunks
///     while let Ok(chunk) = rx.recv() {
///         sender.send_chunk(chunk)?;
///     }
///     
///     handle.join().unwrap();
///     let rows = sender.finish()?;
///     println!("Inserted {} rows", rows);
///     Ok(())
/// }
/// ```
#[derive(Debug)]
pub struct ChunkSender<'conn> {
    connection: &'conn Connection,
    table_name: String,
    columns: Vec<String>,
    writer: Mutex<Option<CopyInWriter<'conn>>>,
    header_sent: std::sync::atomic::AtomicBool,
    total_rows: AtomicU64,
    chunks_sent: AtomicUsize,
}

impl<'conn> ChunkSender<'conn> {
    /// Creates a new chunk sender for the given table.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidTableDefinition`] if `table_def` has zero
    /// columns. The COPY session itself is opened lazily on the first
    /// [`send_chunk`](Self::send_chunk), so transport errors surface there.
    pub fn new(connection: &'conn Connection, table_def: &TableDefinition) -> Result<Self> {
        if table_def.column_count() == 0 {
            return Err(Error::InvalidTableDefinition(
                "Table definition must have at least one column".into(),
            ));
        }

        let columns: Vec<String> = table_def.columns.iter().map(|c| c.name.clone()).collect();
        let table_name = table_def.qualified_name();

        Ok(ChunkSender {
            connection,
            table_name,
            columns,
            writer: Mutex::new(None),
            header_sent: std::sync::atomic::AtomicBool::new(false),
            total_rows: AtomicU64::new(0),
            chunks_sent: AtomicUsize::new(0),
        })
    }

    /// Sends a chunk to Hyper.
    ///
    /// This method is thread-safe - multiple threads can call it concurrently,
    /// but only one chunk will be sent at a time.
    ///
    /// Each `InsertChunk` includes a `HyperBinary` header (19 bytes). This method
    /// automatically handles headers: the first chunk's header is sent, and
    /// headers in subsequent chunks are stripped (`HyperBinary` expects only one
    /// header per COPY stream).
    ///
    /// # Errors
    ///
    /// Returns an error if the chunk is empty or if sending fails.
    pub fn send_chunk(&self, mut chunk: InsertChunk) -> Result<()> {
        // Capture row count before take() resets it
        let row_count = chunk.row_count();

        let Some(buffer) = chunk.take() else {
            return Ok(());
        };

        // Acquire the lock for exclusive send access
        let mut writer_guard = self
            .writer
            .lock()
            .map_err(|_| Error::new("ChunkSender mutex poisoned"))?;

        // Lazily initialize the COPY connection
        if writer_guard.is_none() {
            let client = self.connection.tcp_client().ok_or_else(|| {
                Error::new("ChunkSender requires a TCP connection. gRPC connections do not support COPY operations.")
            })?;
            let columns: Vec<&str> = self
                .columns
                .iter()
                .map(std::string::String::as_str)
                .collect();
            *writer_guard = Some(client.copy_in(&self.table_name, &columns)?);
        }

        // Handle headers: only first chunk should have header in the COPY stream
        // Each InsertChunk includes a 19-byte HyperBinary header, so we need to
        // strip headers from all chunks except the first one sent.
        let is_first = !self.header_sent.swap(true, Ordering::SeqCst);

        let data_to_send = if is_first {
            // First chunk: send with header
            &buffer[..]
        } else {
            // Subsequent chunks: strip the 19-byte header if present
            if buffer.len() > hyperdb_api_core::protocol::copy::HYPER_BINARY_HEADER_SIZE
                && buffer.starts_with(hyperdb_api_core::protocol::copy::HYPER_BINARY_HEADER)
            {
                &buffer[hyperdb_api_core::protocol::copy::HYPER_BINARY_HEADER_SIZE..]
            } else {
                &buffer[..]
            }
        };

        // Write the chunk directly to the socket, avoiding a full-chunk memcpy
        // into the connection's write buffer. flush_stream ensures the data
        // reaches the server before we return.
        if let Some(ref mut writer) = *writer_guard {
            writer.send_direct(data_to_send)?;
            writer.flush_stream()?;
        }

        // Update counters (lock already released for these atomic ops)
        drop(writer_guard);
        self.total_rows
            .fetch_add(row_count as u64, Ordering::Relaxed);
        self.chunks_sent.fetch_add(1, Ordering::Relaxed);

        debug!(
            target: "hyperdb_api",
            chunk = self.chunks_sent.load(Ordering::Relaxed),
            rows = row_count,
            bytes = data_to_send.len(),
            "chunk-sender"
        );

        Ok(())
    }

    /// Returns the total number of rows sent so far.
    pub fn total_rows(&self) -> u64 {
        self.total_rows.load(Ordering::Relaxed)
    }

    /// Returns the number of chunks sent so far.
    pub fn chunks_sent(&self) -> usize {
        self.chunks_sent.load(Ordering::Relaxed)
    }

    /// Finishes the COPY operation and returns the total row count.
    ///
    /// This method consumes the sender. After calling this, the COPY operation
    /// is complete and all data has been committed.
    ///
    /// # Errors
    ///
    /// - Returns [`Error::Other`] with message `"ChunkSender mutex poisoned"`
    ///   if a sender thread panicked while holding the writer lock.
    /// - Returns [`Error::Client`] or [`Error::Io`] if sending the COPY
    ///   trailer or finishing the COPY operation fails.
    pub fn finish(self) -> Result<u64> {
        let mut writer_guard = self
            .writer
            .lock()
            .map_err(|_| Error::new("ChunkSender mutex poisoned"))?;

        // If no chunks were sent, return 0
        let Some(writer) = writer_guard.take() else {
            return Ok(0);
        };

        // Write and send the COPY trailer
        let mut trailer_buf = BytesMut::with_capacity(2);
        copy::write_trailer(&mut trailer_buf);

        // Need to get mutable access to send trailer
        let mut writer = writer;
        writer.send(&trailer_buf)?;

        // Finish the COPY operation
        let rows = writer.finish()?;

        info!(
            target: "hyperdb_api",
            rows,
            chunks = self.chunks_sent.load(Ordering::Relaxed),
            table = %self.table_name,
            "chunk-sender-finish"
        );

        Ok(rows)
    }
}

#[cfg(test)]
mod tests {
    use crate::table_definition::TableDefinition;
    use hyperdb_api_core::types::SqlType;

    use super::InsertChunk;

    fn create_test_table_def() -> TableDefinition {
        TableDefinition::new("test")
            .add_required_column("id", SqlType::int())
            .add_nullable_column("name", SqlType::text())
    }

    #[test]
    fn test_inserter_column_validation() {
        // We can't fully test without a connection, but we can test validation logic
        let table_def = create_test_table_def();
        assert_eq!(table_def.column_count(), 2);
    }

    #[test]
    fn test_insert_chunk_encoding() {
        let table_def = create_test_table_def();
        let mut chunk = InsertChunk::from_table_definition(&table_def);

        // Add a row
        chunk.add_i32(42).unwrap();
        chunk.add_str("hello").unwrap();
        chunk.end_row().unwrap();

        assert_eq!(chunk.row_count(), 1);
        assert!(!chunk.is_empty());
        assert!(!chunk.should_flush()); // Not at limit yet

        // Add more rows
        for i in 0..100 {
            chunk.add_i32(i).unwrap();
            chunk.add_str(&format!("item {i}")).unwrap();
            chunk.end_row().unwrap();
        }

        assert_eq!(chunk.row_count(), 101);

        // Take the buffer
        let buffer = chunk.take().unwrap();
        assert!(!buffer.is_empty());

        // Chunk should now be empty after take
        assert!(chunk.take().is_none());
    }

    #[test]
    fn test_insert_chunk_null_handling() {
        let table_def = create_test_table_def();
        let mut chunk = InsertChunk::from_table_definition(&table_def);

        // First column is NOT NULL, should fail
        assert!(chunk.add_null().is_err());

        // Add the required column first
        chunk.add_i32(1).unwrap();

        // Second column is nullable, should succeed
        chunk.add_null().unwrap();
        chunk.end_row().unwrap();

        assert_eq!(chunk.row_count(), 1);
    }

    #[test]
    fn test_insert_chunk_column_count_validation() {
        let table_def = create_test_table_def();
        let mut chunk = InsertChunk::from_table_definition(&table_def);

        // Add only one column
        chunk.add_i32(1).unwrap();

        // end_row should fail
        assert!(chunk.end_row().is_err());

        // Add second column
        chunk.add_str("test").unwrap();

        // Now end_row should succeed
        chunk.end_row().unwrap();
    }

    #[test]
    fn test_insert_chunk_too_many_columns() {
        let table_def = create_test_table_def();
        let mut chunk = InsertChunk::from_table_definition(&table_def);

        chunk.add_i32(1).unwrap();
        chunk.add_str("test").unwrap();

        // Third column should fail
        assert!(chunk.add_i32(2).is_err());
    }

    #[test]
    fn test_insert_chunk_clear() {
        let table_def = create_test_table_def();
        let mut chunk = InsertChunk::from_table_definition(&table_def);

        chunk.add_i32(1).unwrap();
        chunk.add_str("test").unwrap();
        chunk.end_row().unwrap();

        assert_eq!(chunk.row_count(), 1);

        chunk.clear();

        assert_eq!(chunk.row_count(), 0);
        assert!(chunk.is_empty());
    }
}