This repository has been archived by the owner on Jul 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 586
/
SqlManager.java
1137 lines (1020 loc) · 35.8 KB
/
SqlManager.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
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.sqoop.manager;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.sqoop.accumulo.AccumuloUtil;
import org.apache.sqoop.mapreduce.AccumuloImportJob;
import org.apache.sqoop.mapreduce.HBaseBulkImportJob;
import org.apache.sqoop.mapreduce.JdbcCallExportJob;
import org.apache.sqoop.util.LoggingUtils;
import org.apache.sqoop.util.SqlTypeMap;
import org.apache.sqoop.SqoopOptions;
import org.apache.sqoop.hbase.HBaseUtil;
import org.apache.sqoop.mapreduce.DataDrivenImportJob;
import org.apache.sqoop.mapreduce.HBaseImportJob;
import org.apache.sqoop.mapreduce.ImportJobBase;
import org.apache.sqoop.mapreduce.JdbcExportJob;
import org.apache.sqoop.mapreduce.JdbcUpdateExportJob;
import org.apache.sqoop.mapreduce.db.DataDrivenDBInputFormat;
import org.apache.sqoop.util.ExportException;
import org.apache.sqoop.util.ImportException;
import org.apache.sqoop.util.ResultSetPrinter;
/**
* ConnManager implementation for generic SQL-compliant database.
* This is an abstract class; it requires a database-specific
* ConnManager implementation to actually create the connection.
*/
public abstract class SqlManager
extends org.apache.sqoop.manager.ConnManager {
public static final Log LOG = LogFactory.getLog(SqlManager.class.getName());
/** Substring that must appear in free-form queries submitted by users.
* This is the string '$CONDITIONS'.
*/
public static final String SUBSTITUTE_TOKEN =
DataDrivenDBInputFormat.SUBSTITUTE_TOKEN;
protected static final int DEFAULT_FETCH_SIZE = 1000;
private Statement lastStatement;
/**
* Constructs the SqlManager.
* @param opts the SqoopOptions describing the user's requested action.
*/
public SqlManager(final SqoopOptions opts) {
this.options = opts;
initOptionDefaults();
}
/**
* Sets default values for values that were not provided by the user.
* Only options with database-specific defaults should be configured here.
*/
protected void initOptionDefaults() {
if (options.getFetchSize() == null) {
LOG.info("Using default fetchSize of " + DEFAULT_FETCH_SIZE);
options.setFetchSize(DEFAULT_FETCH_SIZE);
}
}
/**
* @return the SQL query to use in getColumnNames() in case this logic must
* be tuned per-database, but the main extraction loop is still inheritable.
*/
protected String getColNamesQuery(String tableName) {
// adding where clause to prevent loading a big table
return "SELECT t.* FROM " + escapeTableName(tableName) + " AS t WHERE 1=0";
}
@Override
/** {@inheritDoc} */
public String[] getColumnNames(String tableName) {
String stmt = getColNamesQuery(tableName);
return filterSpecifiedColumnNames(getColumnNamesForRawQuery(stmt));
}
/**
* Utilize the --columns option, if specified.
* @param columns
* @return the subset of columns which were specified by --columns option.
*/
protected String[] filterSpecifiedColumnNames(String[] columns) {
if (options.getColumns() == null) {
return columns;
}
List<String> colNames = new ArrayList<String>();
for (String col : columns) {
String userColName = options.getColumnNameCaseInsensitive(col);
if (userColName != null) {
colNames.add(userColName);
}
}
return colNames.toArray(new String[colNames.size()]);
}
@Override
/** {@inheritDoc} */
public String [] getColumnNamesForQuery(String query) {
String rawQuery = query.replace(SUBSTITUTE_TOKEN, " (1 = 0) ");
return getColumnNamesForRawQuery(rawQuery);
}
/**
* Get column names for a query statement that we do not modify further.
*/
public String[] getColumnNamesForRawQuery(String stmt) {
ResultSet results;
try {
results = execute(stmt);
} catch (SQLException sqlE) {
LoggingUtils.logAll(LOG, "Error executing statement: " + sqlE.toString(),
sqlE);
release();
return null;
}
try {
int cols = results.getMetaData().getColumnCount();
ArrayList<String> columns = new ArrayList<String>();
ResultSetMetaData metadata = results.getMetaData();
for (int i = 1; i < cols + 1; i++) {
String colName = metadata.getColumnLabel(i);
if (colName == null || colName.equals("")) {
colName = metadata.getColumnName(i);
if (null == colName) {
colName = "_RESULT_" + i;
}
}
columns.add(colName);
LOG.debug("Found column " + colName);
}
return columns.toArray(new String[0]);
} catch (SQLException sqlException) {
LoggingUtils.logAll(LOG, "Error reading from database: "
+ sqlException.toString(), sqlException);
return null;
} finally {
try {
results.close();
getConnection().commit();
} catch (SQLException sqlE) {
LoggingUtils.logAll(LOG, "SQLException closing ResultSet: "
+ sqlE.toString(), sqlE);
}
release();
}
}
@Override
public String[] getColumnNamesForProcedure(String procedureName) {
List<String> ret = new ArrayList<String>();
try {
DatabaseMetaData metaData = this.getConnection().getMetaData();
ResultSet results = metaData.getProcedureColumns(null, null,
procedureName, null);
if (null == results) {
return null;
}
try {
while (results.next()) {
if (results.getInt("COLUMN_TYPE")
!= DatabaseMetaData.procedureColumnReturn) {
int index = results.getInt("ORDINAL_POSITION") - 1;
if (index < 0) {
continue; // actually the return type
}
for(int i = ret.size(); i < index; ++i) {
ret.add(null);
}
String name = results.getString("COLUMN_NAME");
if (index == ret.size()) {
ret.add(name);
} else {
ret.set(index, name);
}
}
}
LOG.debug("getColumnsNamesForProcedure returns "
+ StringUtils.join(ret, ","));
return ret.toArray(new String[ret.size()]);
} finally {
results.close();
getConnection().commit();
}
} catch (SQLException e) {
LoggingUtils.logAll(LOG, "Error reading procedure metadata: ", e);
throw new RuntimeException("Can't fetch column names for procedure.", e);
}
}
/**
* @return the SQL query to use in getColumnTypes() in case this logic must
* be tuned per-database, but the main extraction loop is still inheritable.
*/
protected String getColTypesQuery(String tableName) {
return getColNamesQuery(tableName);
}
@Override
public Map<String, Integer> getColumnTypes(String tableName) {
String stmt = getColTypesQuery(tableName);
return getColumnTypesForRawQuery(stmt);
}
@Override
public Map<String, Integer> getColumnTypesForQuery(String query) {
// Manipulate the query to return immediately, with zero rows.
String rawQuery = query.replace(SUBSTITUTE_TOKEN, " (1 = 0) ");
return getColumnTypesForRawQuery(rawQuery);
}
/**
* Get column types for a query statement that we do not modify further.
*/
protected Map<String, Integer> getColumnTypesForRawQuery(String stmt) {
Map<String, List<Integer>> colInfo = getColumnInfoForRawQuery(stmt);
if (colInfo == null) {
return null;
}
Map<String, Integer> colTypes = new SqlTypeMap<String, Integer>();
for (String s : colInfo.keySet()) {
List<Integer> info = colInfo.get(s);
colTypes.put(s, info.get(0));
}
return colTypes;
}
@Override
public Map<String, List<Integer>> getColumnInfo(String tableName) {
String stmt = getColNamesQuery(tableName);
return getColumnInfoForRawQuery(stmt);
}
@Override
public Map<String, List<Integer>> getColumnInfoForQuery(String query) {
// Manipulate the query to return immediately, with zero rows.
String rawQuery = query.replace(SUBSTITUTE_TOKEN, " (1 = 0) ");
return getColumnInfoForRawQuery(rawQuery);
}
protected Map<String, List<Integer>> getColumnInfoForRawQuery(String stmt) {
ResultSet results;
LOG.debug("Execute getColumnInfoRawQuery : " + stmt);
try {
results = execute(stmt);
} catch (SQLException sqlE) {
LoggingUtils.logAll(LOG, "Error executing statement: " + sqlE.toString(),
sqlE);
release();
return null;
}
try {
Map<String, List<Integer>> colInfo =
new SqlTypeMap<String, List<Integer>>();
int cols = results.getMetaData().getColumnCount();
ResultSetMetaData metadata = results.getMetaData();
for (int i = 1; i < cols + 1; i++) {
int typeId = metadata.getColumnType(i);
int precision = metadata.getPrecision(i);
int scale = metadata.getScale(i);
// If we have an unsigned int we need to make extra room by
// plopping it into a bigint
if (typeId == Types.INTEGER && !metadata.isSigned(i)){
typeId = Types.BIGINT;
}
String colName = metadata.getColumnLabel(i);
if (colName == null || colName.equals("")) {
colName = metadata.getColumnName(i);
}
List<Integer> info = new ArrayList<Integer>(3);
info.add(Integer.valueOf(typeId));
info.add(precision);
info.add(scale);
colInfo.put(colName, info);
LOG.debug("Found column " + colName + " of type " + info);
}
return colInfo;
} catch (SQLException sqlException) {
LoggingUtils.logAll(LOG, "Error reading from database: "
+ sqlException.toString(), sqlException);
return null;
} finally {
try {
results.close();
getConnection().commit();
} catch (SQLException sqlE) {
LoggingUtils.logAll(LOG,
"SQLException closing ResultSet: " + sqlE.toString(), sqlE);
}
release();
}
}
@Override
public Map<String, String> getColumnTypeNamesForTable(String tableName) {
String stmt = getColTypesQuery(tableName);
return getColumnTypeNamesForRawQuery(stmt);
}
@Override
public Map<String, String> getColumnTypeNamesForQuery(String query) {
// Manipulate the query to return immediately, with zero rows.
String rawQuery = query.replace(SUBSTITUTE_TOKEN, " (1 = 0) ");
return getColumnTypeNamesForRawQuery(rawQuery);
}
protected Map<String, String> getColumnTypeNamesForRawQuery(String stmt) {
ResultSet results;
try {
results = execute(stmt);
} catch (SQLException sqlE) {
LoggingUtils.logAll(LOG, "Error executing statement: " + sqlE.toString(),
sqlE);
release();
return null;
}
try {
Map<String, String> colTypeNames = new HashMap<String, String>();
int cols = results.getMetaData().getColumnCount();
ResultSetMetaData metadata = results.getMetaData();
for (int i = 1; i < cols + 1; i++) {
String colTypeName = metadata.getColumnTypeName(i);
String colName = metadata.getColumnLabel(i);
if (colName == null || colName.equals("")) {
colName = metadata.getColumnName(i);
}
colTypeNames.put(colName, colTypeName);
LOG.debug("Found column " + colName + " of type " + colTypeName);
}
return colTypeNames;
} catch (SQLException sqlException) {
LoggingUtils.logAll(LOG, "Error reading from database: "
+ sqlException.toString(), sqlException);
return null;
} finally {
try {
results.close();
getConnection().commit();
} catch (SQLException sqlE) {
LoggingUtils.logAll(LOG, "SQLException closing ResultSet: "
+ sqlE.toString(), sqlE);
}
release();
}
}
@Override
public ResultSet readTable(String tableName, String[] columns)
throws SQLException {
if (columns == null) {
columns = getColumnNames(tableName);
}
StringBuilder sb = new StringBuilder();
sb.append("SELECT ");
boolean first = true;
for (String col : columns) {
if (!first) {
sb.append(", ");
}
sb.append(escapeColName(col));
first = false;
}
sb.append(" FROM ");
sb.append(escapeTableName(tableName));
sb.append(" AS "); // needed for hsqldb; doesn't hurt anyone else.
sb.append(escapeTableName(tableName));
String sqlCmd = sb.toString();
LOG.debug("Reading table with command: " + sqlCmd);
return execute(sqlCmd);
}
@Override
public String[] listDatabases() {
// TODO(aaron): Implement this!
LOG.error("Generic SqlManager.listDatabases() not implemented.");
return null;
}
@Override
public Map<String, Integer> getColumnTypesForProcedure(String procedureName) {
Map<String, List<Integer>> colInfo =
getColumnInfoForProcedure(procedureName);
if (colInfo == null) {
return null;
}
Map<String, Integer> colTypes = new SqlTypeMap<String, Integer>();
for (String s : colInfo.keySet()) {
List<Integer> info = colInfo.get(s);
colTypes.put(s, info.get(0));
}
return colTypes;
}
@Override
public Map<String, List<Integer>>
getColumnInfoForProcedure(String procedureName) {
Map<String, List<Integer>> ret = new TreeMap<String, List<Integer>>();
try {
DatabaseMetaData metaData = this.getConnection().getMetaData();
ResultSet results = metaData.getProcedureColumns(null, null,
procedureName, null);
if (null == results) {
return null;
}
try {
while (results.next()) {
if (results.getInt("COLUMN_TYPE")
!= DatabaseMetaData.procedureColumnReturn
&& results.getInt("ORDINAL_POSITION") > 0) {
// we don't care if we get several rows for the
// same ORDINAL_POSITION (e.g. like H2 gives us)
// as we'll just overwrite the entry in the map:
List<Integer> info = new ArrayList<Integer>(3);
info.add(results.getInt("DATA_TYPE"));
info.add(results.getInt("PRECISION"));
info.add(results.getInt("SCALE"));
ret.put(results.getString("COLUMN_NAME"), info);
}
}
LOG.debug("Columns returned = " + StringUtils.join(ret.keySet(), ","));
LOG.debug("Types returned = " + StringUtils.join(ret.values(), ","));
return ret.isEmpty() ? null : ret;
} finally {
results.close();
getConnection().commit();
}
} catch (SQLException sqlException) {
LoggingUtils.logAll(LOG, "Error reading primary key metadata: "
+ sqlException.toString(), sqlException);
return null;
}
}
@Override
public Map<String, String>
getColumnTypeNamesForProcedure(String procedureName) {
Map<String, String> ret = new TreeMap<String, String>();
try {
DatabaseMetaData metaData = this.getConnection().getMetaData();
ResultSet results = metaData.getProcedureColumns(null, null,
procedureName, null);
if (null == results) {
return null;
}
try {
while (results.next()) {
if (results.getInt("COLUMN_TYPE")
!= DatabaseMetaData.procedureColumnReturn
&& results.getInt("ORDINAL_POSITION") > 0) {
// we don't care if we get several rows for the
// same ORDINAL_POSITION (e.g. like H2 gives us)
// as we'll just overwrite the entry in the map:
ret.put(
results.getString("COLUMN_NAME"),
results.getString("TYPE_NAME"));
}
}
LOG.debug("Columns returned = " + StringUtils.join(ret.keySet(), ","));
LOG.debug(
"Type names returned = " + StringUtils.join(ret.values(), ","));
return ret.isEmpty() ? null : ret;
} finally {
results.close();
getConnection().commit();
}
} catch (SQLException sqlException) {
LoggingUtils.logAll(LOG, "Error reading primary key metadata: "
+ sqlException.toString(), sqlException);
return null;
}
}
@Override
public String[] listTables() {
ResultSet results = null;
String [] tableTypes = {"TABLE"};
try {
try {
DatabaseMetaData metaData = this.getConnection().getMetaData();
results = metaData.getTables(null, null, null, tableTypes);
} catch (SQLException sqlException) {
LoggingUtils.logAll(LOG, "Error reading database metadata: "
+ sqlException.toString(), sqlException);
return null;
}
if (null == results) {
return null;
}
try {
ArrayList<String> tables = new ArrayList<String>();
while (results.next()) {
String tableName = results.getString("TABLE_NAME");
tables.add(tableName);
}
return tables.toArray(new String[0]);
} catch (SQLException sqlException) {
LoggingUtils.logAll(LOG, "Error reading from database: "
+ sqlException.toString(), sqlException);
return null;
}
} finally {
if (null != results) {
try {
results.close();
getConnection().commit();
} catch (SQLException sqlE) {
LoggingUtils.logAll(LOG, "Exception closing ResultSet: "
+ sqlE.toString(), sqlE);
}
}
}
}
@Override
public String getPrimaryKey(String tableName) {
try {
DatabaseMetaData metaData = this.getConnection().getMetaData();
ResultSet results = metaData.getPrimaryKeys(null, null, tableName);
if (null == results) {
return null;
}
try {
if (results.next()) {
return results.getString("COLUMN_NAME");
} else {
return null;
}
} finally {
results.close();
getConnection().commit();
}
} catch (SQLException sqlException) {
LoggingUtils.logAll(LOG, "Error reading primary key metadata: "
+ sqlException.toString(), sqlException);
return null;
}
}
/**
* Retrieve the actual connection from the outer ConnManager.
*/
public abstract Connection getConnection() throws SQLException;
/**
* Determine what column to use to split the table.
* @param opts the SqoopOptions controlling this import.
* @param tableName the table to import.
* @return the splitting column, if one is set or inferrable, or null
* otherwise.
*/
protected String getSplitColumn(SqoopOptions opts, String tableName) {
String splitCol = opts.getSplitByCol();
if (null == splitCol && null != tableName) {
// If the user didn't specify a splitting column, try to infer one.
splitCol = getPrimaryKey(tableName);
}
return splitCol;
}
/**
* Offers the ConnManager an opportunity to validate that the
* options specified in the ImportJobContext are valid.
* @throws ImportException if the import is misconfigured.
*/
protected void checkTableImportOptions(
org.apache.sqoop.manager.ImportJobContext context)
throws IOException, ImportException {
String tableName = context.getTableName();
SqoopOptions opts = context.getOptions();
// Default implementation: check that the split column is set
// correctly.
String splitCol = getSplitColumn(opts, tableName);
if (null == splitCol && opts.getNumMappers() > 1) {
if (!opts.getAutoResetToOneMapper()) {
// Can't infer a primary key.
throw new ImportException("No primary key could be found for table "
+ tableName + ". Please specify one with --split-by or perform "
+ "a sequential import with '-m 1'.");
} else {
LOG.warn("Split by column not provided or can't be inferred. Resetting to one mapper");
opts.setNumMappers(1);
}
}
}
/**
* Default implementation of importTable() is to launch a MapReduce job
* via DataDrivenImportJob to read the table with DataDrivenDBInputFormat.
*/
public void importTable(org.apache.sqoop.manager.ImportJobContext context)
throws IOException, ImportException {
String tableName = context.getTableName();
String jarFile = context.getJarFile();
SqoopOptions opts = context.getOptions();
context.setConnManager(this);
ImportJobBase importer;
if (opts.getHBaseTable() != null) {
// Import to HBase.
if (!HBaseUtil.isHBaseJarPresent()) {
throw new ImportException("HBase jars are not present in "
+ "classpath, cannot import to HBase!");
}
if (!opts.isBulkLoadEnabled()){
importer = new HBaseImportJob(opts, context);
} else {
importer = new HBaseBulkImportJob(opts, context);
}
} else if (opts.getAccumuloTable() != null) {
// Import to Accumulo.
if (!AccumuloUtil.isAccumuloJarPresent()) {
throw new ImportException("Accumulo jars are not present in "
+ "classpath, cannot import to Accumulo!");
}
importer = new AccumuloImportJob(opts, context);
} else {
// Import to HDFS.
importer = new DataDrivenImportJob(opts, context.getInputFormat(),
context, getParquetJobConfigurator().createParquetImportJobConfigurator());
}
checkTableImportOptions(context);
String splitCol = getSplitColumn(opts, tableName);
importer.runImport(tableName, jarFile, splitCol, opts.getConf());
}
/**
* Default implementation of importQuery() is to launch a MapReduce job
* via DataDrivenImportJob to read the table with DataDrivenDBInputFormat,
* using its free-form query importer.
*/
public void importQuery(org.apache.sqoop.manager.ImportJobContext context)
throws IOException, ImportException {
String jarFile = context.getJarFile();
SqoopOptions opts = context.getOptions();
context.setConnManager(this);
ImportJobBase importer;
if (opts.getHBaseTable() != null) {
// Import to HBase.
if (!HBaseUtil.isHBaseJarPresent()) {
throw new ImportException("HBase jars are not present in classpath,"
+ " cannot import to HBase!");
}
if (!opts.isBulkLoadEnabled()){
importer = new HBaseImportJob(opts, context);
} else {
importer = new HBaseBulkImportJob(opts, context);
}
} else if (opts.getAccumuloTable() != null) {
// Import to Accumulo.
if (!AccumuloUtil.isAccumuloJarPresent()) {
throw new ImportException("Accumulo jars are not present in classpath,"
+ " cannot import to Accumulo!");
}
importer = new AccumuloImportJob(opts, context);
} else {
// Import to HDFS.
importer = new DataDrivenImportJob(opts, context.getInputFormat(),
context, getParquetJobConfigurator().createParquetImportJobConfigurator());
}
String splitCol = getSplitColumn(opts, null);
if (splitCol == null) {
String boundaryQuery = opts.getBoundaryQuery();
if (opts.getNumMappers() > 1) {
// Can't infer a primary key.
throw new ImportException("A split-by column must be specified for "
+ "parallel free-form query imports. Please specify one with "
+ "--split-by or perform a sequential import with '-m 1'.");
} else if (boundaryQuery != null && !boundaryQuery.isEmpty()) {
// Query import with boundary query and no split column specified
throw new ImportException("Using a boundary query for a query based "
+ "import requires specifying the split by column as well. Please "
+ "specify a column name using --split-by and try again.");
}
}
importer.runImport(null, jarFile, splitCol, opts.getConf());
}
/**
* Executes an arbitrary SQL statement.
* @param stmt The SQL statement to execute
* @param fetchSize Overrides default or parameterized fetch size
* @return A ResultSet encapsulating the results or null on error
*/
protected ResultSet execute(String stmt, Integer fetchSize, Object... args)
throws SQLException {
// Release any previously-open statement.
release();
PreparedStatement statement = null;
statement = this.getConnection().prepareStatement(stmt,
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
if (fetchSize != null) {
LOG.debug("Using fetchSize for next query: " + fetchSize);
statement.setFetchSize(fetchSize);
}
this.lastStatement = statement;
if (null != args) {
for (int i = 0; i < args.length; i++) {
statement.setObject(i + 1, args[i]);
}
}
LOG.info("Executing SQL statement: " + stmt);
return statement.executeQuery();
}
/**
* Executes an arbitrary SQL Statement.
* @param stmt The SQL statement to execute
* @return A ResultSet encapsulating the results or null on error
*/
protected ResultSet execute(String stmt, Object... args) throws SQLException {
return execute(stmt, options.getFetchSize(), args);
}
public void close() throws SQLException {
release();
}
/**
* Prints the contents of a ResultSet to the specified PrintWriter.
* The ResultSet is closed at the end of this method.
* @param results the ResultSet to print.
* @param pw the location to print the data to.
*/
protected void formatAndPrintResultSet(ResultSet results, PrintWriter pw) {
try {
try {
int cols = results.getMetaData().getColumnCount();
pw.println("Got " + cols + " columns back");
if (cols > 0) {
ResultSetMetaData rsmd = results.getMetaData();
String schema = rsmd.getSchemaName(1);
String table = rsmd.getTableName(1);
if (null != schema) {
pw.println("Schema: " + schema);
}
if (null != table) {
pw.println("Table: " + table);
}
}
} catch (SQLException sqlE) {
LoggingUtils.logAll(LOG, "SQLException reading result metadata: "
+ sqlE.toString(), sqlE);
}
try {
new ResultSetPrinter().printResultSet(pw, results);
} catch (IOException ioe) {
LOG.error("IOException writing results: " + ioe.toString());
return;
}
} finally {
try {
results.close();
getConnection().commit();
} catch (SQLException sqlE) {
LoggingUtils.logAll(LOG, "SQLException closing ResultSet: "
+ sqlE.toString(), sqlE);
}
release();
}
}
/**
* Poor man's SQL query interface; used for debugging.
* @param s the SQL statement to execute.
*/
public void execAndPrint(String s) {
ResultSet results = null;
try {
results = execute(s);
} catch (SQLException sqlE) {
LoggingUtils.logAll(LOG, "Error executing statement: ", sqlE);
release();
return;
}
PrintWriter pw = new PrintWriter(System.out, true);
try {
formatAndPrintResultSet(results, pw);
} finally {
pw.close();
}
}
/**
* Create a connection to the database; usually used only from within
* getConnection(), which enforces a singleton guarantee around the
* Connection object.
*/
protected Connection makeConnection() throws SQLException {
Connection connection;
String driverClass = getDriverClass();
try {
Class.forName(driverClass);
} catch (ClassNotFoundException cnfe) {
throw new RuntimeException("Could not load db driver class: "
+ driverClass);
}
String username = options.getUsername();
String password = options.getPassword();
String connectString = options.getConnectString();
Properties connectionParams = options.getConnectionParams();
if (connectionParams != null && connectionParams.size() > 0) {
LOG.debug("User specified connection params. "
+ "Using properties specific API for making connection.");
Properties props = new Properties();
if (username != null) {
props.put("user", username);
}
if (password != null) {
props.put("password", password);
}
props.putAll(connectionParams);
connection = DriverManager.getConnection(connectString, props);
} else {
LOG.debug("No connection paramenters specified. "
+ "Using regular API for making connection.");
if (username == null) {
connection = DriverManager.getConnection(connectString);
} else {
connection = DriverManager.getConnection(
connectString, username, password);
}
}
// We only use this for metadata queries. Loosest semantics are okay.
connection.setTransactionIsolation(getMetadataIsolationLevel());
connection.setAutoCommit(false);
return connection;
}
/**
* @return the transaction isolation level to use for metadata queries
* (queries executed by the ConnManager itself).
*/
protected int getMetadataIsolationLevel() {
return options.getMetadataTransactionIsolationLevel();
}
/**
* Export data stored in HDFS into a table in a database.
*/
public void exportTable(org.apache.sqoop.manager.ExportJobContext context)
throws IOException, ExportException {
context.setConnManager(this);
JdbcExportJob exportJob = new JdbcExportJob(context, getParquetJobConfigurator().createParquetExportJobConfigurator());
exportJob.runExport();
}
@Override
public void callTable(org.apache.sqoop.manager.ExportJobContext context)
throws IOException,
ExportException {
context.setConnManager(this);
JdbcCallExportJob exportJob = new JdbcCallExportJob(context, getParquetJobConfigurator().createParquetExportJobConfigurator());
exportJob.runExport();
}
public void release() {
if (null != this.lastStatement) {
try {
this.lastStatement.close();
} catch (SQLException e) {
LoggingUtils.logAll(LOG, "Exception closing executed Statement: "
+ e, e);
}
this.lastStatement = null;
}
}
@Override
/**
* {@inheritDoc}
*/
public void updateTable(
org.apache.sqoop.manager.ExportJobContext context)
throws IOException, ExportException {
context.setConnManager(this);
JdbcUpdateExportJob exportJob = new JdbcUpdateExportJob(context, getParquetJobConfigurator().createParquetExportJobConfigurator());
exportJob.runExport();
}
/**
* @return a SQL query to retrieve the current timestamp from the db.
*/
protected String getCurTimestampQuery() {
return "SELECT CURRENT_TIMESTAMP()";
}
@Override
/**
* {@inheritDoc}
*/
public Timestamp getCurrentDbTimestamp() {
release(); // Release any previous ResultSet.
Statement s = null;
ResultSet rs = null;
try {
Connection c = getConnection();
s = c.createStatement();
rs = s.executeQuery(getCurTimestampQuery());
if (rs == null || !rs.next()) {
return null; // empty ResultSet.
}
return rs.getTimestamp(1);
} catch (SQLException sqlE) {
LoggingUtils.logAll(LOG, "SQL exception accessing current timestamp: "
+ sqlE, sqlE);
return null;
} finally {
try {
if (null != rs) {
rs.close();
}