Java Code Examples for org.apache.phoenix.util.SchemaUtil#getTableNameFromFullName()

The following examples show how to use org.apache.phoenix.util.SchemaUtil#getTableNameFromFullName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConnectionQueryServicesImpl.java    From phoenix with Apache License 2.0 6 votes vote down vote up
private void ensureLocalIndexTableCreated(byte[] physicalTableName, Map<String, Object> tableProps, List<Pair<byte[], Map<String, Object>>> families, byte[][] splits) throws SQLException, TableAlreadyExistsException {
    
    // If we're not allowing local indexes or the hbase version is too low,
    // don't create the local index table
    if (   !this.getProps().getBoolean(QueryServices.ALLOW_LOCAL_INDEX_ATTRIB, QueryServicesOptions.DEFAULT_ALLOW_LOCAL_INDEX) 
        || !this.supportsFeature(Feature.LOCAL_INDEX)) {
                return;
    }
    
    tableProps.put(MetaDataUtil.IS_LOCAL_INDEX_TABLE_PROP_NAME, TRUE_BYTES_AS_STRING);
    HTableDescriptor desc = ensureTableCreated(physicalTableName, PTableType.TABLE, tableProps, families, splits, true);
    if (desc != null) {
        if (!Boolean.TRUE.equals(PBoolean.INSTANCE.toObject(desc.getValue(MetaDataUtil.IS_LOCAL_INDEX_TABLE_PROP_BYTES)))) {
            String fullTableName = Bytes.toString(physicalTableName);
            throw new TableAlreadyExistsException(
                    "Unable to create shared physical table for local indexes.",
                    SchemaUtil.getSchemaNameFromFullName(fullTableName),
                    SchemaUtil.getTableNameFromFullName(fullTableName));
        }
    }
}
 
Example 2
Source File: UpdateCacheConnectionLevelPropIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method that executes a select and upsert query on the table for \p numSelectExecutions
 * times and verifies that \p numExpectedGetTableCalls were made to getTable() for the table.
 *
 * Also resets the spy object for conn2 before returning.
 *
 * @param fullTableName The table's full name
 * @param numExecutions Number of times a select+upsert should be executed on the table
 * @param numExpectedGetTableCalls Number of expected calls to getTable()
 */
private static void verifyExpectedGetTableCalls(String fullTableName, int numExecutions,
        int numExpectedGetTableCalls) throws SQLException {
    String tableName = SchemaUtil.getTableNameFromFullName(fullTableName);
    String schemaName = SchemaUtil.getSchemaNameFromFullName(fullTableName);
    String selectFromTableQuery = "SELECT k, v1, v2, v3 FROM " + fullTableName;

    for (int i = 0; i < numExecutions; i++) {
        // Query the table over the spied connection that has update cache frequency set
        try (Statement stmt = conn2.createStatement();
                ResultSet rs = stmt.executeQuery(selectFromTableQuery)) {
            assertTrue(rs.next());
            stmt.execute("UPSERT INTO " + fullTableName + " VALUES (1, 2, 3, 4)");
        }
    }

    // Verify number of calls to getTable() for our table
    verify(spyForConn2, times(numExpectedGetTableCalls)).getTable((PName) isNull(),
            eq(PVarchar.INSTANCE.toBytes(schemaName)), eq(PVarchar.INSTANCE.toBytes(tableName)),
            anyLong(), anyLong());
    reset(spyForConn2);
}
 
Example 3
Source File: BaseTest.java    From phoenix with Apache License 2.0 6 votes vote down vote up
/**
 * Splits SYSTEM.CATALOG into multiple regions based on the table or view names passed in.
 * Metadata for each table or view is moved to a separate region,
 * @param tenantToTableAndViewMap map from tenant to tables and views owned by the tenant
 */
protected static void splitSystemCatalog(Map<String, List<String>> tenantToTableAndViewMap) throws Exception  {
    List<byte[]> splitPoints = Lists.newArrayListWithExpectedSize(5);
    // add the rows keys of the table or view metadata rows
    Set<String> schemaNameSet=Sets.newHashSetWithExpectedSize(15);
    for (Entry<String, List<String>> entrySet : tenantToTableAndViewMap.entrySet()) {
        String tenantId = entrySet.getKey();
        for (String fullName : entrySet.getValue()) {
            String schemaName = SchemaUtil.getSchemaNameFromFullName(fullName);
            // we don't allow SYSTEM.CATALOG to split within a schema, so to ensure each table
            // or view is on a separate region they need to have a unique tenant and schema name
            assertTrue("Schema names of tables/view must be unique ", schemaNameSet.add(tenantId+"."+schemaName));
            String tableName = SchemaUtil.getTableNameFromFullName(fullName);
            splitPoints.add(
                SchemaUtil.getTableKey(tenantId, "".equals(schemaName) ? null : schemaName, tableName));
        }
    }
    Collections.sort(splitPoints, Bytes.BYTES_COMPARATOR);

    splitTable(PhoenixDatabaseMetaData.SYSTEM_CATALOG_HBASE_TABLE_NAME, splitPoints);
}
 
Example 4
Source File: ImmutableIndexIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
private void createAndPopulateTableAndIndexForConsistentIndex(Connection conn, String tableName, String indexName,
        int numOfRowsToInsert, String storageProps)
        throws Exception {
    String tableOptions = tableDDLOptions;
    if (storageProps != null) {
        tableOptions += " ,IMMUTABLE_STORAGE_SCHEME=" + storageProps;
    }
    String ddl = "CREATE TABLE " + tableName + TestUtil.TEST_TABLE_SCHEMA + tableOptions;
    INDEX_DDL =
            "CREATE " + " INDEX IF NOT EXISTS " + SchemaUtil.getTableNameFromFullName(indexName)
                    + " ON " + tableName + " (long_pk, varchar_pk)"
                    + " INCLUDE (long_col1, long_col2) ";

    conn.createStatement().execute(ddl);
    conn.createStatement().execute(INDEX_DDL);
    upsertRows(conn, tableName, numOfRowsToInsert);
    conn.commit();

    TestUtil.waitForIndexState(conn, indexName, PIndexState.ACTIVE);
}
 
Example 5
Source File: UngroupedAggregateRegionObserver.java    From phoenix with Apache License 2.0 5 votes vote down vote up
private void checkForLocalIndexColumnFamilies(Region region,
        List<IndexMaintainer> indexMaintainers) throws IOException {
    TableDescriptor tableDesc = region.getTableDescriptor();
    String schemaName =
            tableDesc.getTableName().getNamespaceAsString()
                    .equals(NamespaceDescriptor.DEFAULT_NAMESPACE_NAME_STR) ? SchemaUtil
                    .getSchemaNameFromFullName(tableDesc.getTableName().getNameAsString())
                    : tableDesc.getTableName().getNamespaceAsString();
    String tableName = SchemaUtil.getTableNameFromFullName(tableDesc.getTableName().getNameAsString());
    for (IndexMaintainer indexMaintainer : indexMaintainers) {
        Set<ColumnReference> coveredColumns = indexMaintainer.getCoveredColumns();
        if(coveredColumns.isEmpty()) {
            byte[] localIndexCf = indexMaintainer.getEmptyKeyValueFamily().get();
            // When covered columns empty we store index data in default column family so check for it.
            if (tableDesc.getColumnFamily(localIndexCf) == null) {
                ServerUtil.throwIOException("Column Family Not Found",
                    new ColumnFamilyNotFoundException(schemaName, tableName, Bytes
                            .toString(localIndexCf)));
            }
        }
        for (ColumnReference reference : coveredColumns) {
            byte[] cf = IndexUtil.getLocalIndexColumnFamily(reference.getFamily());
            ColumnFamilyDescriptor family = region.getTableDescriptor().getColumnFamily(cf);
            if (family == null) {
                ServerUtil.throwIOException("Column Family Not Found",
                    new ColumnFamilyNotFoundException(schemaName, tableName, Bytes.toString(cf)));
            }
        }
    }
}
 
Example 6
Source File: MutableIndexFailureIT.java    From phoenix with Apache License 2.0 5 votes vote down vote up
private void validateDataWithIndex(Connection conn, String fullTableName, String fullIndexName, boolean localIndex) throws Exception {
    String query = "SELECT /*+ INDEX(" + fullTableName + " " + SchemaUtil.getTableNameFromFullName(fullIndexName) + ")  */ k,v1 FROM " + fullTableName;
    ResultSet rs = conn.createStatement().executeQuery(query);
    String expectedPlan = " OVER "
            + (localIndex
                    ? Bytes.toString(
                            SchemaUtil.getPhysicalTableName(fullTableName.getBytes(), isNamespaceMapped).getName())
                    : SchemaUtil.getPhysicalTableName(fullIndexName.getBytes(), isNamespaceMapped).getNameAsString());
    String explainPlan = QueryUtil.getExplainPlan(conn.createStatement().executeQuery("EXPLAIN " + query));
    assertTrue(explainPlan, explainPlan.contains(expectedPlan));
    if (transactional) { // failed commit does not get retried
        assertTrue(rs.next());
        assertEquals("a", rs.getString(1));
        assertEquals("x", rs.getString(2));
        assertTrue(rs.next());
        assertEquals("a3", rs.getString(1));
        assertEquals("x4", rs.getString(2));
        assertTrue(rs.next());
        assertEquals("b", rs.getString(1));
        assertEquals("y", rs.getString(2));
        assertTrue(rs.next());
        assertEquals("c", rs.getString(1));
        assertEquals("z", rs.getString(2));
        assertFalse(rs.next());
    } else { // failed commit eventually succeeds
        assertTrue(rs.next());
        assertEquals("d", rs.getString(1));
        assertEquals("d", rs.getString(2));
        assertTrue(rs.next());
        assertEquals("a", rs.getString(1));
        assertEquals("x2", rs.getString(2));
        assertTrue(rs.next());
        assertEquals("a3", rs.getString(1));
        assertEquals("x4", rs.getString(2));
        assertTrue(rs.next());
        assertEquals("c", rs.getString(1));
        assertEquals("z", rs.getString(2));
        assertFalse(rs.next());
    }
}
 
Example 7
Source File: IndexUpgradeToolIT.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyViewAndViewIndexes() throws Exception {
    String tableName = generateUniqueName();
    String schemaName = generateUniqueName();
    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
    if (multiTenant) {
        tenantId = generateUniqueName();
        props.setProperty(PhoenixRuntime.TENANT_ID_ATTRIB, tenantId);
    }
    try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
        prepareForTest(conn, schemaName, tableName);
        String viewQuery = IndexUpgradeTool.getViewSql(tableName, schemaName);
        ResultSet rs = conn.createStatement().executeQuery(viewQuery);
        List<String> views = new ArrayList<>();
        List<String> tenants = new ArrayList<>();
        while (rs.next()) {
            //1st column has the view name and 2nd column has the Tenant ID
            views.add(rs.getString(1));
            if(multiTenant) {
                Assert.assertNotNull(rs.getString(2));
            }
            tenants.add(rs.getString(2));
        }
        Assert.assertEquals("view count in system table doesn't match", 2, views.size());

        for (int i = 0; i < views.size(); i++) {
            String viewName = SchemaUtil.getTableNameFromFullName(views.get(i));
            String viewIndexQuery = IndexUpgradeTool.getViewIndexesSql(viewName, schemaName,
                    tenants.get(i));
            rs = conn.createStatement().executeQuery(viewIndexQuery);
            int indexes = 0;
            while (rs.next()) {
                indexes++;
            }
            // first (i=0) TSV has 2 indexes, and second(i=1) TSV has 1 index.
            Assert.assertEquals(VERIFY_COUNT_ASSERT_MESSAGE, 2-i, indexes);
        }
    }
}
 
Example 8
Source File: MetaDataClient.java    From phoenix with Apache License 2.0 5 votes vote down vote up
public PTableStats getTableStats(PTable table) throws SQLException {
    /*
     *  The shared view index case is tricky, because we don't have
     *  table meta data for it, only an HBase table. We do have stats,
     *  though, so we'll query them directly here and cache them so
     *  we don't keep querying for them.
     */
    boolean isSharedIndex = table.getViewIndexId() != null;
    if (isSharedIndex) {
        return connection.getQueryServices().getTableStats(table.getPhysicalName().getBytes(), getClientTimeStamp());
    }
    boolean isView = table.getType() == PTableType.VIEW;
    String physicalName = table.getPhysicalName().getString();
    if (isView && table.getViewType() != ViewType.MAPPED) {
        try {
            return connection.getMetaDataCache().getTable(new PTableKey(null, physicalName)).getTableStats();
        } catch (TableNotFoundException e) {
            // Possible when the table timestamp == current timestamp - 1.
            // This would be most likely during the initial index build of a view index
            // where we're doing an upsert select from the tenant specific table.
            // TODO: would we want to always load the physical table in updateCache in
            // this case too, as we might not update the view with all of it's indexes?
            String physicalSchemaName = SchemaUtil.getSchemaNameFromFullName(physicalName);
            String physicalTableName = SchemaUtil.getTableNameFromFullName(physicalName);
            MetaDataMutationResult result = updateCache(null, physicalSchemaName, physicalTableName, false);
            if (result.getTable() == null) {
                throw new TableNotFoundException(physicalSchemaName, physicalTableName);
            }
            return result.getTable().getTableStats();
        }
    }
    return table.getTableStats();
}
 
Example 9
Source File: ConnectionQueryServicesImpl.java    From phoenix with Apache License 2.0 5 votes vote down vote up
private void ensureViewIndexTableCreated(byte[] physicalTableName, Map<String,Object> tableProps, List<Pair<byte[],Map<String,Object>>> families, byte[][] splits, long timestamp) throws SQLException {
    Long maxFileSize = (Long)tableProps.get(HTableDescriptor.MAX_FILESIZE);
    if (maxFileSize == null) {
        maxFileSize = this.config.getLong(HConstants.HREGION_MAX_FILESIZE, HConstants.DEFAULT_MAX_FILE_SIZE);
    }
    byte[] physicalIndexName = MetaDataUtil.getViewIndexPhysicalName(physicalTableName);

    int indexMaxFileSizePerc;
    // Get percentage to use from table props first and then fallback to config
    Integer indexMaxFileSizePercProp = (Integer)tableProps.remove(QueryServices.INDEX_MAX_FILESIZE_PERC_ATTRIB);
    if (indexMaxFileSizePercProp == null) {
        indexMaxFileSizePerc = config.getInt(QueryServices.INDEX_MAX_FILESIZE_PERC_ATTRIB, QueryServicesOptions.DEFAULT_INDEX_MAX_FILESIZE_PERC);
    } else {
        indexMaxFileSizePerc = indexMaxFileSizePercProp;
    }
    long indexMaxFileSize = maxFileSize * indexMaxFileSizePerc / 100;
    tableProps.put(HTableDescriptor.MAX_FILESIZE, indexMaxFileSize);
    tableProps.put(MetaDataUtil.IS_VIEW_INDEX_TABLE_PROP_NAME, TRUE_BYTES_AS_STRING);
    HTableDescriptor desc = ensureTableCreated(physicalIndexName, PTableType.TABLE, tableProps, families, splits, false);
    if (desc != null) {
        if (!Boolean.TRUE.equals(PBoolean.INSTANCE.toObject(desc.getValue(MetaDataUtil.IS_VIEW_INDEX_TABLE_PROP_BYTES)))) {
            String fullTableName = Bytes.toString(physicalIndexName);
            throw new TableAlreadyExistsException(
                    "Unable to create shared physical table for indexes on views.",
                    SchemaUtil.getSchemaNameFromFullName(fullTableName),
                    SchemaUtil.getTableNameFromFullName(fullTableName));
        }
    }
}
 
Example 10
Source File: SchemaUtilTest.java    From phoenix with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetTableNameFromFullNameByte() {
    String tableDisplayName = SchemaUtil.getTableNameFromFullName(Bytes.toBytes("schemaName.tableName"));
    assertEquals(tableDisplayName, "tableName");
}
 
Example 11
Source File: SchemaUtilTest.java    From phoenix with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetTableNameFromFullNameByte() {
    String tableDisplayName = SchemaUtil.getTableNameFromFullName(Bytes.toBytes("schemaName.tableName"));
    assertEquals(tableDisplayName, "tableName");
}
 
Example 12
Source File: SchemaUtilTest.java    From phoenix with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetTableNameFromFullName() {
    String tableDisplayName = SchemaUtil.getTableNameFromFullName("schemaName.tableName");
    assertEquals(tableDisplayName, "tableName");
}
 
Example 13
Source File: BaseEventSerializer.java    From phoenix with Apache License 2.0 4 votes vote down vote up
@Override
public void initialize() throws SQLException {
    final Properties props = new Properties();
    props.setProperty(UPSERT_BATCH_SIZE_ATTRIB, String.valueOf(this.batchSize)); 
    ResultSet rs = null;
    try {
        this.connection = DriverManager.getConnection(this.jdbcUrl, props);
        this.connection.setAutoCommit(false);
        if(this.createTableDdl != null) {
             SchemaHandler.createTable(connection,createTableDdl);
        }
  
        
        final Map<String,Integer> qualifiedColumnMap = Maps.newLinkedHashMap();
        final Map<String,Integer> unqualifiedColumnMap = Maps.newLinkedHashMap();
        final String schemaName = SchemaUtil.getSchemaNameFromFullName(fullTableName);
        final String tableName  = SchemaUtil.getTableNameFromFullName(fullTableName);
        
        String rowkey = null;
        String  cq = null;
        String  cf = null;
        Integer dt = null;
        rs = connection.getMetaData().getColumns("", StringUtil.escapeLike(SchemaUtil.normalizeIdentifier(schemaName)), StringUtil.escapeLike(SchemaUtil.normalizeIdentifier(tableName)), null);
        while (rs.next()) {
            cf = rs.getString(QueryUtil.COLUMN_FAMILY_POSITION);
            cq = rs.getString(QueryUtil.COLUMN_NAME_POSITION);
            dt = rs.getInt(QueryUtil.DATA_TYPE_POSITION);
            if(Strings.isNullOrEmpty(cf)) {
                rowkey = cq; // this is required only when row key is auto generated
            } else {
                qualifiedColumnMap.put(SchemaUtil.getColumnDisplayName(cf, cq), dt);
            }
            unqualifiedColumnMap.put(SchemaUtil.getColumnDisplayName(null, cq), dt);
         }
        
        //can happen when table not found in Hbase.
        if(unqualifiedColumnMap.isEmpty()) {
            throw new SQLExceptionInfo.Builder(SQLExceptionCode.TABLE_UNDEFINED)
                    .setTableName(tableName).build().buildException();
        }
   
        int colSize = colNames.size();
        int headersSize = headers.size();
        int totalSize = colSize + headersSize + ( autoGenerateKey ? 1 : 0);
        columnMetadata = new ColumnInfo[totalSize] ;
       
        int position = 0;
        position = this.addToColumnMetadataInfo(colNames, qualifiedColumnMap, unqualifiedColumnMap, position);
        position = this.addToColumnMetadataInfo(headers,  qualifiedColumnMap, unqualifiedColumnMap, position);
       
        if(autoGenerateKey) {
            Integer sqlType = unqualifiedColumnMap.get(rowkey);
            if (sqlType == null) {
                throw new SQLExceptionInfo.Builder(SQLExceptionCode.PRIMARY_KEY_MISSING)
                     .setColumnName(rowkey).setTableName(fullTableName).build().buildException();
            }
            columnMetadata[position] = new ColumnInfo(rowkey, sqlType);
            position++;
        }
        
        this.upsertStatement = QueryUtil.constructUpsertStatement(fullTableName, Arrays.asList(columnMetadata));
        logger.info(" the upsert statement is {} " ,this.upsertStatement);
        
    }  catch (SQLException e) {
        logger.error("error {} occurred during initializing connection ",e.getMessage());
        throw e;
    } finally {
        if(rs != null) {
            rs.close();
        }
    }
    doInitialize();
}
 
Example 14
Source File: StaleRegionBoundaryCacheException.java    From phoenix with Apache License 2.0 4 votes vote down vote up
public StaleRegionBoundaryCacheException(byte[] fullTableName) {
    this(SchemaUtil.getSchemaNameFromFullName(fullTableName),SchemaUtil.getTableNameFromFullName(fullTableName));
}
 
Example 15
Source File: StaleRegionBoundaryCacheException.java    From phoenix with Apache License 2.0 4 votes vote down vote up
public StaleRegionBoundaryCacheException(String fullTableName) {
    this(SchemaUtil.getSchemaNameFromFullName(fullTableName),SchemaUtil.getTableNameFromFullName(fullTableName));
}
 
Example 16
Source File: IndexNotFoundException.java    From phoenix with Apache License 2.0 4 votes vote down vote up
public IndexNotFoundException(String tableName) {
    this(SchemaUtil.getSchemaNameFromFullName(tableName),
            SchemaUtil.getTableNameFromFullName(tableName));
}
 
Example 17
Source File: UpdateCacheIT.java    From phoenix with Apache License 2.0 4 votes vote down vote up
private static void helpTestUpdateCache(String fullTableName, int[] expectedRPCs,
           boolean skipUpsertForIndexes) throws Exception {
    String tableName = SchemaUtil.getTableNameFromFullName(fullTableName);
    String schemaName = SchemaUtil.getSchemaNameFromFullName(fullTableName);
	String selectSql = "SELECT * FROM "+fullTableName;
	// use a spyed ConnectionQueryServices so we can verify calls to getTable
	ConnectionQueryServices connectionQueryServices = Mockito.spy(driver.getConnectionQueryServices(getUrl(), PropertiesUtil.deepCopy(TEST_PROPERTIES)));
	Properties props = new Properties();
	props.putAll(PhoenixEmbeddedDriver.DEFAULT_PROPS.asMap());
	Connection conn = connectionQueryServices.connect(getUrl(), props);
	try {
		conn.setAutoCommit(false);
           if (!skipUpsertForIndexes) {
               String upsert = "UPSERT INTO " + fullTableName + "(varchar_pk, char_pk, int_pk, long_pk, decimal_pk, date_pk) VALUES(?, ?, ?, ?, ?, ?)";
               PreparedStatement stmt = conn.prepareStatement(upsert);
               // upsert three rows
               for (int i=0; i<3; i++) {
                   TestUtil.setRowKeyColumns(stmt, i);
                   stmt.execute();
               }
               conn.commit();
               int numUpsertRpcs = expectedRPCs[0];
               // verify only 0 or 1 rpc to fetch table metadata,
               verify(connectionQueryServices, times(numUpsertRpcs)).getTable((PName) isNull(),
                       eq(PVarchar.INSTANCE.toBytes(schemaName)), eq(PVarchar.INSTANCE.toBytes(tableName)),
                       anyLong(), anyLong());
               reset(connectionQueryServices);
           }
           validateSelectRowKeyCols(conn, selectSql, skipUpsertForIndexes);
           validateSelectRowKeyCols(conn, selectSql, skipUpsertForIndexes);
           validateSelectRowKeyCols(conn, selectSql, skipUpsertForIndexes);

        // for non-transactional tables without a scn : verify one rpc to getTable occurs *per* query
           // for non-transactional tables with a scn : verify *only* one rpc occurs
           // for transactional tables : verify *only* one rpc occurs
        // for non-transactional, system tables : verify no rpc occurs
           int numRpcs = skipUpsertForIndexes ? expectedRPCs[0] : expectedRPCs[1];
           verify(connectionQueryServices, times(numRpcs)).getTable((PName) isNull(),
               eq(PVarchar.INSTANCE.toBytes(schemaName)), eq(PVarchar.INSTANCE.toBytes(tableName)),
               anyLong(), anyLong());
	}
       finally {
       	conn.close();
       }
}
 
Example 18
Source File: StaleRegionBoundaryCacheException.java    From phoenix with Apache License 2.0 4 votes vote down vote up
public StaleRegionBoundaryCacheException(String fullTableName) {
    this(SchemaUtil.getSchemaNameFromFullName(fullTableName),SchemaUtil.getTableNameFromFullName(fullTableName));
}
 
Example 19
Source File: StaleRegionBoundaryCacheException.java    From phoenix with Apache License 2.0 4 votes vote down vote up
public StaleRegionBoundaryCacheException(byte[] fullTableName) {
    this(SchemaUtil.getSchemaNameFromFullName(fullTableName),SchemaUtil.getTableNameFromFullName(fullTableName));
}
 
Example 20
Source File: AlterMultiTenantTableWithViewsIT.java    From phoenix with Apache License 2.0 4 votes vote down vote up
public static void assertTableDefinition(Connection conn, String fullTableName, PTableType tableType, String parentTableName, int sequenceNumber, int columnCount, int baseColumnCount, String... columnName) throws Exception {
    String schemaName = SchemaUtil.getSchemaNameFromFullName(fullTableName);
    String tableName = SchemaUtil.getTableNameFromFullName(fullTableName);
    PreparedStatement p = conn.prepareStatement("SELECT * FROM \"SYSTEM\".\"CATALOG\" WHERE TABLE_SCHEM=? AND TABLE_NAME=? AND TABLE_TYPE=?");
    p.setString(1, schemaName);
    p.setString(2, tableName);
    p.setString(3, tableType.getSerializedValue());
    ResultSet rs = p.executeQuery();
    assertTrue(rs.next());
    assertEquals(AlterTableWithViewsIT.getSystemCatalogEntriesForTable(conn, fullTableName, "Mismatch in BaseColumnCount"), baseColumnCount, rs.getInt("BASE_COLUMN_COUNT"));
    assertEquals(AlterTableWithViewsIT.getSystemCatalogEntriesForTable(conn, fullTableName, "Mismatch in columnCount"), columnCount, rs.getInt("COLUMN_COUNT"));
    assertEquals(AlterTableWithViewsIT.getSystemCatalogEntriesForTable(conn, fullTableName, "Mismatch in sequenceNumber"), sequenceNumber, rs.getInt("TABLE_SEQ_NUM"));
    rs.close();

    ResultSet parentTableColumnsRs = null; 
    if (parentTableName != null) {
        parentTableColumnsRs = conn.getMetaData().getColumns(null, null, parentTableName, null);
        parentTableColumnsRs.next();
    }
    
    ResultSet viewColumnsRs = conn.getMetaData().getColumns(null, schemaName, tableName, null);
    for (int i = 0; i < columnName.length; i++) {
        if (columnName[i] != null) {
            assertTrue(viewColumnsRs.next());
            assertEquals(AlterTableWithViewsIT.getSystemCatalogEntriesForTable(conn, fullTableName, "Mismatch in columnName: i=" + i), columnName[i], viewColumnsRs.getString(PhoenixDatabaseMetaData.COLUMN_NAME));
            int viewColOrdinalPos = viewColumnsRs.getInt(PhoenixDatabaseMetaData.ORDINAL_POSITION);
            assertEquals(AlterTableWithViewsIT.getSystemCatalogEntriesForTable(conn, fullTableName, "Mismatch in ordinalPosition: i=" + i), i+1, viewColOrdinalPos);
            // validate that all the columns in the base table are present in the view   
            if (parentTableColumnsRs != null && !parentTableColumnsRs.isAfterLast()) {
                ResultSetMetaData parentTableColumnsMetadata = parentTableColumnsRs.getMetaData();
                assertEquals(parentTableColumnsMetadata.getColumnCount(), viewColumnsRs.getMetaData().getColumnCount());
                int parentTableColOrdinalRs = parentTableColumnsRs.getInt(PhoenixDatabaseMetaData.ORDINAL_POSITION);
                assertEquals(AlterTableWithViewsIT.getSystemCatalogEntriesForTable(conn, fullTableName, "Mismatch in ordinalPosition of view and base table for i=" + i), parentTableColOrdinalRs, viewColOrdinalPos);
                for (int columnIndex = 1; columnIndex < parentTableColumnsMetadata.getColumnCount(); columnIndex++) {
                    String viewColumnValue = viewColumnsRs.getString(columnIndex);
                    String parentTableColumnValue = parentTableColumnsRs.getString(columnIndex);
                    if (!Objects.equal(viewColumnValue, parentTableColumnValue)) {
                        if (parentTableColumnsMetadata.getColumnName(columnIndex).equals(PhoenixDatabaseMetaData.TABLE_NAME)) {
                            assertEquals(parentTableName, parentTableColumnValue);
                            assertEquals(fullTableName, viewColumnValue);
                        } 
                    }
                }
                parentTableColumnsRs.next();
            }
        }
    }
    assertFalse(AlterTableWithViewsIT.getSystemCatalogEntriesForTable(conn, fullTableName, ""), viewColumnsRs.next());
}