Java Code Examples for org.apache.phoenix.jdbc.PhoenixConnection#getTenantId()

The following examples show how to use org.apache.phoenix.jdbc.PhoenixConnection#getTenantId() . 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: PhoenixRuntime.java    From phoenix with Apache License 2.0 6 votes vote down vote up
/**
 * Decode a byte array value back into the Object values of the
 * primary key constraint. If the connection and table are both
 * tenant-specific, the tenant ID column is not expected to have
 * been encoded and will not appear in the returned values.
 * @param conn an open connection
 * @param name the full table name
 * @param encodedValue the value that was encoded with {@link #encodePK(Connection, String, Object[])}
 * @return the Object values encoded in the byte array value
 * @throws SQLException
 */
@Deprecated
public static Object[] decodePK(Connection conn, String name, byte[] value) throws SQLException {
    PTable table = getTable(conn, name);
    PhoenixConnection pconn = conn.unwrap(PhoenixConnection.class);
    int offset = (table.getBucketNum() == null ? 0 : 1) + (table.isMultiTenant() && pconn.getTenantId() != null ? 1 : 0);
    int nValues = table.getPKColumns().size() - offset;
    RowKeySchema schema = table.getRowKeySchema();
    Object[] values = new Object[nValues];
    ImmutableBytesWritable ptr = new ImmutableBytesWritable();
    schema.iterator(value, ptr);
    int i = 0;
    int fieldIdx = offset;
    while (i < nValues && schema.next(ptr, fieldIdx, value.length) != null) {
        values[i] = schema.getField(fieldIdx).getDataType().toObject(ptr);
        i++;
        fieldIdx++;
    }
    return values;
}
 
Example 2
Source File: PhoenixRuntime.java    From phoenix with Apache License 2.0 6 votes vote down vote up
private static List<PColumn> getPkColumns(PTable ptable, Connection conn, boolean forDataTable) throws SQLException {
    PhoenixConnection pConn = conn.unwrap(PhoenixConnection.class);
    List<PColumn> pkColumns = ptable.getPKColumns();
    
    // Skip the salting column and the view index id column if present.
    // Skip the tenant id column too if the connection is tenant specific and the table used by the query plan is multi-tenant
    int offset = (ptable.getBucketNum() == null ? 0 : 1) + (ptable.isMultiTenant() && pConn.getTenantId() != null ? 1 : 0) + (ptable.getViewIndexId() == null ? 0 : 1);
    
    // get a sublist of pkColumns by skipping the offset columns.
    pkColumns = pkColumns.subList(offset, pkColumns.size());
    
    if (ptable.getType() == PTableType.INDEX && forDataTable) {
        // index tables have the same schema name as their parent/data tables.
        String fullDataTableName = ptable.getParentName().getString();
        
        // Get the corresponding columns of the data table.
        List<PColumn> dataColumns = IndexUtil.getDataColumns(fullDataTableName, pkColumns, pConn);
        pkColumns = dataColumns;
    }
    return pkColumns;
}
 
Example 3
Source File: PhoenixRuntime.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Deprecated
private static List<PColumn> getPkColumns(PTable ptable, Connection conn, boolean forDataTable) throws SQLException {
    PhoenixConnection pConn = conn.unwrap(PhoenixConnection.class);
    List<PColumn> pkColumns = ptable.getPKColumns();
    
    // Skip the salting column and the view index id column if present.
    // Skip the tenant id column too if the connection is tenant specific and the table used by the query plan is multi-tenant
    int offset = (ptable.getBucketNum() == null ? 0 : 1) + (ptable.isMultiTenant() && pConn.getTenantId() != null ? 1 : 0) + (ptable.getViewIndexId() == null ? 0 : 1);
    
    // get a sublist of pkColumns by skipping the offset columns.
    pkColumns = pkColumns.subList(offset, pkColumns.size());
    
    if (ptable.getType() == PTableType.INDEX && forDataTable) {
        // index tables have the same schema name as their parent/data tables.
        String fullDataTableName = ptable.getParentName().getString();
        
        // Get the corresponding columns of the data table.
        List<PColumn> dataColumns = IndexUtil.getDataColumns(fullDataTableName, pkColumns, pConn);
        pkColumns = dataColumns;
    }
    return pkColumns;
}
 
Example 4
Source File: PhoenixRuntime.java    From phoenix with Apache License 2.0 6 votes vote down vote up
private static List<PColumn> getPkColumns(PTable ptable, Connection conn) throws SQLException {
    PhoenixConnection pConn = conn.unwrap(PhoenixConnection.class);
    List<PColumn> pkColumns = ptable.getPKColumns();
    
    // Skip the salting column and the view index id column if present.
    // Skip the tenant id column too if the connection is tenant specific and the table used by the query plan is multi-tenant
    int offset = (ptable.getBucketNum() == null ? 0 : 1) + (ptable.isMultiTenant() && pConn.getTenantId() != null ? 1 : 0) + (ptable.getViewIndexId() == null ? 0 : 1);
    
    // get a sublist of pkColumns by skipping the offset columns.
    pkColumns = pkColumns.subList(offset, pkColumns.size());
    
    if (ptable.getType() == PTableType.INDEX) {
        // index tables have the same schema name as their parent/data tables.
        String fullDataTableName = ptable.getParentName().getString();
        
        // Get the corresponding columns of the data table.
        List<PColumn> dataColumns = IndexUtil.getDataColumns(fullDataTableName, pkColumns, pConn);
        pkColumns = dataColumns;
    }
    return pkColumns;
}
 
Example 5
Source File: UpgradeUtil.java    From phoenix with Apache License 2.0 6 votes vote down vote up
private static void updateIndexesSequenceIfPresent(PhoenixConnection connection, PTable dataTable)
        throws SQLException {
    PName tenantId = connection.getTenantId();
    PName physicalName = dataTable.getPhysicalName();
    PName oldPhysicalName = PNameFactory.newName(
            physicalName.toString().replace(QueryConstants.NAMESPACE_SEPARATOR, QueryConstants.NAME_SEPARATOR));
    String oldSchemaName = MetaDataUtil.getViewIndexSequenceSchemaName(oldPhysicalName, false);
    String newSchemaName = MetaDataUtil.getViewIndexSequenceSchemaName(physicalName, true);
    String newSequenceName = MetaDataUtil.getViewIndexSequenceName(physicalName, tenantId, true);
    // create new entry with new schema format
    String upsert = "UPSERT INTO " + PhoenixDatabaseMetaData.SYSTEM_SEQUENCE + " SELECT NULL,\'" + newSchemaName +
        "\',\'" + newSequenceName
            + "\'," + START_WITH + "," + CURRENT_VALUE + "," + INCREMENT_BY + "," + CACHE_SIZE + "," + MIN_VALUE
            + "," + MAX_VALUE + "," + CYCLE_FLAG + "," + LIMIT_REACHED_FLAG + " FROM "
            + PhoenixDatabaseMetaData.SYSTEM_SEQUENCE + " WHERE " + PhoenixDatabaseMetaData.TENANT_ID
            + " IS NULL AND " + PhoenixDatabaseMetaData.SEQUENCE_SCHEMA + " = '" + oldSchemaName + "'";
    connection.createStatement().executeUpdate(upsert);
}
 
Example 6
Source File: QueryUtil.java    From phoenix with Apache License 2.0 6 votes vote down vote up
public static void addTenantIdFilter(PhoenixConnection connection, StringBuilder buf, String tenantIdPattern,
                                     List<String> parameterValues) {
    PName tenantId = connection.getTenantId();
    if (tenantIdPattern == null) {
        if (tenantId != null) {
            appendConjunction(buf);
            buf.append(" (" + TENANT_ID + " IS NULL " +
                    " OR " + TENANT_ID + " = ?) ");
            parameterValues.add(tenantId.getString());
        }
    } else if (tenantIdPattern.length() == 0) {
        appendConjunction(buf);
        buf.append(TENANT_ID + " IS NULL ");
    } else {
        appendConjunction(buf);
        buf.append(" TENANT_ID LIKE ? ");
        parameterValues.add(tenantIdPattern);
        if (tenantId != null) {
            buf.append(" and TENANT_ID = ? ");
            parameterValues.add(tenantId.getString());
        }
    }
}
 
Example 7
Source File: FromCompiler.java    From phoenix with Apache License 2.0 5 votes vote down vote up
public static ColumnResolver getResolverForCreation(final CreateTableStatement statement, final PhoenixConnection connection)
        throws SQLException {
    TableName baseTable = statement.getBaseTableName();
    if (baseTable == null) {
        return EMPTY_TABLE_RESOLVER;
    }
    NamedTableNode tableNode = NamedTableNode.create(null, baseTable, Collections.<ColumnDef>emptyList());
    // Always use non-tenant-specific connection here
    try {
        SingleTableColumnResolver visitor = new SingleTableColumnResolver(connection, tableNode, true);
        return visitor;
    } catch (TableNotFoundException e) {
        // Used for mapped VIEW, since we won't be able to resolve that.
        // Instead, we create a table with just the dynamic columns.
        // A tenant-specific connection may not create a mapped VIEW.
        if (connection.getTenantId() == null && statement.getTableType() == PTableType.VIEW) {
            ConnectionQueryServices services = connection.getQueryServices();
            byte[] fullTableName = SchemaUtil.getTableNameAsBytes(baseTable.getSchemaName(), baseTable.getTableName());
            HTableInterface htable = null;
            try {
                htable = services.getTable(fullTableName);
            } catch (UnsupportedOperationException ignore) {
                throw e; // For Connectionless
            } finally {
                if (htable != null) Closeables.closeQuietly(htable);
            }
            tableNode = NamedTableNode.create(null, baseTable, statement.getColumnDefs());
            return new SingleTableColumnResolver(connection, tableNode, e.getTimeStamp());
        }
        throw e;
    }
}
 
Example 8
Source File: FromCompiler.java    From phoenix with Apache License 2.0 5 votes vote down vote up
public SingleTableColumnResolver(PhoenixConnection connection, NamedTableNode table, long timeStamp) throws SQLException  {
    super(connection, 0);
    List<PColumnFamily> families = Lists.newArrayListWithExpectedSize(table.getDynamicColumns().size());
    for (ColumnDef def : table.getDynamicColumns()) {
        if (def.getColumnDefName().getFamilyName() != null) {
            families.add(new PColumnFamilyImpl(PNameFactory.newName(def.getColumnDefName().getFamilyName()),Collections.<PColumn>emptyList()));
        }
    }
    Long scn = connection.getSCN();
    PTable theTable = new PTableImpl(connection.getTenantId(), table.getName().getSchemaName(), table.getName().getTableName(), scn == null ? HConstants.LATEST_TIMESTAMP : scn, families);
    theTable = this.addDynamicColumns(table.getDynamicColumns(), theTable);
    alias = null;
    tableRefs = ImmutableList.of(new TableRef(alias, theTable, timeStamp, !table.getDynamicColumns().isEmpty()));
}
 
Example 9
Source File: PhoenixRuntime.java    From phoenix with Apache License 2.0 5 votes vote down vote up
/**
 * Encode the primary key values from the table as a byte array. The values must
 * be in the same order as the primary key constraint. If the connection and
 * table are both tenant-specific, the tenant ID column must not be present in
 * the values.
 * @param conn an open connection
 * @param fullTableName the full table name
 * @param values the values of the primary key columns ordered in the same order
 *  as the primary key constraint
 * @return the encoded byte array
 * @throws SQLException if the table cannot be found or the incorrect number of
 *  of values are provided
 * @see #decodePK(Connection, String, byte[]) to decode the byte[] back to the
 *  values
 */
@Deprecated
public static byte[] encodePK(Connection conn, String fullTableName, Object[] values) throws SQLException {
    PTable table = getTable(conn, fullTableName);
    PhoenixConnection pconn = conn.unwrap(PhoenixConnection.class);
    int offset = (table.getBucketNum() == null ? 0 : 1) + (table.isMultiTenant() && pconn.getTenantId() != null ? 1 : 0);
    List<PColumn> pkColumns = table.getPKColumns();
    if (pkColumns.size() - offset != values.length) {
        throw new SQLException("Expected " + (pkColumns.size() - offset) + " but got " + values.length);
    }
    PDataType type = null;
    TrustedByteArrayOutputStream output = new TrustedByteArrayOutputStream(table.getRowKeySchema().getEstimatedValueLength());
    try {
        for (int i = offset; i < pkColumns.size(); i++) {
            if (type != null && !type.isFixedWidth()) {
                output.write(QueryConstants.SEPARATOR_BYTE);
            }
            type = pkColumns.get(i).getDataType();

            //for fixed width data types like CHAR and BINARY, we need to pad values to be of max length.
            Object paddedObj = type.pad(values[i - offset], pkColumns.get(i).getMaxLength());
            byte[] value = type.toBytes(paddedObj);
            output.write(value);
        }
        return output.toByteArray();
    } finally {
        try {
            output.close();
        } catch (IOException e) {
            throw new RuntimeException(e); // Impossible
        }
    }
}
 
Example 10
Source File: PhoenixConfigurationUtil.java    From phoenix with Apache License 2.0 5 votes vote down vote up
public static boolean getStatsForParallelizationProp(PhoenixConnection conn, PTable table) {
    Boolean useStats = table.useStatsForParallelization();
    if (useStats != null) {
        return useStats;
    }
    /*
     * For a view index, we use the property set on view. For indexes on base table, whether
     * global or local, we use the property set on the base table. Null check needed when
     * dropping local indexes.
     */
    PName tenantId = conn.getTenantId();
    int retryCount = 0;
    while (retryCount++<2) {
	    if (table.getType() == PTableType.INDEX && table.getParentName() != null) {
	        String parentTableName = table.getParentName().getString();
			try {
	            PTable parentTable =
	                    conn.getTable(new PTableKey(tenantId, parentTableName));
	            useStats = parentTable.useStatsForParallelization();
	            if (useStats != null) {
	                return useStats;
	            }
			} catch (TableNotFoundException e) {
				// try looking up the table without the tenant id (for
				// global tables)
				if (tenantId != null) {
					tenantId = null;
				} else {
					BaseResultIterators.LOGGER.warn(
							"Unable to find parent table \"" + parentTableName + "\" of table \""
									+ table.getName().getString() + "\" to determine USE_STATS_FOR_PARALLELIZATION",
							e);
				}
			}
	    }
    }
    return conn.getQueryServices().getConfiguration()
            .getBoolean(USE_STATS_FOR_PARALLELIZATION, DEFAULT_USE_STATS_FOR_PARALLELIZATION);
}
 
Example 11
Source File: ExpressionUtil.java    From phoenix with Apache License 2.0 5 votes vote down vote up
/**
 * For table with salted/multiTenant/viewIndexId,some leading rowkey columns should be skipped.
 * @param table
 * @param phoenixConnection
 * @return
 */
public static int getRowKeyColumnOffset(PTable table, PhoenixConnection phoenixConnection) {
    boolean isSalted = table.getBucketNum() != null;
    boolean isMultiTenant = phoenixConnection.getTenantId() != null && table.isMultiTenant();
    boolean isSharedViewIndex = table.getViewIndexId() != null;
    return (isSalted ? 1 : 0) + (isMultiTenant ? 1 : 0) + (isSharedViewIndex ? 1 : 0);
}
 
Example 12
Source File: UpgradeUtil.java    From phoenix with Apache License 2.0 5 votes vote down vote up
private static void updateLink(PhoenixConnection conn, String srcTableName,
        String destTableName, PName schemaName, PName tableName) throws SQLException {
    String updateLinkSql = String.format(UPDATE_LINK, destTableName);
    boolean hasTenantId = conn.getTenantId() != null && conn.getTenantId().getBytes().length!=0;
    if (hasTenantId) {
        updateLinkSql += " AND TENANT_ID  = ? ";
    }
    PreparedStatement updateLinkStatment = conn.prepareStatement(updateLinkSql);
    updateLinkStatment.setString(1, schemaName.getString());
    updateLinkStatment.setString(2, schemaName.getString());
    updateLinkStatment.setString(3, tableName.getString());
    updateLinkStatment.setString(4, srcTableName);
    if (hasTenantId) {
        updateLinkStatment.setString(5, conn.getTenantId().getString());
    }
    updateLinkStatment.execute();
    String deleteLinkSql = DELETE_LINK;
    if (hasTenantId) {
        deleteLinkSql += (" AND TENANT_ID  = ? ");
    }
    PreparedStatement deleteLinkStatment = conn.prepareStatement(deleteLinkSql);
    deleteLinkStatment.setString(1, schemaName.getString());
    deleteLinkStatment.setString(2, schemaName.getString());
    deleteLinkStatment.setString(3, tableName.getString());
    deleteLinkStatment.setString(4, srcTableName);
    if (hasTenantId) {
        deleteLinkStatment.setString(5, conn.getTenantId().getString());
    }
    deleteLinkStatment.execute();
}
 
Example 13
Source File: FromCompiler.java    From phoenix with Apache License 2.0 4 votes vote down vote up
public static ColumnResolver getResolverForCreation(final CreateTableStatement statement, final PhoenixConnection connection)
        throws SQLException {
	
    TableName baseTable = statement.getBaseTableName();
    String schemaName;
    if (baseTable == null) {
        if (SchemaUtil.isSchemaCheckRequired(statement.getTableType(), connection.getQueryServices().getProps())) {
            schemaName = statement.getTableName().getSchemaName();
            if (schemaName != null) {
                new SchemaResolver(connection, statement.getTableName().getSchemaName(), true);
            } else if (connection.getSchema() != null) {
                // To ensure schema set through properties or connection string exists before creating table
                new SchemaResolver(connection, connection.getSchema(), true);
            }
        }
        return EMPTY_TABLE_RESOLVER;
    }
    NamedTableNode tableNode = NamedTableNode.create(null, baseTable, Collections.<ColumnDef>emptyList());
    // Always use non-tenant-specific connection here
    try {
        SingleTableColumnResolver visitor = new SingleTableColumnResolver(connection, tableNode, true);
        return visitor;
    } catch (TableNotFoundException e) {
        // Used for mapped VIEW, since we won't be able to resolve that.
        // Instead, we create a table with just the dynamic columns.
        // A tenant-specific connection may not create a mapped VIEW.
        if (connection.getTenantId() == null && statement.getTableType() == PTableType.VIEW) {
            ConnectionQueryServices services = connection.getQueryServices();
            boolean isNamespaceMapped = SchemaUtil.isNamespaceMappingEnabled(statement.getTableType(), connection.getQueryServices().getProps());
            byte[] fullTableName = SchemaUtil.getPhysicalHBaseTableName(
                baseTable.getSchemaName(), baseTable.getTableName(), isNamespaceMapped).getBytes();
            Table htable = null;
            try {
                htable = services.getTable(fullTableName);
            } catch (UnsupportedOperationException ignore) {
                throw e; // For Connectionless
            } finally {
                if (htable != null) Closeables.closeQuietly(htable);
            }
            tableNode = NamedTableNode.create(null, baseTable, statement.getColumnDefs());
            return new SingleTableColumnResolver(connection, tableNode, e.getTimeStamp(), new HashMap<String, UDFParseNode>(1), isNamespaceMapped);
        }
        throw e;
    }
}
 
Example 14
Source File: FromCompiler.java    From phoenix with Apache License 2.0 4 votes vote down vote up
public SingleTableColumnResolver(PhoenixConnection connection, NamedTableNode table, long timeStamp, Map<String, UDFParseNode> udfParseNodes, boolean isNamespaceMapped) throws SQLException {
    super(connection, 0, false, udfParseNodes, null);
    List<PColumnFamily> families = Lists.newArrayListWithExpectedSize(table.getDynamicColumns().size());
    for (ColumnDef def : table.getDynamicColumns()) {
        if (def.getColumnDefName().getFamilyName() != null) {
            families.add(new PColumnFamilyImpl(PNameFactory.newName(def.getColumnDefName().getFamilyName()),Collections.<PColumn>emptyList()));//, NON_ENCODED_QUALIFIERS));
        }
    }
    Long scn = connection.getSCN();
    String schema = table.getName().getSchemaName();
    if (connection.getSchema() != null) {
        schema = schema != null ? schema : connection.getSchema();
    }

    // Storage scheme and encoding scheme don't matter here since the PTable is being used only for the purposes of create table.
    // The actual values of these two will be determined by the metadata client.
    PName tenantId = connection.getTenantId();
    PTableImpl.checkTenantId(tenantId);
    String tableName = table.getName().getTableName();
    PName name = PNameFactory.newName(SchemaUtil.getTableName(schema, tableName));
    PTable theTable = new PTableImpl.Builder()
            .setTenantId(tenantId)
            .setName(name)
            .setKey(new PTableKey(tenantId, name.getString()))
            .setSchemaName(PNameFactory.newName(schema))
            .setTableName(PNameFactory.newName(tableName))
            .setType(PTableType.VIEW)
            .setViewType(PTable.ViewType.MAPPED)
            .setTimeStamp(scn == null ? HConstants.LATEST_TIMESTAMP : scn)
            .setPkColumns(Collections.emptyList())
            .setAllColumns(Collections.emptyList())
            .setRowKeySchema(RowKeySchema.EMPTY_SCHEMA)
            .setIndexes(Collections.emptyList())
            .setFamilyAttributes(families)
            .setPhysicalNames(Collections.emptyList())
            .setNamespaceMapped(isNamespaceMapped)
            .build();
    theTable = this.addDynamicColumns(table.getDynamicColumns(), theTable);
    alias = null;
    tableRefs = ImmutableList.of(new TableRef(alias, theTable, timeStamp, !table.getDynamicColumns().isEmpty()));
    schemas = ImmutableList.of(new PSchema(theTable.getSchemaName().toString(), timeStamp));
}
 
Example 15
Source File: IndexMetaDataCacheClient.java    From phoenix with Apache License 2.0 4 votes vote down vote up
public static ServerCache setMetaDataOnMutations(PhoenixConnection connection, PTable table, List<? extends Mutation> mutations,
        ImmutableBytesWritable indexMetaDataPtr) throws SQLException {
    final byte[] tenantIdBytes;
    if (table.isMultiTenant()) {
        tenantIdBytes = connection.getTenantId() == null ? null : ScanUtil.getTenantIdBytes(
                table.getRowKeySchema(), table.getBucketNum() != null, connection.getTenantId(),
                table.getViewIndexId() != null);
    } else {
        tenantIdBytes = connection.getTenantId() == null ? null : connection.getTenantId().getBytes();
    }
    ServerCache cache = null;
    byte[] attribValue = null;
    byte[] uuidValue = null;
    byte[] txState = ByteUtil.EMPTY_BYTE_ARRAY;
    if (table.isTransactional()) {
        txState = connection.getMutationState().encodeTransaction();
    }
    boolean hasIndexMetaData = indexMetaDataPtr.getLength() > 0;
    if (hasIndexMetaData) {
        if (useIndexMetadataCache(connection, mutations, indexMetaDataPtr.getLength() + txState.length)) {
            IndexMetaDataCacheClient client = new IndexMetaDataCacheClient(connection, table);
            cache = client.addIndexMetadataCache(mutations, indexMetaDataPtr, txState);
            uuidValue = cache.getId();
        } else {
            attribValue = ByteUtil.copyKeyBytesIfNecessary(indexMetaDataPtr);
            uuidValue = ServerCacheClient.generateId();
        }
    } else if (txState.length == 0) { return null; }
    // Either set the UUID to be able to access the index metadata from the cache
    // or set the index metadata directly on the Mutation
    for (Mutation mutation : mutations) {
        if (connection.getTenantId() != null) {
            mutation.setAttribute(PhoenixRuntime.TENANT_ID_ATTRIB, tenantIdBytes);
        }
        mutation.setAttribute(PhoenixIndexCodec.INDEX_UUID, uuidValue);
        if (attribValue != null) {
            mutation.setAttribute(PhoenixIndexCodec.INDEX_PROTO_MD, attribValue);
            mutation.setAttribute(BaseScannerRegionObserver.CLIENT_VERSION,
                    Bytes.toBytes(MetaDataProtocol.PHOENIX_VERSION));
            if (txState.length > 0) {
                mutation.setAttribute(BaseScannerRegionObserver.TX_STATE, txState);
            }
        } else if (!hasIndexMetaData && txState.length > 0) {
            mutation.setAttribute(BaseScannerRegionObserver.TX_STATE, txState);
        }
    }
    return cache;
}
 
Example 16
Source File: InvalidIndexStateClientSideIT.java    From phoenix with Apache License 2.0 4 votes vote down vote up
@Test
public void testCachedConnections() throws Throwable {
    final String schemaName = generateUniqueName();
    final String tableName = generateUniqueName();
    final String fullTableName = SchemaUtil.getTableName(schemaName, tableName);
    final String indexName = generateUniqueName();
    final String fullIndexName = SchemaUtil.getTableName(schemaName, indexName);
    final Connection conn = DriverManager.getConnection(getUrl());

    // create table and indices
    String createTableSql =
            "CREATE TABLE " + fullTableName
                    + "(org_id VARCHAR NOT NULL PRIMARY KEY, v1 INTEGER, v2 INTEGER, v3 INTEGER)";
    conn.createStatement().execute(createTableSql);
    conn.createStatement()
            .execute("CREATE INDEX " + indexName + " ON " + fullTableName + "(v1)");
    conn.commit();
    PhoenixConnection phoenixConn = conn.unwrap(PhoenixConnection.class);
    ConnectionQueryServices queryServices = phoenixConn.getQueryServices();
    Table metaTable =
            phoenixConn.getQueryServices()
                    .getTable(PhoenixDatabaseMetaData.SYSTEM_CATALOG_NAME_BYTES);
    long ts = EnvironmentEdgeManager.currentTimeMillis();
    MutationCode code =
            IndexUtil
                    .updateIndexState(fullIndexName, ts, metaTable, PIndexState.PENDING_DISABLE)
                    .getMutationCode();
    assertEquals(MutationCode.TABLE_ALREADY_EXISTS, code);
    ts = EnvironmentEdgeManager.currentTimeMillis();

    final byte[] schemaBytes = PVarchar.INSTANCE.toBytes(schemaName);
    final byte[] tableBytes = PVarchar.INSTANCE.toBytes(tableName);
    PName tenantId = phoenixConn.getTenantId();
    final long tableTimestamp = HConstants.LATEST_TIMESTAMP;
    long tableResolvedTimestamp = HConstants.LATEST_TIMESTAMP;
    final long resolvedTimestamp = tableResolvedTimestamp;
    final byte[] tenantIdBytes =
            tenantId == null ? ByteUtil.EMPTY_BYTE_ARRAY : tenantId.getBytes();
    byte[] tableKey = SchemaUtil.getTableKey(tenantIdBytes, schemaBytes, tableBytes);
    Batch.Call<MetaDataService, MetaDataResponse> callable =
            new Batch.Call<MetaDataService, MetaDataResponse>() {
                @Override
                public MetaDataResponse call(MetaDataService instance) throws IOException {
                    ServerRpcController controller = new ServerRpcController();
                    BlockingRpcCallback<MetaDataResponse> rpcCallback =
                            new BlockingRpcCallback<MetaDataResponse>();
                    GetTableRequest.Builder builder = GetTableRequest.newBuilder();
                    builder.setTenantId(ByteStringer.wrap(tenantIdBytes));
                    builder.setSchemaName(ByteStringer.wrap(schemaBytes));
                    builder.setTableName(ByteStringer.wrap(tableBytes));
                    builder.setTableTimestamp(tableTimestamp);
                    builder.setClientTimestamp(resolvedTimestamp);
                    builder.setClientVersion(VersionUtil.encodeVersion(PHOENIX_MAJOR_VERSION,
                        13, PHOENIX_PATCH_NUMBER));
                    instance.getTable(controller, builder.build(), rpcCallback);
                    if (controller.getFailedOn() != null) {
                        throw controller.getFailedOn();
                    }
                    return rpcCallback.get();
                }
            };
    int version = VersionUtil.encodeVersion(PHOENIX_MAJOR_VERSION, 13, PHOENIX_PATCH_NUMBER);
    LOGGER.info("Client version: " + version);
    Table ht =
            queryServices.getTable(PhoenixDatabaseMetaData.SYSTEM_CATALOG_NAME_BYTES);
    try {
        final Map<byte[], MetaDataResponse> results =
                ht.coprocessorService(MetaDataService.class, tableKey, tableKey, callable);

        assert (results.size() == 1);
        MetaDataResponse result = results.values().iterator().next();
        assert (result.getTable().getIndexesCount() == 1);
        assert (PIndexState.valueOf(result.getTable().getIndexes(0).getIndexState())
                .equals(PIndexState.DISABLE));
    } catch (Exception e) {
        LOGGER.error("Exception Occurred: " + e);

    } finally {
        Closeables.closeQuietly(ht);
    }

}