Search in sources :

Example 1 with MutationState

use of org.apache.phoenix.execute.MutationState in project phoenix by apache.

the class PhoenixConnection method setTransactionContext.

public void setTransactionContext(TransactionContext txContext) throws SQLException {
    if (!this.services.getProps().getBoolean(QueryServices.TRANSACTIONS_ENABLED, QueryServicesOptions.DEFAULT_TRANSACTIONS_ENABLED)) {
        throw new SQLExceptionInfo.Builder(SQLExceptionCode.TX_MUST_BE_ENABLED_TO_SET_TX_CONTEXT).build().buildException();
    }
    this.mutationState.rollback();
    this.mutationState = new MutationState(this.mutationState.getMaxSize(), this.mutationState.getMaxSizeBytes(), this, txContext);
    // Write data to HBase after each statement execution as the commit may not
    // come through Phoenix APIs.
    setAutoFlush(true);
}
Also used : MutationState(org.apache.phoenix.execute.MutationState) KeyValueBuilder(org.apache.phoenix.hbase.index.util.KeyValueBuilder) Builder(com.google.common.collect.ImmutableMap.Builder)

Example 2 with MutationState

use of org.apache.phoenix.execute.MutationState in project phoenix by apache.

the class MetaDataClient method buildIndex.

/**
     * For new mutations only should not be used if there are deletes done in the data table between start time and end
     * time passed to the method.
     */
public MutationState buildIndex(PTable index, TableRef dataTableRef, long startTime, long EndTime) throws SQLException {
    boolean wasAutoCommit = connection.getAutoCommit();
    try {
        AlterIndexStatement indexStatement = FACTORY.alterIndex(FACTORY.namedTable(null, TableName.create(index.getSchemaName().getString(), index.getTableName().getString())), dataTableRef.getTable().getTableName().getString(), false, PIndexState.INACTIVE);
        alterIndex(indexStatement);
        connection.setAutoCommit(true);
        MutationPlan mutationPlan = getMutationPlanForBuildingIndex(index, dataTableRef);
        Scan scan = mutationPlan.getContext().getScan();
        try {
            scan.setTimeRange(startTime, EndTime);
        } catch (IOException e) {
            throw new SQLException(e);
        }
        MutationState state = connection.getQueryServices().updateData(mutationPlan);
        indexStatement = FACTORY.alterIndex(FACTORY.namedTable(null, TableName.create(index.getSchemaName().getString(), index.getTableName().getString())), dataTableRef.getTable().getTableName().getString(), false, PIndexState.ACTIVE);
        alterIndex(indexStatement);
        return state;
    } finally {
        connection.setAutoCommit(wasAutoCommit);
    }
}
Also used : MutationState(org.apache.phoenix.execute.MutationState) SQLException(java.sql.SQLException) AlterIndexStatement(org.apache.phoenix.parse.AlterIndexStatement) Scan(org.apache.hadoop.hbase.client.Scan) IOException(java.io.IOException) MutationPlan(org.apache.phoenix.compile.MutationPlan)

Example 3 with MutationState

use of org.apache.phoenix.execute.MutationState in project phoenix by apache.

the class MetaDataClient method updateStatisticsInternal.

private long updateStatisticsInternal(PName physicalName, PTable logicalTable, Map<String, Object> statsProps, List<byte[]> cfs) throws SQLException {
    ReadOnlyProps props = connection.getQueryServices().getProps();
    final long msMinBetweenUpdates = props.getLong(QueryServices.MIN_STATS_UPDATE_FREQ_MS_ATTRIB, props.getLong(QueryServices.STATS_UPDATE_FREQ_MS_ATTRIB, QueryServicesOptions.DEFAULT_STATS_UPDATE_FREQ_MS) / 2);
    byte[] tenantIdBytes = ByteUtil.EMPTY_BYTE_ARRAY;
    Long scn = connection.getSCN();
    // Always invalidate the cache
    long clientTimeStamp = connection.getSCN() == null ? HConstants.LATEST_TIMESTAMP : scn;
    String query = "SELECT CURRENT_DATE()," + LAST_STATS_UPDATE_TIME + " FROM " + PhoenixDatabaseMetaData.SYSTEM_STATS_NAME + " WHERE " + PHYSICAL_NAME + "='" + physicalName.getString() + "' AND " + COLUMN_FAMILY + " IS NULL AND " + LAST_STATS_UPDATE_TIME + " IS NOT NULL";
    ResultSet rs = connection.createStatement().executeQuery(query);
    long msSinceLastUpdate = Long.MAX_VALUE;
    if (rs.next()) {
        msSinceLastUpdate = rs.getLong(1) - rs.getLong(2);
    }
    long rowCount = 0;
    if (msSinceLastUpdate >= msMinBetweenUpdates) {
        /*
             * Execute a COUNT(*) through PostDDLCompiler as we need to use the logicalTable passed through,
             * since it may not represent a "real" table in the case of the view indexes of a base table.
             */
        PostDDLCompiler compiler = new PostDDLCompiler(connection);
        //even if table is transactional, while calculating stats we scan the table non-transactionally to
        //view all the data belonging to the table
        PTable nonTxnLogicalTable = new DelegateTable(logicalTable) {

            @Override
            public boolean isTransactional() {
                return false;
            }
        };
        TableRef tableRef = new TableRef(null, nonTxnLogicalTable, clientTimeStamp, false);
        MutationPlan plan = compiler.compile(Collections.singletonList(tableRef), null, cfs, null, clientTimeStamp);
        Scan scan = plan.getContext().getScan();
        scan.setCacheBlocks(false);
        scan.setAttribute(ANALYZE_TABLE, TRUE_BYTES);
        boolean runUpdateStatsAsync = props.getBoolean(QueryServices.RUN_UPDATE_STATS_ASYNC, DEFAULT_RUN_UPDATE_STATS_ASYNC);
        scan.setAttribute(RUN_UPDATE_STATS_ASYNC_ATTRIB, runUpdateStatsAsync ? TRUE_BYTES : FALSE_BYTES);
        if (statsProps != null) {
            Object gp_width = statsProps.get(QueryServices.STATS_GUIDEPOST_WIDTH_BYTES_ATTRIB);
            if (gp_width != null) {
                scan.setAttribute(BaseScannerRegionObserver.GUIDEPOST_WIDTH_BYTES, PLong.INSTANCE.toBytes(gp_width));
            }
            Object gp_per_region = statsProps.get(QueryServices.STATS_GUIDEPOST_PER_REGION_ATTRIB);
            if (gp_per_region != null) {
                scan.setAttribute(BaseScannerRegionObserver.GUIDEPOST_PER_REGION, PInteger.INSTANCE.toBytes(gp_per_region));
            }
        }
        MutationState mutationState = plan.execute();
        rowCount = mutationState.getUpdateCount();
    }
    /*
         *  Update the stats table so that client will pull the new one with the updated stats.
         *  Even if we don't run the command due to the last update time, invalidate the cache.
         *  This supports scenarios in which a major compaction was manually initiated and the
         *  client wants the modified stats to be reflected immediately.
         */
    if (cfs == null) {
        List<PColumnFamily> families = logicalTable.getColumnFamilies();
        if (families.isEmpty()) {
            connection.getQueryServices().invalidateStats(new GuidePostsKey(physicalName.getBytes(), SchemaUtil.getEmptyColumnFamily(logicalTable)));
        } else {
            for (PColumnFamily family : families) {
                connection.getQueryServices().invalidateStats(new GuidePostsKey(physicalName.getBytes(), family.getName().getBytes()));
            }
        }
    } else {
        for (byte[] cf : cfs) {
            connection.getQueryServices().invalidateStats(new GuidePostsKey(physicalName.getBytes(), cf));
        }
    }
    return rowCount;
}
Also used : GuidePostsKey(org.apache.phoenix.schema.stats.GuidePostsKey) PostDDLCompiler(org.apache.phoenix.compile.PostDDLCompiler) MutationPlan(org.apache.phoenix.compile.MutationPlan) ReadOnlyProps(org.apache.phoenix.util.ReadOnlyProps) MutationState(org.apache.phoenix.execute.MutationState) PUnsignedLong(org.apache.phoenix.schema.types.PUnsignedLong) PLong(org.apache.phoenix.schema.types.PLong) ResultSet(java.sql.ResultSet) Scan(org.apache.hadoop.hbase.client.Scan)

Example 4 with MutationState

use of org.apache.phoenix.execute.MutationState in project phoenix by apache.

the class MetaDataClient method dropTable.

private MutationState dropTable(String schemaName, String tableName, String parentTableName, PTableType tableType, boolean ifExists, boolean cascade) throws SQLException {
    connection.rollback();
    boolean wasAutoCommit = connection.getAutoCommit();
    try {
        PName tenantId = connection.getTenantId();
        String tenantIdStr = tenantId == null ? null : tenantId.getString();
        byte[] key = SchemaUtil.getTableKey(tenantIdStr, schemaName, tableName);
        Long scn = connection.getSCN();
        long clientTimeStamp = scn == null ? HConstants.LATEST_TIMESTAMP : scn;
        List<Mutation> tableMetaData = Lists.newArrayListWithExpectedSize(2);
        Delete tableDelete = new Delete(key, clientTimeStamp);
        tableMetaData.add(tableDelete);
        boolean hasViewIndexTable = false;
        if (parentTableName != null) {
            byte[] linkKey = MetaDataUtil.getParentLinkKey(tenantIdStr, schemaName, parentTableName, tableName);
            Delete linkDelete = new Delete(linkKey, clientTimeStamp);
            tableMetaData.add(linkDelete);
        }
        MetaDataMutationResult result = connection.getQueryServices().dropTable(tableMetaData, tableType, cascade);
        MutationCode code = result.getMutationCode();
        PTable table = result.getTable();
        switch(code) {
            case TABLE_NOT_FOUND:
                if (!ifExists) {
                    throw new TableNotFoundException(schemaName, tableName);
                }
                break;
            case NEWER_TABLE_FOUND:
                throw new NewerTableAlreadyExistsException(schemaName, tableName, result.getTable());
            case UNALLOWED_TABLE_MUTATION:
                throw new SQLExceptionInfo.Builder(SQLExceptionCode.CANNOT_MUTATE_TABLE).setSchemaName(schemaName).setTableName(tableName).build().buildException();
            default:
                connection.removeTable(tenantId, SchemaUtil.getTableName(schemaName, tableName), parentTableName, result.getMutationTime());
                if (table != null) {
                    boolean dropMetaData = false;
                    long ts = (scn == null ? result.getMutationTime() : scn);
                    List<TableRef> tableRefs = Lists.newArrayListWithExpectedSize(2 + table.getIndexes().size());
                    connection.setAutoCommit(true);
                    if (tableType == PTableType.VIEW) {
                        for (PTable index : table.getIndexes()) {
                            tableRefs.add(new TableRef(null, index, ts, false));
                        }
                    } else {
                        dropMetaData = result.getTable().getViewIndexId() == null && connection.getQueryServices().getProps().getBoolean(DROP_METADATA_ATTRIB, DEFAULT_DROP_METADATA);
                        // All multi-tenant tables have a view index table, so no need to check in that case
                        if (parentTableName == null) {
                            // keeping always true for deletion of stats if view index present
                            hasViewIndexTable = true;
                            // or not
                            MetaDataUtil.deleteViewIndexSequences(connection, table.getPhysicalName(), table.isNamespaceMapped());
                            byte[] viewIndexPhysicalName = MetaDataUtil.getViewIndexPhysicalName(table.getPhysicalName().getBytes());
                            if (!dropMetaData) {
                                // we need to drop rows only when actually view index exists
                                try (HBaseAdmin admin = connection.getQueryServices().getAdmin()) {
                                    hasViewIndexTable = admin.tableExists(viewIndexPhysicalName);
                                } catch (IOException e1) {
                                // absorbing as it is not critical check
                                }
                            }
                        }
                        if (tableType == PTableType.TABLE && (table.isMultiTenant() || hasViewIndexTable)) {
                            if (hasViewIndexTable) {
                                byte[] viewIndexPhysicalName = MetaDataUtil.getViewIndexPhysicalName(table.getPhysicalName().getBytes());
                                PTable viewIndexTable = new PTableImpl(null, SchemaUtil.getSchemaNameFromFullName(viewIndexPhysicalName), SchemaUtil.getTableNameFromFullName(viewIndexPhysicalName), ts, table.getColumnFamilies(), table.isNamespaceMapped(), table.getImmutableStorageScheme(), table.getEncodingScheme(), table.useStatsForParallelization());
                                tableRefs.add(new TableRef(null, viewIndexTable, ts, false));
                            }
                        }
                        tableRefs.add(new TableRef(null, table, ts, false));
                        // TODO: Let the standard mutable secondary index maintenance handle this?
                        for (PTable index : table.getIndexes()) {
                            tableRefs.add(new TableRef(null, index, ts, false));
                        }
                        deleteFromStatsTable(tableRefs, ts);
                    }
                    if (!dropMetaData) {
                        MutationPlan plan = new PostDDLCompiler(connection).compile(tableRefs, null, null, Collections.<PColumn>emptyList(), ts);
                        // Delete everything in the column. You'll still be able to do queries at earlier timestamps
                        return connection.getQueryServices().updateData(plan);
                    }
                }
                break;
        }
        return new MutationState(0, 0, connection);
    } finally {
        connection.setAutoCommit(wasAutoCommit);
    }
}
Also used : Delete(org.apache.hadoop.hbase.client.Delete) IOException(java.io.IOException) MutationPlan(org.apache.phoenix.compile.MutationPlan) PostDDLCompiler(org.apache.phoenix.compile.PostDDLCompiler) MutationCode(org.apache.phoenix.coprocessor.MetaDataProtocol.MutationCode) HBaseAdmin(org.apache.hadoop.hbase.client.HBaseAdmin) MutationState(org.apache.phoenix.execute.MutationState) PUnsignedLong(org.apache.phoenix.schema.types.PUnsignedLong) PLong(org.apache.phoenix.schema.types.PLong) Mutation(org.apache.hadoop.hbase.client.Mutation) MetaDataMutationResult(org.apache.phoenix.coprocessor.MetaDataProtocol.MetaDataMutationResult)

Example 5 with MutationState

use of org.apache.phoenix.execute.MutationState in project phoenix by apache.

the class MetaDataClient method dropSequence.

public MutationState dropSequence(DropSequenceStatement statement) throws SQLException {
    Long scn = connection.getSCN();
    long timestamp = scn == null ? HConstants.LATEST_TIMESTAMP : scn;
    String schemaName = connection.getSchema() != null && statement.getSequenceName().getSchemaName() == null ? connection.getSchema() : statement.getSequenceName().getSchemaName();
    String sequenceName = statement.getSequenceName().getTableName();
    String tenantId = connection.getTenantId() == null ? null : connection.getTenantId().getString();
    try {
        connection.getQueryServices().dropSequence(tenantId, schemaName, sequenceName, timestamp);
    } catch (SequenceNotFoundException e) {
        if (statement.ifExists()) {
            return new MutationState(0, 0, connection);
        }
        throw e;
    }
    return new MutationState(1, 1000, connection);
}
Also used : MutationState(org.apache.phoenix.execute.MutationState) PUnsignedLong(org.apache.phoenix.schema.types.PUnsignedLong) PLong(org.apache.phoenix.schema.types.PLong)

Aggregations

MutationState (org.apache.phoenix.execute.MutationState)35 PhoenixConnection (org.apache.phoenix.jdbc.PhoenixConnection)12 PLong (org.apache.phoenix.schema.types.PLong)11 PUnsignedLong (org.apache.phoenix.schema.types.PUnsignedLong)11 MutationPlan (org.apache.phoenix.compile.MutationPlan)10 MetaDataMutationResult (org.apache.phoenix.coprocessor.MetaDataProtocol.MetaDataMutationResult)9 Mutation (org.apache.hadoop.hbase.client.Mutation)8 MutationCode (org.apache.phoenix.coprocessor.MetaDataProtocol.MutationCode)8 Scan (org.apache.hadoop.hbase.client.Scan)7 PostDDLCompiler (org.apache.phoenix.compile.PostDDLCompiler)7 PhoenixStatement (org.apache.phoenix.jdbc.PhoenixStatement)7 PreparedStatement (java.sql.PreparedStatement)6 SQLException (java.sql.SQLException)6 SQLExceptionInfo (org.apache.phoenix.exception.SQLExceptionInfo)6 ResultSet (java.sql.ResultSet)5 ArrayList (java.util.ArrayList)5 List (java.util.List)5 ColumnResolver (org.apache.phoenix.compile.ColumnResolver)5 PTable (org.apache.phoenix.schema.PTable)5 IOException (java.io.IOException)4