Skip to content

Commit

Permalink
Added formatters to output: text, html and csv
Browse files Browse the repository at this point in the history
  • Loading branch information
jdlopez committed Mar 16, 2022
1 parent b1786c4 commit 690d7f0
Show file tree
Hide file tree
Showing 10 changed files with 272 additions and 35 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ Usage:
FROM MY_TABLE
EOF

If _mailSendTo_ configured the tool sends an email with formatted output.

## Config values:

* jdbcDriverPath=Path to jdbc driver jar (loaded dynamically) if null it must be in classpath
Expand All @@ -19,8 +21,11 @@ Usage:
* jdbcPass=
* inputSQL=Path to input sql file (not required/optional if not present it uses stdin)
* outputResult=Path to output file (if not present uses stdout)

## Printing and formatting values:
* printHeader=true/false If true adds header with query's column name. Default true
* printFieldSeparator=Field separator for printing. Default tab (\t)
* formatterName=Formatter type, possible values: text, html or csv (default text)

## Mail config values:

Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>io.github.jdlopez</groupId>
<artifactId>sqlcmd</artifactId>
<version>1.1</version>
<version>1.1.1</version>

<dependencies>
<dependency>
Expand Down
59 changes: 59 additions & 0 deletions src/main/java/es/jdlopez/sqlcmd/CsvFormatter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package es.jdlopez.sqlcmd;

import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class CsvFormatter extends ResultFormatter {
private RunnerConfig conf;

public CsvFormatter(RunnerConfig c) {
this.conf = c;
}

@Override
public void writeHeader(PrintWriter out, ResultSetMetaData rsmd) throws SQLException {
int colCount = rsmd.getColumnCount();
if (conf.getPrintHeader()) {
for (int i = 1; i <= colCount; i++) {
out.print(rsmd.getColumnName(i));
if (i < colCount) {
out.print(conf.getPrintFieldSeparator());
}
}
out.println();
} // header

}

@Override
public void writeRow(PrintWriter out, ResultSet resultSet, int colCount) throws SQLException {
for (int i = 1; i <= colCount; i++) {
out.print(resultSet.getString(i));
if (i < colCount)
out.print(conf.getPrintFieldSeparator());
} // for col
out.println();
}

@Override
public void writeEndResultSet(PrintWriter out) {
// nothing needed
}

@Override
public void writeBeginResultSet(PrintWriter out) {
// nothing needed
}

@Override
public void writeUpdate(PrintWriter out, int updateCount) {
out.println(updateCount);
}

@Override
public String getMime() {
return "text/csv";
}
}
57 changes: 57 additions & 0 deletions src/main/java/es/jdlopez/sqlcmd/HtmlFormatter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package es.jdlopez.sqlcmd;

import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

// TODO: put all html code in configurable templates
public class HtmlFormatter extends ResultFormatter {
private RunnerConfig conf;

public HtmlFormatter(RunnerConfig c) {
this.conf = c;
}

@Override
public void writeHeader(PrintWriter out, ResultSetMetaData rsmd) throws SQLException {
if (conf.getPrintHeader()) { // this check must be on MainRunner :-(
int colCount = rsmd.getColumnCount();
// add thead tag???
out.println("<tr>");
for (int i = 1; i <= colCount; i++) {
out.print(String.format("<th>%s</th>", rsmd.getColumnName(i)));
}
out.println("</tr>");
} // header
}

@Override
public void writeRow(PrintWriter out, ResultSet resultSet, int colCount) throws SQLException {
out.println("<tr>");
for (int i = 1; i <= colCount; i++) {
out.print(String.format("<td>%s</td>", resultSet.getString(i)));
} // for col
out.println("</tr>");
}

@Override
public void writeBeginResultSet(PrintWriter out) {
out.println("<table>");
}

@Override
public void writeEndResultSet(PrintWriter out) {
out.println("</table>");
}

@Override
public void writeUpdate(PrintWriter out, int updateCount) {
out.println(String.format("<hr/>UpdateCount: %d<hr/>", updateCount));
}

@Override
public String getMime() {
return "text/html";
}
}
46 changes: 14 additions & 32 deletions src/main/java/es/jdlopez/sqlcmd/MainRunner.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
Expand Down Expand Up @@ -81,7 +80,11 @@ else if (config.getOutputResult() == null)
config.getMailPort(),
config.getMailFrom());
}
sendMail.sendText(config.getMailSubject(), mailBody.toString(), config.getMailSendTo());
if (ResultFormatter.HTML.equalsIgnoreCase(config.getFormatterName()))
sendMail.sendMime(config.buildFormatter().getMime(),
config.getMailSubject(), mailBody.toString(), config.getMailSendTo());
else // careful 'no object DCH for MIME type csv or others needs activation
sendMail.sendText(config.getMailSubject(), mailBody.toString(), config.getMailSendTo());
}

} finally {
Expand All @@ -91,44 +94,21 @@ else if (config.getOutputResult() == null)
}

private static void writeUpdateCount(int updateCount, PrintWriter out, RunnerConfig config) {
String s;
if (config.getPrintHeader())
s = String.format("==================\nUpdateCount = %d\n==================", updateCount);
else
s = "UpdateCount = " + updateCount;
out.println(s);

ResultFormatter fmt = config.buildFormatter();
fmt.writeUpdate(out, updateCount);
}

private static void writeResultSet(ResultSet resultSet, PrintWriter out, RunnerConfig conf) throws SQLException {
ResultSetMetaData rsmd = resultSet.getMetaData();
int colCount = rsmd.getColumnCount();
if (conf.getPrintHeader()) {
StringBuffer underline = new StringBuffer();
for (int i = 1; i <= colCount; i++) {
out.print(rsmd.getColumnName(i));
underline.append(repeatChar('=', rsmd.getColumnName(i).length()));
if (i < colCount) {
out.print(conf.getPrintFieldSeparator());
underline.append(conf.getPrintFieldSeparator());
}
}
out.println();
out.println(underline.toString());
} // header
ResultFormatter fmt = conf.buildFormatter();
fmt.writeBeginResultSet(out);
fmt.writeHeader(out, rsmd);
while (resultSet.next()) {
for (int i = 1; i <= colCount; i++) {
out.print(resultSet.getString(i));
if (i < colCount)
out.print(conf.getPrintFieldSeparator());
} // for col
out.println();
fmt.writeRow(out, resultSet, colCount);
} // while row
out.flush();
}

private static String repeatChar(char c, int length) {
return new String(new char[length]).replace('\0', c);
fmt.writeEndResultSet(out);
}

private static String readAll(InputStream in) throws IOException {
Expand Down Expand Up @@ -169,6 +149,8 @@ private static RunnerConfig readArgs(String[] args) throws ConfigException {
conf.setPrintFieldSeparator("\t");
if (conf.getPrintHeader() == null)
conf.setPrintHeader(true);
if (conf.getFormatterName() == null)
conf.setFormatterName("text");
return conf;
}
}
30 changes: 30 additions & 0 deletions src/main/java/es/jdlopez/sqlcmd/ResultFormatter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package es.jdlopez.sqlcmd;

import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public abstract class ResultFormatter {

public static final String TEXT = "text";
public static final String HTML = "html";
public static final String CSV = "csv";

public abstract void writeHeader(PrintWriter out, ResultSetMetaData rsmd) throws SQLException;

public abstract void writeRow(PrintWriter out, ResultSet resultSet, int colCount) throws SQLException;

public abstract void writeEndResultSet(PrintWriter out);

public abstract void writeUpdate(PrintWriter out, int updateCount);

public abstract void writeBeginResultSet(PrintWriter out);

public abstract String getMime();

public static String repeatChar(char c, int length) {
return new String(new char[length]).replace('\0', c);
}

}
23 changes: 23 additions & 0 deletions src/main/java/es/jdlopez/sqlcmd/RunnerConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,21 @@ public class RunnerConfig {
private String mailPass;
private String mailFrom;
private String mailSubject;
private String formatterName;

private ResultFormatter formatter = null;
public ResultFormatter buildFormatter() {
if (formatter == null) {
if (ResultFormatter.HTML.equalsIgnoreCase(formatterName))
formatter = new HtmlFormatter(this);
else if (ResultFormatter.CSV.equalsIgnoreCase(formatterName))
formatter = new CsvFormatter(this);
//if (ResultFormatter.TEXT.equalsIgnoreCase(formatterName))
else
formatter = new TextFormatter(this);
}
return formatter;
}

public String getInputSQL() {
return inputSQL;
Expand Down Expand Up @@ -164,4 +179,12 @@ public String getMailSubject() {
public void setMailSubject(String mailSubject) {
this.mailSubject = mailSubject;
}

public String getFormatterName() {
return formatterName;
}

public void setFormatterName(String formatterName) {
this.formatterName = formatterName;
}
}
10 changes: 10 additions & 0 deletions src/main/java/es/jdlopez/sqlcmd/SendMail.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,14 @@ public void sendText(String subject, String body, String to) throws MessagingExc

Transport.send(msg);
}

public void sendMime(String mime, String subject, String body, String to) throws MessagingException {
Session session = Session.getInstance(sessionProps, auth);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
msg.setSubject(subject);
msg.setContent(body, mime);
Transport.send(msg);
}
}
68 changes: 68 additions & 0 deletions src/main/java/es/jdlopez/sqlcmd/TextFormatter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package es.jdlopez.sqlcmd;

import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class TextFormatter extends ResultFormatter {
private RunnerConfig conf;

public TextFormatter(RunnerConfig c) {
this.conf = c;
}

@Override
public void writeHeader(PrintWriter out, ResultSetMetaData rsmd) throws SQLException {
int colCount = rsmd.getColumnCount();
if (conf.getPrintHeader()) {
StringBuffer underline = new StringBuffer();
for (int i = 1; i <= colCount; i++) {
out.print(rsmd.getColumnName(i));
underline.append(repeatChar('=', rsmd.getColumnName(i).length()));
if (i < colCount) {
out.print(conf.getPrintFieldSeparator());
underline.append(conf.getPrintFieldSeparator());
}
}
out.println();
out.println(underline.toString());
} // header

}

@Override
public void writeRow(PrintWriter out, ResultSet resultSet, int colCount) throws SQLException {
for (int i = 1; i <= colCount; i++) {
out.print(resultSet.getString(i));
if (i < colCount)
out.print(conf.getPrintFieldSeparator());
} // for col
out.println();
}

@Override
public void writeEndResultSet(PrintWriter out) {
// nothing needed
}

@Override
public void writeBeginResultSet(PrintWriter out) {
// nothing needed
}

@Override
public void writeUpdate(PrintWriter out, int updateCount) {
String s;
if (conf.getPrintHeader())
s = String.format("==================\nUpdateCount = %d\n==================", updateCount);
else
s = "UpdateCount = " + updateCount;
out.println(s);
}

@Override
public String getMime() {
return "text/plain";
}
}
7 changes: 5 additions & 2 deletions src/test/resources/sample.properties
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@ jdbcUser=SA
jdbcPass=

# mail config
mailFrom=[email protected]
mailSubject=SqlCmd subject sent
mailSendTo=[email protected]
mailSubject=SqlCmd subject sent
# mail server
mailFrom=[email protected]
mailHost=localhost
mailPort=25

formatterName=html

0 comments on commit 690d7f0

Please sign in to comment.