/* * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, * and the EPL 1.0 (https://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.tools; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.ArrayList; import org.h2.api.ErrorCode; import org.h2.engine.Constants; import org.h2.message.DbException; import org.h2.mvstore.DataUtils; import org.h2.store.fs.FileUtils; import org.h2.util.IOUtils; import org.h2.util.JdbcUtils; import org.h2.util.StringUtils; import org.h2.util.Utils; /** * A facility to read from and write to CSV (comma separated values) files. When * reading, the BOM (the byte-order-mark) character 0xfeff at the beginning of * the file is ignored. * * @author Thomas Mueller, Sylvain Cuaz */ public class Csv implements SimpleRowSource { private String[] columnNames; private String characterSet; private char escapeCharacter = '\"'; private char fieldDelimiter = '\"'; private char fieldSeparatorRead = ','; private String fieldSeparatorWrite = ","; private boolean caseSensitiveColumnNames; private boolean preserveWhitespace; private boolean writeColumnHeader = true; private char lineComment; private String lineSeparator = System.lineSeparator(); private String nullString = ""; private String fileName; private BufferedReader input; private char[] inputBuffer; private int inputBufferPos; private int inputBufferStart = -1; private int inputBufferEnd; private Writer output; private boolean endOfLine, endOfFile; private int writeResultSet(ResultSet rs) throws SQLException { try { int rows = 0; ResultSetMetaData meta = rs.getMetaData(); int columnCount = meta.getColumnCount(); String[] row = new String[columnCount]; for (int i = 0; i < columnCount; i++) { row[i] = meta.getColumnLabel(i + 1); } if (writeColumnHeader) { writeRow(row); } while (rs.next()) { for (int i = 0; i < columnCount; i++) { row[i] = rs.getString(i + 1); } writeRow(row); rows++; } output.close(); return rows; } catch (IOException e) { throw DbException.convertIOException(e, null); } finally { close(); JdbcUtils.closeSilently(rs); } } /** * Writes the result set to a file in the CSV format. * * @param writer the writer * @param rs the result set * @return the number of rows written * @throws SQLException on failure */ public int write(Writer writer, ResultSet rs) throws SQLException { this.output = writer; return writeResultSet(rs); } /** * Writes the result set to a file in the CSV format. The result set is read * using the following loop: * *
* while (rs.next()) {
* writeRow(row);
* }
*
*
* @param outputFileName the name of the csv file
* @param rs the result set - the result set must be positioned before the
* first row.
* @param charset the charset or null to use the system default charset
* @return the number of rows written
* @throws SQLException on failure
*/
public int write(String outputFileName, ResultSet rs, String charset)
throws SQLException {
init(outputFileName, charset);
try {
initWrite();
return writeResultSet(rs);
} catch (IOException e) {
throw convertException("IOException writing " + outputFileName, e);
}
}
/**
* Writes the result set of a query to a file in the CSV format.
*
* @param conn the connection
* @param outputFileName the file name
* @param sql the query
* @param charset the charset or null to use the system default charset
* (see system property file.encoding)
* @return the number of rows written
* @throws SQLException on failure
*/
public int write(Connection conn, String outputFileName, String sql,
String charset) throws SQLException {
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery(sql);
int rows = write(outputFileName, rs, charset);
stat.close();
return rows;
}
/**
* Reads from the CSV file and returns a result set. The rows in the result
* set are created on demand, that means the file is kept open until all
* rows are read or the result set is closed.
*
* If the columns are read from the CSV file, then the following rules are
* used: columns names that start with a letter or '_', and only
* contain letters, '_', and digits, are considered case insensitive
* and are converted to uppercase. Other column names are considered
* case sensitive (that means they need to be quoted when accessed).
*
* @param inputFileName the file name
* @param colNames or null if the column names should be read from the CSV
* file
* @param charset the charset or null to use the system default charset
* @return the result set
* @throws SQLException on failure
*/
public ResultSet read(String inputFileName, String[] colNames,
String charset) throws SQLException {
init(inputFileName, charset);
try {
return readResultSet(colNames);
} catch (IOException e) {
throw convertException("IOException reading " + inputFileName, e);
}
}
/**
* Reads CSV data from a reader and returns a result set. The rows in the
* result set are created on demand, that means the reader is kept open
* until all rows are read or the result set is closed.
*
* @param reader the reader
* @param colNames or null if the column names should be read from the CSV
* file
* @return the result set
* @throws IOException on failure
*/
public ResultSet read(Reader reader, String[] colNames) throws IOException {
init(null, null);
this.input = reader instanceof BufferedReader ? (BufferedReader) reader
: new BufferedReader(reader, Constants.IO_BUFFER_SIZE);
return readResultSet(colNames);
}
private ResultSet readResultSet(String[] colNames) throws IOException {
this.columnNames = colNames;
initRead();
SimpleResultSet result = new SimpleResultSet(this);
makeColumnNamesUnique();
for (String columnName : columnNames) {
result.addColumn(columnName, Types.VARCHAR, Integer.MAX_VALUE, 0);
}
return result;
}
private void makeColumnNamesUnique() {
for (int i = 0; i < columnNames.length; i++) {
StringBuilder buff = new StringBuilder();
String n = columnNames[i];
if (n == null || n.isEmpty()) {
buff.append('C').append(i + 1);
} else {
buff.append(n);
}
for (int j = 0; j < i; j++) {
String y = columnNames[j];
if (buff.toString().equals(y)) {
buff.append('1');
j = -1;
}
}
columnNames[i] = buff.toString();
}
}
private void init(String newFileName, String charset) {
this.fileName = newFileName;
this.characterSet = charset;
}
private void initWrite() throws IOException {
if (output == null) {
try {
OutputStream out = FileUtils.newOutputStream(fileName, false);
out = new BufferedOutputStream(out, Constants.IO_BUFFER_SIZE);
output = new BufferedWriter(characterSet != null ?
new OutputStreamWriter(out, characterSet) : new OutputStreamWriter(out));
} catch (Exception e) {
close();
throw DataUtils.convertToIOException(e);
}
}
}
private void writeRow(String[] values) throws IOException {
for (int i = 0; i < values.length; i++) {
if (i > 0) {
if (fieldSeparatorWrite != null) {
output.write(fieldSeparatorWrite);
}
}
String s = values[i];
if (s != null) {
if (escapeCharacter != 0) {
if (fieldDelimiter != 0) {
output.write(fieldDelimiter);
}
output.write(escape(s));
if (fieldDelimiter != 0) {
output.write(fieldDelimiter);
}
} else {
output.write(s);
}
} else if (nullString != null && nullString.length() > 0) {
output.write(nullString);
}
}
output.write(lineSeparator);
}
private String escape(String data) {
if (data.indexOf(fieldDelimiter) < 0) {
if (escapeCharacter == fieldDelimiter || data.indexOf(escapeCharacter) < 0) {
return data;
}
}
int length = data.length();
StringBuilder buff = new StringBuilder(length);
for (int i = 0; i < length; i++) {
char ch = data.charAt(i);
if (ch == fieldDelimiter || ch == escapeCharacter) {
buff.append(escapeCharacter);
}
buff.append(ch);
}
return buff.toString();
}
private void initRead() throws IOException {
if (input == null) {
try {
input = FileUtils.newBufferedReader(fileName,
characterSet != null ? Charset.forName(characterSet) : StandardCharsets.UTF_8);
} catch (IOException e) {
close();
throw e;
}
}
input.mark(1);
int bom = input.read();
if (bom != 0xfeff) {
// Microsoft Excel compatibility
// ignore pseudo-BOM
input.reset();
}
inputBuffer = new char[Constants.IO_BUFFER_SIZE * 2];
if (columnNames == null) {
readHeader();
}
}
private void readHeader() throws IOException {
ArrayList
* Data: He said "Hello".
* Escape character: "
* Field delimiter: "
* CSV file: "He said ""Hello""."
*
* If the field delimiter is a double quote and the escape character is a
* backslash, then escaping is done similar to Java (however, only the field
* delimiter is escaped). Example:
*
* Data: He said "Hello".
* Escape character: \
* Field delimiter: "
* CSV file: "He said \"Hello\"."
*
* The value 0 means no escape character is used.
*
* @param escapeCharacter the escape character
*/
public void setEscapeCharacter(char escapeCharacter) {
this.escapeCharacter = escapeCharacter;
}
/**
* Get the current escape character.
*
* @return the escape character
*/
public char getEscapeCharacter() {
return escapeCharacter;
}
/**
* Set the line separator used for writing. This is usually a line feed (\n
* or \r\n depending on the system settings). The line separator is written
* after each row (including the last row), so this option can include an
* end-of-row marker if needed.
*
* @param lineSeparator the line separator
*/
public void setLineSeparator(String lineSeparator) {
this.lineSeparator = lineSeparator;
}
/**
* Get the line separator used for writing.
*
* @return the line separator
*/
public String getLineSeparator() {
return lineSeparator;
}
/**
* Set the value that represents NULL. It is only used for non-delimited
* values.
*
* @param nullString the null
*/
public void setNullString(String nullString) {
this.nullString = nullString;
}
/**
* Get the current null string.
*
* @return the null string.
*/
public String getNullString() {
return nullString;
}
/**
* Enable or disable preserving whitespace in unquoted text.
*
* @param value the new value for the setting
*/
public void setPreserveWhitespace(boolean value) {
this.preserveWhitespace = value;
}
/**
* Whether whitespace in unquoted text is preserved.
*
* @return the current value for the setting
*/
public boolean getPreserveWhitespace() {
return preserveWhitespace;
}
/**
* Enable or disable writing the column header.
*
* @param value the new value for the setting
*/
public void setWriteColumnHeader(boolean value) {
this.writeColumnHeader = value;
}
/**
* Whether the column header is written.
*
* @return the current value for the setting
*/
public boolean getWriteColumnHeader() {
return writeColumnHeader;
}
/**
* INTERNAL.
* Parse and set the CSV options.
*
* @param options the options
* @return the character set
*/
public String setOptions(String options) {
String charset = null;
String[] keyValuePairs = StringUtils.arraySplit(options, ' ', false);
for (String pair : keyValuePairs) {
if (pair.isEmpty()) {
continue;
}
int index = pair.indexOf('=');
String key = StringUtils.trimSubstring(pair, 0, index);
String value = pair.substring(index + 1);
char ch = value.isEmpty() ? 0 : value.charAt(0);
if (isParam(key, "escape", "esc", "escapeCharacter")) {
setEscapeCharacter(ch);
} else if (isParam(key, "fieldDelimiter", "fieldDelim")) {
setFieldDelimiter(ch);
} else if (isParam(key, "fieldSeparator", "fieldSep")) {
setFieldSeparatorRead(ch);
setFieldSeparatorWrite(value);
} else if (isParam(key, "lineComment", "lineCommentCharacter")) {
setLineCommentCharacter(ch);
} else if (isParam(key, "lineSeparator", "lineSep")) {
setLineSeparator(value);
} else if (isParam(key, "null", "nullString")) {
setNullString(value);
} else if (isParam(key, "charset", "characterSet")) {
charset = value;
} else if (isParam(key, "preserveWhitespace")) {
setPreserveWhitespace(Utils.parseBoolean(value, false, false));
} else if (isParam(key, "writeColumnHeader")) {
setWriteColumnHeader(Utils.parseBoolean(value, true, false));
} else if (isParam(key, "caseSensitiveColumnNames")) {
setCaseSensitiveColumnNames(Utils.parseBoolean(value, false, false));
} else {
throw DbException.getUnsupportedException(key);
}
}
return charset;
}
private static boolean isParam(String key, String... values) {
for (String v : values) {
if (key.equalsIgnoreCase(v)) {
return true;
}
}
return false;
}
}