Search in sources :

Example 11 with PFunction

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

the class MetaDataClient method createFunction.

public MutationState createFunction(CreateFunctionStatement stmt) throws SQLException {
    boolean wasAutoCommit = connection.getAutoCommit();
    connection.rollback();
    try {
        PFunction function = new PFunction(stmt.getFunctionInfo(), stmt.isTemporary(), stmt.isReplace());
        connection.setAutoCommit(false);
        String tenantIdStr = connection.getTenantId() == null ? null : connection.getTenantId().getString();
        List<Mutation> functionData = Lists.newArrayListWithExpectedSize(function.getFunctionArguments().size() + 1);
        List<FunctionArgument> args = function.getFunctionArguments();
        try (PreparedStatement argUpsert = connection.prepareStatement(INSERT_FUNCTION_ARGUMENT)) {
            for (int i = 0; i < args.size(); i++) {
                FunctionArgument arg = args.get(i);
                addFunctionArgMutation(function.getFunctionName(), arg, argUpsert, i);
            }
            functionData.addAll(connection.getMutationState().toMutations().next().getSecond());
            connection.rollback();
        }
        try (PreparedStatement functionUpsert = connection.prepareStatement(CREATE_FUNCTION)) {
            functionUpsert.setString(1, tenantIdStr);
            functionUpsert.setString(2, function.getFunctionName());
            functionUpsert.setInt(3, function.getFunctionArguments().size());
            functionUpsert.setString(4, function.getClassName());
            functionUpsert.setString(5, function.getJarPath());
            functionUpsert.setString(6, function.getReturnType());
            functionUpsert.execute();
            functionData.addAll(connection.getMutationState().toMutations(null).next().getSecond());
            connection.rollback();
        }
        MetaDataMutationResult result = connection.getQueryServices().createFunction(functionData, function, stmt.isTemporary());
        MutationCode code = result.getMutationCode();
        switch(code) {
            case FUNCTION_ALREADY_EXISTS:
                if (!function.isReplace()) {
                    throw new FunctionAlreadyExistsException(function.getFunctionName(), result.getFunctions().get(0));
                } else {
                    connection.removeFunction(function.getTenantId(), function.getFunctionName(), result.getMutationTime());
                    addFunctionToCache(result);
                }
            case NEWER_FUNCTION_FOUND:
                // it to this connection as we can't see it.
                throw new NewerFunctionAlreadyExistsException(function.getFunctionName(), result.getFunctions().get(0));
            default:
                List<PFunction> functions = new ArrayList<PFunction>(1);
                functions.add(function);
                result = new MetaDataMutationResult(code, result.getMutationTime(), functions, true);
                if (function.isReplace()) {
                    connection.removeFunction(function.getTenantId(), function.getFunctionName(), result.getMutationTime());
                }
                addFunctionToCache(result);
        }
    } finally {
        connection.setAutoCommit(wasAutoCommit);
    }
    return new MutationState(1, 1000, connection);
}
Also used : PFunction(org.apache.phoenix.parse.PFunction) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) IndexKeyConstraint(org.apache.phoenix.parse.IndexKeyConstraint) PrimaryKeyConstraint(org.apache.phoenix.parse.PrimaryKeyConstraint) ColumnDefInPkConstraint(org.apache.phoenix.parse.ColumnDefInPkConstraint) MutationCode(org.apache.phoenix.coprocessor.MetaDataProtocol.MutationCode) MutationState(org.apache.phoenix.execute.MutationState) Mutation(org.apache.hadoop.hbase.client.Mutation) FunctionArgument(org.apache.phoenix.parse.PFunction.FunctionArgument) MetaDataMutationResult(org.apache.phoenix.coprocessor.MetaDataProtocol.MetaDataMutationResult)

Example 12 with PFunction

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

the class ExpressionCompiler method visitLeave.

@Override
public /**
     * @param node a function expression node
     * @param children the child expression arguments to the function expression node.
     */
Expression visitLeave(FunctionParseNode node, List<Expression> children) throws SQLException {
    PFunction function = null;
    if (node instanceof UDFParseNode) {
        function = context.getResolver().resolveFunction(node.getName());
        BuiltInFunctionInfo info = new BuiltInFunctionInfo(function);
        node = new UDFParseNode(node.getName(), node.getChildren(), info);
    }
    children = node.validate(children, context);
    Expression expression = null;
    if (function == null) {
        expression = node.create(children, context);
    } else {
        expression = node.create(children, function, context);
    }
    ImmutableBytesWritable ptr = context.getTempPtr();
    BuiltInFunctionInfo info = node.getInfo();
    for (int i = 0; i < info.getRequiredArgCount(); i++) {
        // we can get the proper type to use.
        if (node.evalToNullIfParamIsNull(context, i)) {
            Expression child = children.get(i);
            if (ExpressionUtil.isNull(child, ptr)) {
                return ExpressionUtil.getNullExpression(expression);
            }
        }
    }
    if (ExpressionUtil.isConstant(expression)) {
        return ExpressionUtil.getConstantExpression(expression, ptr);
    }
    expression = addExpression(expression);
    expression = wrapGroupByExpression(expression);
    if (aggregateFunction == node) {
        // Turn back off on the way out
        aggregateFunction = null;
    }
    return expression;
}
Also used : UDFParseNode(org.apache.phoenix.parse.UDFParseNode) ImmutableBytesWritable(org.apache.hadoop.hbase.io.ImmutableBytesWritable) PFunction(org.apache.phoenix.parse.PFunction) DecimalAddExpression(org.apache.phoenix.expression.DecimalAddExpression) TimestampSubtractExpression(org.apache.phoenix.expression.TimestampSubtractExpression) ArrayConstructorExpression(org.apache.phoenix.expression.ArrayConstructorExpression) Expression(org.apache.phoenix.expression.Expression) LikeExpression(org.apache.phoenix.expression.LikeExpression) ByteBasedLikeExpression(org.apache.phoenix.expression.ByteBasedLikeExpression) DoubleSubtractExpression(org.apache.phoenix.expression.DoubleSubtractExpression) LiteralExpression(org.apache.phoenix.expression.LiteralExpression) InListExpression(org.apache.phoenix.expression.InListExpression) DateSubtractExpression(org.apache.phoenix.expression.DateSubtractExpression) ArrayElemRefExpression(org.apache.phoenix.expression.function.ArrayElemRefExpression) CaseExpression(org.apache.phoenix.expression.CaseExpression) DoubleDivideExpression(org.apache.phoenix.expression.DoubleDivideExpression) NotExpression(org.apache.phoenix.expression.NotExpression) DoubleAddExpression(org.apache.phoenix.expression.DoubleAddExpression) DecimalDivideExpression(org.apache.phoenix.expression.DecimalDivideExpression) RowKeyColumnExpression(org.apache.phoenix.expression.RowKeyColumnExpression) RowValueConstructorExpression(org.apache.phoenix.expression.RowValueConstructorExpression) RoundTimestampExpression(org.apache.phoenix.expression.function.RoundTimestampExpression) StringConcatExpression(org.apache.phoenix.expression.StringConcatExpression) ComparisonExpression(org.apache.phoenix.expression.ComparisonExpression) TimestampAddExpression(org.apache.phoenix.expression.TimestampAddExpression) CoerceExpression(org.apache.phoenix.expression.CoerceExpression) StringBasedLikeExpression(org.apache.phoenix.expression.StringBasedLikeExpression) ArrayAnyComparisonExpression(org.apache.phoenix.expression.function.ArrayAnyComparisonExpression) DecimalSubtractExpression(org.apache.phoenix.expression.DecimalSubtractExpression) ModulusExpression(org.apache.phoenix.expression.ModulusExpression) DoubleMultiplyExpression(org.apache.phoenix.expression.DoubleMultiplyExpression) DecimalMultiplyExpression(org.apache.phoenix.expression.DecimalMultiplyExpression) DateAddExpression(org.apache.phoenix.expression.DateAddExpression) RoundDecimalExpression(org.apache.phoenix.expression.function.RoundDecimalExpression) LongAddExpression(org.apache.phoenix.expression.LongAddExpression) LongSubtractExpression(org.apache.phoenix.expression.LongSubtractExpression) IsNullExpression(org.apache.phoenix.expression.IsNullExpression) AndExpression(org.apache.phoenix.expression.AndExpression) LongMultiplyExpression(org.apache.phoenix.expression.LongMultiplyExpression) ArrayAllComparisonExpression(org.apache.phoenix.expression.function.ArrayAllComparisonExpression) OrExpression(org.apache.phoenix.expression.OrExpression) LongDivideExpression(org.apache.phoenix.expression.LongDivideExpression) BuiltInFunctionInfo(org.apache.phoenix.parse.FunctionParseNode.BuiltInFunctionInfo)

Example 13 with PFunction

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

the class MetaDataEndpointImpl method buildFunctions.

private List<PFunction> buildFunctions(List<byte[]> keys, Region region, long clientTimeStamp, boolean isReplace, List<Mutation> deleteMutationsForReplace) throws IOException, SQLException {
    List<KeyRange> keyRanges = Lists.newArrayListWithExpectedSize(keys.size());
    for (byte[] key : keys) {
        byte[] stopKey = ByteUtil.concat(key, QueryConstants.SEPARATOR_BYTE_ARRAY);
        ByteUtil.nextKey(stopKey, stopKey.length);
        keyRanges.add(PVarbinary.INSTANCE.getKeyRange(key, true, stopKey, false));
    }
    Scan scan = new Scan();
    scan.setTimeRange(MIN_TABLE_TIMESTAMP, clientTimeStamp);
    ScanRanges scanRanges = ScanRanges.createPointLookup(keyRanges);
    scanRanges.initializeScan(scan);
    scan.setFilter(scanRanges.getSkipScanFilter());
    RegionScanner scanner = region.getScanner(scan);
    Cache<ImmutableBytesPtr, PMetaDataEntity> metaDataCache = GlobalCache.getInstance(this.env).getMetaDataCache();
    List<PFunction> functions = new ArrayList<PFunction>();
    PFunction function = null;
    try {
        for (int i = 0; i < keys.size(); i++) {
            function = null;
            function = getFunction(scanner, isReplace, clientTimeStamp, deleteMutationsForReplace);
            if (function == null) {
                return null;
            }
            byte[] functionKey = SchemaUtil.getFunctionKey(function.getTenantId() == null ? ByteUtil.EMPTY_BYTE_ARRAY : function.getTenantId().getBytes(), Bytes.toBytes(function.getFunctionName()));
            metaDataCache.put(new FunctionBytesPtr(functionKey), function);
            functions.add(function);
        }
        return functions;
    } finally {
        scanner.close();
    }
}
Also used : PFunction(org.apache.phoenix.parse.PFunction) KeyRange(org.apache.phoenix.query.KeyRange) ImmutableBytesPtr(org.apache.phoenix.hbase.index.util.ImmutableBytesPtr) ArrayList(java.util.ArrayList) ScanRanges(org.apache.phoenix.compile.ScanRanges) PTinyint(org.apache.phoenix.schema.types.PTinyint) PSmallint(org.apache.phoenix.schema.types.PSmallint) RegionScanner(org.apache.hadoop.hbase.regionserver.RegionScanner) PMetaDataEntity(org.apache.phoenix.schema.PMetaDataEntity) Scan(org.apache.hadoop.hbase.client.Scan) FunctionBytesPtr(org.apache.phoenix.cache.GlobalCache.FunctionBytesPtr)

Example 14 with PFunction

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

the class MetaDataEndpointImpl method buildDeletedFunction.

private PFunction buildDeletedFunction(byte[] key, ImmutableBytesPtr cacheKey, Region region, long clientTimeStamp) throws IOException {
    if (clientTimeStamp == HConstants.LATEST_TIMESTAMP) {
        return null;
    }
    Scan scan = MetaDataUtil.newTableRowsScan(key, clientTimeStamp, HConstants.LATEST_TIMESTAMP);
    scan.setFilter(new FirstKeyOnlyFilter());
    scan.setRaw(true);
    List<Cell> results = Lists.<Cell>newArrayList();
    try (RegionScanner scanner = region.getScanner(scan)) {
        scanner.next(results);
    }
    // HBase ignores the time range on a raw scan (HBASE-7362)
    if (!results.isEmpty() && results.get(0).getTimestamp() > clientTimeStamp) {
        Cell kv = results.get(0);
        if (kv.getTypeByte() == Type.Delete.getCode()) {
            Cache<ImmutableBytesPtr, PMetaDataEntity> metaDataCache = GlobalCache.getInstance(this.env).getMetaDataCache();
            PFunction function = newDeletedFunctionMarker(kv.getTimestamp());
            metaDataCache.put(cacheKey, function);
            return function;
        }
    }
    return null;
}
Also used : RegionScanner(org.apache.hadoop.hbase.regionserver.RegionScanner) PMetaDataEntity(org.apache.phoenix.schema.PMetaDataEntity) PFunction(org.apache.phoenix.parse.PFunction) FirstKeyOnlyFilter(org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter) ImmutableBytesPtr(org.apache.phoenix.hbase.index.util.ImmutableBytesPtr) Scan(org.apache.hadoop.hbase.client.Scan) Cell(org.apache.hadoop.hbase.Cell)

Example 15 with PFunction

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

the class MetaDataEndpointImpl method createFunction.

@Override
public void createFunction(RpcController controller, CreateFunctionRequest request, RpcCallback<MetaDataResponse> done) {
    MetaDataResponse.Builder builder = MetaDataResponse.newBuilder();
    byte[][] rowKeyMetaData = new byte[2][];
    byte[] functionName = null;
    try {
        List<Mutation> functionMetaData = ProtobufUtil.getMutations(request);
        boolean temporaryFunction = request.getTemporary();
        MetaDataUtil.getTenantIdAndFunctionName(functionMetaData, rowKeyMetaData);
        byte[] tenantIdBytes = rowKeyMetaData[PhoenixDatabaseMetaData.TENANT_ID_INDEX];
        functionName = rowKeyMetaData[PhoenixDatabaseMetaData.FUNTION_NAME_INDEX];
        byte[] lockKey = SchemaUtil.getFunctionKey(tenantIdBytes, functionName);
        Region region = env.getRegion();
        MetaDataMutationResult result = checkFunctionKeyInRegion(lockKey, region);
        if (result != null) {
            done.run(MetaDataMutationResult.toProto(result));
            return;
        }
        List<RowLock> locks = Lists.newArrayList();
        long clientTimeStamp = MetaDataUtil.getClientTimeStamp(functionMetaData);
        try {
            acquireLock(region, lockKey, locks);
            // Get as of latest timestamp so we can detect if we have a newer function that already
            // exists without making an additional query
            ImmutableBytesPtr cacheKey = new FunctionBytesPtr(lockKey);
            PFunction function = loadFunction(env, lockKey, cacheKey, clientTimeStamp, clientTimeStamp, request.getReplace(), functionMetaData);
            if (function != null) {
                if (function.getTimeStamp() < clientTimeStamp) {
                    // continue
                    if (!isFunctionDeleted(function)) {
                        builder.setReturnCode(MetaDataProtos.MutationCode.FUNCTION_ALREADY_EXISTS);
                        builder.setMutationTime(EnvironmentEdgeManager.currentTimeMillis());
                        builder.addFunction(PFunction.toProto(function));
                        done.run(builder.build());
                        if (!request.getReplace()) {
                            return;
                        }
                    }
                } else {
                    builder.setReturnCode(MetaDataProtos.MutationCode.NEWER_FUNCTION_FOUND);
                    builder.setMutationTime(EnvironmentEdgeManager.currentTimeMillis());
                    builder.addFunction(PFunction.toProto(function));
                    done.run(builder.build());
                    return;
                }
            }
            // Don't store function info for temporary functions.
            if (!temporaryFunction) {
                region.mutateRowsWithLocks(functionMetaData, Collections.<byte[]>emptySet(), HConstants.NO_NONCE, HConstants.NO_NONCE);
            }
            // Invalidate the cache - the next getFunction call will add it
            // TODO: consider loading the function that was just created here, patching up the parent function, and updating the cache
            Cache<ImmutableBytesPtr, PMetaDataEntity> metaDataCache = GlobalCache.getInstance(this.env).getMetaDataCache();
            metaDataCache.invalidate(cacheKey);
            // Get timeStamp from mutations - the above method sets it if it's unset
            long currentTimeStamp = MetaDataUtil.getClientTimeStamp(functionMetaData);
            builder.setReturnCode(MetaDataProtos.MutationCode.FUNCTION_NOT_FOUND);
            builder.setMutationTime(currentTimeStamp);
            done.run(builder.build());
            return;
        } finally {
            region.releaseRowLocks(locks);
        }
    } catch (Throwable t) {
        logger.error("createFunction failed", t);
        ProtobufUtil.setControllerException(controller, ServerUtil.createIOException(Bytes.toString(functionName), t));
    }
}
Also used : MetaDataResponse(org.apache.phoenix.coprocessor.generated.MetaDataProtos.MetaDataResponse) PFunction(org.apache.phoenix.parse.PFunction) ImmutableBytesPtr(org.apache.phoenix.hbase.index.util.ImmutableBytesPtr) PMetaDataEntity(org.apache.phoenix.schema.PMetaDataEntity) Region(org.apache.hadoop.hbase.regionserver.Region) Mutation(org.apache.hadoop.hbase.client.Mutation) RowLock(org.apache.hadoop.hbase.regionserver.Region.RowLock) FunctionBytesPtr(org.apache.phoenix.cache.GlobalCache.FunctionBytesPtr)

Aggregations

PFunction (org.apache.phoenix.parse.PFunction)16 ArrayList (java.util.ArrayList)8 Scan (org.apache.hadoop.hbase.client.Scan)5 Region (org.apache.hadoop.hbase.regionserver.Region)5 ImmutableBytesPtr (org.apache.phoenix.hbase.index.util.ImmutableBytesPtr)5 PMetaDataEntity (org.apache.phoenix.schema.PMetaDataEntity)5 FunctionBytesPtr (org.apache.phoenix.cache.GlobalCache.FunctionBytesPtr)4 MetaDataMutationResult (org.apache.phoenix.coprocessor.MetaDataProtocol.MetaDataMutationResult)4 Cell (org.apache.hadoop.hbase.Cell)3 Delete (org.apache.hadoop.hbase.client.Delete)3 Mutation (org.apache.hadoop.hbase.client.Mutation)3 RegionScanner (org.apache.hadoop.hbase.regionserver.RegionScanner)3 MutationCode (org.apache.phoenix.coprocessor.MetaDataProtocol.MutationCode)3 FunctionNotFoundException (org.apache.phoenix.schema.FunctionNotFoundException)3 PSmallint (org.apache.phoenix.schema.types.PSmallint)3 PTinyint (org.apache.phoenix.schema.types.PTinyint)3 SQLException (java.sql.SQLException)2 List (java.util.List)2 ImmutableBytesWritable (org.apache.hadoop.hbase.io.ImmutableBytesWritable)2 RowLock (org.apache.hadoop.hbase.regionserver.Region.RowLock)2