forked from microsoft/mssql-jdbc
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSQLServerBulkCopy.java
3506 lines (3116 loc) · 166 KB
/
SQLServerBulkCopy.java
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
/*
* Microsoft JDBC Driver for SQL Server Copyright(c) Microsoft Corporation All rights reserved. This program is made
* available under the terms of the MIT License. See the LICENSE file in the project root for more information.
*/
package com.microsoft.sqlserver.jdbc;
import static java.nio.charset.StandardCharsets.UTF_16LE;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.Serializable;
import java.io.StringReader;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.MessageFormat;
import java.time.DateTimeException;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAccessor;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Level;
import javax.sql.RowSet;
import javax.sql.XAConnection;
import microsoft.sql.DateTimeOffset;
/**
* Provides functionality to efficiently bulk load a SQL Server table with data from another source. <br>
* <br>
* Microsoft SQL Server includes a popular command-prompt utility named bcp for moving data from one table to another,
* whether on a single server or between servers. The SQLServerBulkCopy class lets you write code solutions in Java that
* provide similar functionality. There are other ways to load data into a SQL Server table (INSERT statements, for
* example), but SQLServerBulkCopy offers a significant performance advantage over them. <br>
* The SQLServerBulkCopy class can be used to write data only to SQL Server tables. However, the data source is not
* limited to SQL Server; any data source can be used, as long as the data can be read with a ResultSet or
* ISQLServerBulkRecord instance.
*/
public class SQLServerBulkCopy implements java.lang.AutoCloseable, java.io.Serializable {
/**
* Update serialVersionUID when making changes to this file
*/
private static final long serialVersionUID = 1989903904654306244L;
/**
* Represents the column mappings between the source and destination table
*/
private class ColumnMapping implements Serializable {
/**
* Always update serialVersionUID when prompted.
*/
private static final long serialVersionUID = 6428337550654423919L;
String sourceColumnName = null;
int sourceColumnOrdinal = -1;
String destinationColumnName = null;
int destinationColumnOrdinal = -1;
ColumnMapping(String source, String dest) {
this.sourceColumnName = source;
this.destinationColumnName = dest;
}
ColumnMapping(String source, int dest) {
this.sourceColumnName = source;
this.destinationColumnOrdinal = dest;
}
ColumnMapping(int source, String dest) {
this.sourceColumnOrdinal = source;
this.destinationColumnName = dest;
}
ColumnMapping(int source, int dest) {
this.sourceColumnOrdinal = source;
this.destinationColumnOrdinal = dest;
}
}
/**
* Class name for logging.
*/
private static final String loggerClassName = "com.microsoft.sqlserver.jdbc.SQLServerBulkCopy";
/**
* Logger
*/
private static final java.util.logging.Logger loggerExternal = java.util.logging.Logger.getLogger(loggerClassName);
/**
* Destination server connection.
*/
private SQLServerConnection connection;
/**
* Options to control how the WriteToServer methods behave.
*/
private SQLServerBulkCopyOptions copyOptions;
/**
* Mappings between columns in the data source and columns in the destination
*/
private List<ColumnMapping> columnMappings;
/**
* Flag if SQLServerBulkCopy owns the connection and should close it when Close is called
*/
private boolean ownsConnection;
/**
* Name of destination table on server. If destinationTable has not been set when WriteToServer is called, an
* Exception is thrown. destinationTable is a three-part name {@code (<database>.<owningschema>.<name>)}. You can
* qualify the table name with its database and owning schema if you choose. However, if the table name uses an
* underscore ("_") or any other special characters, you must escape the name using surrounding brackets. For more
* information, see "Identifiers" in SQL Server Books Online. You can bulk-copy data to a temporary table by using a
* value such as {@code tempdb..#table or tempdb.<owner>.#table} for the destinationTable property.
*/
private String destinationTableName;
/**
* Source data (from a Record). Is null unless the corresponding version of writeToServer is called.
*/
private ISQLServerBulkRecord sourceBulkRecord;
/**
* Source data (from ResultSet). Is null unless the corresponding version of writeToServer is called.
*/
private ResultSet sourceResultSet;
/**
* Metadata for the source table columns
*/
private ResultSetMetaData sourceResultSetMetaData;
/**
* The CekTable for the destination table.
*/
private CekTable destCekTable = null;
/**
* Statement level encryption setting needed for querying against encrypted columns.
*/
private SQLServerStatementColumnEncryptionSetting stmtColumnEncriptionSetting = SQLServerStatementColumnEncryptionSetting.UseConnectionSetting;
private ResultSet destinationTableMetadata;
/**
* Metadata for the destination table columns
*/
class BulkColumnMetaData {
String columnName;
SSType ssType = null;
int jdbcType;
int precision, scale;
SQLCollation collation;
byte[] flags = new byte[2];
boolean isIdentity = false;
boolean isNullable;
String collationName;
CryptoMetadata cryptoMeta = null;
DateTimeFormatter dateTimeFormatter = null;
// used when allowEncryptedValueModifications is on and encryption is turned off in connection
String encryptionType = null;
BulkColumnMetaData(Column column) throws SQLServerException {
this.cryptoMeta = column.getCryptoMetadata();
TypeInfo typeInfo = column.getTypeInfo();
this.columnName = column.getColumnName();
this.ssType = typeInfo.getSSType();
this.flags = typeInfo.getFlags();
this.isIdentity = typeInfo.isIdentity();
this.isNullable = typeInfo.isNullable();
precision = typeInfo.getPrecision();
this.scale = typeInfo.getScale();
collation = typeInfo.getSQLCollation();
this.jdbcType = ssType.getJDBCType().getIntValue();
}
// This constructor is needed for the source meta data.
BulkColumnMetaData(String colName, boolean isNullable, int precision, int scale, int jdbcType,
DateTimeFormatter dateTimeFormatter) throws SQLServerException {
this.columnName = colName;
this.isNullable = isNullable;
this.precision = precision;
this.scale = scale;
this.jdbcType = jdbcType;
this.dateTimeFormatter = dateTimeFormatter;
}
BulkColumnMetaData(Column column, String collationName, String encryptionType) throws SQLServerException {
this(column);
this.collationName = collationName;
this.encryptionType = encryptionType;
}
// update the cryptoMeta of source when reading from forward only resultset
BulkColumnMetaData(BulkColumnMetaData bulkColumnMetaData, CryptoMetadata cryptoMeta) {
this.columnName = bulkColumnMetaData.columnName;
this.isNullable = bulkColumnMetaData.isNullable;
this.precision = bulkColumnMetaData.precision;
this.scale = bulkColumnMetaData.scale;
this.jdbcType = bulkColumnMetaData.jdbcType;
this.cryptoMeta = cryptoMeta;
}
}
/**
* A map to store the metadata information for the destination table.
*/
private Map<Integer, BulkColumnMetaData> destColumnMetadata;
/**
* A map to store the metadata information for the source table.
*/
private Map<Integer, BulkColumnMetaData> srcColumnMetadata;
/**
* Variable to store destination column count.
*/
private int destColumnCount;
/**
* Variable to store source column count.
*/
private int srcColumnCount;
private ScheduledFuture<?> timeout;
/**
* The maximum temporal precision we can send when using varchar(precision) in bulkcommand, to send a
* smalldatetime/datetime value.
*/
private static final int sourceBulkRecordTemporalMaxPrecision = 50;
/**
* Constructs a SQLServerBulkCopy using the specified open instance of SQLServerConnection.
*
* @param connection
* Open instance of Connection to destination server. Must be from the Microsoft JDBC driver for SQL Server.
* @throws SQLServerException
* If the supplied type is not a connection from the Microsoft JDBC driver for SQL Server.
*/
public SQLServerBulkCopy(Connection connection) throws SQLServerException {
loggerExternal.entering(loggerClassName, "SQLServerBulkCopy", connection);
if (null == connection || !(connection instanceof ISQLServerConnection)) {
SQLServerException.makeFromDriverError(null, null,
SQLServerException.getErrString("R_invalidDestConnection"), null, false);
}
if (connection instanceof SQLServerConnection) {
this.connection = (SQLServerConnection) connection;
} else if (connection instanceof SQLServerConnectionPoolProxy) {
this.connection = ((SQLServerConnectionPoolProxy) connection).getWrappedConnection();
} else {
SQLServerException.makeFromDriverError(null, null,
SQLServerException.getErrString("R_invalidDestConnection"), null, false);
}
ownsConnection = false;
// useInternalTransaction will be false by default. When a connection object is passed in, bulk copy
// will use that connection object's transaction, i.e. no transaction management is done by bulk copy.
copyOptions = new SQLServerBulkCopyOptions();
initializeDefaults();
loggerExternal.exiting(loggerClassName, "SQLServerBulkCopy");
}
/**
* Constructs a SQLServerBulkCopy based on the supplied connectionString.
*
* @param connectionUrl
* Connection string for the destination server.
* @throws SQLServerException
* If a connection cannot be established.
*/
public SQLServerBulkCopy(String connectionUrl) throws SQLServerException {
loggerExternal.entering(loggerClassName, "SQLServerBulkCopy", "connectionUrl not traced.");
if ((connectionUrl == null) || "".equals(connectionUrl.trim())) {
throw new SQLServerException(null, SQLServerException.getErrString("R_nullConnection"), null, 0, false);
}
ownsConnection = true;
SQLServerDriver driver = new SQLServerDriver();
connection = (SQLServerConnection) driver.connect(connectionUrl, null);
if (null == connection) {
throw new SQLServerException(null, SQLServerException.getErrString("R_invalidConnection"), null, 0, false);
}
copyOptions = new SQLServerBulkCopyOptions();
initializeDefaults();
loggerExternal.exiting(loggerClassName, "SQLServerBulkCopy");
}
/**
* Adds a new column mapping, using ordinals to specify both the source and destination columns.
*
* @param sourceColumn
* Source column ordinal.
* @param destinationColumn
* Destination column ordinal.
* @throws SQLServerException
* If the column mapping is invalid
*/
public void addColumnMapping(int sourceColumn, int destinationColumn) throws SQLServerException {
loggerExternal.entering(loggerClassName, "addColumnMapping", new Object[] {sourceColumn, destinationColumn});
if (0 >= sourceColumn) {
throwInvalidArgument("sourceColumn");
} else if (0 >= destinationColumn) {
throwInvalidArgument("destinationColumn");
}
columnMappings.add(new ColumnMapping(sourceColumn, destinationColumn));
loggerExternal.exiting(loggerClassName, "addColumnMapping");
}
/**
* Adds a new column mapping, using an ordinal for the source column and a string for the destination column.
*
* @param sourceColumn
* Source column ordinal.
* @param destinationColumn
* Destination column name.
* @throws SQLServerException
* If the column mapping is invalid
*/
public void addColumnMapping(int sourceColumn, String destinationColumn) throws SQLServerException {
loggerExternal.entering(loggerClassName, "addColumnMapping", new Object[] {sourceColumn, destinationColumn});
if (0 >= sourceColumn) {
throwInvalidArgument("sourceColumn");
} else if (null == destinationColumn || destinationColumn.isEmpty()) {
throwInvalidArgument("destinationColumn");
}
columnMappings.add(new ColumnMapping(sourceColumn, destinationColumn.trim()));
loggerExternal.exiting(loggerClassName, "addColumnMapping");
}
/**
* Adds a new column mapping, using a column name to describe the source column and an ordinal to specify the
* destination column.
*
* @param sourceColumn
* Source column name.
* @param destinationColumn
* Destination column ordinal.
* @throws SQLServerException
* If the column mapping is invalid
*/
public void addColumnMapping(String sourceColumn, int destinationColumn) throws SQLServerException {
loggerExternal.entering(loggerClassName, "addColumnMapping", new Object[] {sourceColumn, destinationColumn});
if (0 >= destinationColumn) {
throwInvalidArgument("destinationColumn");
} else if (null == sourceColumn || sourceColumn.isEmpty()) {
throwInvalidArgument("sourceColumn");
}
columnMappings.add(new ColumnMapping(sourceColumn.trim(), destinationColumn));
loggerExternal.exiting(loggerClassName, "addColumnMapping");
}
/**
* Adds a new column mapping, using column names to specify both source and destination columns.
*
* @param sourceColumn
* Source column name.
* @param destinationColumn
* Destination column name.
* @throws SQLServerException
* If the column mapping is invalid
*/
public void addColumnMapping(String sourceColumn, String destinationColumn) throws SQLServerException {
loggerExternal.entering(loggerClassName, "addColumnMapping", new Object[] {sourceColumn, destinationColumn});
if (null == sourceColumn || sourceColumn.isEmpty()) {
throwInvalidArgument("sourceColumn");
} else if (null == destinationColumn || destinationColumn.isEmpty()) {
throwInvalidArgument("destinationColumn");
}
columnMappings.add(new ColumnMapping(sourceColumn.trim(), destinationColumn.trim()));
loggerExternal.exiting(loggerClassName, "addColumnMapping");
}
/**
* Clears the contents of the column mappings
*/
public void clearColumnMappings() {
loggerExternal.entering(loggerClassName, "clearColumnMappings");
columnMappings.clear();
loggerExternal.exiting(loggerClassName, "clearColumnMappings");
}
/**
* Closes the SQLServerBulkCopy instance
*/
public void close() {
loggerExternal.entering(loggerClassName, "close");
if (ownsConnection) {
try {
connection.close();
} catch (SQLException e) {
// Ignore this exception
}
}
loggerExternal.exiting(loggerClassName, "close");
}
/**
* Returns the name of the destination table on the server.
*
* @return Destination table name.
*/
public String getDestinationTableName() {
return destinationTableName;
}
/**
* Sets the name of the destination table on the server.
*
* @param tableName
* Destination table name.
* @throws SQLServerException
* If the table name is null
*/
public void setDestinationTableName(String tableName) throws SQLServerException {
loggerExternal.entering(loggerClassName, "setDestinationTableName", tableName);
if (null == tableName || 0 == tableName.trim().length()) {
throwInvalidArgument("tableName");
}
destinationTableName = tableName.trim();
loggerExternal.exiting(loggerClassName, "setDestinationTableName");
}
/**
* Returns the current SQLServerBulkCopyOptions.
*
* @return Current SQLServerBulkCopyOptions settings.
*/
public SQLServerBulkCopyOptions getBulkCopyOptions() {
return copyOptions;
}
/**
* Update the behavior of the SQLServerBulkCopy instance according to the options supplied, if supplied
* SQLServerBulkCopyOption is not null.
*
* @param copyOptions
* Settings to change how the WriteToServer methods behave.
* @throws SQLServerException
* If the SQLServerBulkCopyOption class was constructed using an existing Connection and the
* UseInternalTransaction option is specified.
*/
public void setBulkCopyOptions(SQLServerBulkCopyOptions copyOptions) throws SQLServerException {
loggerExternal.entering(loggerClassName, "updateBulkCopyOptions", copyOptions);
if (null != copyOptions) {
// Verify that copyOptions does not have useInternalTransaction set.
// UseInternalTrasnaction can only be used with a connection string.
// Setting it with an external connection object should throw
// exception.
if (!ownsConnection && copyOptions.isUseInternalTransaction()) {
SQLServerException.makeFromDriverError(null, null,
SQLServerException.getErrString("R_invalidTransactionOption"), null, false);
}
this.copyOptions = copyOptions;
}
loggerExternal.exiting(loggerClassName, "updateBulkCopyOptions");
}
/**
* Copies all rows in the supplied ResultSet to a destination table specified by the destinationTableName property
* of the SQLServerBulkCopy object.
*
* @param sourceData
* ResultSet to read data rows from.
* @throws SQLServerException
* If there are any issues encountered when performing the bulk copy operation
*/
public void writeToServer(ResultSet sourceData) throws SQLServerException {
writeResultSet(sourceData, false);
}
/**
* Copies all rows in the supplied RowSet to a destination table specified by the destinationTableName property of
* the SQLServerBulkCopy object.
*
* @param sourceData
* RowSet to read data rows from.
* @throws SQLServerException
* If there are any issues encountered when performing the bulk copy operation
*/
public void writeToServer(RowSet sourceData) throws SQLServerException {
writeResultSet(sourceData, true);
}
/**
* Copies all rows in the supplied ResultSet to a destination table specified by the destinationTableName property
* of the SQLServerBulkCopy object.
*
* @param sourceData
* ResultSet to read data rows from.
* @param isRowSet
* @throws SQLServerException
* If there are any issues encountered when performing the bulk copy operation
*/
private void writeResultSet(ResultSet sourceData, boolean isRowSet) throws SQLServerException {
loggerExternal.entering(loggerClassName, "writeToServer");
if (null == sourceData) {
throwInvalidArgument("sourceData");
}
try {
if (isRowSet) // Default RowSet implementation in Java doesn't have isClosed() implemented so need to do an
// alternate check instead.
{
if (!sourceData.isBeforeFirst()) {
sourceData.beforeFirst();
}
} else {
if (sourceData.isClosed()) {
SQLServerException.makeFromDriverError(null, null,
SQLServerException.getErrString("R_resultsetClosed"), null, false);
}
}
} catch (SQLException e) {
throw new SQLServerException(null, e.getMessage(), null, 0, false);
}
sourceResultSet = sourceData;
sourceBulkRecord = null;
// Save the resultset metadata as it is used in many places.
try {
sourceResultSetMetaData = sourceResultSet.getMetaData();
} catch (SQLException e) {
throw new SQLServerException(SQLServerException.getErrString("R_unableRetrieveColMeta"), e);
}
writeToServer();
loggerExternal.exiting(loggerClassName, "writeToServer");
}
/**
* Copies all rows from the supplied ISQLServerBulkRecord to a destination table specified by the
* destinationTableName property of the SQLServerBulkCopy object.
*
* @param sourceData
* SQLServerBulkReader to read data rows from.
* @throws SQLServerException
* If there are any issues encountered when performing the bulk copy operation
*/
public void writeToServer(ISQLServerBulkRecord sourceData) throws SQLServerException {
loggerExternal.entering(loggerClassName, "writeToServer");
if (null == sourceData) {
throwInvalidArgument("sourceData");
}
sourceBulkRecord = sourceData;
sourceResultSet = null;
writeToServer();
loggerExternal.exiting(loggerClassName, "writeToServer");
}
/**
* Initializes the defaults for member variables that require it.
*/
private void initializeDefaults() {
columnMappings = new LinkedList<>();
destinationTableName = null;
sourceBulkRecord = null;
sourceResultSet = null;
sourceResultSetMetaData = null;
srcColumnCount = 0;
srcColumnMetadata = null;
destColumnMetadata = null;
destColumnCount = 0;
}
private void sendBulkLoadBCP() throws SQLServerException {
final class InsertBulk extends TDSCommand {
/**
* Always update serialVersionUID when prompted.
*/
private static final long serialVersionUID = 6714118105257791547L;
InsertBulk() {
super("InsertBulk", 0, 0);
}
final boolean doExecute() throws SQLServerException {
int timeoutSeconds = copyOptions.getBulkCopyTimeout();
if (timeoutSeconds > 0) {
connection.checkClosed();
timeout = connection.getSharedTimer().schedule(new TDSTimeoutTask(this, connection),
timeoutSeconds);
}
// doInsertBulk inserts the rows in one batch. It returns true if there are more rows in
// the resultset, false otherwise. We keep sending rows, one batch at a time until the
// resultset is done.
try {
while (doInsertBulk(this));
} catch (SQLServerException topLevelException) {
// Get to the root of this exception.
Throwable rootCause = topLevelException;
while (null != rootCause.getCause()) {
rootCause = rootCause.getCause();
}
// Check whether it is a timeout exception.
if (rootCause instanceof SQLException && timeout != null && timeout.isDone()) {
SQLException sqlEx = (SQLException) rootCause;
if (sqlEx.getSQLState() != null
&& sqlEx.getSQLState().equals(SQLState.STATEMENT_CANCELED.getSQLStateCode())) {
// If SQLServerBulkCopy is managing the transaction, a rollback is needed.
if (copyOptions.isUseInternalTransaction()) {
connection.rollback();
}
throw new SQLServerException(SQLServerException.getErrString("R_queryTimedOut"),
SQLState.STATEMENT_CANCELED, DriverError.NOT_SET, sqlEx);
}
}
// It is not a timeout exception. Re-throw.
throw topLevelException;
}
if (timeout != null) {
timeout.cancel(true);
timeout = null;
}
return true;
}
}
connection.executeCommand(new InsertBulk());
}
/**
* write ColumnData token in COLMETADATA header
*/
private void writeColumnMetaDataColumnData(TDSWriter tdsWriter, int idx) throws SQLServerException {
int srcColumnIndex, destPrecision;
int bulkJdbcType, bulkPrecision, bulkScale;
SQLCollation collation;
SSType destSSType;
boolean isStreaming, srcNullable;
// For varchar, precision is the size of the varchar type.
/*
* UserType USHORT/ULONG; (Changed to ULONG in TDS 7.2) The user type ID of the data type of the column. The
* value will be 0x0000 with the exceptions of TIMESTAMP (0x0050) and alias types (greater than 0x00FF)
*/
byte[] userType = new byte[4];
userType[0] = (byte) 0x00;
userType[1] = (byte) 0x00;
userType[2] = (byte) 0x00;
userType[3] = (byte) 0x00;
tdsWriter.writeBytes(userType);
/**
* Flags token - Bit flags in least significant bit order https://msdn.microsoft.com/en-us/library/dd357363.aspx
* flags[0] = (byte) 0x05; flags[1] = (byte) 0x00;
*/
int destColumnIndex = columnMappings.get(idx).destinationColumnOrdinal;
/**
* TYPE_INFO FIXEDLENTYPE Example INT: tdsWriter.writeByte((byte) 0x38);
*/
srcColumnIndex = columnMappings.get(idx).sourceColumnOrdinal;
byte flags[] = destColumnMetadata.get(destColumnIndex).flags;
// If AllowEncryptedValueModification is set to true (and of course AE is off),
// the driver will not sent AE information, so, we need to set Encryption bit flag to 0.
if (null == srcColumnMetadata.get(srcColumnIndex).cryptoMeta
&& null == destColumnMetadata.get(destColumnIndex).cryptoMeta
&& copyOptions.isAllowEncryptedValueModifications()) {
// flags[1]>>3 & 0x01 is the encryption bit flag.
// it is the 4th least significant bit in this byte, so minus 8 to set it to 0.
if (1 == (flags[1] >> 3 & 0x01)) {
flags[1] = (byte) (flags[1] - 8);
}
}
tdsWriter.writeBytes(flags);
bulkJdbcType = srcColumnMetadata.get(srcColumnIndex).jdbcType;
bulkPrecision = srcColumnMetadata.get(srcColumnIndex).precision;
bulkScale = srcColumnMetadata.get(srcColumnIndex).scale;
srcNullable = srcColumnMetadata.get(srcColumnIndex).isNullable;
destSSType = destColumnMetadata.get(destColumnIndex).ssType;
destPrecision = destColumnMetadata.get(destColumnIndex).precision;
bulkPrecision = validateSourcePrecision(bulkPrecision, bulkJdbcType, destPrecision);
collation = destColumnMetadata.get(destColumnIndex).collation;
if (null == collation)
collation = connection.getDatabaseCollation();
if ((java.sql.Types.NCHAR == bulkJdbcType) || (java.sql.Types.NVARCHAR == bulkJdbcType)
|| (java.sql.Types.LONGNVARCHAR == bulkJdbcType)) {
isStreaming = (DataTypes.SHORT_VARTYPE_MAX_CHARS < bulkPrecision)
|| (DataTypes.SHORT_VARTYPE_MAX_CHARS < destPrecision);
} else {
isStreaming = (DataTypes.SHORT_VARTYPE_MAX_BYTES < bulkPrecision)
|| (DataTypes.SHORT_VARTYPE_MAX_BYTES < destPrecision);
}
CryptoMetadata destCryptoMeta = destColumnMetadata.get(destColumnIndex).cryptoMeta;
/*
* if source is encrypted and destination is unencrypted, use destination's sql type to send since there is no
* way of finding if source is encrypted without accessing the resultset. Send destination type if source
* resultset set is of type SQLServer, encryption is enabled and destination column is not encrypted
*/
if ((sourceResultSet instanceof SQLServerResultSet) && (connection.isColumnEncryptionSettingEnabled())
&& (null != destCryptoMeta)) {
bulkJdbcType = destColumnMetadata.get(destColumnIndex).jdbcType;
bulkPrecision = destPrecision;
bulkScale = destColumnMetadata.get(destColumnIndex).scale;
}
// use varbinary to send if destination is encrypted
if (((null != destColumnMetadata.get(destColumnIndex).encryptionType)
&& copyOptions.isAllowEncryptedValueModifications())
|| (null != destColumnMetadata.get(destColumnIndex).cryptoMeta)) {
tdsWriter.writeByte((byte) 0xA5);
if (isStreaming) {
tdsWriter.writeShort((short) 0xFFFF);
} else {
tdsWriter.writeShort((short) (bulkPrecision));
}
}
// In this case we will explicitly send binary value.
else if (((java.sql.Types.CHAR == bulkJdbcType) || (java.sql.Types.VARCHAR == bulkJdbcType)
|| (java.sql.Types.LONGVARCHAR == bulkJdbcType))
&& (SSType.BINARY == destSSType || SSType.VARBINARY == destSSType || SSType.VARBINARYMAX == destSSType
|| SSType.IMAGE == destSSType)) {
if (isStreaming) {
// Send as VARBINARY if streaming is enabled
tdsWriter.writeByte((byte) 0xA5);
} else {
tdsWriter.writeByte((byte) ((SSType.BINARY == destSSType) ? 0xAD : 0xA5));
}
tdsWriter.writeShort((short) (bulkPrecision));
} else {
writeTypeInfo(tdsWriter, bulkJdbcType, bulkScale, bulkPrecision, destSSType, collation, isStreaming,
srcNullable, false);
}
if (null != destCryptoMeta) {
int baseDestJDBCType = destCryptoMeta.baseTypeInfo.getSSType().getJDBCType().asJavaSqlType();
int baseDestPrecision = destCryptoMeta.baseTypeInfo.getPrecision();
if ((java.sql.Types.NCHAR == baseDestJDBCType) || (java.sql.Types.NVARCHAR == baseDestJDBCType)
|| (java.sql.Types.LONGNVARCHAR == baseDestJDBCType))
isStreaming = (DataTypes.SHORT_VARTYPE_MAX_CHARS < baseDestPrecision);
else
isStreaming = (DataTypes.SHORT_VARTYPE_MAX_BYTES < baseDestPrecision);
// Send CryptoMetaData
tdsWriter.writeShort(destCryptoMeta.getOrdinal()); // Ordinal
tdsWriter.writeBytes(userType); // usertype
// BaseTypeInfo
writeTypeInfo(tdsWriter, baseDestJDBCType, destCryptoMeta.baseTypeInfo.getScale(), baseDestPrecision,
destCryptoMeta.baseTypeInfo.getSSType(), collation, isStreaming, srcNullable, true);
tdsWriter.writeByte(destCryptoMeta.cipherAlgorithmId);
tdsWriter.writeByte(destCryptoMeta.encryptionType.getValue());
tdsWriter.writeByte(destCryptoMeta.normalizationRuleVersion);
}
/*
* ColName token The column name. Contains the column name length and column name. see: SQLServerConnection.java
* toUCS16(String s)
*/
int destColNameLen = columnMappings.get(idx).destinationColumnName.length();
String destColName = columnMappings.get(idx).destinationColumnName;
byte colName[] = new byte[2 * destColNameLen];
for (int i = 0; i < destColNameLen; ++i) {
int c = destColName.charAt(i);
colName[2 * i] = (byte) (c & 0xFF);
colName[2 * i + 1] = (byte) ((c >> 8) & 0xFF);
}
tdsWriter.writeByte((byte) destColNameLen);
tdsWriter.writeBytes(colName);
}
private void writeTypeInfo(TDSWriter tdsWriter, int srcJdbcType, int srcScale, int srcPrecision, SSType destSSType,
SQLCollation collation, boolean isStreaming, boolean srcNullable,
boolean isBaseType) throws SQLServerException {
switch (srcJdbcType) {
case java.sql.Types.INTEGER: // 0x38
if (!srcNullable) {
tdsWriter.writeByte(TDSType.INT4.byteValue());
} else {
tdsWriter.writeByte(TDSType.INTN.byteValue());
tdsWriter.writeByte((byte) 0x04);
}
break;
case java.sql.Types.BIGINT: // 0x7f
if (!srcNullable) {
tdsWriter.writeByte(TDSType.INT8.byteValue());
} else {
tdsWriter.writeByte(TDSType.INTN.byteValue());
tdsWriter.writeByte((byte) 0x08);
}
break;
case java.sql.Types.BIT: // 0x32
if (!srcNullable) {
tdsWriter.writeByte(TDSType.BIT1.byteValue());
} else {
tdsWriter.writeByte(TDSType.BITN.byteValue());
tdsWriter.writeByte((byte) 0x01);
}
break;
case java.sql.Types.SMALLINT: // 0x34
if (!srcNullable) {
tdsWriter.writeByte(TDSType.INT2.byteValue());
} else {
tdsWriter.writeByte(TDSType.INTN.byteValue());
tdsWriter.writeByte((byte) 0x02);
}
break;
case java.sql.Types.TINYINT: // 0x30
if (!srcNullable) {
tdsWriter.writeByte(TDSType.INT1.byteValue());
} else {
tdsWriter.writeByte(TDSType.INTN.byteValue());
tdsWriter.writeByte((byte) 0x01);
}
break;
case java.sql.Types.DOUBLE: // (FLT8TYPE) 0x3E
if (!srcNullable) {
tdsWriter.writeByte(TDSType.FLOAT8.byteValue());
} else {
tdsWriter.writeByte(TDSType.FLOATN.byteValue());
tdsWriter.writeByte((byte) 0x08);
}
break;
case java.sql.Types.REAL: // (FLT4TYPE) 0x3B
if (!srcNullable) {
tdsWriter.writeByte(TDSType.FLOAT4.byteValue());
} else {
tdsWriter.writeByte(TDSType.FLOATN.byteValue());
tdsWriter.writeByte((byte) 0x04);
}
break;
case microsoft.sql.Types.MONEY:
case microsoft.sql.Types.SMALLMONEY:
case java.sql.Types.NUMERIC:
case java.sql.Types.DECIMAL:
if (isBaseType && ((SSType.MONEY == destSSType) || (SSType.SMALLMONEY == destSSType))) {
tdsWriter.writeByte(TDSType.MONEYN.byteValue()); // 0x6E
if (SSType.MONEY == destSSType)
tdsWriter.writeByte((byte) 8);
else
tdsWriter.writeByte((byte) 4);
} else {
if (java.sql.Types.DECIMAL == srcJdbcType)
tdsWriter.writeByte(TDSType.DECIMALN.byteValue()); // 0x6A
else
tdsWriter.writeByte(TDSType.NUMERICN.byteValue()); // 0x6C
tdsWriter.writeByte((byte) TDSWriter.BIGDECIMAL_MAX_LENGTH); // maximum length
tdsWriter.writeByte((byte) srcPrecision); // unsigned byte
tdsWriter.writeByte((byte) srcScale); // unsigned byte
}
break;
case microsoft.sql.Types.GUID:
case java.sql.Types.CHAR: // 0xAF
if (isBaseType && (SSType.GUID == destSSType)) {
tdsWriter.writeByte(TDSType.GUID.byteValue());
tdsWriter.writeByte((byte) 0x10);
} else {
// BIGCHARTYPE
tdsWriter.writeByte(TDSType.BIGCHAR.byteValue());
tdsWriter.writeShort((short) (srcPrecision));
collation.writeCollation(tdsWriter);
}
break;
case java.sql.Types.NCHAR: // 0xEF
tdsWriter.writeByte(TDSType.NCHAR.byteValue());
tdsWriter.writeShort(isBaseType ? (short) (srcPrecision) : (short) (2 * srcPrecision));
collation.writeCollation(tdsWriter);
break;
case java.sql.Types.LONGVARCHAR:
case java.sql.Types.VARCHAR: // 0xA7
// BIGVARCHARTYPE
tdsWriter.writeByte(TDSType.BIGVARCHAR.byteValue());
if (isStreaming) {
tdsWriter.writeShort((short) 0xFFFF);
} else {
tdsWriter.writeShort((short) (srcPrecision));
}
collation.writeCollation(tdsWriter);
break;
case java.sql.Types.LONGNVARCHAR:
case java.sql.Types.NVARCHAR: // 0xE7
tdsWriter.writeByte(TDSType.NVARCHAR.byteValue());
if (isStreaming) {
tdsWriter.writeShort((short) 0xFFFF);
} else {
tdsWriter.writeShort(isBaseType ? (short) (srcPrecision) : (short) (2 * srcPrecision));
}
collation.writeCollation(tdsWriter);
break;
case java.sql.Types.BINARY: // 0xAD
tdsWriter.writeByte(TDSType.BIGBINARY.byteValue());
tdsWriter.writeShort((short) (srcPrecision));
break;
case java.sql.Types.LONGVARBINARY:
case java.sql.Types.VARBINARY: // 0xA5
// BIGVARBINARY
tdsWriter.writeByte(TDSType.BIGVARBINARY.byteValue());
if (isStreaming) {
tdsWriter.writeShort((short) 0xFFFF);
} else {
tdsWriter.writeShort((short) (srcPrecision));
}
break;
case microsoft.sql.Types.DATETIME:
case microsoft.sql.Types.SMALLDATETIME:
case java.sql.Types.TIMESTAMP:
if ((!isBaseType) && (null != sourceBulkRecord)) {
tdsWriter.writeByte(TDSType.BIGVARCHAR.byteValue());
tdsWriter.writeShort((short) (srcPrecision));
collation.writeCollation(tdsWriter);
} else {
switch (destSSType) {
case SMALLDATETIME:
if (!srcNullable)