|
7 | 7 | import static com.databricks.jdbc.common.util.SQLInterpolator.surroundPlaceholdersWithQuotes; |
8 | 8 | import static com.databricks.jdbc.common.util.ValidationUtil.throwErrorIfNull; |
9 | 9 |
|
| 10 | +import com.databricks.jdbc.common.DatabricksJdbcConstants; |
10 | 11 | import com.databricks.jdbc.common.StatementType; |
11 | 12 | import com.databricks.jdbc.common.util.DatabricksTypeUtil; |
| 13 | +import com.databricks.jdbc.common.util.InsertStatementParser; |
12 | 14 | import com.databricks.jdbc.exception.*; |
13 | 15 | import com.databricks.jdbc.log.JdbcLogger; |
14 | 16 | import com.databricks.jdbc.log.JdbcLoggerFactory; |
@@ -88,6 +90,138 @@ public int[] executeBatch() throws DatabricksBatchUpdateException { |
88 | 90 | @Override |
89 | 91 | public long[] executeLargeBatch() throws DatabricksBatchUpdateException { |
90 | 92 | LOGGER.debug("public long executeLargeBatch()"); |
| 93 | + |
| 94 | + if (databricksBatchParameterMetaData.isEmpty()) { |
| 95 | + return new long[0]; |
| 96 | + } |
| 97 | + |
| 98 | + // Try to optimize INSERT statements with multi-row batching |
| 99 | + if (canUseBatchedInsert()) { |
| 100 | + return executeBatchedInsert(); |
| 101 | + } else { |
| 102 | + // Fall back to individual execution for non-INSERT or incompatible statements |
| 103 | + return executeIndividualStatements(); |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + /** |
| 108 | + * Checks if the current batch can be optimized using multi-row INSERT. All statements must be |
| 109 | + * compatible INSERT operations. |
| 110 | + * |
| 111 | + * <p>A batch is eligible for multi-row INSERT optimization when: |
| 112 | + * |
| 113 | + * <ul> |
| 114 | + * <li>The EnableBatchedInserts connection property is enabled (default: true) |
| 115 | + * <li>The SQL statement is an INSERT operation |
| 116 | + * <li>The INSERT can be parsed successfully (has table name and column list) |
| 117 | + * <li>The batch contains parameter sets for multiple rows |
| 118 | + * </ul> |
| 119 | + * |
| 120 | + * <p>Compatible INSERT operations target the same table with the same columns in the same order. |
| 121 | + * When compatible, multiple individual INSERTs like: |
| 122 | + * |
| 123 | + * <pre> |
| 124 | + * INSERT INTO users (id, name) VALUES (?, ?) -- with parameters [1, "Alice"] |
| 125 | + * INSERT INTO users (id, name) VALUES (?, ?) -- with parameters [2, "Bob"] |
| 126 | + * </pre> |
| 127 | + * |
| 128 | + * Are combined into a single multi-row INSERT: |
| 129 | + * |
| 130 | + * <pre> |
| 131 | + * INSERT INTO users (id, name) VALUES (?, ?), (?, ?) -- with parameters [1, "Alice", 2, "Bob"] |
| 132 | + * </pre> |
| 133 | + */ |
| 134 | + private boolean canUseBatchedInsert() { |
| 135 | + // Check if batched inserts are enabled via connection property |
| 136 | + if (!connection.getConnectionContext().isBatchedInsertsEnabled()) { |
| 137 | + return false; |
| 138 | + } |
| 139 | + |
| 140 | + // Use strict exception-based parsing for better error handling |
| 141 | + try { |
| 142 | + InsertStatementParser.parseInsertStrict(sql); |
| 143 | + return !databricksBatchParameterMetaData.isEmpty(); |
| 144 | + } catch (Exception e) { |
| 145 | + // Not a valid INSERT statement suitable for batching |
| 146 | + return false; |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + /** Executes the batch as a single multi-row INSERT statement. */ |
| 151 | + private long[] executeBatchedInsert() throws DatabricksBatchUpdateException { |
| 152 | + LOGGER.debug("Executing batched INSERT with {} rows", databricksBatchParameterMetaData.size()); |
| 153 | + |
| 154 | + try { |
| 155 | + InsertStatementParser.InsertInfo insertInfo = InsertStatementParser.parseInsertStrict(sql); |
| 156 | + |
| 157 | + // Calculate how many rows we can fit in one chunk based on parameter limit |
| 158 | + int parametersPerRow = insertInfo.getColumnCount(); |
| 159 | + int maxRowsPerChunk = DatabricksJdbcConstants.MAX_QUERY_PARAMETERS / parametersPerRow; |
| 160 | + |
| 161 | + // Ensure we have at least 1 row per chunk |
| 162 | + if (maxRowsPerChunk < 1) { |
| 163 | + maxRowsPerChunk = 1; |
| 164 | + } |
| 165 | + |
| 166 | + long[] allUpdateCounts = new long[databricksBatchParameterMetaData.size()]; |
| 167 | + int processedRows = 0; |
| 168 | + |
| 169 | + // Process batches in chunks |
| 170 | + for (int startIndex = 0; |
| 171 | + startIndex < databricksBatchParameterMetaData.size(); |
| 172 | + startIndex += maxRowsPerChunk) { |
| 173 | + int endIndex = |
| 174 | + Math.min(startIndex + maxRowsPerChunk, databricksBatchParameterMetaData.size()); |
| 175 | + int chunkSize = endIndex - startIndex; |
| 176 | + |
| 177 | + LOGGER.debug("Processing chunk {}-{} ({} rows)", startIndex + 1, endIndex, chunkSize); |
| 178 | + |
| 179 | + // Generate multi-row SQL for this chunk |
| 180 | + String multiRowSql = InsertStatementParser.generateMultiRowInsert(insertInfo, chunkSize); |
| 181 | + |
| 182 | + // Combine parameters for this chunk |
| 183 | + Map<Integer, ImmutableSqlParameter> chunkParams = new HashMap<>(); |
| 184 | + int paramIndex = 1; |
| 185 | + |
| 186 | + for (int i = startIndex; i < endIndex; i++) { |
| 187 | + DatabricksParameterMetaData batchParams = databricksBatchParameterMetaData.get(i); |
| 188 | + Map<Integer, ImmutableSqlParameter> rowParams = batchParams.getParameterBindings(); |
| 189 | + for (int j = 1; j <= rowParams.size(); j++) { |
| 190 | + if (rowParams.containsKey(j)) { |
| 191 | + chunkParams.put(paramIndex++, rowParams.get(j)); |
| 192 | + } |
| 193 | + } |
| 194 | + } |
| 195 | + |
| 196 | + // Execute this chunk |
| 197 | + executeInternal(multiRowSql, chunkParams, StatementType.UPDATE, false); |
| 198 | + |
| 199 | + // Set update counts for this chunk (each row typically affects 1 row) |
| 200 | + for (int i = startIndex; i < endIndex; i++) { |
| 201 | + allUpdateCounts[i] = 1; |
| 202 | + } |
| 203 | + |
| 204 | + processedRows += chunkSize; |
| 205 | + } |
| 206 | + |
| 207 | + LOGGER.debug("Successfully processed {} rows in chunks", processedRows); |
| 208 | + return allUpdateCounts; |
| 209 | + |
| 210 | + } catch (Exception e) { |
| 211 | + LOGGER.error("Error executing batched INSERT: {}", e.getMessage(), e); |
| 212 | + long[] failedCounts = new long[databricksBatchParameterMetaData.size()]; |
| 213 | + for (int i = 0; i < failedCounts.length; i++) { |
| 214 | + failedCounts[i] = Statement.EXECUTE_FAILED; |
| 215 | + } |
| 216 | + throw new DatabricksBatchUpdateException( |
| 217 | + e.getMessage(), DatabricksDriverErrorCode.BATCH_EXECUTE_EXCEPTION, failedCounts); |
| 218 | + } |
| 219 | + } |
| 220 | + |
| 221 | + /** Executes batch statements individually (fallback method). */ |
| 222 | + private long[] executeIndividualStatements() throws DatabricksBatchUpdateException { |
| 223 | + LOGGER.debug( |
| 224 | + "Executing batch individually with {} statements", databricksBatchParameterMetaData.size()); |
91 | 225 | long[] largeUpdateCount = new long[databricksBatchParameterMetaData.size()]; |
92 | 226 |
|
93 | 227 | for (int sqlQueryIndex = 0; |
|
0 commit comments