You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by lz...@apache.org on 2020/03/03 11:44:57 UTC

[flink] branch release-1.10 updated: [FLINK-16281][jdbc] Parameter 'maxRetryTimes' can not work in AppendOnlyWriter (#11293)

This is an automated email from the ASF dual-hosted git repository.

lzljs3620320 pushed a commit to branch release-1.10
in repository https://gitbox.apache.org/repos/asf/flink.git


The following commit(s) were added to refs/heads/release-1.10 by this push:
     new 833924d  [FLINK-16281][jdbc] Parameter 'maxRetryTimes' can not work in AppendOnlyWriter (#11293)
833924d is described below

commit 833924dcab13879a5c896effb8fce8dc1963e826
Author: Leonard Xu <xb...@163.com>
AuthorDate: Tue Mar 3 19:44:44 2020 +0800

    [FLINK-16281][jdbc] Parameter 'maxRetryTimes' can not work in AppendOnlyWriter (#11293)
---
 .../api/java/io/jdbc/JDBCUpsertOutputFormat.java   |   8 +-
 .../api/java/io/jdbc/writer/AppendOnlyWriter.java  |  18 +++-
 .../flink/api/java/io/jdbc/writer/JDBCWriter.java  |   2 +-
 .../api/java/io/jdbc/writer/UpsertWriter.java      |  23 ++---
 .../api/java/io/jdbc/JDBCAppenOnlyWriterTest.java  | 105 +++++++++++++++++++++
 5 files changed, 133 insertions(+), 23 deletions(-)

diff --git a/flink-connectors/flink-jdbc/src/main/java/org/apache/flink/api/java/io/jdbc/JDBCUpsertOutputFormat.java b/flink-connectors/flink-jdbc/src/main/java/org/apache/flink/api/java/io/jdbc/JDBCUpsertOutputFormat.java
index cd1ced3..1736c28 100644
--- a/flink-connectors/flink-jdbc/src/main/java/org/apache/flink/api/java/io/jdbc/JDBCUpsertOutputFormat.java
+++ b/flink-connectors/flink-jdbc/src/main/java/org/apache/flink/api/java/io/jdbc/JDBCUpsertOutputFormat.java
@@ -62,6 +62,7 @@ public class JDBCUpsertOutputFormat extends AbstractJDBCOutputFormat<Tuple2<Bool
 	private transient JDBCWriter jdbcWriter;
 	private transient int batchCount = 0;
 	private transient volatile boolean closed = false;
+	private transient boolean objectReuse;
 
 	private transient ScheduledExecutorService scheduler;
 	private transient ScheduledFuture scheduledFuture;
@@ -97,13 +98,13 @@ public class JDBCUpsertOutputFormat extends AbstractJDBCOutputFormat<Tuple2<Bool
 	public void open(int taskNumber, int numTasks) throws IOException {
 		try {
 			establishConnection();
+			objectReuse = getRuntimeContext().getExecutionConfig().isObjectReuseEnabled();
 			if (keyFields == null || keyFields.length == 0) {
 				String insertSQL = dialect.getInsertIntoStatement(tableName, fieldNames);
 				jdbcWriter = new AppendOnlyWriter(insertSQL, fieldTypes);
 			} else {
 				jdbcWriter = UpsertWriter.create(
-					dialect, tableName, fieldNames, fieldTypes, keyFields,
-					getRuntimeContext().getExecutionConfig().isObjectReuseEnabled());
+					dialect, tableName, fieldNames, fieldTypes, keyFields);
 			}
 			jdbcWriter.open(connection);
 		} catch (SQLException sqe) {
@@ -141,7 +142,8 @@ public class JDBCUpsertOutputFormat extends AbstractJDBCOutputFormat<Tuple2<Bool
 		checkFlushException();
 
 		try {
-			jdbcWriter.addRecord(tuple2);
+			Tuple2<Boolean, Row> record = objectReuse ? new Tuple2<>(tuple2.f0, Row.copy(tuple2.f1)) : tuple2;
+			jdbcWriter.addRecord(record);
 			batchCount++;
 			if (batchCount >= flushMaxSize) {
 				flush();
diff --git a/flink-connectors/flink-jdbc/src/main/java/org/apache/flink/api/java/io/jdbc/writer/AppendOnlyWriter.java b/flink-connectors/flink-jdbc/src/main/java/org/apache/flink/api/java/io/jdbc/writer/AppendOnlyWriter.java
index 899a22f..ff07874 100644
--- a/flink-connectors/flink-jdbc/src/main/java/org/apache/flink/api/java/io/jdbc/writer/AppendOnlyWriter.java
+++ b/flink-connectors/flink-jdbc/src/main/java/org/apache/flink/api/java/io/jdbc/writer/AppendOnlyWriter.java
@@ -24,6 +24,8 @@ import org.apache.flink.types.Row;
 import java.sql.Connection;
 import java.sql.PreparedStatement;
 import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
 
 import static org.apache.flink.api.java.io.jdbc.JDBCUtils.setRecordToStatement;
 import static org.apache.flink.util.Preconditions.checkArgument;
@@ -38,6 +40,7 @@ public class AppendOnlyWriter implements JDBCWriter {
 	private final String insertSQL;
 	private final int[] fieldTypes;
 
+	private transient List<Row> cachedRows;
 	private transient PreparedStatement statement;
 
 	public AppendOnlyWriter(String insertSQL, int[] fieldTypes) {
@@ -47,19 +50,26 @@ public class AppendOnlyWriter implements JDBCWriter {
 
 	@Override
 	public void open(Connection connection) throws SQLException {
+		this.cachedRows = new ArrayList<>();
 		this.statement = connection.prepareStatement(insertSQL);
 	}
 
 	@Override
-	public void addRecord(Tuple2<Boolean, Row> record) throws SQLException {
+	public void addRecord(Tuple2<Boolean, Row> record) {
 		checkArgument(record.f0, "Append mode can not receive retract/delete message.");
-		setRecordToStatement(statement, fieldTypes, record.f1);
-		statement.addBatch();
+		cachedRows.add(record.f1);
 	}
 
 	@Override
 	public void executeBatch() throws SQLException {
-		statement.executeBatch();
+		if (cachedRows.size() > 0) {
+			for (Row row : cachedRows) {
+				setRecordToStatement(statement, fieldTypes, row);
+				statement.addBatch();
+			}
+			statement.executeBatch();
+			cachedRows.clear();
+		}
 	}
 
 	@Override
diff --git a/flink-connectors/flink-jdbc/src/main/java/org/apache/flink/api/java/io/jdbc/writer/JDBCWriter.java b/flink-connectors/flink-jdbc/src/main/java/org/apache/flink/api/java/io/jdbc/writer/JDBCWriter.java
index 8ce4759..1a6797a 100644
--- a/flink-connectors/flink-jdbc/src/main/java/org/apache/flink/api/java/io/jdbc/writer/JDBCWriter.java
+++ b/flink-connectors/flink-jdbc/src/main/java/org/apache/flink/api/java/io/jdbc/writer/JDBCWriter.java
@@ -38,7 +38,7 @@ public interface JDBCWriter extends Serializable {
 	/**
 	 * Add record to writer, the writer may cache the data.
 	 */
-	void addRecord(Tuple2<Boolean, Row> record) throws SQLException;
+	void addRecord(Tuple2<Boolean, Row> record);
 
 	/**
 	 * Submits a batch of commands to the database for execution.
diff --git a/flink-connectors/flink-jdbc/src/main/java/org/apache/flink/api/java/io/jdbc/writer/UpsertWriter.java b/flink-connectors/flink-jdbc/src/main/java/org/apache/flink/api/java/io/jdbc/writer/UpsertWriter.java
index dcc807e..7d07b95 100644
--- a/flink-connectors/flink-jdbc/src/main/java/org/apache/flink/api/java/io/jdbc/writer/UpsertWriter.java
+++ b/flink-connectors/flink-jdbc/src/main/java/org/apache/flink/api/java/io/jdbc/writer/UpsertWriter.java
@@ -48,8 +48,7 @@ public abstract class UpsertWriter implements JDBCWriter {
 		String tableName,
 		String[] fieldNames,
 		int[] fieldTypes,
-		String[] keyFields,
-		boolean objectReuse) {
+		String[] keyFields) {
 
 		checkNotNull(keyFields);
 
@@ -62,10 +61,10 @@ public abstract class UpsertWriter implements JDBCWriter {
 		Optional<String> upsertSQL = dialect.getUpsertStatement(tableName, fieldNames, keyFields);
 		return upsertSQL.map((Function<String, UpsertWriter>) sql ->
 				new UpsertWriterUsingUpsertStatement(
-						fieldTypes, pkFields, pkTypes, objectReuse, deleteSQL, sql))
+						fieldTypes, pkFields, pkTypes, deleteSQL, sql))
 				.orElseGet(() ->
 						new UpsertWriterUsingInsertUpdateStatement(
-								fieldTypes, pkFields, pkTypes, objectReuse, deleteSQL,
+								fieldTypes, pkFields, pkTypes, deleteSQL,
 								dialect.getRowExistsStatement(tableName, keyFields),
 								dialect.getInsertIntoStatement(tableName, fieldNames),
 								dialect.getUpdateStatement(tableName, fieldNames, keyFields)));
@@ -75,17 +74,15 @@ public abstract class UpsertWriter implements JDBCWriter {
 	final int[] pkTypes;
 	private final int[] pkFields;
 	private final String deleteSQL;
-	private final boolean objectReuse;
 
 	private transient Map<Row, Tuple2<Boolean, Row>> keyToRows;
 	private transient PreparedStatement deleteStatement;
 
-	private UpsertWriter(int[] fieldTypes, int[] pkFields, int[] pkTypes, String deleteSQL, boolean objectReuse) {
+	private UpsertWriter(int[] fieldTypes, int[] pkFields, int[] pkTypes, String deleteSQL) {
 		this.fieldTypes = fieldTypes;
 		this.pkFields = pkFields;
 		this.pkTypes = pkTypes;
 		this.deleteSQL = deleteSQL;
-		this.objectReuse = objectReuse;
 	}
 
 	@Override
@@ -94,11 +91,9 @@ public abstract class UpsertWriter implements JDBCWriter {
 		this.deleteStatement = connection.prepareStatement(deleteSQL);
 	}
 
-	public void addRecord(Tuple2<Boolean, Row> record) throws SQLException {
-		// we don't need perform a deep copy, because jdbc field are immutable object.
-		Tuple2<Boolean, Row> tuple2 = objectReuse ? new Tuple2<>(record.f0, Row.copy(record.f1)) : record;
+	public void addRecord(Tuple2<Boolean, Row> record) {
 		// add records to buffer
-		keyToRows.put(getPrimaryKey(tuple2.f1), tuple2);
+		keyToRows.put(getPrimaryKey(record.f1), record);
 	}
 
 	@Override
@@ -153,10 +148,9 @@ public abstract class UpsertWriter implements JDBCWriter {
 			int[] fieldTypes,
 			int[] pkFields,
 			int[] pkTypes,
-			boolean objectReuse,
 			String deleteSQL,
 			String upsertSQL) {
-			super(fieldTypes, pkFields, pkTypes, deleteSQL, objectReuse);
+			super(fieldTypes, pkFields, pkTypes, deleteSQL);
 			this.upsertSQL = upsertSQL;
 		}
 
@@ -202,12 +196,11 @@ public abstract class UpsertWriter implements JDBCWriter {
 			int[] fieldTypes,
 			int[] pkFields,
 			int[] pkTypes,
-			boolean objectReuse,
 			String deleteSQL,
 			String existSQL,
 			String insertSQL,
 			String updateSQL) {
-			super(fieldTypes, pkFields, pkTypes, deleteSQL, objectReuse);
+			super(fieldTypes, pkFields, pkTypes, deleteSQL);
 			this.existSQL = existSQL;
 			this.insertSQL = insertSQL;
 			this.updateSQL = updateSQL;
diff --git a/flink-connectors/flink-jdbc/src/test/java/org/apache/flink/api/java/io/jdbc/JDBCAppenOnlyWriterTest.java b/flink-connectors/flink-jdbc/src/test/java/org/apache/flink/api/java/io/jdbc/JDBCAppenOnlyWriterTest.java
new file mode 100644
index 0000000..36bae77
--- /dev/null
+++ b/flink-connectors/flink-jdbc/src/test/java/org/apache/flink/api/java/io/jdbc/JDBCAppenOnlyWriterTest.java
@@ -0,0 +1,105 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.api.java.io.jdbc;
+
+import org.apache.flink.api.common.ExecutionConfig;
+import org.apache.flink.api.common.functions.RuntimeContext;
+import org.apache.flink.api.java.io.jdbc.writer.AppendOnlyWriter;
+import org.apache.flink.api.java.tuple.Tuple2;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.sql.BatchUpdateException;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.Statement;
+
+import static org.apache.flink.api.java.io.jdbc.JDBCOutputFormatTest.toRow;
+import static org.mockito.Mockito.doReturn;
+
+/**
+ * Test for the {@link AppendOnlyWriter}.
+ */
+public class JDBCAppenOnlyWriterTest extends JDBCTestBase {
+
+	private JDBCUpsertOutputFormat format;
+	private String[] fieldNames;
+
+	@Before
+	public void setup() {
+		fieldNames = new String[]{"id", "title", "author", "price", "qty"};
+	}
+
+	@Test(expected = BatchUpdateException.class)
+	public void testMaxRetry() throws Exception {
+		format = JDBCUpsertOutputFormat.builder()
+			.setOptions(JDBCOptions.builder()
+				.setDBUrl(DB_URL)
+				.setTableName(OUTPUT_TABLE)
+				.build())
+			.setFieldNames(fieldNames)
+			.setKeyFields(null)
+			.build();
+		RuntimeContext context = Mockito.mock(RuntimeContext.class);
+		ExecutionConfig config = Mockito.mock(ExecutionConfig.class);
+		doReturn(config).when(context).getExecutionConfig();
+		doReturn(true).when(config).isObjectReuseEnabled();
+		format.setRuntimeContext(context);
+		format.open(0, 1);
+
+		// alter table schema to trigger retry logic after failure.
+		alterTable();
+		for (TestEntry entry : TEST_DATA) {
+			format.writeRecord(Tuple2.of(true, toRow(entry)));
+		}
+
+		// after retry default times, throws a BatchUpdateException.
+		format.flush();
+	}
+
+	private void alterTable() throws Exception {
+		Class.forName(DRIVER_CLASS);
+		try (Connection conn = DriverManager.getConnection(DB_URL);
+			Statement stat = conn.createStatement()) {
+			stat.execute("ALTER  TABLE " + OUTPUT_TABLE + " DROP COLUMN " + fieldNames[1]);
+		}
+	}
+
+	@After
+	public void clear() throws Exception {
+		if (format != null) {
+			try {
+				format.close();
+			} catch (RuntimeException e) {
+				// ignore exception when close.
+			}
+		}
+		format = null;
+		Class.forName(DRIVER_CLASS);
+		try (
+			Connection conn = DriverManager.getConnection(DB_URL);
+			Statement stat = conn.createStatement()) {
+			stat.execute("DELETE FROM " + OUTPUT_TABLE);
+		}
+	}
+
+}