Skip to content

Instantly share code, notes, and snippets.

@michelmilezzi
Created November 28, 2017 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michelmilezzi/e35cc4ad257893043fc9bff1b91c3c0f to your computer and use it in GitHub Desktop.
Save michelmilezzi/e35cc4ad257893043fc9bff1b91c3c0f to your computer and use it in GitHub Desktop.
A simple java class to get PostgreSQL COPY content from STDOUT to compressed file
package br.com.michelmilezzi.database.data;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.postgresql.PGConnection;
import org.postgresql.copy.PGCopyInputStream;
public final class DataCopyManager {
private static final byte[] BUFFER = new byte[1024*16];
private DataCopyManager() {
}
public static void copyDataToCompressedCSVFile(final Connection conn,
final String sql,
final String compressedFilename,
final File destinationFile) throws SQLException, IOException {
final PGConnection pgConn = prepareConnection(conn);
try (PGCopyInputStream originCopyInStream = new PGCopyInputStream(pgConn, getCopyToCSVCommand(sql));
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destinationFile))) {
ZipEntry ze = new ZipEntry(compressedFilename);
zos.putNextEntry(ze);
int len;
while ((len = originCopyInStream.read(BUFFER)) > 0) {
zos.write(BUFFER, 0, len);
}
zos.closeEntry();
}
}
private static String getCopyToCSVCommand(final String sql) {
return String.format("COPY (%s) TO STDOUT WITH CSV ENCODING 'UTF-8'", sql);
}
private static PGConnection prepareConnection(final Connection conn) throws SQLException {
return conn.unwrap(PGConnection.class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment