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