forked from databricks/databricks-jdbc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInlineChunkProvider.java
More file actions
225 lines (204 loc) · 7.7 KB
/
InlineChunkProvider.java
File metadata and controls
225 lines (204 loc) · 7.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package com.databricks.jdbc.api.impl.arrow;
import static com.databricks.jdbc.common.util.DatabricksTypeUtil.*;
import static com.databricks.jdbc.common.util.DecompressionUtil.decompress;
import com.databricks.jdbc.api.internal.IDatabricksSession;
import com.databricks.jdbc.api.internal.IDatabricksStatementInternal;
import com.databricks.jdbc.common.CompressionCodec;
import com.databricks.jdbc.exception.DatabricksParsingException;
import com.databricks.jdbc.exception.DatabricksSQLException;
import com.databricks.jdbc.log.JdbcLogger;
import com.databricks.jdbc.log.JdbcLoggerFactory;
import com.databricks.jdbc.model.client.thrift.generated.*;
import com.databricks.jdbc.model.core.ResultData;
import com.databricks.jdbc.model.core.ResultManifest;
import com.databricks.jdbc.model.telemetry.enums.DatabricksDriverErrorCode;
import com.google.common.annotations.VisibleForTesting;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.arrow.vector.types.pojo.ArrowType;
import org.apache.arrow.vector.types.pojo.Field;
import org.apache.arrow.vector.types.pojo.FieldType;
import org.apache.arrow.vector.types.pojo.Schema;
import org.apache.arrow.vector.util.SchemaUtility;
/** Class to manage inline Arrow chunks */
public class InlineChunkProvider implements ChunkProvider {
private static final JdbcLogger LOGGER = JdbcLoggerFactory.getLogger(InlineChunkProvider.class);
private long totalRows;
private long currentChunkIndex;
private boolean isClosed;
private final ArrowResultChunk
arrowResultChunk; // There is only one packet of data in case of inline arrow
InlineChunkProvider(
TFetchResultsResp resultsResp,
IDatabricksStatementInternal parentStatement,
IDatabricksSession session)
throws DatabricksParsingException {
this.currentChunkIndex = -1;
this.totalRows = 0;
ByteArrayInputStream byteStream = initializeByteStream(resultsResp, session, parentStatement);
ArrowResultChunk.Builder builder =
ArrowResultChunk.builder().withInputStream(byteStream, totalRows);
if (parentStatement != null) {
builder.withStatementId(parentStatement.getStatementId());
}
arrowResultChunk = builder.build();
}
/**
* Constructor for inline arrow chunk provider from {@link ResultData} and {@link ResultManifest}.
*
* @param resultData Data object containing the result data
* @param resultManifest Manifest object containing the result metadata
* @throws DatabricksSQLException if there is an error in processing the inline arrow data
*/
InlineChunkProvider(ResultData resultData, ResultManifest resultManifest)
throws DatabricksSQLException {
this.currentChunkIndex = -1;
this.totalRows = resultManifest.getTotalRowCount();
// Decompress the inline data if applicable and create an ArrowResultChunk
CompressionCodec compressionType = resultManifest.getResultCompression();
byte[] decompressedBytes =
decompress(
resultData.getAttachment(),
compressionType,
"Data fetch for inline arrow batch with decompression algorithm : " + compressionType);
this.arrowResultChunk =
ArrowResultChunk.builder()
.withInputStream(new ByteArrayInputStream(decompressedBytes), totalRows)
.build();
}
/** {@inheritDoc} */
@Override
public boolean hasNextChunk() {
return this.currentChunkIndex == -1;
}
/** {@inheritDoc} */
@Override
public boolean next() {
if (!hasNextChunk()) {
return false;
}
this.currentChunkIndex++;
return true;
}
/** {@inheritDoc} */
@Override
public ArrowResultChunk getChunk() {
return arrowResultChunk;
}
/** {@inheritDoc} */
@Override
public void close() {
isClosed = true;
arrowResultChunk.releaseChunk();
}
@Override
public long getRowCount() {
return totalRows;
}
@Override
public long getChunkCount() {
return 0;
}
@Override
public boolean isClosed() {
return isClosed;
}
private ByteArrayInputStream initializeByteStream(
TFetchResultsResp resultsResp,
IDatabricksSession session,
IDatabricksStatementInternal parentStatement)
throws DatabricksParsingException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CompressionCodec compressionType =
CompressionCodec.getCompressionMapping(resultsResp.getResultSetMetadata());
try {
byte[] serializedSchema = getSerializedSchema(resultsResp.getResultSetMetadata());
if (serializedSchema != null) {
baos.write(serializedSchema);
}
writeToByteOutputStream(
compressionType, parentStatement, resultsResp.getResults().getArrowBatches(), baos);
while (resultsResp.hasMoreRows) {
resultsResp = session.getDatabricksClient().getMoreResults(parentStatement);
writeToByteOutputStream(
compressionType, parentStatement, resultsResp.getResults().getArrowBatches(), baos);
}
return new ByteArrayInputStream(baos.toByteArray());
} catch (DatabricksSQLException | IOException e) {
handleError(e);
}
return null;
}
private void writeToByteOutputStream(
CompressionCodec compressionCodec,
IDatabricksStatementInternal parentStatement,
List<TSparkArrowBatch> arrowBatchList,
ByteArrayOutputStream baos)
throws DatabricksSQLException, IOException {
for (TSparkArrowBatch arrowBatch : arrowBatchList) {
byte[] decompressedBytes =
decompress(
arrowBatch.getBatch(),
compressionCodec,
String.format(
"Data fetch for inline arrow batch [%d] and statement [%s] with decompression algorithm : [%s]",
arrowBatch.getRowCount(), parentStatement, compressionCodec));
totalRows += arrowBatch.getRowCount();
baos.write(decompressedBytes);
}
}
private byte[] getSerializedSchema(TGetResultSetMetadataResp metadata)
throws DatabricksSQLException {
if (metadata.getArrowSchema() != null) {
return metadata.getArrowSchema();
}
Schema arrowSchema = hiveSchemaToArrowSchema(metadata.getSchema());
try {
return SchemaUtility.serialize(arrowSchema);
} catch (IOException e) {
handleError(e);
}
// should never reach here;
return null;
}
private Schema hiveSchemaToArrowSchema(TTableSchema hiveSchema)
throws DatabricksParsingException {
List<Field> fields = new ArrayList<>();
if (hiveSchema == null) {
return new Schema(fields);
}
try {
hiveSchema
.getColumns()
.forEach(
columnDesc -> {
try {
fields.add(getArrowField(columnDesc));
} catch (SQLException e) {
throw new RuntimeException(e);
}
});
} catch (RuntimeException e) {
handleError(e);
}
return new Schema(fields);
}
private Field getArrowField(TColumnDesc columnDesc) throws SQLException {
TPrimitiveTypeEntry primitiveTypeEntry = getTPrimitiveTypeOrDefault(columnDesc.getTypeDesc());
ArrowType arrowType = mapThriftToArrowType(primitiveTypeEntry.getType());
FieldType fieldType = new FieldType(true, arrowType, null);
return new Field(columnDesc.getColumnName(), fieldType, null);
}
@VisibleForTesting
void handleError(Exception e) throws DatabricksParsingException {
String errorMessage =
String.format("Cannot process inline arrow format. Error: %s", e.getMessage());
LOGGER.error(errorMessage);
throw new DatabricksParsingException(
errorMessage, e, DatabricksDriverErrorCode.INLINE_CHUNK_PARSING_ERROR);
}
}