tiberius 0.13.0

A TDS (MSSQL) driver
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
pub(crate) mod auth;
mod config;
mod connection;

mod tls;
#[cfg(any(
    feature = "rustls",
    feature = "native-tls",
    feature = "vendored-openssl"
))]
mod tls_stream;

pub use auth::*;
pub use config::*;
pub(crate) use connection::*;

use crate::bulk_options::{ColumnOrderHint, SortOrder, SqlBulkCopyOption, SqlBulkCopyOptions};
use crate::tds::codec::RpcValue;
use crate::tds::stream::ReceivedToken;
use crate::{
    result::ExecuteResult,
    tds::{
        codec::{self, IteratorJoin},
        stream::{QueryStream, TokenStream},
    },
    BulkLoadRequest, MetaDataColumn, SqlReadBytes, ToSql,
};
use codec::{
    BatchRequest, ColumnData, IsolationLevel, PacketHeader, RpcParam, RpcProcId, TokenRpcRequest,
    TransactionManagerRequest,
};
use enumflags2::BitFlags;
use futures_util::io::{AsyncRead, AsyncWrite};
use futures_util::stream::TryStreamExt;
use std::{borrow::Cow, fmt::Debug};

/// `Client` is the main entry point to the SQL Server, providing query
/// execution capabilities.
///
/// A `Client` is created using the [`Config`], defining the needed
/// connection options and capabilities.
///
/// # Example
///
/// ```no_run
/// # use tiberius::{Config, AuthMethod};
/// use tokio_util::compat::TokioAsyncWriteCompatExt;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut config = Config::new();
///
/// config.host("0.0.0.0");
/// config.port(1433);
/// config.authentication(AuthMethod::sql_server("SA", "<Mys3cureP4ssW0rD>"));
///
/// let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;
/// tcp.set_nodelay(true)?;
/// // Client is ready to use.
/// let client = tiberius::Client::connect(config, tcp.compat_write()).await?;
/// # Ok(())
/// # }
/// ```
///
/// # Cancellation safety
///
/// A single [`Client`] drives one connection and one request at a time. If a
/// `query`/`execute`/`simple_query` future — or the result stream it returns —
/// is dropped before the request has been sent in full and the response fully
/// consumed (for example under a `tokio::time::timeout` or a `select!` branch
/// that loses the race), the connection may be left mid-message and out of sync
/// with the server. A cancelled *write* is detected and any further use of that
/// connection fails cleanly; a result stream dropped mid-response cannot be
/// recovered. In both cases the safe course is to drop the `Client` and open a
/// new connection (a connection pool should discard the connection on error)
/// rather than reuse it.
///
/// [`Config`]: struct.Config.html
#[derive(Debug)]
pub struct Client<S: AsyncRead + AsyncWrite + Unpin + Send> {
    pub(crate) connection: Connection<S>,
}

impl<S: AsyncRead + AsyncWrite + Unpin + Send> Client<S> {
    /// Uses an instance of [`Config`] to specify the connection
    /// options required to connect to the database using an established
    /// tcp connection
    ///
    /// Note: `tcp_stream` is a connected stream, so some parts of the `Config`
    /// (such as multi-subnet failover, which selects between resolved
    /// addresses) must be handled while establishing that stream, outside of
    /// this constructor.
    ///
    /// [`Config`]: struct.Config.html
    pub async fn connect(config: Config, tcp_stream: S) -> crate::Result<Client<S>> {
        Ok(Client {
            connection: Connection::connect(config, tcp_stream).await?,
        })
    }

    /// Executes SQL statements in the SQL Server, returning the number rows
    /// affected. Useful for `INSERT`, `UPDATE` and `DELETE` statements. The
    /// `query` can define the parameter placement by annotating them with
    /// `@PN`, where N is the index of the parameter, starting from `1`. If
    /// executing multiple queries at a time, delimit them with `;` and refer to
    /// [`ExecuteResult`] how to get results for the separate queries.
    ///
    /// For mapping of Rust types when writing, see the documentation for
    /// [`ToSql`]. For reading data from the database, see the documentation for
    /// [`FromSql`].
    ///
    /// This API is not quite suitable for dynamic query parameters. In these
    /// cases using a [`Query`] object might be easier.
    ///
    /// # Errors
    ///
    /// Returns an error if the statement cannot be sent, if the server reports
    /// an error while executing it, or if the connection fails during the
    /// request.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use tiberius::Config;
    /// # use tokio_util::compat::TokioAsyncWriteCompatExt;
    /// # use std::env;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let c_str = env::var("TIBERIUS_TEST_CONNECTION_STRING").unwrap_or(
    /// #     "server=tcp:localhost,1433;integratedSecurity=true;TrustServerCertificate=true".to_owned(),
    /// # );
    /// # let config = Config::from_ado_string(&c_str)?;
    /// # let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;
    /// # tcp.set_nodelay(true)?;
    /// # let mut client = tiberius::Client::connect(config, tcp.compat_write()).await?;
    /// let results = client
    ///     .execute(
    ///         "INSERT INTO ##Test (id) VALUES (@P1), (@P2), (@P3)",
    ///         &[&1i32, &2i32, &3i32],
    ///     )
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`ExecuteResult`]: struct.ExecuteResult.html
    /// [`ToSql`]: trait.ToSql.html
    /// [`FromSql`]: trait.FromSql.html
    /// [`Query`]: struct.Query.html
    pub async fn execute<'a>(
        &mut self,
        query: impl Into<Cow<'a, str>>,
        params: &[&dyn ToSql],
    ) -> crate::Result<ExecuteResult> {
        self.connection.flush_stream().await?;
        let rpc_params = Self::rpc_params(query);

        let params = params.iter().map(|s| s.to_sql());
        self.rpc_perform_query(RpcProcId::ExecuteSQL, rpc_params, params)
            .await?;

        ExecuteResult::new(&mut self.connection).await
    }

    /// Executes SQL statements in the SQL Server, returning resulting rows.
    /// Useful for `SELECT` statements. The `query` can define the parameter
    /// placement by annotating them with `@PN`, where N is the index of the
    /// parameter, starting from `1`. If executing multiple queries at a time,
    /// delimit them with `;` and refer to [`QueryStream`] on proper stream
    /// handling.
    ///
    /// For mapping of Rust types when writing, see the documentation for
    /// [`ToSql`]. For reading data from the database, see the documentation for
    /// [`FromSql`].
    ///
    /// This API can be cumbersome for dynamic query parameters. In these cases,
    /// if fighting too much with the compiler, using a [`Query`] object might be
    /// easier.
    ///
    /// # Errors
    ///
    /// Returns an error if the statement cannot be sent, if the server reports
    /// an error while executing it, or if the connection fails during the
    /// request. Note that per-statement server errors may instead surface while
    /// consuming the returned [`QueryStream`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use tiberius::Config;
    /// # use tokio_util::compat::TokioAsyncWriteCompatExt;
    /// # use std::env;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let c_str = env::var("TIBERIUS_TEST_CONNECTION_STRING").unwrap_or(
    /// #     "server=tcp:localhost,1433;integratedSecurity=true;TrustServerCertificate=true".to_owned(),
    /// # );
    /// # let config = Config::from_ado_string(&c_str)?;
    /// # let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;
    /// # tcp.set_nodelay(true)?;
    /// # let mut client = tiberius::Client::connect(config, tcp.compat_write()).await?;
    /// let stream = client
    ///     .query(
    ///         "SELECT @P1, @P2, @P3",
    ///         &[&1i32, &2i32, &3i32],
    ///     )
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`QueryStream`]: struct.QueryStream.html
    /// [`Query`]: struct.Query.html
    /// [`ToSql`]: trait.ToSql.html
    /// [`FromSql`]: trait.FromSql.html
    pub async fn query<'a, 'b>(
        &'a mut self,
        query: impl Into<Cow<'b, str>>,
        params: &'b [&'b dyn ToSql],
    ) -> crate::Result<QueryStream<'a>>
    where
        'a: 'b,
    {
        self.connection.flush_stream().await?;
        let rpc_params = Self::rpc_params(query);

        let params = params.iter().map(|p| p.to_sql());
        self.rpc_perform_query(RpcProcId::ExecuteSQL, rpc_params, params)
            .await?;

        let ts = TokenStream::new(&mut self.connection);
        let mut result = QueryStream::new(ts.try_unfold());
        result.forward_to_metadata().await?;

        Ok(result)
    }

    /// Execute multiple queries, delimited with `;` and return multiple result
    /// sets; one for each query.
    ///
    /// # Errors
    ///
    /// Returns an error if the batch cannot be sent, if the server reports an
    /// error while executing it, or if the connection fails during the request.
    /// Per-statement server errors may instead surface while consuming the
    /// returned [`QueryStream`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use tiberius::Config;
    /// # use tokio_util::compat::TokioAsyncWriteCompatExt;
    /// # use std::env;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let c_str = env::var("TIBERIUS_TEST_CONNECTION_STRING").unwrap_or(
    /// #     "server=tcp:localhost,1433;integratedSecurity=true;TrustServerCertificate=true".to_owned(),
    /// # );
    /// # let config = Config::from_ado_string(&c_str)?;
    /// # let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;
    /// # tcp.set_nodelay(true)?;
    /// # let mut client = tiberius::Client::connect(config, tcp.compat_write()).await?;
    /// let row = client.simple_query("SELECT 1 AS col").await?.into_row().await?.unwrap();
    /// assert_eq!(Some(1i32), row.get("col"));
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Warning
    ///
    /// Do not use this with any user specified input. Please resort to prepared
    /// statements using the [`query`] method.
    ///
    /// [`query`]: #method.query
    pub async fn simple_query<'a, 'b>(
        &'a mut self,
        query: impl Into<Cow<'b, str>>,
    ) -> crate::Result<QueryStream<'a>>
    where
        'a: 'b,
    {
        self.connection.flush_stream().await?;

        let req = BatchRequest::new(query, self.connection.context().transaction_descriptor());

        let id = self.connection.context_mut().next_packet_id();
        self.connection.send(PacketHeader::batch(id), req).await?;

        let ts = TokenStream::new(&mut self.connection);

        let mut result = QueryStream::new(ts.try_unfold());
        result.forward_to_metadata().await?;

        Ok(result)
    }

    /// Execute a `BULK INSERT` statement, efficiently storing a large number of
    /// rows to a specified table. Note: make sure the input row follows the same
    /// schema as the table, otherwise calling `send()` will return an error.
    ///
    /// This is equivalent to `bulk_insert_columns(table, &["*"])`, inserting into
    /// all of a table's columns.
    ///
    /// # Security
    ///
    /// `table` is interpolated **directly** into the SQL batch sent to the
    /// server. SQL Server does not allow table (or column) identifiers to be
    /// supplied as bound parameters, so this value cannot be parameterized — it
    /// becomes part of the SQL text verbatim. The caller MUST therefore pass a
    /// **trusted, hard-coded or otherwise validated** identifier and MUST NOT
    /// pass untrusted or user-supplied input, which would open a SQL injection
    /// vector. As cheap defense-in-depth this method rejects obviously-malformed
    /// identifiers (NUL/ASCII control characters or an unbalanced `]` bracket),
    /// but that guard is not a substitute for passing trusted input.
    ///
    /// # Errors
    ///
    /// Returns an error if `table` is a malformed identifier, if the column
    /// metadata query fails, or if the server rejects the `INSERT BULK`
    /// statement. Row-level failures surface later from [`send`] and
    /// [`finalize`] on the returned request.
    ///
    /// [`send`]: BulkLoadRequest::send
    /// [`finalize`]: BulkLoadRequest::finalize
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use tiberius::{Config, IntoRow};
    /// # use tokio_util::compat::TokioAsyncWriteCompatExt;
    /// # use std::env;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let c_str = env::var("TIBERIUS_TEST_CONNECTION_STRING").unwrap_or(
    /// #     "server=tcp:localhost,1433;integratedSecurity=true;TrustServerCertificate=true".to_owned(),
    /// # );
    /// # let config = Config::from_ado_string(&c_str)?;
    /// # let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;
    /// # tcp.set_nodelay(true)?;
    /// # let mut client = tiberius::Client::connect(config, tcp.compat_write()).await?;
    /// let create_table = r#"
    ///     CREATE TABLE ##bulk_test (
    ///         id INT IDENTITY PRIMARY KEY,
    ///         val INT NOT NULL
    ///     )
    /// "#;
    ///
    /// client.simple_query(create_table).await?;
    ///
    /// // Start the bulk insert with the client.
    /// let mut req = client.bulk_insert("##bulk_test").await?;
    ///
    /// for i in [0i32, 1i32, 2i32] {
    ///     let row = (i).into_row();
    ///
    ///     // The request will handle flushing to the wire in an optimal way,
    ///     // balancing between memory usage and IO performance.
    ///     req.send(row).await?;
    /// }
    ///
    /// // The request must be finalized.
    /// let res = req.finalize().await?;
    /// assert_eq!(3, res.total());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn bulk_insert<'a>(
        &'a mut self,
        table: &'a str,
    ) -> crate::Result<BulkLoadRequest<'a, S>> {
        self.bulk_insert_columns(table, &["*"]).await
    }

    /// Execute a `BULK INSERT` statement, efficiently storing a large number of
    /// rows to a specified table. Note: make sure the input row follows the same
    /// schema as the column list, otherwise calling `send()` will return an error.
    ///
    /// # Security
    ///
    /// Both `table` and the entries of `columns` are interpolated **directly**
    /// into the SQL batches sent to the server (the `SELECT` used to fetch
    /// column metadata and the `INSERT BULK` statement). SQL Server does not
    /// allow identifiers to be supplied as bound parameters, so these values
    /// cannot be parameterized — they become part of the SQL text verbatim. The
    /// caller MUST therefore pass **trusted, hard-coded or otherwise validated**
    /// identifiers and MUST NOT pass untrusted or user-supplied input, which
    /// would open a SQL injection vector. As cheap defense-in-depth this method
    /// rejects an obviously-malformed `table` (NUL/ASCII control characters or an
    /// unbalanced `]` bracket), but that guard is not a substitute for passing
    /// trusted input.
    ///
    /// # Errors
    ///
    /// Returns an error if `table` is a malformed identifier, if the column
    /// metadata query fails, or if the server rejects the `INSERT BULK`
    /// statement. Row-level failures surface later from [`send`] and
    /// [`finalize`] on the returned request.
    ///
    /// [`send`]: BulkLoadRequest::send
    /// [`finalize`]: BulkLoadRequest::finalize
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use tiberius::{Config, IntoRow};
    /// # use tokio_util::compat::TokioAsyncWriteCompatExt;
    /// # use std::env;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let c_str = env::var("TIBERIUS_TEST_CONNECTION_STRING").unwrap_or(
    /// #     "server=tcp:localhost,1433;integratedSecurity=true;TrustServerCertificate=true".to_owned(),
    /// # );
    /// # let config = Config::from_ado_string(&c_str)?;
    /// # let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;
    /// # tcp.set_nodelay(true)?;
    /// # let mut client = tiberius::Client::connect(config, tcp.compat_write()).await?;
    /// let create_table = r#"
    ///     CREATE TABLE ##bulk_test_columns (
    ///         id INT IDENTITY PRIMARY KEY,
    ///         foo INT NOT NULL,
    ///         bar FLOAT NOT NULL
    ///     )
    /// "#;
    ///
    /// client.simple_query(create_table).await?;
    ///
    /// // Start the bulk insert with the client.
    /// let mut req = client.bulk_insert_columns("##bulk_test_columns", &["foo", "bar"]).await?;
    ///
    /// for (i, j) in [(0i32, 0f64), (1i32, 1f64), (2i32, 2f64)] {
    ///     let row = (i, j).into_row();
    ///
    ///     // The request will handle flushing to the wire in an optimal way,
    ///     // balancing between memory usage and IO performance.
    ///     req.send(row).await?;
    /// }
    ///
    /// // The request must be finalized.
    /// let res = req.finalize().await?;
    /// assert_eq!(3, res.total());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn bulk_insert_columns<'a>(
        &'a mut self,
        table: &'a str,
        columns: &'a [&'a str],
    ) -> crate::Result<BulkLoadRequest<'a, S>> {
        self.bulk_insert_with_options(table, columns, SqlBulkCopyOptions::empty(), &[])
            .await
    }

    /// Execute a `BULK INSERT` statement like [`bulk_insert_columns`], with
    /// additional control over the emitted `WITH (...)` clause.
    ///
    /// `options` is a set of [`SqlBulkCopyOption`] flags (combine them with `|`,
    /// or pass [`SqlBulkCopyOptions::empty`] for none), and `order_hints`
    /// declares the sort order the incoming rows are already in via an
    /// `ORDER (...)` clause. Pass `&["*"]` as `columns` to target every column,
    /// exactly like [`bulk_insert`] does internally.
    ///
    /// When `options` is empty and `order_hints` is empty this emits the exact
    /// same statement as [`bulk_insert_columns`] (no `WITH` clause).
    ///
    /// # Security
    ///
    /// `table`, every entry of `columns`, and every order-hint column name are
    /// interpolated **directly** into the SQL batches sent to the server (T-SQL
    /// does not allow identifiers to be parameterized). The caller MUST pass
    /// **trusted, hard-coded or otherwise validated** identifiers and MUST NOT
    /// pass untrusted or user-supplied input. As cheap defense-in-depth this
    /// method rejects obviously-malformed identifiers — NUL/ASCII control
    /// characters, an unbalanced `]` bracket, a top-level space, statement-
    /// breaking punctuation (`;`, quotes, `-`, etc.) and tokens spliced onto a
    /// closing `]`/`)` — for the table, columns *and* order-hint columns, but
    /// that guard is not a substitute for passing trusted input.
    ///
    /// # Errors
    ///
    /// Returns an error if `table`, a column, or an order-hint column is a
    /// malformed identifier, if the column metadata query fails, or if the
    /// server rejects the `INSERT BULK` statement. Row-level failures surface
    /// later from [`send`] and [`finalize`] on the returned request.
    ///
    /// [`bulk_insert`]: #method.bulk_insert
    /// [`bulk_insert_columns`]: #method.bulk_insert_columns
    /// [`send`]: BulkLoadRequest::send
    /// [`finalize`]: BulkLoadRequest::finalize
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use tiberius::{Config, IntoRow, SqlBulkCopyOption, SortOrder};
    /// # use tokio_util::compat::TokioAsyncWriteCompatExt;
    /// # use std::env;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let c_str = env::var("TIBERIUS_TEST_CONNECTION_STRING").unwrap_or(
    /// #     "server=tcp:localhost,1433;integratedSecurity=true;TrustServerCertificate=true".to_owned(),
    /// # );
    /// # let config = Config::from_ado_string(&c_str)?;
    /// # let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;
    /// # tcp.set_nodelay(true)?;
    /// # let mut client = tiberius::Client::connect(config, tcp.compat_write()).await?;
    /// let mut req = client
    ///     .bulk_insert_with_options(
    ///         "##bulk_test",
    ///         &["id", "val"],
    ///         SqlBulkCopyOption::KeepIdentity | SqlBulkCopyOption::TableLock,
    ///         &[("id", SortOrder::Ascending)],
    ///     )
    ///     .await?;
    ///
    /// for i in [0i32, 1i32, 2i32] {
    ///     req.send((i, i).into_row()).await?;
    /// }
    ///
    /// let res = req.finalize().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn bulk_insert_with_options<'a>(
        &'a mut self,
        table: &'a str,
        columns: &'a [&'a str],
        options: SqlBulkCopyOptions,
        order_hints: &'a [ColumnOrderHint<'a>],
    ) -> crate::Result<BulkLoadRequest<'a, S>> {
        // `table` is interpolated directly into the SQL batch (identifiers cannot
        // be parameterized in T-SQL). Reject obviously-malformed/dangerous input
        // as cheap defense-in-depth; see the `# Security` note above.
        validate_bulk_table_identifier(table)?;

        // Each `columns` entry is likewise interpolated directly into the SQL
        // (both the metadata `SELECT` and the `INSERT BULK` column list), so it
        // gets the same cheap defense-in-depth guard as `table`.
        for column in columns {
            validate_bulk_column_identifier(column)?;
        }

        // Order-hint column names are interpolated into the `ORDER (...)` clause,
        // so they get the exact same guard (and, below, the same bracket
        // escaping) as the regular column list.
        for &(column, _) in order_hints {
            validate_bulk_column_identifier(column)?;
        }

        // Retrieve column metadata from the server, keeping only the updateable
        // columns as bulk targets (read-only/computed columns are skipped).
        //
        // Identity columns are normally read-only (so filtered out, letting the
        // server assign values), but `KEEP_IDENTITY` is implemented — exactly as
        // ADO.NET's `SqlBulkCopy` does — by *including* the identity column in
        // the bulk column list so the caller supplies explicit values; there is
        // no `KEEP_IDENTITY` keyword in the `INSERT BULK` `WITH (...)` grammar.
        // So when the flag is set, identity columns are additionally retained.
        let keep_identity = options.contains(SqlBulkCopyOption::KeepIdentity);
        let mut columns: Vec<_> = self
            .column_metadata(table, columns)
            .await?
            .into_iter()
            .filter(|column| bulk_column_is_target(&column.base, keep_identity))
            .collect();

        // `text`/`ntext`/`image` columns must carry the destination TableName in
        // the COLMETADATA we emit for the bulk load (MS-TDS §2.2.7.4). Record the
        // target table on every column; the encoder only emits it for those
        // types, so this is a no-op on the wire for all other columns.
        for column in columns.iter_mut() {
            column.base.table_name = Some(table.to_string());
        }

        // now start bulk upload
        self.connection.flush_stream().await?;
        let col_data = columns.iter().map(|c| format!("{}", c)).join(", ");
        let query = build_insert_bulk_sql(table, &col_data, options, order_hints);

        let req = BatchRequest::new(query, self.connection.context().transaction_descriptor());
        let id = self.connection.context_mut().next_packet_id();

        self.connection.send(PacketHeader::batch(id), req).await?;

        let ts = TokenStream::new(&mut self.connection);
        ts.flush_done().await?;

        BulkLoadRequest::new(&mut self.connection, columns)
    }

    /// Retrieve the column metadata for a set of columns of a table, including
    /// the column names, types (with their size, precision and scale) and flags
    /// such as nullability and whether a column is an identity column.
    ///
    /// Pass `&["*"]` as `columns` to return the metadata for every column of the
    /// table.
    ///
    /// # Security
    ///
    /// Both `table` and the entries of `columns` are interpolated **directly**
    /// into the SQL batch sent to the server (`SELECT TOP 0 {columns} FROM
    /// {table}`). SQL Server does not allow identifiers to be supplied as bound
    /// parameters, so these values cannot be parameterized — they become part of
    /// the SQL text verbatim. The caller MUST therefore pass **trusted,
    /// hard-coded or otherwise validated** identifiers and MUST NOT pass
    /// untrusted or user-supplied input, which would open a SQL injection
    /// vector. As cheap defense-in-depth this method rejects obviously-malformed
    /// identifiers (NUL/ASCII control characters or an unbalanced `]` bracket),
    /// but that guard is not a substitute for passing trusted input.
    ///
    /// # Errors
    ///
    /// Returns an error if `table` is a malformed identifier, if the metadata
    /// `SELECT` fails, or if the server reports an error while executing it.
    ///
    /// ```no_run
    /// # use tiberius::Config;
    /// # use tokio_util::compat::TokioAsyncWriteCompatExt;
    /// # use std::env;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let c_str = env::var("TIBERIUS_TEST_CONNECTION_STRING").unwrap_or(
    /// #     "server=tcp:localhost,1433;integratedSecurity=true;TrustServerCertificate=true".to_owned(),
    /// # );
    /// # let config = Config::from_ado_string(&c_str)?;
    /// # let tcp = tokio::net::TcpStream::connect(config.get_addr()).await?;
    /// # tcp.set_nodelay(true)?;
    /// # let mut client = tiberius::Client::connect(config, tcp.compat_write()).await?;
    /// let meta = client.column_metadata("some_table", &["*"]).await?;
    /// assert!(meta[0].base().is_identity());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn column_metadata(
        &mut self,
        table: &str,
        columns: &[&str],
    ) -> crate::Result<Vec<MetaDataColumn<'static>>> {
        // `table` and each `column` are interpolated directly into the SQL
        // batch below (identifiers cannot be parameterized in T-SQL). Reject
        // obviously-malformed/dangerous input as cheap defense-in-depth; see the
        // `# Security` note above.
        validate_bulk_table_identifier(table)?;
        for column in columns {
            validate_bulk_column_identifier(column)?;
        }

        self.connection.flush_stream().await?;

        // Ask the server for the column layout without returning any rows.
        let columns = columns.join(", ");
        let query = format!("SELECT TOP 0 {columns} FROM {table}");

        let req = BatchRequest::new(query, self.connection.context().transaction_descriptor());
        let id = self.connection.context_mut().next_packet_id();
        self.connection.send(PacketHeader::batch(id), req).await?;

        let token_stream = TokenStream::new(&mut self.connection).try_unfold();

        let columns = token_stream
            .try_fold(None, |mut columns, token| async move {
                if let ReceivedToken::NewResultset(metadata) = token {
                    columns = Some(metadata.columns.clone());
                };

                Ok(columns)
            })
            .await?;

        let columns = columns.ok_or_else(|| {
            crate::Error::Protocol("expecting column metadata from query but not found".into())
        })?;

        // Own the column names so the returned metadata is not tied to the
        // lifetime of the token stream.
        Ok(columns
            .into_iter()
            .map(|c| MetaDataColumn {
                base: c.base,
                col_name: std::borrow::Cow::Owned(c.col_name.into_owned()),
            })
            .collect())
    }

    /// Sends a TDS Attention signal to the server (packet type `0x06`,
    /// MS-TDS section 2.2.1.6) to cancel the request that is currently in
    /// flight on this connection, and drains the acknowledging token stream so
    /// the connection can be reused for further queries.
    ///
    /// The server responds to the Attention signal by aborting the running
    /// batch or RPC and returning a `DONE` token with the `DONE_ATTN` status
    /// bit set. This method waits for that acknowledgement before returning,
    /// discarding any remaining rows or tokens from the cancelled request.
    ///
    /// # Query cancellation and futures
    ///
    /// Dropping a [`query`], [`execute`] or [`simple_query`] future (for
    /// example when a `tokio::time::timeout` elapses or a `select!` branch is
    /// cancelled) stops the client from polling the stream, but it does *not*
    /// tell the server to stop working on the request. To actually cancel the
    /// in-flight work on the server, keep the [`Client`] and call
    /// `cancel_query` on it. Because `cancel_query` borrows the client
    /// mutably, it can only be issued once the borrowing result stream has
    /// been dropped — typically from a separate task holding the client, or
    /// after a cancelled/timed-out future has released its borrow.
    ///
    /// [`query`]: #method.query
    /// [`execute`]: #method.execute
    /// [`simple_query`]: #method.simple_query
    pub async fn cancel_query(&mut self) -> crate::Result<()> {
        self.connection.cancel_request().await?;
        Ok(())
    }

    /// Closes this database connection explicitly.
    pub async fn close(self) -> crate::Result<()> {
        self.connection.close().await
    }

    /// Begins a new transaction using a Transaction Manager request
    /// (`TM_BEGIN_XACT`, MS-TDS 2.2.6.8) instead of a `BEGIN TRAN` T-SQL
    /// batch.
    ///
    /// On success the server replies with a `BeginTransaction` environment
    /// change token whose descriptor is stored in the connection context and
    /// automatically attached to subsequent requests, scoping them to the
    /// transaction. Commit the work with [`commit_transaction`] or discard it
    /// with [`rollback_transaction`].
    ///
    /// The transaction uses the server's default isolation level. Use
    /// [`begin_transaction_with_isolation`] to request a specific one.
    ///
    /// [`commit_transaction`]: #method.commit_transaction
    /// [`rollback_transaction`]: #method.rollback_transaction
    /// [`begin_transaction_with_isolation`]: #method.begin_transaction_with_isolation
    pub async fn begin_transaction(&mut self) -> crate::Result<()> {
        self.begin_transaction_with_isolation(IsolationLevel::Unspecified)
            .await
    }

    /// Begins a new transaction with an explicit isolation level using a
    /// Transaction Manager request (`TM_BEGIN_XACT`, MS-TDS 2.2.6.8).
    ///
    /// See [`begin_transaction`] for details on transaction scoping.
    ///
    /// [`begin_transaction`]: #method.begin_transaction
    pub async fn begin_transaction_with_isolation(
        &mut self,
        isolation_level: IsolationLevel,
    ) -> crate::Result<()> {
        let req = TransactionManagerRequest::begin(
            self.connection.context().transaction_descriptor(),
            isolation_level,
            "",
        );

        self.send_transaction_manager_request(req).await
    }

    /// Commits the active transaction using a Transaction Manager request
    /// (`TM_COMMIT_XACT`, MS-TDS 2.2.6.8).
    ///
    /// After a successful commit the connection is no longer scoped to a
    /// transaction.
    pub async fn commit_transaction(&mut self) -> crate::Result<()> {
        let req = TransactionManagerRequest::commit(
            self.connection.context().transaction_descriptor(),
            "",
        );

        self.send_transaction_manager_request(req).await
    }

    /// Rolls back the active transaction using a Transaction Manager request
    /// (`TM_ROLLBACK_XACT`, MS-TDS 2.2.6.8).
    ///
    /// After a successful rollback the connection is no longer scoped to a
    /// transaction.
    pub async fn rollback_transaction(&mut self) -> crate::Result<()> {
        let req = TransactionManagerRequest::rollback(
            self.connection.context().transaction_descriptor(),
            "",
        );

        self.send_transaction_manager_request(req).await
    }

    /// Creates a named savepoint in the active transaction using a Transaction
    /// Manager request (`TM_SAVE_XACT`, MS-TDS 2.2.6.8).
    ///
    /// The savepoint can later be targeted by a T-SQL `ROLLBACK TRANSACTION
    /// <name>` to undo work performed after it while keeping the surrounding
    /// transaction open.
    pub async fn save_transaction<'a>(
        &mut self,
        name: impl Into<Cow<'a, str>>,
    ) -> crate::Result<()> {
        let req = TransactionManagerRequest::save(
            self.connection.context().transaction_descriptor(),
            name,
        );

        self.send_transaction_manager_request(req).await
    }

    async fn send_transaction_manager_request(
        &mut self,
        req: TransactionManagerRequest<'_>,
    ) -> crate::Result<()> {
        self.connection.flush_stream().await?;

        let id = self.connection.context_mut().next_packet_id();
        self.connection
            .send(PacketHeader::transaction_manager(id), req)
            .await?;

        // The server responds with a DONE token (plus an ENVCHANGE token that
        // the token stream applies to the connection context, updating the
        // active transaction descriptor).
        TokenStream::new(&mut self.connection).flush_done().await?;

        Ok(())
    }

    pub(crate) fn rpc_params<'a>(query: impl Into<Cow<'a, str>>) -> Vec<RpcParam<'a>> {
        vec![
            RpcParam {
                name: Cow::Borrowed("stmt"),
                flags: BitFlags::empty(),
                value: RpcValue::Scalar(ColumnData::String(Some(query.into()))),
            },
            RpcParam {
                name: Cow::Borrowed("params"),
                flags: BitFlags::empty(),
                value: RpcValue::Scalar(ColumnData::I32(Some(0))),
            },
        ]
    }

    pub(crate) async fn rpc_perform_query<'a, 'b>(
        &'a mut self,
        proc_id: RpcProcId,
        mut rpc_params: Vec<RpcParam<'b>>,
        params: impl Iterator<Item = ColumnData<'b>>,
    ) -> crate::Result<()>
    where
        'a: 'b,
    {
        let mut param_str = String::new();

        for (i, param) in params.enumerate() {
            if i > 0 {
                param_str.push(',')
            }
            param_str.push_str(&format!("@P{} ", i + 1));
            param_str.push_str(&param.type_name());

            rpc_params.push(RpcParam {
                name: Cow::Owned(format!("@P{}", i + 1)),
                flags: BitFlags::empty(),
                value: RpcValue::Scalar(param),
            });
        }

        if let Some(params) = rpc_params.iter_mut().find(|x| x.name == "params") {
            params.value = RpcValue::Scalar(ColumnData::String(Some(param_str.into())));
        }

        let req = TokenRpcRequest::new(
            proc_id,
            rpc_params,
            self.connection.context().transaction_descriptor(),
        );

        let id = self.connection.context_mut().next_packet_id();
        self.connection.send(PacketHeader::rpc(id), req).await?;

        Ok(())
    }

    /// Sends a named-procedure RPC request with the given parameters. The caller
    /// is responsible for flushing the connection beforehand and for consuming
    /// the resulting token stream.
    pub(crate) async fn rpc_run_command<'a, 'b>(
        &'a mut self,
        command_name: Cow<'b, str>,
        rpc_params: Vec<RpcParam<'b>>,
    ) -> crate::Result<()>
    where
        'a: 'b,
    {
        let req = TokenRpcRequest::new(
            command_name,
            rpc_params,
            self.connection.context().transaction_descriptor(),
        );

        let id = self.connection.context_mut().next_packet_id();
        self.connection.send(PacketHeader::rpc(id), req).await?;

        Ok(())
    }

    /// Runs a batch query solely to retrieve its column metadata. Used to
    /// resolve the column layout of a table-valued parameter type.
    pub(crate) async fn query_run_for_metadata<'b>(
        &mut self,
        query: String,
    ) -> crate::Result<Option<Vec<MetaDataColumn<'b>>>> {
        self.connection.flush_stream().await?;

        let req = BatchRequest::new(query, self.connection.context().transaction_descriptor());

        let id = self.connection.context_mut().next_packet_id();
        self.connection.send(PacketHeader::batch(id), req).await?;

        let token_stream = TokenStream::new(&mut self.connection).try_unfold();

        let columns = token_stream
            .try_fold(None, |mut columns, token| async move {
                if let ReceivedToken::NewResultset(metadata) = token {
                    columns = Some(metadata.columns.clone());
                };

                Ok(columns)
            })
            .await?;

        Ok(columns)
    }
}

/// Build the `INSERT BULK <table> (<cols>) [WITH (...)]` statement text.
///
/// `col_data` is the already-formatted column list (each column bracket-quoted
/// with its type, joined by `, `). Active [`SqlBulkCopyOptions`] flags and any
/// `order_hints` are collected into a `WITH (...)` clause; when both are empty
/// no `WITH` clause is emitted, so this reproduces the plain
/// `INSERT BULK <table> (<cols>)` used by `bulk_insert_columns`.
///
/// Order-hint column names are interpolated verbatim as already-valid SQL
/// identifiers — exactly like `table` and the `columns` entries elsewhere in
/// this module — so a caller may pass a plain (`id`), bracket-quoted (`[id]`,
/// `[my]]col]`) or multi-part name and get that same text back. Callers are
/// expected to have run every identifier through [`validate_bulk_column_identifier`]
/// first; do NOT re-bracket here, or an already-quoted name like `[id]` would be
/// double-escaped into the wrong identifier `[[id]]]`.
///
/// Note there is deliberately no `KEEP_IDENTITY` keyword: the `INSERT BULK`
/// `WITH (...)` grammar has no such option (unlike the textual `BULK INSERT`
/// statement). [`SqlBulkCopyOption::KeepIdentity`] is honoured by the caller
/// keeping the identity column in `col_data` instead.
fn build_insert_bulk_sql(
    table: &str,
    col_data: &str,
    options: SqlBulkCopyOptions,
    order_hints: &[ColumnOrderHint<'_>],
) -> String {
    let mut clauses: Vec<String> = Vec::new();

    // NB: `KeepIdentity` intentionally emits no keyword here — it is a
    // column-inclusion concern handled in `bulk_insert_with_options`.
    if options.contains(SqlBulkCopyOption::CheckConstraints) {
        clauses.push("CHECK_CONSTRAINTS".to_owned());
    }
    if options.contains(SqlBulkCopyOption::TableLock) {
        clauses.push("TABLOCK".to_owned());
    }
    if options.contains(SqlBulkCopyOption::KeepNulls) {
        clauses.push("KEEP_NULLS".to_owned());
    }
    if options.contains(SqlBulkCopyOption::FireTriggers) {
        clauses.push("FIRE_TRIGGERS".to_owned());
    }

    if !order_hints.is_empty() {
        let hints = order_hints
            .iter()
            .map(|(col, order)| {
                // Interpolate the (already-validated) identifier verbatim, like
                // `table`/`columns`. Re-bracketing here would double-escape an
                // already-quoted name (`[id]` -> `[[id]]]`).
                format!(
                    "{col} {}",
                    match order {
                        SortOrder::Ascending => "ASC",
                        SortOrder::Descending => "DESC",
                    }
                )
            })
            .join(", ");

        clauses.push(format!("ORDER({hints})"));
    }

    let mut query = format!("INSERT BULK {table} ({col_data})");

    if !clauses.is_empty() {
        query.push_str(" WITH (");
        query.push_str(&clauses.join(", "));
        query.push(')');
    }

    query
}

/// Decide whether a server-reported column is a bulk-insert target.
///
/// Read-only/computed columns are skipped so the server assigns their values.
/// Identity columns are read-only by default (filtered out, letting the server
/// assign them), but when [`SqlBulkCopyOption::KeepIdentity`] is set they are
/// additionally retained so the caller can supply explicit values — matching
/// ADO.NET's `SqlBulkCopy` (there is no `KEEP_IDENTITY` keyword in the
/// `INSERT BULK` `WITH (...)` grammar). Factored out of
/// [`Client::bulk_insert_with_options`] so this selection logic is unit-testable
/// without a live server.
fn bulk_column_is_target(
    base: &crate::tds::codec::BaseMetaDataColumn,
    keep_identity: bool,
) -> bool {
    base.is_updateable() || (keep_identity && base.is_identity())
}

/// Reject an obviously-malformed or dangerous bulk-insert table identifier.
///
/// The `table` argument of [`Client::bulk_insert`] / [`Client::bulk_insert_columns`]
/// is interpolated directly into the SQL batch because T-SQL does not allow
/// identifiers to be parameterized. This guard is cheap defense-in-depth — it
/// does NOT make untrusted input safe. It only rejects input that cannot be a
/// legitimate identifier (see [`validate_sql_identifier`] for the exact rules).
///
/// It deliberately does NOT try to quote or rewrite the identifier, so
/// multi-part names (`schema.table`), already-bracketed names (`[my table]`) and
/// temp tables (`##bulk_test`) keep working unchanged.
fn validate_bulk_table_identifier(table: &str) -> crate::Result<()> {
    validate_sql_identifier("bulk insert table", table)
}

/// Reject an obviously-malformed or dangerous bulk-insert `column` identifier.
///
/// Column names are interpolated into the metadata `SELECT` and `INSERT BULK`
/// column list exactly like `table`, so they get the same cheap
/// defense-in-depth check. See [`validate_bulk_table_identifier`].
fn validate_bulk_column_identifier(column: &str) -> crate::Result<()> {
    validate_sql_identifier("bulk insert column", column)
}

/// Reject an obviously-malformed or dangerous SQL identifier that will be
/// interpolated directly into a SQL batch because T-SQL does not allow
/// identifiers or type names to be parameterized. `what` names the kind of
/// identifier for the error message.
///
/// This is cheap defense-in-depth — it does NOT make untrusted input safe. It
/// rejects input that cannot be a legitimate identifier:
///
/// - a NUL byte or any ASCII control character;
/// - **outside** a `[...]` bracket-quoted segment, any character that is not
///   identifier-safe. Only alphanumerics and the punctuation needed for real
///   identifiers/type names are allowed — `_`, `.` (multi-part names like
///   `dbo.MyType`), `@`/`#` (variable/temp-style names), `*` (a bulk column
///   list may be `*`), and `(`, `)`, `,` (parameterized types such as
///   `decimal(10,2)` / `varchar(max)`). Parens must be balanced — an unbalanced
///   `)` *or* an unclosed `(` is rejected — and both a space and a comma are allowed only *inside*
///   those parens (e.g. `decimal(18, 4)`); a top-level space or comma is
///   rejected because it would let one identifier split into several SQL tokens
///   (a top-level comma would splice a verbatim order hint `a,b` into two
///   columns). This rejects statement-breaking characters such as `;`, quotes
///   and `-`, so a value like `1; DROP TABLE Users--` cannot slip through; and
/// - **inside** a `[...]` bracket-quoted segment anything is allowed except an
///   unescaped `]` (per the T-SQL bracket-escaping rule a literal `]` must be
///   doubled as `]]`). The segment must be terminated — an unclosed `[` running
///   to the end of the string is rejected. A `]` seen outside any bracket is
///   unbalanced and rejected. A closing `]`, and a top-level closing `)`, are themselves SQL
///   token boundaries, so a segment may only be followed by `.` (the next part
///   of a multi-part name) or the end of the string — this stops delimiter-
///   adjacent splicing such as `[t]UNION(...)` or `foo(1)UNION(...)` that needs
///   no space.
///
/// It deliberately does NOT try to quote or rewrite the identifier, so
/// multi-part names (`schema.table`), already-bracketed names (`[my table]`,
/// `[dbo].[my table]`, `[weird]]name]`) and temp tables (`##bulk_test`) keep
/// working unchanged. This is shared by the bulk-insert guards here and by
/// `validate_db_type_identifier` in `src/command.rs`.
pub(crate) fn validate_sql_identifier(what: &str, ident: &str) -> crate::Result<()> {
    if ident.chars().any(|c| c.is_ascii_control()) {
        return Err(crate::Error::BulkInput(
            format!("{what} identifier must not contain NUL or control characters").into(),
        ));
    }

    // Apply the T-SQL bracket rule: inside a `[...]` quoted identifier a literal
    // `]` must be doubled (`]]`); a single `]` closes the bracket. A `]` seen
    // outside of any bracket is unbalanced and rejected. Tracking bracket state
    // keeps legitimate names like `[dbo].[my table]` and `[weird]]name]`
    // working while catching stray closing brackets such as `Foo]`.
    let mut chars = ident.chars().peekable();
    let mut in_bracket = false;
    let mut paren_depth: u32 = 0;
    while let Some(c) = chars.next() {
        if in_bracket {
            if c == ']' {
                if chars.peek() == Some(&']') {
                    chars.next(); // consume the doubled `]]` escape
                } else {
                    in_bracket = false;
                    // A quoted-identifier segment may only be followed by `.`
                    // (introducing the next part of a multi-part name) or the
                    // end of the string. Anything else — e.g. `[t]UNION ...` —
                    // splices a fresh SQL token directly onto the closing `]`
                    // (which is itself a token boundary, needing no space), so
                    // reject it.
                    match chars.peek() {
                        None | Some('.') => {}
                        Some(_) => {
                            return Err(crate::Error::BulkInput(
                                format!("{what} identifier has trailing characters after a bracket-quoted segment").into(),
                            ));
                        }
                    }
                }
            }
            continue;
        }

        match c {
            '[' => in_bracket = true,
            ']' => {
                return Err(crate::Error::BulkInput(
                    format!("{what} identifier contains an unbalanced `]` bracket").into(),
                ));
            }
            '(' => paren_depth += 1,
            ')' => {
                // A `)` with no matching `(` is unbalanced. Left unchecked
                // (`saturating_sub`) it would sail through and, interpolated
                // verbatim, could close a caller-supplied enclosing paren early
                // — e.g. an order hint `col)` desyncing `ORDER(col) ...)`. Reject
                // it exactly like an unbalanced `]`.
                if paren_depth == 0 {
                    return Err(crate::Error::BulkInput(
                        format!("{what} identifier contains an unbalanced `)`").into(),
                    ));
                }
                paren_depth -= 1;
                // A parameterized type ends at its closing paren; nothing is a
                // legitimate continuation after a top-level `)`. Rejecting it
                // stops `)`-delimited token splicing such as `foo(1)UNION(...)`
                // (the `)` is a token boundary, so no space is required).
                if paren_depth == 0 && chars.peek().is_some() {
                    return Err(crate::Error::BulkInput(
                        format!("{what} identifier has trailing characters after a closing `)`")
                            .into(),
                    ));
                }
            }
            // A space is only legitimate inside a parameterized type's parens
            // (e.g. `decimal(18, 4)`) or inside a bracket-quoted name (handled
            // above). A *top-level* space would let a single identifier split
            // into several SQL tokens (`t UNION SELECT ...`, `t WHERE ...`)
            // without using any otherwise-blocked character, so reject it.
            ' ' if paren_depth == 0 => {
                return Err(crate::Error::BulkInput(
                    format!("{what} identifier contains a disallowed character").into(),
                ));
            }
            // A comma is only legitimate inside a parameterized type's parens
            // (`decimal(10,2)`). A *top-level* comma would splice a single
            // identifier into two — e.g. a verbatim order hint `a,b` becoming
            // two order columns `a` and `b` — so reject it like a top-level
            // space.
            ',' if paren_depth == 0 => {
                return Err(crate::Error::BulkInput(
                    format!("{what} identifier contains a disallowed character").into(),
                ));
            }
            // Outside a bracket-quoted segment only identifier-safe characters
            // are permitted (see the doc comment). Everything else — `;`,
            // quotes, `-`, etc. — is rejected.
            c if c.is_alphanumeric() => {}
            '_' | '.' | '@' | '#' | ',' | ' ' | '*' => {}
            _ => {
                return Err(crate::Error::BulkInput(
                    format!("{what} identifier contains a disallowed character").into(),
                ));
            }
        }
    }

    // Reject unbalanced *openers* left dangling at end of input, mirroring the
    // rejection of unbalanced closers above. An unterminated `[` would quote and
    // swallow whatever follows when interpolated (e.g. an order hint `[abc`
    // becoming `ORDER([abc ASC))`); an unclosed `(` leaves an enclosing paren
    // open. A legitimate identifier/type name never ends mid-bracket or with an
    // open paren.
    if in_bracket {
        return Err(crate::Error::BulkInput(
            format!("{what} identifier has an unterminated `[` bracket-quoted segment").into(),
        ));
    }
    if paren_depth != 0 {
        return Err(crate::Error::BulkInput(
            format!("{what} identifier contains an unbalanced `(`").into(),
        ));
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{
        build_insert_bulk_sql, bulk_column_is_target, validate_bulk_column_identifier,
        validate_bulk_table_identifier,
    };
    use crate::tds::codec::{BaseMetaDataColumn, ColumnFlag, TypeInfo, VarLenContext, VarLenType};
    use crate::{SortOrder, SqlBulkCopyOption, SqlBulkCopyOptions};
    use enumflags2::BitFlags;

    // Build a `BaseMetaDataColumn` carrying exactly `flags`, so the bulk-target
    // selection predicate can be exercised without a live server. The column
    // type is irrelevant to the predicate; a small fixed-len type stands in.
    fn base_with_flags(flags: BitFlags<ColumnFlag>) -> BaseMetaDataColumn {
        BaseMetaDataColumn {
            flags,
            ty: TypeInfo::VarLenSized(VarLenContext::new(VarLenType::Intn, 4, None)),
            table_name: None,
        }
    }

    #[test]
    fn bulk_column_is_target_selects_writeable_and_keep_identity() {
        let updateable: BitFlags<ColumnFlag> = ColumnFlag::Updateable.into();
        let unknown: BitFlags<ColumnFlag> = ColumnFlag::UpdateableUnknown.into();
        let read_only = BitFlags::<ColumnFlag>::empty();
        let identity_ro: BitFlags<ColumnFlag> = ColumnFlag::Identity.into();
        // An identity column SQL Server also reports as updateable-unknown.
        let identity_unknown = ColumnFlag::Identity | ColumnFlag::UpdateableUnknown;

        // Read/write and updateable-unknown columns are always targets,
        // regardless of the KeepIdentity flag.
        for keep in [false, true] {
            assert!(bulk_column_is_target(&base_with_flags(updateable), keep));
            assert!(bulk_column_is_target(&base_with_flags(unknown), keep));
            // A plain read-only (non-identity) column is never a target.
            assert!(!bulk_column_is_target(&base_with_flags(read_only), keep));
        }

        // A read-only identity column is skipped by default (server assigns the
        // value) but retained when KeepIdentity is set.
        assert!(!bulk_column_is_target(&base_with_flags(identity_ro), false));
        assert!(bulk_column_is_target(&base_with_flags(identity_ro), true));

        // KeepIdentity only *adds* identity columns; it never drops a column that
        // was already a target on its own merits.
        assert!(bulk_column_is_target(
            &base_with_flags(identity_unknown),
            false
        ));
        assert!(bulk_column_is_target(
            &base_with_flags(identity_unknown),
            true
        ));

        // A non-identity read-only column is not resurrected by KeepIdentity.
        assert!(!bulk_column_is_target(&base_with_flags(read_only), true));
    }

    // A fixed, hand-written column list stands in for the server-provided
    // `MetaDataColumn` Display output so the SQL-string builder can be unit
    // tested without a live connection.
    const COLS: &str = "[id] int, [val] int";

    #[test]
    fn build_sql_no_options_no_hints_emits_no_with_clause() {
        // Empty options + empty hints must reproduce the plain statement that
        // `bulk_insert_columns` has always emitted.
        assert_eq!(
            build_insert_bulk_sql("t", COLS, SqlBulkCopyOptions::empty(), &[]),
            "INSERT BULK t ([id] int, [val] int)"
        );
    }

    #[test]
    fn build_sql_each_flag_emits_expected_keyword() {
        // `KeepIdentity` is deliberately absent: the `INSERT BULK` `WITH (...)`
        // grammar has no `KEEP_IDENTITY` keyword (it is a column-inclusion
        // concern), so only these four flags map to keywords.
        for (flag, keyword) in [
            (SqlBulkCopyOption::CheckConstraints, "CHECK_CONSTRAINTS"),
            (SqlBulkCopyOption::TableLock, "TABLOCK"),
            (SqlBulkCopyOption::KeepNulls, "KEEP_NULLS"),
            (SqlBulkCopyOption::FireTriggers, "FIRE_TRIGGERS"),
        ] {
            assert_eq!(
                build_insert_bulk_sql("t", COLS, flag.into(), &[]),
                format!("INSERT BULK t ([id] int, [val] int) WITH ({keyword})"),
                "flag {flag:?} did not emit {keyword}",
            );
        }
    }

    #[test]
    fn build_sql_keep_identity_emits_no_with_keyword() {
        // Regression guard: emitting `KEEP_IDENTITY` into the `WITH (...)` clause
        // is a syntax error against the TDS `INSERT BULK` statement (verified
        // against ADO.NET's `SqlBulkCopy` and go-mssqldb, neither of which emits
        // it). `KeepIdentity` alone must therefore produce no `WITH` clause at
        // all; the flag's effect is entirely in column selection.
        let sql = build_insert_bulk_sql("t", COLS, SqlBulkCopyOption::KeepIdentity.into(), &[]);
        assert_eq!(sql, "INSERT BULK t ([id] int, [val] int)", "got: {sql}");
        assert!(!sql.contains("KEEP_IDENTITY"), "got: {sql}");
    }

    #[test]
    fn build_sql_combined_flags_join_in_fixed_order() {
        // `KeepIdentity` contributes no keyword, so only TABLOCK/FIRE_TRIGGERS
        // appear even though it is set.
        let opts = SqlBulkCopyOption::KeepIdentity
            | SqlBulkCopyOption::TableLock
            | SqlBulkCopyOption::FireTriggers;

        assert_eq!(
            build_insert_bulk_sql("t", COLS, opts, &[]),
            "INSERT BULK t ([id] int, [val] int) WITH (TABLOCK, FIRE_TRIGGERS)"
        );
    }

    #[test]
    fn build_sql_all_flags() {
        // `all()` includes `KeepIdentity`, which emits nothing, so the keyword
        // list is the four real `WITH` options.
        let opts = SqlBulkCopyOptions::all();
        assert_eq!(
            build_insert_bulk_sql("t", COLS, opts, &[]),
            "INSERT BULK t ([id] int, [val] int) WITH (CHECK_CONSTRAINTS, TABLOCK, KEEP_NULLS, FIRE_TRIGGERS)"
        );
    }

    #[test]
    fn build_sql_order_hints_asc_and_desc() {
        // Plain column names are interpolated verbatim (like `columns`), not
        // re-bracketed, and the reference `ORDER(` has no space.
        let hints = [("id", SortOrder::Ascending), ("val", SortOrder::Descending)];
        assert_eq!(
            build_insert_bulk_sql("t", COLS, SqlBulkCopyOptions::empty(), &hints),
            "INSERT BULK t ([id] int, [val] int) WITH (ORDER(id ASC, val DESC))"
        );
    }

    #[test]
    fn build_sql_options_and_order_hints_combine() {
        let hints = [("id", SortOrder::Ascending)];
        assert_eq!(
            build_insert_bulk_sql("t", COLS, SqlBulkCopyOption::TableLock.into(), &hints),
            "INSERT BULK t ([id] int, [val] int) WITH (TABLOCK, ORDER(id ASC))"
        );
    }

    #[test]
    fn build_sql_order_hint_bracketed_name_not_double_escaped() {
        // Regression guard: order-hint column names are interpolated verbatim as
        // already-valid identifiers, exactly like `table`/`columns`. An
        // already-bracket-quoted name (which the validator accepts) must be
        // emitted as-is — NOT re-bracketed into `[[id]]]` or `[[my]]]]col]]]`.
        let hints = [
            ("[id]", SortOrder::Ascending),
            ("[my]]col]", SortOrder::Descending),
        ];
        assert_eq!(
            build_insert_bulk_sql("t", COLS, SqlBulkCopyOptions::empty(), &hints),
            "INSERT BULK t ([id] int, [val] int) WITH (ORDER([id] ASC, [my]]col] DESC))"
        );
    }

    #[test]
    fn build_sql_empty_hints_emits_no_order_clause() {
        let sql = build_insert_bulk_sql("t", COLS, SqlBulkCopyOption::TableLock.into(), &[]);
        assert!(!sql.contains("ORDER"), "got: {sql}");
        assert_eq!(sql, "INSERT BULK t ([id] int, [val] int) WITH (TABLOCK)");
    }

    #[test]
    fn build_sql_order_hint_column_names_are_validated_like_columns() {
        // The public API runs order-hint column names through the same guard as
        // the column list; confirm that guard rejects a stray `]`.
        assert!(validate_bulk_column_identifier("my]col").is_err());
        assert!(validate_bulk_column_identifier("[my]]col]").is_ok());
    }

    #[test]
    fn accepts_normal_column_identifiers() {
        for column in ["foo", "bar", "*", "[my col]", "[weird]]col]"] {
            assert!(
                validate_bulk_column_identifier(column).is_ok(),
                "expected column {column:?} to be accepted",
            );
        }
    }

    #[test]
    fn rejects_bad_column_identifiers() {
        // control character
        assert!(validate_bulk_column_identifier("foo\0bar").is_err());
        assert!(validate_bulk_column_identifier("foo\nbar").is_err());
        // lone / unbalanced closing bracket
        assert!(validate_bulk_column_identifier("foo]").is_err());
        assert!(validate_bulk_column_identifier("a]b").is_err());
    }

    #[test]
    fn accepts_normal_identifiers() {
        for table in [
            "Foo",
            "dbo.Foo",
            "##bulk_test",
            "#temp",
            "[my table]",
            "[dbo].[my table]",
            "[weird]]name]", // doubled `]]` escape inside brackets
        ] {
            assert!(
                validate_bulk_table_identifier(table).is_ok(),
                "expected {table:?} to be accepted",
            );
        }
    }

    #[test]
    fn rejects_control_characters() {
        assert!(validate_bulk_table_identifier("Foo\0bar").is_err());
        assert!(validate_bulk_table_identifier("Foo\nbar").is_err());
        assert!(validate_bulk_table_identifier("Foo\tbar").is_err());
    }

    #[test]
    fn rejects_unbalanced_closing_bracket() {
        assert!(validate_bulk_table_identifier("Foo]").is_err());
        assert!(validate_bulk_table_identifier("[my] table]").is_err());
        assert!(validate_bulk_table_identifier("a]b").is_err());
    }

    #[test]
    fn column_metadata_guards_reject_bad_identifiers() {
        // `column_metadata` interpolates `table`/`columns` into
        // `SELECT TOP 0 {columns} FROM {table}` and now validates both with the
        // same guards as `bulk_insert*`. A malformed table or column identifier
        // must be rejected before any SQL is built.
        assert!(validate_bulk_table_identifier("Foo]").is_err());
        assert!(validate_bulk_table_identifier("Foo\nbar").is_err());
        assert!(validate_bulk_column_identifier("id]").is_err());
        assert!(validate_bulk_column_identifier("col\0").is_err());
    }

    #[test]
    fn rejects_statement_breaking_identifiers() {
        // The guard must reject statement-breakers (`;`, quotes, `--`, `=`)
        // that would let an injected column/table escape the interpolated SQL.
        for bad in [
            "1; DROP TABLE Users--",
            "id = 1",
            "foo'bar",
            "foo\"bar",
            "foo--bar",
            "foo;bar",
        ] {
            assert!(
                validate_bulk_column_identifier(bad).is_err(),
                "expected column {bad:?} to be rejected",
            );
            assert!(
                validate_bulk_table_identifier(bad).is_err(),
                "expected table {bad:?} to be rejected",
            );
        }
    }

    #[test]
    fn accepts_star_and_bracketed_statement_breakers() {
        // `*` must stay valid as a whole column list (bulk_insert uses `&["*"]`),
        // and characters that would be statement-breakers outside brackets are
        // fine when properly bracket-quoted.
        assert!(validate_bulk_column_identifier("*").is_ok());
        assert!(validate_bulk_column_identifier("[weird;name]").is_ok());
        assert!(validate_bulk_table_identifier("[dbo].[my;table]").is_ok());
    }

    #[test]
    fn rejects_top_level_space_but_allows_it_inside_parens_and_brackets() {
        // A top-level space lets a single identifier split into multiple SQL
        // tokens without any otherwise-blocked character, so it is rejected.
        assert!(validate_bulk_table_identifier("t UNION SELECT name FROM sysobjects").is_err());
        assert!(validate_bulk_table_identifier("t WHERE 1=1").is_err());
        assert!(validate_bulk_column_identifier("a b").is_err());

        // A space is still fine inside a parameterized type's parens...
        assert!(super::validate_sql_identifier("db_type", "decimal(18, 4)").is_ok());
        // ...and inside a bracket-quoted name.
        assert!(validate_bulk_table_identifier("[my table]").is_ok());
        // The canonical no-space forms keep working.
        assert!(super::validate_sql_identifier("db_type", "decimal(10,2)").is_ok());
        assert!(super::validate_sql_identifier("db_type", "varchar(max)").is_ok());
    }

    #[test]
    fn rejects_delimiter_adjacent_token_splicing() {
        // A `]` or `)` is itself a SQL token boundary, so an attacker can splice
        // a new token onto one without any (now-blocked) top-level space. Both
        // forms must be rejected.
        assert!(
            validate_bulk_table_identifier("[RealTable]UNION(SELECT secret FROM users)").is_err()
        );
        assert!(validate_bulk_table_identifier("[t]UNION").is_err());
        assert!(validate_bulk_table_identifier("[t](1)").is_err());
        assert!(super::validate_sql_identifier("t", "foo(1)UNION(SELECT x)").is_err());
        assert!(super::validate_sql_identifier("t", "decimal(10,2)x").is_err());

        // ...while every legitimate multi-part / parameterized form still passes.
        assert!(validate_bulk_table_identifier("[dbo].[my table]").is_ok());
        assert!(validate_bulk_table_identifier("[db].[schema].[tbl]").is_ok());
        assert!(validate_bulk_table_identifier("[weird]]name]").is_ok());
        assert!(super::validate_sql_identifier("db_type", "decimal(18,4)").is_ok());
        assert!(super::validate_sql_identifier("db_type", "numeric(38, 38)").is_ok());
        assert!(super::validate_sql_identifier("db_type", "varchar(max)").is_ok());
    }

    #[test]
    fn rejects_unbalanced_closing_paren_and_top_level_comma() {
        // Order-hint columns are interpolated verbatim into `ORDER( ... )`, so a
        // value the guard accepts must not be able to close that paren early or
        // splice a second column: a lone trailing `)` (no matching `(`) and a
        // top-level comma are both rejected.
        assert!(validate_bulk_column_identifier("col)").is_err());
        assert!(validate_bulk_column_identifier(")").is_err());
        assert!(validate_bulk_column_identifier("a,b").is_err());
        assert!(validate_bulk_table_identifier("t)").is_err());
        assert!(super::validate_sql_identifier("db_type", "decimal(10,2))").is_err());

        // The symmetric openers must also be rejected: an unbalanced `(` never
        // closed, and an unterminated `[` that would swallow trailing SQL when
        // interpolated verbatim into `ORDER( ... )`.
        assert!(validate_bulk_column_identifier("a(b").is_err());
        assert!(validate_bulk_column_identifier("(").is_err());
        assert!(validate_bulk_column_identifier("[abc").is_err());
        assert!(validate_bulk_table_identifier("dbo.[my table").is_err());
        assert!(super::validate_sql_identifier("db_type", "decimal(10,2").is_err());

        // Balanced parens with an interior comma/space are still fine.
        assert!(super::validate_sql_identifier("db_type", "decimal(10,2)").is_ok());
        assert!(super::validate_sql_identifier("db_type", "numeric(18, 4)").is_ok());
        // A bracket-quoted name may still contain `)`/`,` literally.
        assert!(validate_bulk_column_identifier("[weird,name)]").is_ok());
    }
}