Search in sources :

Example 1 with PSchema

use of org.apache.phoenix.parse.PSchema in project phoenix by apache.

the class PostDDLCompiler method compile.

public MutationPlan compile(final List<TableRef> tableRefs, final byte[] emptyCF, final List<byte[]> projectCFs, final List<PColumn> deleteList, final long timestamp) throws SQLException {
    PhoenixStatement statement = new PhoenixStatement(connection);
    final StatementContext context = new StatementContext(statement, new ColumnResolver() {

        @Override
        public List<TableRef> getTables() {
            return tableRefs;
        }

        @Override
        public TableRef resolveTable(String schemaName, String tableName) throws SQLException {
            throw new UnsupportedOperationException();
        }

        @Override
        public ColumnRef resolveColumn(String schemaName, String tableName, String colName) throws SQLException {
            throw new UnsupportedOperationException();
        }

        @Override
        public List<PFunction> getFunctions() {
            return Collections.<PFunction>emptyList();
        }

        @Override
        public PFunction resolveFunction(String functionName) throws SQLException {
            throw new FunctionNotFoundException(functionName);
        }

        @Override
        public boolean hasUDFs() {
            return false;
        }

        @Override
        public PSchema resolveSchema(String schemaName) throws SQLException {
            throw new SchemaNotFoundException(schemaName);
        }

        @Override
        public List<PSchema> getSchemas() {
            throw new UnsupportedOperationException();
        }
    }, scan, new SequenceManager(statement));
    return new BaseMutationPlan(context, Operation.UPSERT) {

        /* FIXME */
        @Override
        public MutationState execute() throws SQLException {
            if (tableRefs.isEmpty()) {
                return new MutationState(0, 1000, connection);
            }
            boolean wasAutoCommit = connection.getAutoCommit();
            try {
                connection.setAutoCommit(true);
                SQLException sqlE = null;
                /*
                     * Handles:
                     * 1) deletion of all rows for a DROP TABLE and subsequently deletion of all rows for a DROP INDEX;
                     * 2) deletion of all column values for a ALTER TABLE DROP COLUMN
                     * 3) updating the necessary rows to have an empty KV
                     * 4) updating table stats
                     */
                long totalMutationCount = 0;
                for (final TableRef tableRef : tableRefs) {
                    Scan scan = ScanUtil.newScan(context.getScan());
                    SelectStatement select = SelectStatement.COUNT_ONE;
                    // We need to use this tableRef
                    ColumnResolver resolver = new ColumnResolver() {

                        @Override
                        public List<TableRef> getTables() {
                            return Collections.singletonList(tableRef);
                        }

                        @Override
                        public java.util.List<PFunction> getFunctions() {
                            return Collections.emptyList();
                        }

                        ;

                        @Override
                        public TableRef resolveTable(String schemaName, String tableName) throws SQLException {
                            throw new UnsupportedOperationException();
                        }

                        @Override
                        public ColumnRef resolveColumn(String schemaName, String tableName, String colName) throws SQLException {
                            PColumn column = tableName != null ? tableRef.getTable().getColumnFamily(tableName).getPColumnForColumnName(colName) : tableRef.getTable().getColumnForColumnName(colName);
                            return new ColumnRef(tableRef, column.getPosition());
                        }

                        @Override
                        public PFunction resolveFunction(String functionName) throws SQLException {
                            throw new UnsupportedOperationException();
                        }

                        ;

                        @Override
                        public boolean hasUDFs() {
                            return false;
                        }

                        @Override
                        public List<PSchema> getSchemas() {
                            throw new UnsupportedOperationException();
                        }

                        @Override
                        public PSchema resolveSchema(String schemaName) throws SQLException {
                            throw new SchemaNotFoundException(schemaName);
                        }
                    };
                    PhoenixStatement statement = new PhoenixStatement(connection);
                    StatementContext context = new StatementContext(statement, resolver, scan, new SequenceManager(statement));
                    long ts = timestamp;
                    // in this case, so maybe this is ok.
                    if (ts != HConstants.LATEST_TIMESTAMP && tableRef.getTable().isTransactional()) {
                        ts = TransactionUtil.convertToNanoseconds(ts);
                    }
                    ScanUtil.setTimeRange(scan, scan.getTimeRange().getMin(), ts);
                    if (emptyCF != null) {
                        scan.setAttribute(BaseScannerRegionObserver.EMPTY_CF, emptyCF);
                        scan.setAttribute(BaseScannerRegionObserver.EMPTY_COLUMN_QUALIFIER, EncodedColumnsUtil.getEmptyKeyValueInfo(tableRef.getTable()).getFirst());
                    }
                    ServerCache cache = null;
                    try {
                        if (deleteList != null) {
                            if (deleteList.isEmpty()) {
                                scan.setAttribute(BaseScannerRegionObserver.DELETE_AGG, QueryConstants.TRUE);
                            // In the case of a row deletion, add index metadata so mutable secondary indexing works
                            /* TODO: we currently manually run a scan to delete the index data here
                                    ImmutableBytesWritable ptr = context.getTempPtr();
                                    tableRef.getTable().getIndexMaintainers(ptr);
                                    if (ptr.getLength() > 0) {
                                        IndexMetaDataCacheClient client = new IndexMetaDataCacheClient(connection, tableRef);
                                        cache = client.addIndexMetadataCache(context.getScanRanges(), ptr);
                                        byte[] uuidValue = cache.getId();
                                        scan.setAttribute(PhoenixIndexCodec.INDEX_UUID, uuidValue);
                                    }
                                    */
                            } else {
                                // In the case of the empty key value column family changing, do not send the index
                                // metadata, as we're currently managing this from the client. It's possible for the
                                // data empty column family to stay the same, while the index empty column family
                                // changes.
                                PColumn column = deleteList.get(0);
                                byte[] cq = column.getColumnQualifierBytes();
                                if (emptyCF == null) {
                                    scan.addColumn(column.getFamilyName().getBytes(), cq);
                                }
                                scan.setAttribute(BaseScannerRegionObserver.DELETE_CF, column.getFamilyName().getBytes());
                                scan.setAttribute(BaseScannerRegionObserver.DELETE_CQ, cq);
                            }
                        }
                        List<byte[]> columnFamilies = Lists.newArrayListWithExpectedSize(tableRef.getTable().getColumnFamilies().size());
                        if (projectCFs == null) {
                            for (PColumnFamily family : tableRef.getTable().getColumnFamilies()) {
                                columnFamilies.add(family.getName().getBytes());
                            }
                        } else {
                            for (byte[] projectCF : projectCFs) {
                                columnFamilies.add(projectCF);
                            }
                        }
                        // Need to project all column families into the scan, since we haven't yet created our empty key value
                        RowProjector projector = ProjectionCompiler.compile(context, SelectStatement.COUNT_ONE, GroupBy.EMPTY_GROUP_BY);
                        context.getAggregationManager().compile(context, GroupBy.EMPTY_GROUP_BY);
                        // since at this point we haven't added the empty key value everywhere.
                        if (columnFamilies != null) {
                            scan.getFamilyMap().clear();
                            for (byte[] family : columnFamilies) {
                                scan.addFamily(family);
                            }
                            projector = new RowProjector(projector, false);
                        }
                        // any other Post DDL operations.
                        try {
                            // Since dropping a VIEW does not affect the underlying data, we do
                            // not need to pass through the view statement here.
                            // Push where clause into scan
                            WhereCompiler.compile(context, select);
                        } catch (ColumnFamilyNotFoundException e) {
                            continue;
                        } catch (ColumnNotFoundException e) {
                            continue;
                        } catch (AmbiguousColumnException e) {
                            continue;
                        }
                        QueryPlan plan = new AggregatePlan(context, select, tableRef, projector, null, null, OrderBy.EMPTY_ORDER_BY, null, GroupBy.EMPTY_GROUP_BY, null);
                        try {
                            ResultIterator iterator = plan.iterator();
                            try {
                                Tuple row = iterator.next();
                                ImmutableBytesWritable ptr = context.getTempPtr();
                                totalMutationCount += (Long) projector.getColumnProjector(0).getValue(row, PLong.INSTANCE, ptr);
                            } catch (SQLException e) {
                                sqlE = e;
                            } finally {
                                try {
                                    iterator.close();
                                } catch (SQLException e) {
                                    if (sqlE == null) {
                                        sqlE = e;
                                    } else {
                                        sqlE.setNextException(e);
                                    }
                                } finally {
                                    if (sqlE != null) {
                                        throw sqlE;
                                    }
                                }
                            }
                        } catch (TableNotFoundException e) {
                        // Ignore and continue, as HBase throws when table hasn't been written to
                        // FIXME: Remove if this is fixed in 0.96
                        }
                    } finally {
                        if (cache != null) {
                            // Remove server cache if there is one
                            cache.close();
                        }
                    }
                }
                final long count = totalMutationCount;
                return new MutationState(1, 1000, connection) {

                    @Override
                    public long getUpdateCount() {
                        return count;
                    }
                };
            } finally {
                if (!wasAutoCommit)
                    connection.setAutoCommit(wasAutoCommit);
            }
        }
    };
}
Also used : ServerCache(org.apache.phoenix.cache.ServerCacheClient.ServerCache) PFunction(org.apache.phoenix.parse.PFunction) SQLException(java.sql.SQLException) PhoenixStatement(org.apache.phoenix.jdbc.PhoenixStatement) PColumn(org.apache.phoenix.schema.PColumn) SelectStatement(org.apache.phoenix.parse.SelectStatement) TableNotFoundException(org.apache.phoenix.schema.TableNotFoundException) List(java.util.List) AmbiguousColumnException(org.apache.phoenix.schema.AmbiguousColumnException) AggregatePlan(org.apache.phoenix.execute.AggregatePlan) ImmutableBytesWritable(org.apache.hadoop.hbase.io.ImmutableBytesWritable) ResultIterator(org.apache.phoenix.iterate.ResultIterator) PSchema(org.apache.phoenix.parse.PSchema) PColumnFamily(org.apache.phoenix.schema.PColumnFamily) ColumnFamilyNotFoundException(org.apache.phoenix.schema.ColumnFamilyNotFoundException) FunctionNotFoundException(org.apache.phoenix.schema.FunctionNotFoundException) ColumnNotFoundException(org.apache.phoenix.schema.ColumnNotFoundException) MutationState(org.apache.phoenix.execute.MutationState) Scan(org.apache.hadoop.hbase.client.Scan) ColumnRef(org.apache.phoenix.schema.ColumnRef) SchemaNotFoundException(org.apache.phoenix.schema.SchemaNotFoundException) TableRef(org.apache.phoenix.schema.TableRef) Tuple(org.apache.phoenix.schema.tuple.Tuple)

Example 2 with PSchema

use of org.apache.phoenix.parse.PSchema in project phoenix by apache.

the class ConnectionlessQueryServicesImpl method getSchema.

@Override
public MetaDataMutationResult getSchema(String schemaName, long clientTimestamp) throws SQLException {
    try {
        PSchema schema = metaData.getSchema(new PTableKey(null, schemaName));
        new MetaDataMutationResult(MutationCode.SCHEMA_ALREADY_EXISTS, schema, 0);
    } catch (SchemaNotFoundException e) {
    }
    return new MetaDataMutationResult(MutationCode.SCHEMA_NOT_FOUND, 0, null);
}
Also used : PSchema(org.apache.phoenix.parse.PSchema) SchemaNotFoundException(org.apache.phoenix.schema.SchemaNotFoundException) PTableKey(org.apache.phoenix.schema.PTableKey) MetaDataMutationResult(org.apache.phoenix.coprocessor.MetaDataProtocol.MetaDataMutationResult)

Example 3 with PSchema

use of org.apache.phoenix.parse.PSchema in project phoenix by apache.

the class MetaDataClient method createSchema.

public MutationState createSchema(CreateSchemaStatement create) throws SQLException {
    boolean wasAutoCommit = connection.getAutoCommit();
    connection.rollback();
    try {
        if (!SchemaUtil.isNamespaceMappingEnabled(null, connection.getQueryServices().getProps())) {
            throw new SQLExceptionInfo.Builder(SQLExceptionCode.CREATE_SCHEMA_NOT_ALLOWED).setSchemaName(create.getSchemaName()).build().buildException();
        }
        boolean isIfNotExists = create.isIfNotExists();
        validateSchema(create.getSchemaName());
        PSchema schema = new PSchema(create.getSchemaName());
        connection.setAutoCommit(false);
        List<Mutation> schemaMutations;
        try (PreparedStatement schemaUpsert = connection.prepareStatement(CREATE_SCHEMA)) {
            schemaUpsert.setString(1, schema.getSchemaName());
            schemaUpsert.setString(2, MetaDataClient.EMPTY_TABLE);
            schemaUpsert.execute();
            schemaMutations = connection.getMutationState().toMutations(null).next().getSecond();
            connection.rollback();
        }
        MetaDataMutationResult result = connection.getQueryServices().createSchema(schemaMutations, schema.getSchemaName());
        MutationCode code = result.getMutationCode();
        switch(code) {
            case SCHEMA_ALREADY_EXISTS:
                if (result.getSchema() != null) {
                    addSchemaToCache(result);
                }
                if (!isIfNotExists) {
                    throw new SchemaAlreadyExistsException(schema.getSchemaName());
                }
                break;
            case NEWER_SCHEMA_FOUND:
                throw new NewerSchemaAlreadyExistsException(schema.getSchemaName());
            default:
                result = new MetaDataMutationResult(code, schema, result.getMutationTime());
                addSchemaToCache(result);
        }
    } finally {
        connection.setAutoCommit(wasAutoCommit);
    }
    return new MutationState(0, 0, connection);
}
Also used : MutationState(org.apache.phoenix.execute.MutationState) PSchema(org.apache.phoenix.parse.PSchema) PreparedStatement(java.sql.PreparedStatement) Mutation(org.apache.hadoop.hbase.client.Mutation) SQLExceptionInfo(org.apache.phoenix.exception.SQLExceptionInfo) MetaDataMutationResult(org.apache.phoenix.coprocessor.MetaDataProtocol.MetaDataMutationResult) MutationCode(org.apache.phoenix.coprocessor.MetaDataProtocol.MutationCode)

Example 4 with PSchema

use of org.apache.phoenix.parse.PSchema in project phoenix by apache.

the class MetaDataEndpointImpl method loadSchema.

private PSchema loadSchema(RegionCoprocessorEnvironment env, byte[] key, ImmutableBytesPtr cacheKey, long clientTimeStamp, long asOfTimeStamp) throws IOException, SQLException {
    Region region = env.getRegion();
    Cache<ImmutableBytesPtr, PMetaDataEntity> metaDataCache = GlobalCache.getInstance(this.env).getMetaDataCache();
    PSchema schema = (PSchema) metaDataCache.getIfPresent(cacheKey);
    // We always cache the latest version - fault in if not in cache
    if (schema != null) {
        return schema;
    }
    ArrayList<byte[]> arrayList = new ArrayList<byte[]>(1);
    arrayList.add(key);
    List<PSchema> schemas = buildSchemas(arrayList, region, asOfTimeStamp, cacheKey);
    if (schemas != null)
        return schemas.get(0);
    // found
    if (schema == null && (schema = buildDeletedSchema(key, cacheKey, region, clientTimeStamp)) != null) {
        return schema;
    }
    return null;
}
Also used : PMetaDataEntity(org.apache.phoenix.schema.PMetaDataEntity) ImmutableBytesPtr(org.apache.phoenix.hbase.index.util.ImmutableBytesPtr) ArrayList(java.util.ArrayList) Region(org.apache.hadoop.hbase.regionserver.Region) PSchema(org.apache.phoenix.parse.PSchema)

Example 5 with PSchema

use of org.apache.phoenix.parse.PSchema in project phoenix by apache.

the class MetaDataEndpointImpl method getSchema.

@Override
public void getSchema(RpcController controller, GetSchemaRequest request, RpcCallback<MetaDataResponse> done) {
    MetaDataResponse.Builder builder = MetaDataResponse.newBuilder();
    Region region = env.getRegion();
    String schemaName = request.getSchemaName();
    byte[] lockKey = SchemaUtil.getSchemaKey(schemaName);
    MetaDataMutationResult result = checkSchemaKeyInRegion(lockKey, region);
    if (result != null) {
        done.run(MetaDataMutationResult.toProto(result));
        return;
    }
    long clientTimeStamp = request.getClientTimestamp();
    List<RowLock> locks = Lists.newArrayList();
    try {
        acquireLock(region, lockKey, locks);
        // Get as of latest timestamp so we can detect if we have a
        // newer schema that already
        // exists without making an additional query
        ImmutableBytesPtr cacheKey = new ImmutableBytesPtr(lockKey);
        PSchema schema = loadSchema(env, lockKey, cacheKey, clientTimeStamp, clientTimeStamp);
        if (schema != null) {
            if (schema.getTimeStamp() < clientTimeStamp) {
                if (!isSchemaDeleted(schema)) {
                    builder.setReturnCode(MetaDataProtos.MutationCode.SCHEMA_ALREADY_EXISTS);
                    builder.setMutationTime(EnvironmentEdgeManager.currentTimeMillis());
                    builder.setSchema(PSchema.toProto(schema));
                    done.run(builder.build());
                    return;
                } else {
                    builder.setReturnCode(MetaDataProtos.MutationCode.NEWER_SCHEMA_FOUND);
                    builder.setMutationTime(EnvironmentEdgeManager.currentTimeMillis());
                    builder.setSchema(PSchema.toProto(schema));
                    done.run(builder.build());
                    return;
                }
            }
        }
    } catch (Exception e) {
        long currentTime = EnvironmentEdgeManager.currentTimeMillis();
        builder.setReturnCode(MetaDataProtos.MutationCode.SCHEMA_NOT_FOUND);
        builder.setMutationTime(currentTime);
        done.run(builder.build());
        return;
    } finally {
        region.releaseRowLocks(locks);
    }
}
Also used : MetaDataResponse(org.apache.phoenix.coprocessor.generated.MetaDataProtos.MetaDataResponse) ImmutableBytesPtr(org.apache.phoenix.hbase.index.util.ImmutableBytesPtr) Region(org.apache.hadoop.hbase.regionserver.Region) PSchema(org.apache.phoenix.parse.PSchema) ByteString(com.google.protobuf.ByteString) CoprocessorException(org.apache.hadoop.hbase.coprocessor.CoprocessorException) SequenceNotFoundException(org.apache.phoenix.schema.SequenceNotFoundException) IOException(java.io.IOException) ColumnNotFoundException(org.apache.phoenix.schema.ColumnNotFoundException) DoNotRetryIOException(org.apache.hadoop.hbase.DoNotRetryIOException) ColumnFamilyNotFoundException(org.apache.phoenix.schema.ColumnFamilyNotFoundException) TableNotFoundException(org.apache.phoenix.schema.TableNotFoundException) SQLException(java.sql.SQLException) SequenceAlreadyExistsException(org.apache.phoenix.schema.SequenceAlreadyExistsException) RowLock(org.apache.hadoop.hbase.regionserver.Region.RowLock)

Aggregations

PSchema (org.apache.phoenix.parse.PSchema)13 ImmutableBytesPtr (org.apache.phoenix.hbase.index.util.ImmutableBytesPtr)6 Scan (org.apache.hadoop.hbase.client.Scan)5 Region (org.apache.hadoop.hbase.regionserver.Region)4 MetaDataMutationResult (org.apache.phoenix.coprocessor.MetaDataProtocol.MetaDataMutationResult)4 SQLException (java.sql.SQLException)3 Cell (org.apache.hadoop.hbase.Cell)3 Mutation (org.apache.hadoop.hbase.client.Mutation)3 RegionScanner (org.apache.hadoop.hbase.regionserver.RegionScanner)3 MutationState (org.apache.phoenix.execute.MutationState)3 PMetaDataEntity (org.apache.phoenix.schema.PMetaDataEntity)3 ByteString (com.google.protobuf.ByteString)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 RowLock (org.apache.hadoop.hbase.regionserver.Region.RowLock)2 MutationCode (org.apache.phoenix.coprocessor.MetaDataProtocol.MutationCode)2 MetaDataResponse (org.apache.phoenix.coprocessor.generated.MetaDataProtos.MetaDataResponse)2 ResultIterator (org.apache.phoenix.iterate.ResultIterator)2 PhoenixStatement (org.apache.phoenix.jdbc.PhoenixStatement)2 PFunction (org.apache.phoenix.parse.PFunction)2