diff --git a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/MetaDataEndpointImpl.java b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/MetaDataEndpointImpl.java index bd38a263fed..1bcb519233b 100644 --- a/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/MetaDataEndpointImpl.java +++ b/phoenix-core-server/src/main/java/org/apache/phoenix/coprocessor/MetaDataEndpointImpl.java @@ -622,6 +622,10 @@ public static PName newPName(byte[] keyBuffer, int keyOffset, int keyLength) { } private static boolean failConcurrentMutateAddColumnOneTimeForTesting = false; + // A test names a table here to make the read after its create fail one time. The test can also + // make the build from mutations fail, so that the create returns without the table. + private static volatile String failReadAfterCreateTableForTesting; + private static volatile boolean failBuildAfterCreateTableForTesting; private static final String FORCE_INDEX_MUTATE_METADATA_AS_ATTRIB = String.valueOf(Integer.MAX_VALUE); private RegionCoprocessorEnvironment env; @@ -648,6 +652,21 @@ public static void setFailConcurrentMutateAddColumnOneTimeForTesting(boolean fai failConcurrentMutateAddColumnOneTimeForTesting = fail; } + public static void setFailReadAfterCreateTableForTesting(String fullTableName, + boolean failBuild) { + failBuildAfterCreateTableForTesting = failBuild; + failReadAfterCreateTableForTesting = fullTableName; + } + + /** Returns true one time for the table that a test names. */ + private static boolean consumeFailReadAfterCreateTableForTesting(String fullTableName) { + if (!fullTableName.equals(failReadAfterCreateTableForTesting)) { + return false; + } + failReadAfterCreateTableForTesting = null; + return true; + } + /** * Stores a reference to the coprocessor environment provided by the * {@link org.apache.hadoop.hbase.regionserver.RegionCoprocessorHost} from the region where this @@ -2981,7 +3000,36 @@ Collections. emptySet(), HConstants.NO_NONCE, HConstants.NO_NONCE, // used by buildTable does not include 't' due to how SCN is implemented. clientTimeStamp += 1; } - PTable newTable = buildTable(tableKey, cacheKey, region, clientTimeStamp, clientVersion); + // The catalog rows are already committed here, so a failed read must not report a + // failure. If the read fails, for example because the region moves, build the table from + // the committed mutations. These mutations carry the server-side values that the client + // needs, such as the last DDL timestamp and the external schema id. For a base table this + // build needs no read. For a view or an index it still reads parent and link rows, so it + // can fail too. If that build also fails, return success without the table. The client + // then builds the table from its own metadata. + PTable newTable = null; + boolean failBuildForTesting = false; + try { + if (consumeFailReadAfterCreateTableForTesting(fullTableName)) { + failBuildForTesting = failBuildAfterCreateTableForTesting; + throw new IOException("Read failure injected for testing"); + } + newTable = buildTable(tableKey, cacheKey, region, clientTimeStamp, clientVersion); + } catch (IOException | SQLException | RuntimeException e) { + LOGGER.warn("Could not read {} {} after create, key {}; building it from mutations", + tableType, fullTableName, Bytes.toStringBinary(tableKey), e); + try { + if (failBuildForTesting) { + throw new IOException("Build failure injected for testing"); + } + newTable = getTableFromMutations(getTableRowMutations(tableMetadata, tableKey), + clientTimeStamp, clientVersion, null); + } catch (IOException | SQLException | RuntimeException buildException) { + LOGGER.warn( + "Could not build {} {} from mutations, key {}; returning success without it", + tableType, fullTableName, Bytes.toStringBinary(tableKey), buildException); + } + } if (newTable != null) { builder.setTable(PTableImpl.toProto(newTable, clientVersion)); } @@ -3010,8 +3058,12 @@ private void updateCreateTableDdlSuccessMetrics(PTableType tableType) { } } - private void exportSchema(List tableMetadata, byte[] tableKey, long clientTimestamp, - int clientVersion, PTable oldTable) throws SQLException, IOException { + /** + * Builds a PTable from the catalog mutations of a DDL operation. For a base table this needs no + * read from the region. For a view or an index the build still reads parent and link rows. + */ + private PTable getTableFromMutations(List tableMetadata, long clientTimeStamp, + int clientVersion, PTable oldTable) throws IOException, SQLException { List tableCellList = MetaDataUtil.getTableCellsFromMutations(tableMetadata); List> allColumnsCellList = @@ -3021,9 +3073,32 @@ private void exportSchema(List tableMetadata, byte[] tableKey, long cl for (List columnCellList : allColumnsCellList) { Collections.sort(columnCellList, KeyValue.COMPARATOR); } + return getTableFromCells(tableCellList, allColumnsCellList, clientTimeStamp, clientVersion, + oldTable); + } + + /** + * Returns the mutations for the header, column and link rows of one table. A scan of the table + * key reads the same rows. + */ + private static List getTableRowMutations(List tableMetadata, + byte[] tableKey) { + List tableRows = new ArrayList<>(tableMetadata.size()); + for (Mutation m : tableMetadata) { + byte[] row = m.getRow(); + boolean childRow = row.length > tableKey.length && Bytes.startsWith(row, tableKey) + && row[tableKey.length] == QueryConstants.SEPARATOR_BYTE; + if (childRow || Bytes.equals(row, tableKey)) { + tableRows.add(m); + } + } + return tableRows; + } - PTable newTable = getTableFromCells(tableCellList, allColumnsCellList, clientTimestamp, - clientVersion, oldTable); + private void exportSchema(List tableMetadata, byte[] tableKey, long clientTimestamp, + int clientVersion, PTable oldTable) throws SQLException, IOException { + PTable newTable = + getTableFromMutations(tableMetadata, clientTimestamp, clientVersion, oldTable); PTable parentTable = null; // if this is a view, we need to get the columns from its parent table / view if (newTable != null && newTable.getType().equals(PTableType.VIEW)) { diff --git a/phoenix-core/src/it/java/org/apache/phoenix/end2end/MetaDataEndpointImplIT.java b/phoenix-core/src/it/java/org/apache/phoenix/end2end/MetaDataEndpointImplIT.java index 85a9cd2cddf..d18f8e39102 100644 --- a/phoenix-core/src/it/java/org/apache/phoenix/end2end/MetaDataEndpointImplIT.java +++ b/phoenix-core/src/it/java/org/apache/phoenix/end2end/MetaDataEndpointImplIT.java @@ -19,10 +19,13 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.sql.Connection; import java.sql.DriverManager; +import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.List; @@ -30,11 +33,13 @@ import java.util.Properties; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.TableName; +import org.apache.phoenix.coprocessor.MetaDataEndpointImpl; import org.apache.phoenix.exception.SQLExceptionCode; import org.apache.phoenix.jdbc.PhoenixConnection; import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData; import org.apache.phoenix.schema.PColumn; import org.apache.phoenix.schema.PTable; +import org.apache.phoenix.schema.PTableKey; import org.apache.phoenix.schema.TableNotFoundException; import org.apache.phoenix.util.PhoenixRuntime; import org.apache.phoenix.util.PropertiesUtil; @@ -381,6 +386,55 @@ public void testWhereClause() throws Exception { assertNotNull(grandChildViewTable.getColumnForColumnName("A2").getViewConstant()); } + @Test + public void testCreateTableAfterFailedReadReturnsTableFromMutations() throws Exception { + assertCreateTableAfterFailedRead(false); + } + + @Test + public void testCreateTableAfterFailedReadAndBuildReturnsSuccess() throws Exception { + assertCreateTableAfterFailedRead(true); + } + + /** + * Makes the server read after a create fail, and optionally the build from mutations too. The + * create must succeed in both cases. The client keeps the server DDL timestamp only when the + * response carries the table. + */ + private void assertCreateTableAfterFailedRead(boolean failBuild) throws Exception { + String tableName = generateUniqueName(); + try (PhoenixConnection conn = + DriverManager.getConnection(getUrl()).unwrap(PhoenixConnection.class)) { + MetaDataEndpointImpl.setFailReadAfterCreateTableForTesting(tableName, failBuild); + try { + conn.createStatement() + .execute("CREATE TABLE " + tableName + " (K VARCHAR PRIMARY KEY, V VARCHAR)"); + } finally { + MetaDataEndpointImpl.setFailReadAfterCreateTableForTesting(null, false); + } + PTable cached = conn.getTableRef(new PTableKey(null, tableName)).getTable(); + // Read the stored value from the catalog. A metadata refresh keeps the cached table + // because the table did not change on the server. + ResultSet catalog = conn.createStatement() + .executeQuery("SELECT LAST_DDL_TIMESTAMP FROM SYSTEM.CATALOG WHERE TENANT_ID IS NULL" + + " AND TABLE_SCHEM IS NULL AND TABLE_NAME = '" + tableName + "'" + + " AND COLUMN_NAME IS NULL AND COLUMN_FAMILY IS NULL"); + assertTrue(catalog.next()); + long stored = catalog.getLong(1); + assertTrue(stored > 0); + if (failBuild) { + assertNull(cached.getLastDDLTimestamp()); + } else { + assertEquals(Long.valueOf(stored), cached.getLastDDLTimestamp()); + } + conn.createStatement().execute("UPSERT INTO " + tableName + " VALUES ('a', 'b')"); + conn.commit(); + ResultSet rs = conn.createStatement().executeQuery("SELECT V FROM " + tableName); + assertTrue(rs.next()); + assertEquals("b", rs.getString(1)); + } + } + private void assertColumnNamesEqual(PTable table, String... cols) { List actual = Lists.newArrayList(); for (PColumn column : table.getColumns()) {