org.apache.phoenix.compile.StatementContext Java Examples

The following examples show how to use org.apache.phoenix.compile.StatementContext. 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: ScanPlan.java    From phoenix with Apache License 2.0 6 votes vote down vote up
/**
 * @return Pair of numbers in which the first part is estimated number of bytes that will be
 *         scanned and the second part is estimated number of rows. Returned value is null if
 *         estimated size of data to scan is beyond a threshold.
 * @throws SQLException
 */
private static Pair<Long, Long> getEstimateOfDataSizeToScanIfWithinThreshold(StatementContext context, PTable table, Integer perScanLimit) throws SQLException {
    Scan scan = context.getScan();
    ConnectionQueryServices services = context.getConnection().getQueryServices();
    long estRowSize = SchemaUtil.estimateRowSize(table);
    long regionSize = services.getProps().getLong(HConstants.HREGION_MAX_FILESIZE,
            HConstants.DEFAULT_MAX_FILE_SIZE);
    if (perScanLimit == null || scan.getFilter() != null) {
        /*
         * If a limit is not provided or if we have a filter, then we are not able to decide whether
         * the amount of data we need to scan is less than the threshold.
         */
        return null;
    } 
    float factor =
        services.getProps().getFloat(QueryServices.LIMITED_QUERY_SERIAL_THRESHOLD,
            QueryServicesOptions.DEFAULT_LIMITED_QUERY_SERIAL_THRESHOLD);
    long threshold = (long)(factor * regionSize);
    long estimatedBytes = perScanLimit * estRowSize;
    long estimatedRows = perScanLimit;
    return (perScanLimit * estRowSize < threshold) ? new Pair<>(estimatedBytes, estimatedRows) : null;
}
 
Example #2
Source File: PhoenixStatement.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public MutationPlan compilePlan(final PhoenixStatement stmt, Sequence.ValueOp seqAction) throws SQLException {
        final StatementContext context = new StatementContext(stmt);
        return new BaseMutationPlan(context, this.getOperation()) {

            @Override
            public ParameterMetaData getParameterMetaData() {
                return PhoenixParameterMetaData.EMPTY_PARAMETER_META_DATA;
            }

            @Override
            public ExplainPlan getExplainPlan() throws SQLException {
                return new ExplainPlan(Collections.singletonList("DROP FUNCTION"));
            }

            @Override
            public MutationState execute() throws SQLException {
                MetaDataClient client = new MetaDataClient(getContext().getConnection());
                return client.dropFunction(ExecutableDropFunctionStatement.this);
            }
        };
}
 
Example #3
Source File: PhoenixResultSet.java    From phoenix with Apache License 2.0 6 votes vote down vote up
public PhoenixResultSet(ResultIterator resultIterator, RowProjector rowProjector,
        StatementContext ctx) throws SQLException {
    this.rowProjector = rowProjector;
    this.scanner = resultIterator;
    this.context = ctx;
    this.statement = context.getStatement();
    this.readMetricsQueue = context.getReadMetricsQueue();
    this.overAllQueryMetrics = context.getOverallQueryMetrics();
    this.queryLogger = context.getQueryLogger() != null ? context.getQueryLogger() : QueryLogger.NO_OP_INSTANCE;
    this.wildcardIncludesDynamicCols = this.context.getConnection().getQueryServices()
            .getConfiguration().getBoolean(WILDCARD_QUERY_DYNAMIC_COLS_ATTRIB,
                    DEFAULT_WILDCARD_QUERY_DYNAMIC_COLS_ATTRIB);
    if (this.wildcardIncludesDynamicCols) {
        Pair<List<PColumn>, Integer> res = getStaticColsAndStartingPosForDynCols();
        this.staticColumns = res.getFirst();
        this.startPositionForDynamicCols = res.getSecond();
    } else {
        this.staticColumns = null;
        this.startPositionForDynamicCols = 0;
    }
}
 
Example #4
Source File: ScanPlan.java    From phoenix with Apache License 2.0 6 votes vote down vote up
private ScanPlan(StatementContext context, FilterableStatement statement, TableRef table, RowProjector projector, Integer limit, Integer offset,
        OrderBy orderBy, ParallelIteratorFactory parallelIteratorFactory, boolean allowPageFilter, Expression dynamicFilter, QueryPlan dataPlan, Optional<byte[]> rowOffset) throws SQLException {
    super(context, statement, table, projector, context.getBindManager().getParameterMetaData(), limit,offset, orderBy, GroupBy.EMPTY_GROUP_BY,
            parallelIteratorFactory != null ? parallelIteratorFactory :
                    buildResultIteratorFactory(context, statement, table, orderBy, limit, offset, allowPageFilter), dynamicFilter, dataPlan);
    this.allowPageFilter = allowPageFilter;
    boolean isOrdered = !orderBy.getOrderByExpressions().isEmpty();
    if (isOrdered) { // TopN
        ScanRegionObserver.serializeIntoScan(context.getScan(),
            limit == null ? -1 : QueryUtil.getOffsetLimit(limit, offset),
            orderBy.getOrderByExpressions(), projector.getEstimatedRowByteSize());
        ScanUtil.setClientVersion(context.getScan(), MetaDataProtocol.PHOENIX_VERSION);
    }
    Integer perScanLimit = !allowPageFilter || isOrdered ? null : limit;
    perScanLimit = QueryUtil.getOffsetLimit(perScanLimit, offset);
    Pair<Long, Long> estimate = getEstimateOfDataSizeToScanIfWithinThreshold(context, table.getTable(), perScanLimit);
    this.isDataToScanWithinThreshold = estimate != null;
    this.isSerial = isSerial(context, statement, tableRef, orderBy, isDataToScanWithinThreshold);
    if (isSerial) {
        serialBytesEstimate = estimate.getFirst();
        serialRowsEstimate = estimate.getSecond();
        serialEstimateInfoTs = StatisticsUtil.NOT_STATS_BASED_TS;
    }
    this.actualOutputOrderBy = convertActualOutputOrderBy(orderBy, context);
    this.rowOffset = rowOffset;
}
 
Example #5
Source File: PhoenixStatement.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public MutationPlan compilePlan(final PhoenixStatement stmt, Sequence.ValueOp seqAction) throws SQLException {
    final StatementContext context = new StatementContext(stmt);
    return new BaseMutationPlan(context, this.getOperation()) {

        @Override
        public ExplainPlan getExplainPlan() throws SQLException {
            return new ExplainPlan(Collections.singletonList("ALTER " + getTableType() + " ADD COLUMN"));
        }

        @Override
        public MutationState execute() throws SQLException {
            MetaDataClient client = new MetaDataClient(getContext().getConnection());
            return client.addColumn(ExecutableAddColumnStatement.this);
        }
    };
}
 
Example #6
Source File: IndexUtil.java    From phoenix with Apache License 2.0 6 votes vote down vote up
/**
 * Rewrite a view statement to be valid against an index
 * @param conn
 * @param index
 * @param table
 * @return
 * @throws SQLException
 */
public static String rewriteViewStatement(PhoenixConnection conn, PTable index, PTable table, String viewStatement) throws SQLException {
    if (viewStatement == null) {
        return null;
    }
    SelectStatement select = new SQLParser(viewStatement).parseQuery();
    ColumnResolver resolver = FromCompiler.getResolver(new TableRef(table));
    SelectStatement translatedSelect = IndexStatementRewriter.translate(select, resolver);
    ParseNode whereNode = translatedSelect.getWhere();
    PhoenixStatement statement = new PhoenixStatement(conn);
    TableRef indexTableRef = new TableRef(index) {
        @Override
        public String getColumnDisplayName(ColumnRef ref, boolean schemaNameCaseSensitive, boolean colNameCaseSensitive) {
            return '"' + ref.getColumn().getName().getString() + '"';
        }
    };
    ColumnResolver indexResolver = FromCompiler.getResolver(indexTableRef);
    StatementContext context = new StatementContext(statement, indexResolver);
    // Compile to ensure validity
    WhereCompiler.compile(context, whereNode);
    StringBuilder buf = new StringBuilder();
    whereNode.toSQL(indexResolver, buf);
    return QueryUtil.getViewStatement(index.getSchemaName().getString(), index.getTableName().getString(), buf.toString());
}
 
Example #7
Source File: IndexUtil.java    From phoenix with Apache License 2.0 6 votes vote down vote up
/**
 * Rewrite a view statement to be valid against an index
 * @param conn
 * @param index
 * @param table
 * @return
 * @throws SQLException
 */
public static String rewriteViewStatement(PhoenixConnection conn, PTable index, PTable table, String viewStatement) throws SQLException {
    if (viewStatement == null) {
        return null;
    }
    SelectStatement select = new SQLParser(viewStatement).parseQuery();
    ColumnResolver resolver = FromCompiler.getResolver(new TableRef(table));
    SelectStatement translatedSelect = IndexStatementRewriter.translate(select, resolver);
    ParseNode whereNode = translatedSelect.getWhere();
    PhoenixStatement statement = new PhoenixStatement(conn);
    TableRef indexTableRef = new TableRef(index) {
        @Override
        public String getColumnDisplayName(ColumnRef ref, boolean schemaNameCaseSensitive, boolean colNameCaseSensitive) {
            return '"' + ref.getColumn().getName().getString() + '"';
        }
    };
    ColumnResolver indexResolver = FromCompiler.getResolver(indexTableRef);
    StatementContext context = new StatementContext(statement, indexResolver);
    // Compile to ensure validity
    WhereCompiler.compile(context, whereNode);
    StringBuilder buf = new StringBuilder();
    whereNode.toSQL(indexResolver, buf);
    return QueryUtil.getViewStatement(index.getSchemaName().getString(), index.getTableName().getString(), buf.toString());
}
 
Example #8
Source File: ToCharParseNode.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Override
public FunctionExpression create(List<Expression> children, StatementContext context) throws SQLException {
    PDataType dataType = children.get(0).getDataType();
    String formatString = (String)((LiteralExpression)children.get(1)).getValue(); // either date or number format string
    Format formatter;
    FunctionArgumentType type;
    if (dataType.isCoercibleTo(PTimestamp.INSTANCE)) {
        if (formatString == null) {
            formatString = context.getDateFormat();
            formatter = context.getDateFormatter();
        } else {
            formatter = FunctionArgumentType.TEMPORAL.getFormatter(formatString);
        }
        type = FunctionArgumentType.TEMPORAL;
    }
    else if (dataType.isCoercibleTo(PDecimal.INSTANCE)) {
        if (formatString == null)
            formatString = context.getNumberFormat();
        formatter = FunctionArgumentType.NUMERIC.getFormatter(formatString);
        type = FunctionArgumentType.NUMERIC;
    }
    else {
        throw new SQLException(dataType + " type is unsupported for TO_CHAR().  Numeric and temporal types are supported.");
    }
    return new ToCharFunction(children, type, formatString, formatter);
}
 
Example #9
Source File: BaseQueryPlan.java    From phoenix with Apache License 2.0 6 votes vote down vote up
protected BaseQueryPlan(
        StatementContext context, FilterableStatement statement, TableRef table,
        RowProjector projection, ParameterMetaData paramMetaData, Integer limit, Integer offset, OrderBy orderBy,
        GroupBy groupBy, ParallelIteratorFactory parallelIteratorFactory,
        Expression dynamicFilter, QueryPlan dataPlan) {
    this.context = context;
    this.statement = statement;
    this.tableRef = table;
    this.tableRefs = ImmutableSet.of(table);
    this.projection = projection;
    this.paramMetaData = paramMetaData;
    this.limit = limit;
    this.offset = offset;
    this.orderBy = orderBy;
    this.groupBy = groupBy;
    this.parallelIteratorFactory = parallelIteratorFactory;
    this.dynamicFilter = dynamicFilter;
    this.dataPlan = dataPlan;
}
 
Example #10
Source File: PhoenixStatement.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public MutationPlan compilePlan(final PhoenixStatement stmt, Sequence.ValueOp seqAction) throws SQLException {
    final StatementContext context = new StatementContext(stmt);
    return new MutationPlan() {

        @Override
        public StatementContext getContext() {
            return context;
        }

        @Override
        public ParameterMetaData getParameterMetaData() {
            return PhoenixParameterMetaData.EMPTY_PARAMETER_META_DATA;
        }

        @Override
        public ExplainPlan getExplainPlan() throws SQLException {
            return new ExplainPlan(Collections.singletonList("UPDATE STATISTICS"));
        }

        @Override
        public PhoenixConnection getConnection() {
            return stmt.getConnection();
        }

        @Override
        public MutationState execute() throws SQLException {
            MetaDataClient client = new MetaDataClient(getConnection());
            return client.updateStatistics(ExecutableUpdateStatisticsStatement.this);
        }
    };
}
 
Example #11
Source File: PhoenixStatement.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public MutationPlan compilePlan(final PhoenixStatement stmt, Sequence.ValueOp seqAction) throws SQLException {
    final StatementContext context = new StatementContext(stmt);
    return new MutationPlan() {

        @Override
        public StatementContext getContext() {
            return context;
        }

        @Override
        public ParameterMetaData getParameterMetaData() {
            return PhoenixParameterMetaData.EMPTY_PARAMETER_META_DATA;
        }

        @Override
        public ExplainPlan getExplainPlan() throws SQLException {
            return new ExplainPlan(Collections.singletonList("ALTER " + getTableType() + " ADD COLUMN"));
        }

        @Override
        public PhoenixConnection getConnection() {
            return stmt.getConnection();
        }

        @Override
        public MutationState execute() throws SQLException {
            MetaDataClient client = new MetaDataClient(getConnection());
            return client.addColumn(ExecutableAddColumnStatement.this);
        }
    };
}
 
Example #12
Source File: ToNumberFunction.java    From phoenix with Apache License 2.0 5 votes vote down vote up
public ToNumberFunction(List<Expression> children, StatementContext context) throws SQLException {
    super(children.subList(0, 1));
    PDataType dataType = children.get(0).getDataType();
    String formatString = (String)((LiteralExpression)children.get(1)).getValue(); // either date or number format string
    Format formatter =  null;
    FunctionArgumentType type;

    if (dataType.isCoercibleTo(PTimestamp.INSTANCE)) {
        if (formatString == null) {
            formatString = context.getDateFormat();
            formatter = context.getDateFormatter();
        } else {
            formatter = FunctionArgumentType.TEMPORAL.getFormatter(formatString);
        }
        type = FunctionArgumentType.TEMPORAL;
    }
    else if (dataType.isCoercibleTo(PChar.INSTANCE)) {
        if (formatString != null) {
            formatter = FunctionArgumentType.CHAR.getFormatter(formatString);
        }
        type = FunctionArgumentType.CHAR;
    }
    else {
        throw new SQLException(dataType + " type is unsupported for TO_NUMBER().  Numeric and temporal types are supported.");
    }
    Preconditions.checkNotNull(type);
    this.type = type;
    this.formatString = formatString;
    this.format = formatter;
}
 
Example #13
Source File: ToNumberParseNode.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Override
public FunctionExpression create(List<Expression> children, StatementContext context) throws SQLException {
    PDataType dataType = children.get(0).getDataType();
    String formatString = (String)((LiteralExpression)children.get(1)).getValue(); // either date or number format string
    Format formatter =  null;
    FunctionArgumentType type;
    
    if (dataType.isCoercibleTo(PTimestamp.INSTANCE)) {
        if (formatString == null) {
            formatString = context.getDateFormat();
            formatter = context.getDateFormatter();
        } else {
            formatter = FunctionArgumentType.TEMPORAL.getFormatter(formatString);
        }
        type = FunctionArgumentType.TEMPORAL;
    }
    else if (dataType.isCoercibleTo(PChar.INSTANCE)) {
        if (formatString != null) {
            formatter = FunctionArgumentType.CHAR.getFormatter(formatString);
        }
        type = FunctionArgumentType.CHAR;
    }
    else {
        throw new SQLException(dataType + " type is unsupported for TO_NUMBER().  Numeric and temporal types are supported.");
    }
    return new ToNumberFunction(children, type, formatString, formatter);
}
 
Example #14
Source File: RoundRobinResultIteratorIT.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Test
public void testIteratorsPickedInRoundRobinFashionForSaltedTable() throws Exception {
    try (Connection conn = getConnection()) {
        String testTable = "testIteratorsPickedInRoundRobinFashionForSaltedTable".toUpperCase();
        Statement stmt = conn.createStatement();
        stmt.execute("CREATE TABLE " + testTable + "(K VARCHAR PRIMARY KEY) SALT_BUCKETS = 8");
        PhoenixConnection phxConn = conn.unwrap(PhoenixConnection.class);
        MockParallelIteratorFactory parallelIteratorFactory = new MockParallelIteratorFactory();
        phxConn.setIteratorFactory(parallelIteratorFactory);
        ResultSet rs = stmt.executeQuery("SELECT * FROM " + testTable);
        StatementContext ctx = rs.unwrap(PhoenixResultSet.class).getContext();
        PTable table = ctx.getResolver().getTables().get(0).getTable();
        parallelIteratorFactory.setTable(table);
        PhoenixStatement pstmt = stmt.unwrap(PhoenixStatement.class);
        int numIterators = pstmt.getQueryPlan().getSplits().size();
        assertEquals(8, numIterators);
        int numFetches = 2 * numIterators;
        List<String> iteratorOrder = new ArrayList<>(numFetches);
        for (int i = 1; i <= numFetches; i++) {
            rs.next();
            iteratorOrder.add(rs.getString(1));
        }
        /*
         * Because TableResultIterators are created in parallel in multiple threads, their relative order is not
         * deterministic. However, once the iterators are assigned to a RoundRobinResultIterator, the order in which
         * the next iterator is picked is deterministic - i1, i2, .. i7, i8, i1, i2, .. i7, i8, i1, i2, ..
         */
        for (int i = 0; i < numIterators; i++) {
            assertEquals(iteratorOrder.get(i), iteratorOrder.get(i + numIterators));
        }
    }
}
 
Example #15
Source File: ChunkedResultIterator.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Override
public PeekingResultIterator newIterator(StatementContext context, ResultIterator scanner, Scan scan) throws SQLException {
    scanner.close(); //close the iterator since we don't need it anymore.
    if (logger.isDebugEnabled()) logger.debug(LogUtil.addCustomAnnotations("ChunkedResultIteratorFactory.newIterator over " + tableRef.getTable().getName().getString() + " with " + scan, ScanUtil.getCustomAnnotations(scan)));
    return new ChunkedResultIterator(delegateFactory, context, tableRef, scan,
            context.getConnection().getQueryServices().getProps().getLong(
                                QueryServices.SCAN_RESULT_CHUNK_SIZE,
                                QueryServicesOptions.DEFAULT_SCAN_RESULT_CHUNK_SIZE));
}
 
Example #16
Source File: AvgAggregateParseNode.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Override
public FunctionExpression create(List<Expression> children, StatementContext context) throws SQLException {
    SumAggregateFunction sumFunc;
    CountAggregateFunction countFunc = (CountAggregateFunction)context.getExpressionManager().addIfAbsent(new CountAggregateFunction(children));
    if (!countFunc.isConstantExpression()) {
        sumFunc = (SumAggregateFunction)context.getExpressionManager().addIfAbsent(new SumAggregateFunction(countFunc.getChildren(),null));
    } else {
        sumFunc = null;
    }

    return new AvgAggregateFunction(children, countFunc, sumFunc);
}
 
Example #17
Source File: ToDateParseNode.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Override
public FunctionExpression create(List<Expression> children, StatementContext context) throws SQLException {
    String dateFormat = (String) ((LiteralExpression) children.get(1)).getValue();
    String timeZoneId = (String) ((LiteralExpression) children.get(2)).getValue();
    if (dateFormat == null) {
        dateFormat = context.getDateFormat();
    }
    if (timeZoneId == null) {
        timeZoneId = context.getDateFormatTimeZone().getID();
    }
    return new ToDateFunction(children, dateFormat, timeZoneId);
}
 
Example #18
Source File: ToCharFunction.java    From phoenix with Apache License 2.0 5 votes vote down vote up
public ToCharFunction(List<Expression> children, StatementContext context) throws SQLException {
    super(children.subList(0, 1));
    PDataType dataType = children.get(0).getDataType();
    String formatString = (String)((LiteralExpression)children.get(1)).getValue(); // either date or number format string
    Format formatter;
    FunctionArgumentType type;
    if (dataType.isCoercibleTo(PTimestamp.INSTANCE)) {
        if (formatString == null) {
            formatString = context.getDateFormat();
            formatter = context.getDateFormatter();
        } else {
            formatter = FunctionArgumentType.TEMPORAL.getFormatter(formatString);
        }
        type = FunctionArgumentType.TEMPORAL;
    }
    else if (dataType.isCoercibleTo(PDecimal.INSTANCE)) {
        if (formatString == null)
            formatString = context.getNumberFormat();
        formatter = FunctionArgumentType.NUMERIC.getFormatter(formatString);
        type = FunctionArgumentType.NUMERIC;
    }
    else {
        throw new SQLException(dataType + " type is unsupported for TO_CHAR().  Numeric and temporal types are supported.");
    }
    Preconditions.checkNotNull(formatString);
    Preconditions.checkNotNull(formatter);
    Preconditions.checkNotNull(type);
    this.type = type;
    this.formatString = formatString;
    this.formatter = formatter;
}
 
Example #19
Source File: DelegateConstantToCountParseNode.java    From phoenix with Apache License 2.0 5 votes vote down vote up
protected CountAggregateFunction getDelegateFunction(List<Expression> children, StatementContext context) {
    CountAggregateFunction countFunc = null;
    if (getChildren().get(0).isStateless()) {
        countFunc = (CountAggregateFunction)context.getExpressionManager().addIfAbsent(new CountAggregateFunction(children));
    }
    return countFunc;
}
 
Example #20
Source File: ToTimeParseNode.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Override
public FunctionExpression create(List<Expression> children, StatementContext context) throws SQLException {
    String dateFormat = (String) ((LiteralExpression) children.get(1)).getValue();
    String timeZoneId = (String) ((LiteralExpression) children.get(2)).getValue();
    if (dateFormat == null) {
        dateFormat = context.getTimeFormat();
    }
    if (timeZoneId == null) {
        timeZoneId = context.getDateFormatTimeZone().getID();
    }
    return new ToTimeFunction(children, dateFormat, timeZoneId);
}
 
Example #21
Source File: AvgAggregateParseNode.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Override
public FunctionExpression create(List<Expression> children, StatementContext context) throws SQLException {
    SumAggregateFunction sumFunc;
    CountAggregateFunction countFunc = (CountAggregateFunction)context.getExpressionManager().addIfAbsent(new CountAggregateFunction(children));
    if (!countFunc.isConstantExpression()) {
        sumFunc = (SumAggregateFunction)context.getExpressionManager().addIfAbsent(new SumAggregateFunction(countFunc.getChildren(),null));
    } else {
        sumFunc = null;
    }

    return new AvgAggregateFunction(children, countFunc, sumFunc);
}
 
Example #22
Source File: ClientAggregatePlan.java    From phoenix with Apache License 2.0 5 votes vote down vote up
private OrderBy convertActualOutputOrderBy(OrderBy orderBy, GroupBy groupBy, StatementContext statementContext) {
    if(!orderBy.isEmpty()) {
        return OrderBy.convertCompiledOrderByToOutputOrderBy(orderBy);
    }

    if(this.useHashAgg &&
       !groupBy.isEmpty() &&
       !groupBy.isOrderPreserving() &&
       orderBy != OrderBy.FWD_ROW_KEY_ORDER_BY &&
       orderBy != OrderBy.REV_ROW_KEY_ORDER_BY) {
        return OrderBy.EMPTY_ORDER_BY;
    }

    return ExpressionUtil.convertGroupByToOrderBy(groupBy, orderBy == OrderBy.REV_ROW_KEY_ORDER_BY);
}
 
Example #23
Source File: PhoenixStatement.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public MutationPlan compilePlan(final PhoenixStatement stmt, Sequence.ValueOp seqAction) throws SQLException {
    final StatementContext context = new StatementContext(stmt);
    return new MutationPlan() {

        @Override
        public StatementContext getContext() {
            return context;
        }

        @Override
        public ParameterMetaData getParameterMetaData() {
            return PhoenixParameterMetaData.EMPTY_PARAMETER_META_DATA;
        }

        @Override
        public ExplainPlan getExplainPlan() throws SQLException {
            return new ExplainPlan(Collections.singletonList("DROP TABLE"));
        }

        @Override
        public PhoenixConnection getConnection() {
            return stmt.getConnection();
        }

        @Override
        public MutationState execute() throws SQLException {
            MetaDataClient client = new MetaDataClient(getConnection());
            return client.dropTable(ExecutableDropTableStatement.this);
        }
    };
}
 
Example #24
Source File: BaseResultIterators.java    From phoenix with Apache License 2.0 5 votes vote down vote up
public BaseResultIterators(QueryPlan plan, Integer perScanLimit, Integer offset, ParallelScanGrouper scanGrouper, Scan scan, Map<ImmutableBytesPtr,ServerCache> caches, QueryPlan dataPlan) throws SQLException {
    super(plan.getContext(), plan.getTableRef(), plan.getGroupBy(), plan.getOrderBy(),
            plan.getStatement().getHint(), QueryUtil.getOffsetLimit(plan.getLimit(), plan.getOffset()), offset);
    this.plan = plan;
    this.scan = scan;
    this.caches = caches;
    this.scanGrouper = scanGrouper;
    this.dataPlan = dataPlan;
    StatementContext context = plan.getContext();
    // Clone MutationState as the one on the connection will change if auto commit is on
    // yet we need the original one with the original transaction from TableResultIterator.
    this.mutationState = new MutationState(context.getConnection().getMutationState());
    TableRef tableRef = plan.getTableRef();
    PTable table = tableRef.getTable();
    physicalTableName = table.getPhysicalName().getBytes();
    Long currentSCN = context.getConnection().getSCN();
    if (null == currentSCN) {
      currentSCN = HConstants.LATEST_TIMESTAMP;
    }
    // Used to tie all the scans together during logging
    scanId = new UUID(ThreadLocalRandom.current().nextLong(), ThreadLocalRandom.current().nextLong()).toString();
    
    initializeScan(plan, perScanLimit, offset, scan);
    this.useStatsForParallelization = PhoenixConfigurationUtil.getStatsForParallelizationProp(context.getConnection(), table);
    this.scans = getParallelScans();
    List<KeyRange> splitRanges = Lists.newArrayListWithExpectedSize(scans.size() * ESTIMATED_GUIDEPOSTS_PER_REGION);
    for (List<Scan> scanList : scans) {
        for (Scan aScan : scanList) {
            splitRanges.add(KeyRange.getKeyRange(aScan.getStartRow(), aScan.getStopRow()));
        }
    }
    this.splits = ImmutableList.copyOf(splitRanges);
    // If split detected, this will be more than one, but that's unlikely
    this.allFutures = Lists.newArrayListWithExpectedSize(1);
}
 
Example #25
Source File: ToTimestampParseNode.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Override
public FunctionExpression create(List<Expression> children, StatementContext context) throws SQLException {
    String dateFormat = (String) ((LiteralExpression) children.get(1)).getValue();
    String timeZoneId = (String) ((LiteralExpression) children.get(2)).getValue();
    if (dateFormat == null) {
        dateFormat = context.getTimestampFormat();
    }
    if (timeZoneId == null) {
        timeZoneId = context.getDateFormatTimeZone().getID();
    }
    return new ToTimestampFunction(children, dateFormat, timeZoneId);
}
 
Example #26
Source File: RegexpReplaceParseNode.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Override
public Expression create(List<Expression> children, StatementContext context)
        throws SQLException {
    QueryServices services = context.getConnection().getQueryServices();
    boolean useByteBasedRegex =
            services.getProps().getBoolean(QueryServices.USE_BYTE_BASED_REGEX_ATTRIB,
                QueryServicesOptions.DEFAULT_USE_BYTE_BASED_REGEX);
    if (useByteBasedRegex) {
        return new ByteBasedRegexpReplaceFunction(children);
    } else {
        return new StringBasedRegexpReplaceFunction(children);
    }
}
 
Example #27
Source File: ClientAggregatePlan.java    From phoenix with Apache License 2.0 5 votes vote down vote up
public ClientAggregatePlan(StatementContext context, FilterableStatement statement, TableRef table, RowProjector projector,
        Integer limit, Expression where, OrderBy orderBy, GroupBy groupBy, Expression having, QueryPlan delegate) {
    super(context, statement, table, projector, limit, where, orderBy, delegate);
    this.groupBy = groupBy;
    this.having = having;
    this.serverAggregators =
            ServerAggregators.deserialize(context.getScan()
                    .getAttribute(BaseScannerRegionObserver.AGGREGATORS), QueryServicesOptions.withDefaults().getConfiguration());
    this.clientAggregators = context.getAggregationManager().getAggregators();
}
 
Example #28
Source File: DelegateConstantToCountParseNode.java    From phoenix with Apache License 2.0 5 votes vote down vote up
protected CountAggregateFunction getDelegateFunction(List<Expression> children, StatementContext context) {
    CountAggregateFunction countFunc = null;
    if (getChildren().get(0).isStateless()) {
        countFunc = (CountAggregateFunction)context.getExpressionManager().addIfAbsent(new CountAggregateFunction(children));
    }
    return countFunc;
}
 
Example #29
Source File: AggregatePlan.java    From phoenix with Apache License 2.0 5 votes vote down vote up
public AggregatePlan(
        StatementContext context, FilterableStatement statement, TableRef table, RowProjector projector,
        Integer limit, OrderBy orderBy, ParallelIteratorFactory parallelIteratorFactory, GroupBy groupBy,
        Expression having) {
    super(context, statement, table, projector, context.getBindManager().getParameterMetaData(), limit, orderBy, groupBy, parallelIteratorFactory);
    this.having = having;
    this.aggregators = context.getAggregationManager().getAggregators();
}
 
Example #30
Source File: QueryLoggerIT.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithLoggingOFF() throws Exception{
    String tableName = generateUniqueName();
    createTableAndInsertValues(tableName, true);
    Properties props= new Properties();
    props.setProperty(QueryServices.LOG_LEVEL, LogLevel.OFF.name());
    Connection conn = DriverManager.getConnection(getUrl(),props);
    assertEquals(conn.unwrap(PhoenixConnection.class).getLogLevel(),LogLevel.OFF);

    // delete old data
    conn.createStatement().executeUpdate("delete from " + SYSTEM_CATALOG_SCHEMA + ".\"" + SYSTEM_LOG_TABLE + "\"");
    conn.commit();

    String query = "SELECT * FROM " + tableName;
    ResultSet rs = conn.createStatement().executeQuery(query);
    StatementContext context = ((PhoenixResultSet)rs).getContext();
    assertEquals(context.getQueryLogger(), QueryLogger.NO_OP_INSTANCE);
    while (rs.next()) {
        rs.getString(1);
        rs.getString(2);
    }

    String logQuery = "SELECT count(*) FROM " + SYSTEM_CATALOG_SCHEMA + ".\"" + SYSTEM_LOG_TABLE + "\"";
    int delay = 5000;

    // sleep for sometime to let query log committed
    Thread.sleep(delay);
    rs = conn.createStatement().executeQuery(logQuery);
    assertTrue(rs.next());
    assertEquals(rs.getInt(1), 0);
    assertFalse(rs.next());
    conn.close();
}