# HG changeset patch
# User Joeri van Ruth <joeri.van.ruth@monetdbsolutions.com>
# Date 1629382372 -7200
# Node ID 13b48891ac54477cf90bb3e95df6afb8758c903f
# Parent  4554977830266ec2381038cca8635210ec2dd322
add getStream to DownloadHandle

diff --git a/src/main/java/org/monetdb/jdbc/MonetConnection.java b/src/main/java/org/monetdb/jdbc/MonetConnection.java
--- a/src/main/java/org/monetdb/jdbc/MonetConnection.java
+++ b/src/main/java/org/monetdb/jdbc/MonetConnection.java
@@ -3254,17 +3254,13 @@ public class MonetConnection
 		}
 
 		MonetDownloadHandle handle = new MonetDownloadHandle(server);
-		try {
-			downloader.handleDownload(handle, path, true);
-			if (!handle.hasBeenUsed()) {
-				String message = String.format("Call to %s.handleDownload for path '%s' sent neither data nor an error message",
-						downloader.getClass().getCanonicalName(), path);
-				throw new IOException(message);
-			}
-			handle.close();
-		} finally {
-			//
+		downloader.handleDownload(handle, path, true);
+		if (!handle.hasBeenUsed()) {
+			String message = String.format("Call to %s.handleDownload for path '%s' sent neither data nor an error message",
+					downloader.getClass().getCanonicalName(), path);
+			throw new IOException(message);
 		}
+		handle.close();
 		return handle.getError();
 	}
 }
diff --git a/src/main/java/org/monetdb/jdbc/MonetDownloadHandle.java b/src/main/java/org/monetdb/jdbc/MonetDownloadHandle.java
--- a/src/main/java/org/monetdb/jdbc/MonetDownloadHandle.java
+++ b/src/main/java/org/monetdb/jdbc/MonetDownloadHandle.java
@@ -6,7 +6,9 @@ import java.io.*;
 
 public class MonetDownloadHandle {
 	private final MapiSocket server;
+	private MapiSocket.DownloadStream stream = null;
 	private String error = null;
+	boolean closed = false;
 
 	MonetDownloadHandle(MapiSocket server) {
 		this.server = server;
@@ -19,14 +21,33 @@ public class MonetDownloadHandle {
 		error = errorMessage;
 	}
 
+	public InputStream getStream() throws IOException {
+		if (error != null) {
+			throw new IOException("cannot receive data after error has been sent");
+		}
+		if (stream == null) {
+			stream = server.downloadStream();
+			server.getOutputStream().write('\n');
+			server.getOutputStream().flush();
+		}
+		return stream;
+	}
+
 	public boolean hasBeenUsed() {
-		return error != null;
+		return error != null || stream != null;
 	}
 
 	public String getError() {
 		return error;
 	}
 
-	public void close() {
+	public void close() throws IOException {
+		if (closed) {
+			return;
+		}
+		if (stream != null) {
+			stream.close();
+		}
+		closed = true;
 	}
 }