-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDBTablePrinter.java
615 lines (523 loc) · 20.8 KB
/
DBTablePrinter.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
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
public class DBTablePrinter {
/**
* Default maximum number of rows to query and print.
*/
private static final int DEFAULT_MAX_ROWS = 10;
/**
* Default maximum width for text columns
* (like a <code>VARCHAR</code>) column.
*/
private static final int DEFAULT_MAX_TEXT_COL_WIDTH = 150;
/**
* Column type category for <code>CHAR</code>, <code>VARCHAR</code>
* and similar text columns.
*/
public static final int CATEGORY_STRING = 1;
/**
* Column type category for <code>TINYINT</code>, <code>SMALLINT</code>,
* <code>INT</code> and <code>BIGINT</code> columns.
*/
public static final int CATEGORY_INTEGER = 2;
/**
* Column type category for <code>REAL</code>, <code>DOUBLE</code>,
* and <code>DECIMAL</code> columns.
*/
public static final int CATEGORY_DOUBLE = 3;
/**
* Column type category for date and time related columns like
* <code>DATE</code>, <code>TIME</code>, <code>TIMESTAMP</code> etc.
*/
public static final int CATEGORY_DATETIME = 4;
/**
* Column type category for <code>BOOLEAN</code> columns.
*/
public static final int CATEGORY_BOOLEAN = 5;
/**
* Column type category for types for which the type name
* will be printed instead of the content, like <code>BLOB</code>,
* <code>BINARY</code>, <code>ARRAY</code> etc.
*/
public static final int CATEGORY_OTHER = 0;
/**
* Represents a database table column.
*/
private static class Column {
/**
* Column label.
*/
private String label;
/**
* Generic SQL type of the column as defined in
* <a target="_blank"
* href="http://docs.oracle.com/javase/8/docs/api/java/sql/Types.html">
* java.sql.Types
* </a>.
*/
private int type;
/**
* Generic SQL type name of the column as defined in
* <a target="_blank"
* href="http://docs.oracle.com/javase/8/docs/api/java/sql/Types.html">
* java.sql.Types
* </a>.
*/
private String typeName;
/**
* Width of the column that will be adjusted according to column label
* and values to be printed.
*/
private int width = 0;
/**
* Column values from each row of a <code>ResultSet</code>.
*/
private List<String> values = new ArrayList<>();
/**
* Flag for text justification using <code>String.format</code>.
* Empty string (<code>""</code>) to justify right,
* dash (<code>-</code>) to justify left.
*
* @see #justifyLeft()
*/
private String justifyFlag = "";
/**
* Column type category. The columns will be categorised according
* to their column types and specific needs to print them correctly.
*/
private int typeCategory = 0;
/**
* Constructs a new <code>Column</code> with a column label,
* generic SQL type and type name (as defined in
* <a target="_blank"
* href="http://docs.oracle.com/javase/8/docs/api/java/sql/Types.html">
* java.sql.Types
* </a>)
*
* @param label Column label or name
* @param type Generic SQL type
* @param typeName Generic SQL type name
*/
public Column (String label, int type, String typeName) {
this.label = label;
this.type = type;
this.typeName = typeName;
}
/**
* Returns the column label
*
* @return Column label
*/
public String getLabel() {
return label;
}
/**
* Returns the generic SQL type of the column
*
* @return Generic SQL type
*/
public int getType() {
return type;
}
/**
* Returns the generic SQL type name of the column
*
* @return Generic SQL type name
*/
public String getTypeName() {
return typeName;
}
/**
* Returns the width of the column
*
* @return Column width
*/
public int getWidth() {
return width;
}
/**
* Sets the width of the column to <code>width</code>
*
* @param width Width of the column
*/
public void setWidth(int width) {
this.width = width;
}
/**
* Adds a <code>String</code> representation (<code>value</code>)
* of a value to this column object's {@link #values} list.
* These values will come from each row of a
* <a target="_blank"
* href="http://docs.oracle.com/javase/8/docs/api/java/sql/ResultSet.html">
* ResultSet
* </a> of a database query.
*
* @param value The column value to add to {@link #values}
*/
public void addValue(String value) {
values.add(value);
}
/**
* Returns the column value at row index <code>i</code>.
* Note that the index starts at 0 so that <code>getValue(0)</code>
* will get the value for this column from the first row
* of a <a target="_blank"
* href="http://docs.oracle.com/javase/8/docs/api/java/sql/ResultSet.html">
* ResultSet</a>.
*
* @param i The index of the column value to get
* @return The String representation of the value
*/
public String getValue(int i) {
return values.get(i);
}
/**
* Returns the value of the {@link #justifyFlag}. The column
* values will be printed using <code>String.format</code> and
* this flag will be used to right or left justify the text.
*
* @return The {@link #justifyFlag} of this column
* @see #justifyLeft()
*/
public String getJustifyFlag() {
return justifyFlag;
}
/**
* Sets {@link #justifyFlag} to <code>"-"</code> so that
* the column value will be left justified when printed with
* <code>String.format</code>. Typically numbers will be right
* justified and text will be left justified.
*/
public void justifyLeft() {
this.justifyFlag = "-";
}
/**
* Returns the generic SQL type category of the column
*
* @return The {@link #typeCategory} of the column
*/
public int getTypeCategory() {
return typeCategory;
}
/**
* Sets the {@link #typeCategory} of the column
*
* @param typeCategory The type category
*/
public void setTypeCategory(int typeCategory) {
this.typeCategory = typeCategory;
}
}
/**
* Overloaded method that prints rows from table <code>tableName</code>
* to standard out using the given database connection
* <code>conn</code>. Total number of rows will be limited to
* {@link #DEFAULT_MAX_ROWS} and
* {@link #DEFAULT_MAX_TEXT_COL_WIDTH} will be used to limit
* the width of text columns (like a <code>VARCHAR</code> column).
*
* @param conn Database connection object (java.sql.Connection)
* @param tableName Name of the database table
*/
public static void printTable(Connection conn, String tableName){
printTable(conn, tableName, DEFAULT_MAX_ROWS, DEFAULT_MAX_TEXT_COL_WIDTH);
}
/**
* Overloaded method that prints rows from table <code>tableName</code>
* to standard out using the given database connection
* <code>conn</code>. Total number of rows will be limited to
* <code>maxRows</code> and
* {@link #DEFAULT_MAX_TEXT_COL_WIDTH} will be used to limit
* the width of text columns (like a <code>VARCHAR</code> column).
*
* @param conn Database connection object (java.sql.Connection)
* @param tableName Name of the database table
* @param maxRows Number of max. rows to query and print
*/
public static void printTable(Connection conn, String tableName, int maxRows) {
printTable(conn, tableName, maxRows, DEFAULT_MAX_TEXT_COL_WIDTH);
}
/**
* Overloaded method that prints rows from table <code>tableName</code>
* to standard out using the given database connection
* <code>conn</code>. Total number of rows will be limited to
* <code>maxRows</code> and
* <code>maxStringColWidth</code> will be used to limit
* the width of text columns (like a <code>VARCHAR</code> column).
*
* @param conn Database connection object (java.sql.Connection)
* @param tableName Name of the database table
* @param maxRows Number of max. rows to query and print
* @param maxStringColWidth Max. width of text columns
*/
public static void printTable(Connection conn, String tableName, int maxRows, int maxStringColWidth) {
if (conn == null) {
System.err.println("DBTablePrinter Error: No connection to database (Connection is null)!");
return;
}
if (tableName == null) {
System.err.println("DBTablePrinter Error: No table name (tableName is null)!");
return;
}
if (tableName.length() == 0) {
System.err.println("DBTablePrinter Error: Empty table name!");
return;
}
if (maxRows < 1) {
System.err.println("DBTablePrinter Info: Invalid max. rows number. Using default!");
maxRows = DEFAULT_MAX_ROWS;
}
Statement stmt = null;
ResultSet rs = null;
try {
if (conn.isClosed()) {
System.err.println("DBTablePrinter Error: Connection is closed!");
return;
}
String sqlSelectAll = "SELECT * FROM " + tableName + " LIMIT " + maxRows;
stmt = conn.createStatement();
rs = stmt.executeQuery(sqlSelectAll);
printResultSet(rs, maxStringColWidth);
} catch (SQLException e) {
System.err.println("SQL exception in DBTablePrinter. Message:");
System.err.println(e.getMessage());
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (rs != null) {
rs.close();
}
} catch (SQLException ignore) {
// ignore
}
}
}
/**
* Overloaded method to print rows of a <a target="_blank"
* href="http://docs.oracle.com/javase/8/docs/api/java/sql/ResultSet.html">
* ResultSet</a> to standard out using {@link #DEFAULT_MAX_TEXT_COL_WIDTH}
* to limit the width of text columns.
*
* @param rs The <code>ResultSet</code> to print
*/
public static void printResultSet(ResultSet rs) {
printResultSet(rs, DEFAULT_MAX_TEXT_COL_WIDTH);
}
/**
* Overloaded method to print rows of a <a target="_blank"
* href="http://docs.oracle.com/javase/8/docs/api/java/sql/ResultSet.html">
* ResultSet</a> to standard out using <code>maxStringColWidth</code>
* to limit the width of text columns.
*
* @param rs The <code>ResultSet</code> to print
* @param maxStringColWidth Max. width of text columns
*/
public static void printResultSet(ResultSet rs, int maxStringColWidth) {
try {
if (rs == null) {
System.err.println("DBTablePrinter Error: Result set is null!");
return;
}
if (rs.isClosed()) {
System.err.println("DBTablePrinter Error: Result Set is closed!");
return;
}
if (maxStringColWidth < 1) {
System.err.println("DBTablePrinter Info: Invalid max. varchar column width. Using default!");
maxStringColWidth = DEFAULT_MAX_TEXT_COL_WIDTH;
}
// Get the meta data object of this ResultSet.
ResultSetMetaData rsmd;
rsmd = rs.getMetaData();
// Total number of columns in this ResultSet
int columnCount = rsmd.getColumnCount();
// List of Column objects to store each columns of the ResultSet
// and the String representation of their values.
List<Column> columns = new ArrayList<>(columnCount);
// List of table names. Can be more than one if it is a joined
// table query
List<String> tableNames = new ArrayList<>(columnCount);
// Get the columns and their meta data.
// NOTE: columnIndex for rsmd.getXXX methods STARTS AT 1 NOT 0
for (int i = 1; i <= columnCount; i++) {
Column c = new Column(rsmd.getColumnLabel(i),
rsmd.getColumnType(i), rsmd.getColumnTypeName(i));
c.setWidth(c.getLabel().length());
c.setTypeCategory(whichCategory(c.getType()));
columns.add(c);
if (!tableNames.contains(rsmd.getTableName(i))) {
tableNames.add(rsmd.getTableName(i));
}
}
// Go through each row, get values of each column and adjust
// column widths.
int rowCount = 0;
while (rs.next()) {
// NOTE: columnIndex for rs.getXXX methods STARTS AT 1 NOT 0
for (int i = 0; i < columnCount; i++) {
Column c = columns.get(i);
String value;
int category = c.getTypeCategory();
if (category == CATEGORY_OTHER) {
// Use generic SQL type name instead of the actual value
// for column types BLOB, BINARY etc.
value = "(" + c.getTypeName() + ")";
} else {
value = rs.getString(i+1) == null ? "NULL" : rs.getString(i+1);
}
switch (category) {
case CATEGORY_DOUBLE:
// For real numbers, format the string value to have 3 digits
// after the point. THIS IS TOTALLY ARBITRARY and can be
// improved to be CONFIGURABLE.
if (!value.equals("NULL")) {
Double dValue = rs.getDouble(i+1);
value = String.format("%.3f", dValue);
}
break;
case CATEGORY_STRING:
// Left justify the text columns
c.justifyLeft();
// and apply the width limit
if (value.length() > maxStringColWidth) {
value = value.substring(0, maxStringColWidth - 3) + "...";
}
break;
}
// Adjust the column width
c.setWidth(value.length() > c.getWidth() ? value.length() : c.getWidth());
c.addValue(value);
} // END of for loop columnCount
rowCount++;
} // END of while (rs.next)
/*
At this point we have gone through meta data, get the
columns and created all Column objects, iterated over the
ResultSet rows, populated the column values and adjusted
the column widths.
We cannot start printing just yet because we have to prepare
a row separator String.
*/
// For the fun of it, I will use StringBuilder
StringBuilder strToPrint = new StringBuilder();
StringBuilder rowSeparator = new StringBuilder();
/*
Prepare column labels to print as well as the row separator.
It should look something like this:
+--------+------------+------------+-----------+ (row separator)
| EMP_NO | BIRTH_DATE | FIRST_NAME | LAST_NAME | (labels row)
+--------+------------+------------+-----------+ (row separator)
*/
// Iterate over columns
for (Column c : columns) {
int width = c.getWidth();
// Center the column label
String toPrint;
String name = c.getLabel();
int diff = width - name.length();
if ((diff%2) == 1) {
// diff is not divisible by 2, add 1 to width (and diff)
// so that we can have equal padding to the left and right
// of the column label.
width++;
diff++;
c.setWidth(width);
}
int paddingSize = diff/2; // InteliJ says casting to int is redundant.
// Cool String repeater code thanks to user102008 at stackoverflow.com
// (http://tinyurl.com/7x9qtyg) "Simple way to repeat a string in java"
String padding = new String(new char[paddingSize]).replace("\0", " ");
toPrint = "| " + padding + name + padding + " ";
// END centering the column label
strToPrint.append(toPrint);
rowSeparator.append("+");
rowSeparator.append(new String(new char[width + 2]).replace("\0", "-"));
}
String lineSeparator = System.getProperty("line.separator");
// Is this really necessary ??
lineSeparator = lineSeparator == null ? "\n" : lineSeparator;
rowSeparator.append("+").append(lineSeparator);
strToPrint.append("|").append(lineSeparator);
strToPrint.insert(0, rowSeparator);
strToPrint.append(rowSeparator);
StringJoiner sj = new StringJoiner(", ");
for (String name : tableNames) {
sj.add(name);
}
String info = "Printing " + rowCount;
info += rowCount > 1 ? " rows from " : " row from ";
info += tableNames.size() > 1 ? "tables " : "table ";
info += sj.toString();
System.out.println(info);
// Print out the formatted column labels
System.out.print(strToPrint.toString());
String format;
// Print out the rows
for (int i = 0; i < rowCount; i++) {
for (Column c : columns) {
// This should form a format string like: "%-60s"
format = String.format("| %%%s%ds ", c.getJustifyFlag(), c.getWidth());
System.out.print(
String.format(format, c.getValue(i))
);
}
System.out.println("|");
System.out.print(rowSeparator);
}
System.out.println();
} catch (SQLException e) {
System.err.println("SQL exception in DBTablePrinter. Message:");
System.err.println(e.getMessage());
}
}
/**
* Takes a generic SQL type and returns the category this type
* belongs to. Types are categorized according to print formatting
* needs:
* <p>
* Integers should not be truncated so column widths should
* be adjusted without a column width limit. Text columns should be
* left justified and can be truncated to a max. column width etc...</p>
*
* See also: <a target="_blank"
* href="http://docs.oracle.com/javase/8/docs/api/java/sql/Types.html">
* java.sql.Types</a>
*
* @param type Generic SQL type
* @return The category this type belongs to
*/
private static int whichCategory(int type) {
switch (type) {
case Types.BIGINT:
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
return CATEGORY_INTEGER;
case Types.REAL:
case Types.DOUBLE:
case Types.DECIMAL:
return CATEGORY_DOUBLE;
case Types.DATE:
case Types.TIME:
case Types.TIME_WITH_TIMEZONE:
case Types.TIMESTAMP:
case Types.TIMESTAMP_WITH_TIMEZONE:
return CATEGORY_DATETIME;
case Types.BOOLEAN:
return CATEGORY_BOOLEAN;
case Types.VARCHAR:
case Types.NVARCHAR:
case Types.LONGVARCHAR:
case Types.LONGNVARCHAR:
case Types.CHAR:
case Types.NCHAR:
return CATEGORY_STRING;
default:
return CATEGORY_OTHER;
}
}
}