Search in sources :

Example 26 with AsterixException

use of org.apache.asterix.common.exceptions.AsterixException in project asterixdb by apache.

the class SubsetCollectionDescriptor method createUnnestingEvaluatorFactory.

@Override
public IUnnestingEvaluatorFactory createUnnestingEvaluatorFactory(final IScalarEvaluatorFactory[] args) {
    return new IUnnestingEvaluatorFactory() {

        private static final long serialVersionUID = 1L;

        @Override
        public IUnnestingEvaluator createUnnestingEvaluator(IHyracksTaskContext ctx) throws HyracksDataException {
            return new IUnnestingEvaluator() {

                private IPointable inputVal = new VoidPointable();

                private IScalarEvaluator evalList = args[0].createScalarEvaluator(ctx);

                private IScalarEvaluator evalStart = args[1].createScalarEvaluator(ctx);

                private IScalarEvaluator evalLen = args[2].createScalarEvaluator(ctx);

                private ArrayBackedValueStorage resultStorage = new ArrayBackedValueStorage();

                private int numItems;

                private int numItemsMax;

                private int posStart;

                private int posCrt;

                private ATypeTag itemTag;

                private boolean selfDescList = false;

                private boolean metUnknown = false;

                @Override
                public void init(IFrameTupleReference tuple) throws HyracksDataException {
                    try {
                        evalStart.evaluate(tuple, inputVal);
                        posStart = ATypeHierarchy.getIntegerValue(getIdentifier().getName(), 0, inputVal.getByteArray(), inputVal.getStartOffset());
                        evalLen.evaluate(tuple, inputVal);
                        numItems = ATypeHierarchy.getIntegerValue(getIdentifier().getName(), 1, inputVal.getByteArray(), inputVal.getStartOffset());
                        evalList.evaluate(tuple, inputVal);
                        byte[] serList = inputVal.getByteArray();
                        int offset = inputVal.getStartOffset();
                        metUnknown = false;
                        byte typeTag = serList[offset];
                        if (typeTag == ATypeTag.SERIALIZED_MISSING_TYPE_TAG || typeTag == ATypeTag.SERIALIZED_NULL_TYPE_TAG) {
                            metUnknown = true;
                            return;
                        }
                        if (typeTag != ATypeTag.SERIALIZED_ORDEREDLIST_TYPE_TAG && typeTag != ATypeTag.SERIALIZED_UNORDEREDLIST_TYPE_TAG) {
                            throw new RuntimeDataException(ErrorCode.COERCION, getIdentifier());
                        }
                        if (typeTag == ATypeTag.SERIALIZED_ORDEREDLIST_TYPE_TAG) {
                            numItemsMax = AOrderedListSerializerDeserializer.getNumberOfItems(serList, offset);
                        } else {
                            numItemsMax = AUnorderedListSerializerDeserializer.getNumberOfItems(serList, offset);
                        }
                        itemTag = EnumDeserializer.ATYPETAGDESERIALIZER.deserialize(serList[offset + 1]);
                        if (itemTag == ATypeTag.ANY) {
                            selfDescList = true;
                        }
                        posCrt = posStart;
                    } catch (IOException e) {
                        throw new HyracksDataException(e);
                    }
                }

                @Override
                public boolean step(IPointable result) throws HyracksDataException {
                    if (!metUnknown && posCrt < posStart + numItems && posCrt < numItemsMax) {
                        resultStorage.reset();
                        byte[] serList = inputVal.getByteArray();
                        int offset = inputVal.getStartOffset();
                        int itemLength = 0;
                        try {
                            int itemOffset = AOrderedListSerializerDeserializer.getItemOffset(serList, offset, posCrt);
                            if (selfDescList) {
                                itemTag = EnumDeserializer.ATYPETAGDESERIALIZER.deserialize(serList[itemOffset]);
                            }
                            itemLength = NonTaggedFormatUtil.getFieldValueLength(serList, itemOffset, itemTag, selfDescList);
                            if (!selfDescList) {
                                resultStorage.getDataOutput().writeByte(itemTag.serialize());
                            }
                            resultStorage.getDataOutput().write(serList, itemOffset, itemLength + (!selfDescList ? 0 : 1));
                        } catch (IOException e) {
                            throw new HyracksDataException(e);
                        } catch (AsterixException e) {
                            throw new HyracksDataException(e);
                        }
                        result.set(resultStorage);
                        ++posCrt;
                        return true;
                    }
                    return false;
                }
            };
        }
    };
}
Also used : IPointable(org.apache.hyracks.data.std.api.IPointable) IOException(java.io.IOException) IUnnestingEvaluatorFactory(org.apache.hyracks.algebricks.runtime.base.IUnnestingEvaluatorFactory) IScalarEvaluator(org.apache.hyracks.algebricks.runtime.base.IScalarEvaluator) HyracksDataException(org.apache.hyracks.api.exceptions.HyracksDataException) ArrayBackedValueStorage(org.apache.hyracks.data.std.util.ArrayBackedValueStorage) AsterixException(org.apache.asterix.common.exceptions.AsterixException) IUnnestingEvaluator(org.apache.hyracks.algebricks.runtime.base.IUnnestingEvaluator) ATypeTag(org.apache.asterix.om.types.ATypeTag) IHyracksTaskContext(org.apache.hyracks.api.context.IHyracksTaskContext) VoidPointable(org.apache.hyracks.data.std.primitive.VoidPointable) IFrameTupleReference(org.apache.hyracks.dataflow.common.data.accessors.IFrameTupleReference) RuntimeDataException(org.apache.asterix.common.exceptions.RuntimeDataException)

Example 27 with AsterixException

use of org.apache.asterix.common.exceptions.AsterixException in project asterixdb by apache.

the class IntroduceSecondaryIndexInsertDeleteRule method rewritePost.

@Override
public boolean rewritePost(Mutable<ILogicalOperator> opRef, IOptimizationContext context) throws AlgebricksException {
    AbstractLogicalOperator op0 = (AbstractLogicalOperator) opRef.getValue();
    if (op0.getOperatorTag() != LogicalOperatorTag.DELEGATE_OPERATOR && op0.getOperatorTag() != LogicalOperatorTag.SINK) {
        return false;
    }
    if (op0.getOperatorTag() == LogicalOperatorTag.DELEGATE_OPERATOR) {
        DelegateOperator eOp = (DelegateOperator) op0;
        if (!(eOp.getDelegate() instanceof CommitOperator)) {
            return false;
        }
    }
    AbstractLogicalOperator op1 = (AbstractLogicalOperator) op0.getInputs().get(0).getValue();
    if (op1.getOperatorTag() != LogicalOperatorTag.INSERT_DELETE_UPSERT) {
        return false;
    }
    /** find the record variable */
    InsertDeleteUpsertOperator primaryIndexModificationOp = (InsertDeleteUpsertOperator) op0.getInputs().get(0).getValue();
    boolean isBulkload = primaryIndexModificationOp.isBulkload();
    ILogicalExpression newRecordExpr = primaryIndexModificationOp.getPayloadExpression().getValue();
    List<Mutable<ILogicalExpression>> newMetaExprs = primaryIndexModificationOp.getAdditionalNonFilteringExpressions();
    LogicalVariable newRecordVar;
    LogicalVariable newMetaVar = null;
    /**
         * inputOp is the assign operator which extracts primary keys from the input
         * variables (record or meta)
         */
    AbstractLogicalOperator inputOp = (AbstractLogicalOperator) primaryIndexModificationOp.getInputs().get(0).getValue();
    newRecordVar = getRecordVar(context, inputOp, newRecordExpr, 0);
    if (newMetaExprs != null && !newMetaExprs.isEmpty()) {
        if (newMetaExprs.size() > 1) {
            throw new AlgebricksException("Number of meta records can't be more than 1. Number of meta records found = " + newMetaExprs.size());
        }
        newMetaVar = getRecordVar(context, inputOp, newMetaExprs.get(0).getValue(), 1);
    }
    /*
         * At this point, we have the record variable and the insert/delete/upsert operator
         * Note: We have two operators:
         * 1. An InsertDeleteOperator (primary)
         * 2. An IndexInsertDeleteOperator (secondary)
         * The current primaryIndexModificationOp is of the first type
         */
    DataSource datasetSource = (DataSource) primaryIndexModificationOp.getDataSource();
    MetadataProvider mp = (MetadataProvider) context.getMetadataProvider();
    String dataverseName = datasetSource.getId().getDataverseName();
    String datasetName = datasetSource.getId().getDatasourceName();
    Dataset dataset = mp.findDataset(dataverseName, datasetName);
    if (dataset == null) {
        throw new AlgebricksException("Unknown dataset " + datasetName + " in dataverse " + dataverseName);
    }
    if (dataset.getDatasetType() == DatasetType.EXTERNAL) {
        return false;
    }
    // Create operators for secondary index insert / delete.
    String itemTypeName = dataset.getItemTypeName();
    IAType itemType = mp.findType(dataset.getItemTypeDataverseName(), itemTypeName);
    if (itemType.getTypeTag() != ATypeTag.OBJECT) {
        throw new AlgebricksException("Only record types can be indexed.");
    }
    ARecordType recType = (ARecordType) itemType;
    // meta type
    ARecordType metaType = null;
    if (dataset.hasMetaPart()) {
        metaType = (ARecordType) mp.findType(dataset.getMetaItemTypeDataverseName(), dataset.getMetaItemTypeName());
    }
    List<Index> indexes = mp.getDatasetIndexes(dataset.getDataverseName(), dataset.getDatasetName());
    // Set the top operator pointer to the primary IndexInsertDeleteOperator
    ILogicalOperator currentTop = primaryIndexModificationOp;
    boolean hasSecondaryIndex = false;
    // Put an n-gram or a keyword index in the later stage of index-update,
    // since TokenizeOperator needs to be involved.
    Collections.sort(indexes, (o1, o2) -> o1.getIndexType().ordinal() - o2.getIndexType().ordinal());
    // At this point, we have the data type info, and the indexes info as well
    int secondaryIndexTotalCnt = indexes.size() - 1;
    if (secondaryIndexTotalCnt > 0) {
        op0.getInputs().clear();
    } else {
        return false;
    }
    // Initialize inputs to the SINK operator Op0 (The SINK) is now without input
    // Prepare filtering field information (This is the filter created using the "filter with" key word in the
    // create dataset ddl)
    List<String> filteringFields = ((InternalDatasetDetails) dataset.getDatasetDetails()).getFilterField();
    List<LogicalVariable> filteringVars;
    List<Mutable<ILogicalExpression>> filteringExpressions = null;
    if (filteringFields != null) {
        // The filter field var already exists. we can simply get it from the insert op
        filteringVars = new ArrayList<>();
        filteringExpressions = new ArrayList<>();
        for (Mutable<ILogicalExpression> filteringExpression : primaryIndexModificationOp.getAdditionalFilteringExpressions()) {
            filteringExpression.getValue().getUsedVariables(filteringVars);
            for (LogicalVariable var : filteringVars) {
                filteringExpressions.add(new MutableObject<ILogicalExpression>(new VariableReferenceExpression(var)));
            }
        }
    }
    // Replicate Operator is applied only when doing the bulk-load.
    ReplicateOperator replicateOp = null;
    if (secondaryIndexTotalCnt > 1 && primaryIndexModificationOp.isBulkload()) {
        // Split the logical plan into "each secondary index update branch"
        // to replicate each <PK,OBJECT> pair.
        replicateOp = new ReplicateOperator(secondaryIndexTotalCnt);
        replicateOp.getInputs().add(new MutableObject<ILogicalOperator>(currentTop));
        replicateOp.setExecutionMode(ExecutionMode.PARTITIONED);
        context.computeAndSetTypeEnvironmentForOperator(replicateOp);
        currentTop = replicateOp;
    }
    /*
         * The two maps are used to store variables to which [casted] field access is assigned.
         * One for the beforeOp record and the other for the new record.
         * There are two uses for these maps:
         * 1. used for shared fields in indexes with overlapping keys.
         * 2. used for setting variables of secondary keys for each secondary index operator.
         */
    Map<IndexFieldId, LogicalVariable> fieldVarsForBeforeOperation = new HashMap<>();
    Map<IndexFieldId, LogicalVariable> fieldVarsForNewRecord = new HashMap<>();
    /*
         * if the index is enforcing field types (For open indexes), We add a cast
         * operator to ensure type safety
         */
    try {
        if (primaryIndexModificationOp.getOperation() == Kind.INSERT || primaryIndexModificationOp.getOperation() == Kind.UPSERT || /* Actually, delete should not be here but it is now until issue
                     * https://issues.apache.org/jira/browse/ASTERIXDB-1507
                     * is solved
                     */
        primaryIndexModificationOp.getOperation() == Kind.DELETE) {
            injectFieldAccessesForIndexes(context, dataset, indexes, fieldVarsForNewRecord, recType, metaType, newRecordVar, newMetaVar, primaryIndexModificationOp, false);
            if (replicateOp != null) {
                context.computeAndSetTypeEnvironmentForOperator(replicateOp);
            }
        }
        if (primaryIndexModificationOp.getOperation() == Kind.UPSERT) /* Actually, delete should be here but it is not until issue
             * https://issues.apache.org/jira/browse/ASTERIXDB-1507
             * is solved
             */
        {
            List<LogicalVariable> beforeOpMetaVars = primaryIndexModificationOp.getBeforeOpAdditionalNonFilteringVars();
            LogicalVariable beforeOpMetaVar = beforeOpMetaVars == null ? null : beforeOpMetaVars.get(0);
            currentTop = injectFieldAccessesForIndexes(context, dataset, indexes, fieldVarsForBeforeOperation, recType, metaType, primaryIndexModificationOp.getBeforeOpRecordVar(), beforeOpMetaVar, currentTop, true);
        }
    } catch (AsterixException e) {
        throw new AlgebricksException(e);
    }
    // At first, op1 is the index insert op insertOp
    for (Index index : indexes) {
        if (!index.isSecondaryIndex()) {
            continue;
        }
        hasSecondaryIndex = true;
        // Get the secondary fields names and types
        List<List<String>> secondaryKeyFields = index.getKeyFieldNames();
        List<LogicalVariable> secondaryKeyVars = new ArrayList<>();
        List<Mutable<ILogicalExpression>> secondaryExpressions = new ArrayList<>();
        List<Mutable<ILogicalExpression>> beforeOpSecondaryExpressions = new ArrayList<>();
        ILogicalOperator replicateOutput;
        for (int i = 0; i < secondaryKeyFields.size(); i++) {
            IndexFieldId indexFieldId = new IndexFieldId(index.getKeyFieldSourceIndicators().get(i), secondaryKeyFields.get(i));
            LogicalVariable skVar = fieldVarsForNewRecord.get(indexFieldId);
            secondaryKeyVars.add(skVar);
            secondaryExpressions.add(new MutableObject<ILogicalExpression>(new VariableReferenceExpression(skVar)));
            if (primaryIndexModificationOp.getOperation() == Kind.UPSERT) {
                beforeOpSecondaryExpressions.add(new MutableObject<ILogicalExpression>(new VariableReferenceExpression(fieldVarsForBeforeOperation.get(indexFieldId))));
            }
        }
        IndexInsertDeleteUpsertOperator indexUpdate;
        if (index.getIndexType() != IndexType.RTREE) {
            // Create an expression per key
            Mutable<ILogicalExpression> filterExpression = (primaryIndexModificationOp.getOperation() == Kind.UPSERT) ? null : createFilterExpression(secondaryKeyVars, context.getOutputTypeEnvironment(currentTop), index.isEnforcingKeyFileds());
            DataSourceIndex dataSourceIndex = new DataSourceIndex(index, dataverseName, datasetName, mp);
            // and index type is keyword or n-gram.
            if (index.getIndexType() != IndexType.BTREE && primaryIndexModificationOp.isBulkload()) {
                // Note: Bulk load case, we don't need to take care of it for upsert operation
                // Check whether the index is length-partitioned or not.
                // If partitioned, [input variables to TokenizeOperator,
                // token, number of token] pairs will be generated and
                // fed into the IndexInsertDeleteOperator.
                // If not, [input variables, token] pairs will be generated
                // and fed into the IndexInsertDeleteOperator.
                // Input variables are passed since TokenizeOperator is not an
                // filtering operator.
                boolean isPartitioned = index.getIndexType() == IndexType.LENGTH_PARTITIONED_WORD_INVIX || index.getIndexType() == IndexType.LENGTH_PARTITIONED_NGRAM_INVIX;
                // Create a new logical variable - token
                List<LogicalVariable> tokenizeKeyVars = new ArrayList<>();
                List<Mutable<ILogicalExpression>> tokenizeKeyExprs = new ArrayList<>();
                LogicalVariable tokenVar = context.newVar();
                tokenizeKeyVars.add(tokenVar);
                tokenizeKeyExprs.add(new MutableObject<ILogicalExpression>(new VariableReferenceExpression(tokenVar)));
                // Check the field type of the secondary key.
                IAType secondaryKeyType;
                Pair<IAType, Boolean> keyPairType = Index.getNonNullableOpenFieldType(index.getKeyFieldTypes().get(0), secondaryKeyFields.get(0), recType);
                secondaryKeyType = keyPairType.first;
                List<Object> varTypes = new ArrayList<>();
                varTypes.add(NonTaggedFormatUtil.getTokenType(secondaryKeyType));
                // The type is short, and this does not contain type info.
                if (isPartitioned) {
                    LogicalVariable lengthVar = context.newVar();
                    tokenizeKeyVars.add(lengthVar);
                    tokenizeKeyExprs.add(new MutableObject<ILogicalExpression>(new VariableReferenceExpression(lengthVar)));
                    varTypes.add(BuiltinType.SHORTWITHOUTTYPEINFO);
                }
                // TokenizeOperator to tokenize [SK, PK] pairs
                TokenizeOperator tokenUpdate = new TokenizeOperator(dataSourceIndex, primaryIndexModificationOp.getPrimaryKeyExpressions(), secondaryExpressions, tokenizeKeyVars, filterExpression, primaryIndexModificationOp.getOperation(), primaryIndexModificationOp.isBulkload(), isPartitioned, varTypes);
                tokenUpdate.getInputs().add(new MutableObject<ILogicalOperator>(currentTop));
                context.computeAndSetTypeEnvironmentForOperator(tokenUpdate);
                replicateOutput = tokenUpdate;
                indexUpdate = new IndexInsertDeleteUpsertOperator(dataSourceIndex, primaryIndexModificationOp.getPrimaryKeyExpressions(), tokenizeKeyExprs, filterExpression, primaryIndexModificationOp.getOperation(), primaryIndexModificationOp.isBulkload(), primaryIndexModificationOp.getAdditionalNonFilteringExpressions() == null ? 0 : primaryIndexModificationOp.getAdditionalNonFilteringExpressions().size());
                indexUpdate.setAdditionalFilteringExpressions(filteringExpressions);
                indexUpdate.getInputs().add(new MutableObject<ILogicalOperator>(tokenUpdate));
            } else {
                // When TokenizeOperator is not needed
                indexUpdate = new IndexInsertDeleteUpsertOperator(dataSourceIndex, primaryIndexModificationOp.getPrimaryKeyExpressions(), secondaryExpressions, filterExpression, primaryIndexModificationOp.getOperation(), primaryIndexModificationOp.isBulkload(), primaryIndexModificationOp.getAdditionalNonFilteringExpressions() == null ? 0 : primaryIndexModificationOp.getAdditionalNonFilteringExpressions().size());
                indexUpdate.setAdditionalFilteringExpressions(filteringExpressions);
                replicateOutput = indexUpdate;
                // We add the necessary expressions for upsert
                if (primaryIndexModificationOp.getOperation() == Kind.UPSERT) {
                    indexUpdate.setBeforeOpSecondaryKeyExprs(beforeOpSecondaryExpressions);
                    if (filteringFields != null) {
                        indexUpdate.setBeforeOpAdditionalFilteringExpression(new MutableObject<ILogicalExpression>(new VariableReferenceExpression(primaryIndexModificationOp.getBeforeOpFilterVar())));
                    }
                }
                indexUpdate.getInputs().add(new MutableObject<ILogicalOperator>(currentTop));
            }
        } else {
            // Get type, dimensions and number of keys
            Pair<IAType, Boolean> keyPairType = Index.getNonNullableOpenFieldType(index.getKeyFieldTypes().get(0), secondaryKeyFields.get(0), recType);
            IAType spatialType = keyPairType.first;
            boolean isPointMBR = spatialType.getTypeTag() == ATypeTag.POINT || spatialType.getTypeTag() == ATypeTag.POINT3D;
            int dimension = NonTaggedFormatUtil.getNumDimensions(spatialType.getTypeTag());
            int numKeys = (isPointMBR && isBulkload) ? dimension : dimension * 2;
            // Get variables and expressions
            List<LogicalVariable> keyVarList = new ArrayList<>();
            List<Mutable<ILogicalExpression>> keyExprList = new ArrayList<>();
            for (int i = 0; i < numKeys; i++) {
                LogicalVariable keyVar = context.newVar();
                keyVarList.add(keyVar);
                AbstractFunctionCallExpression createMBR = new ScalarFunctionCallExpression(FunctionUtil.getFunctionInfo(BuiltinFunctions.CREATE_MBR));
                createMBR.getArguments().add(new MutableObject<ILogicalExpression>(new VariableReferenceExpression(secondaryKeyVars.get(0))));
                createMBR.getArguments().add(new MutableObject<ILogicalExpression>(new ConstantExpression(new AsterixConstantValue(new AInt32(dimension)))));
                createMBR.getArguments().add(new MutableObject<ILogicalExpression>(new ConstantExpression(new AsterixConstantValue(new AInt32(i)))));
                keyExprList.add(new MutableObject<ILogicalExpression>(createMBR));
            }
            secondaryExpressions.clear();
            for (LogicalVariable secondaryKeyVar : keyVarList) {
                secondaryExpressions.add(new MutableObject<ILogicalExpression>(new VariableReferenceExpression(secondaryKeyVar)));
            }
            if (isPointMBR && isBulkload) {
                //createFieldPermutationForBulkLoadOp(int) for more details.
                for (LogicalVariable secondaryKeyVar : keyVarList) {
                    secondaryExpressions.add(new MutableObject<ILogicalExpression>(new VariableReferenceExpression(secondaryKeyVar)));
                }
            }
            AssignOperator assignCoordinates = new AssignOperator(keyVarList, keyExprList);
            assignCoordinates.getInputs().add(new MutableObject<ILogicalOperator>(currentTop));
            context.computeAndSetTypeEnvironmentForOperator(assignCoordinates);
            replicateOutput = assignCoordinates;
            Mutable<ILogicalExpression> filterExpression = null;
            AssignOperator originalAssignCoordinates = null;
            // We do something similar for beforeOp key if the operation is an upsert
            if (primaryIndexModificationOp.getOperation() == Kind.UPSERT) {
                List<LogicalVariable> originalKeyVarList = new ArrayList<>();
                List<Mutable<ILogicalExpression>> originalKeyExprList = new ArrayList<>();
                // we don't do any filtering since nulls are expected here and there
                for (int i = 0; i < numKeys; i++) {
                    LogicalVariable keyVar = context.newVar();
                    originalKeyVarList.add(keyVar);
                    AbstractFunctionCallExpression createMBR = new ScalarFunctionCallExpression(FunctionUtil.getFunctionInfo(BuiltinFunctions.CREATE_MBR));
                    createMBR.getArguments().add(beforeOpSecondaryExpressions.get(0));
                    createMBR.getArguments().add(new MutableObject<ILogicalExpression>(new ConstantExpression(new AsterixConstantValue(new AInt32(dimension)))));
                    createMBR.getArguments().add(new MutableObject<ILogicalExpression>(new ConstantExpression(new AsterixConstantValue(new AInt32(i)))));
                    originalKeyExprList.add(new MutableObject<ILogicalExpression>(createMBR));
                }
                beforeOpSecondaryExpressions.clear();
                for (LogicalVariable secondaryKeyVar : originalKeyVarList) {
                    beforeOpSecondaryExpressions.add(new MutableObject<ILogicalExpression>(new VariableReferenceExpression(secondaryKeyVar)));
                }
                originalAssignCoordinates = new AssignOperator(originalKeyVarList, originalKeyExprList);
                originalAssignCoordinates.getInputs().add(new MutableObject<ILogicalOperator>(assignCoordinates));
                context.computeAndSetTypeEnvironmentForOperator(originalAssignCoordinates);
            } else {
                // We must enforce the filter if the originating spatial type is
                // nullable.
                boolean forceFilter = keyPairType.second;
                filterExpression = createFilterExpression(keyVarList, context.getOutputTypeEnvironment(assignCoordinates), forceFilter);
            }
            DataSourceIndex dataSourceIndex = new DataSourceIndex(index, dataverseName, datasetName, mp);
            indexUpdate = new IndexInsertDeleteUpsertOperator(dataSourceIndex, primaryIndexModificationOp.getPrimaryKeyExpressions(), secondaryExpressions, filterExpression, primaryIndexModificationOp.getOperation(), primaryIndexModificationOp.isBulkload(), primaryIndexModificationOp.getAdditionalNonFilteringExpressions() == null ? 0 : primaryIndexModificationOp.getAdditionalNonFilteringExpressions().size());
            indexUpdate.setAdditionalFilteringExpressions(filteringExpressions);
            if (primaryIndexModificationOp.getOperation() == Kind.UPSERT) {
                // set before op secondary key expressions
                if (filteringFields != null) {
                    indexUpdate.setBeforeOpAdditionalFilteringExpression(new MutableObject<ILogicalExpression>(new VariableReferenceExpression(primaryIndexModificationOp.getBeforeOpFilterVar())));
                }
                // set filtering expressions
                indexUpdate.setBeforeOpSecondaryKeyExprs(beforeOpSecondaryExpressions);
                // assign --> assign beforeOp values --> secondary index upsert
                indexUpdate.getInputs().add(new MutableObject<ILogicalOperator>(originalAssignCoordinates));
            } else {
                indexUpdate.getInputs().add(new MutableObject<ILogicalOperator>(assignCoordinates));
            }
        }
        context.computeAndSetTypeEnvironmentForOperator(indexUpdate);
        if (!primaryIndexModificationOp.isBulkload() || secondaryIndexTotalCnt == 1) {
            currentTop = indexUpdate;
        } else {
            replicateOp.getOutputs().add(new MutableObject<>(replicateOutput));
        }
        if (primaryIndexModificationOp.isBulkload()) {
            // For bulk load, we connect all fanned out insert operator to a single SINK operator
            op0.getInputs().add(new MutableObject<ILogicalOperator>(indexUpdate));
        }
    }
    if (!hasSecondaryIndex) {
        return false;
    }
    if (!primaryIndexModificationOp.isBulkload()) {
        // If this is an upsert, we need to
        // Remove the current input to the SINK operator (It is actually already removed above)
        op0.getInputs().clear();
        // Connect the last index update to the SINK
        op0.getInputs().add(new MutableObject<ILogicalOperator>(currentTop));
    }
    return true;
}
Also used : HashMap(java.util.HashMap) ConstantExpression(org.apache.hyracks.algebricks.core.algebra.expressions.ConstantExpression) ArrayList(java.util.ArrayList) Index(org.apache.asterix.metadata.entities.Index) DataSourceIndex(org.apache.asterix.metadata.declared.DataSourceIndex) AString(org.apache.asterix.om.base.AString) AsterixException(org.apache.asterix.common.exceptions.AsterixException) TokenizeOperator(org.apache.hyracks.algebricks.core.algebra.operators.logical.TokenizeOperator) AsterixConstantValue(org.apache.asterix.om.constants.AsterixConstantValue) DelegateOperator(org.apache.hyracks.algebricks.core.algebra.operators.logical.DelegateOperator) List(java.util.List) AOrderedList(org.apache.asterix.om.base.AOrderedList) ArrayList(java.util.ArrayList) CommitOperator(org.apache.asterix.algebra.operators.CommitOperator) ScalarFunctionCallExpression(org.apache.hyracks.algebricks.core.algebra.expressions.ScalarFunctionCallExpression) ReplicateOperator(org.apache.hyracks.algebricks.core.algebra.operators.logical.ReplicateOperator) AbstractFunctionCallExpression(org.apache.hyracks.algebricks.core.algebra.expressions.AbstractFunctionCallExpression) AlgebricksException(org.apache.hyracks.algebricks.common.exceptions.AlgebricksException) DataSource(org.apache.asterix.metadata.declared.DataSource) MetadataProvider(org.apache.asterix.metadata.declared.MetadataProvider) VariableReferenceExpression(org.apache.hyracks.algebricks.core.algebra.expressions.VariableReferenceExpression) MutableObject(org.apache.commons.lang3.mutable.MutableObject) IAObject(org.apache.asterix.om.base.IAObject) IAType(org.apache.asterix.om.types.IAType) LogicalVariable(org.apache.hyracks.algebricks.core.algebra.base.LogicalVariable) AbstractLogicalOperator(org.apache.hyracks.algebricks.core.algebra.operators.logical.AbstractLogicalOperator) Dataset(org.apache.asterix.metadata.entities.Dataset) ILogicalOperator(org.apache.hyracks.algebricks.core.algebra.base.ILogicalOperator) InternalDatasetDetails(org.apache.asterix.metadata.entities.InternalDatasetDetails) DataSourceIndex(org.apache.asterix.metadata.declared.DataSourceIndex) IndexInsertDeleteUpsertOperator(org.apache.hyracks.algebricks.core.algebra.operators.logical.IndexInsertDeleteUpsertOperator) AssignOperator(org.apache.hyracks.algebricks.core.algebra.operators.logical.AssignOperator) AInt32(org.apache.asterix.om.base.AInt32) Mutable(org.apache.commons.lang3.mutable.Mutable) ILogicalExpression(org.apache.hyracks.algebricks.core.algebra.base.ILogicalExpression) IndexInsertDeleteUpsertOperator(org.apache.hyracks.algebricks.core.algebra.operators.logical.IndexInsertDeleteUpsertOperator) InsertDeleteUpsertOperator(org.apache.hyracks.algebricks.core.algebra.operators.logical.InsertDeleteUpsertOperator) ARecordType(org.apache.asterix.om.types.ARecordType)

Example 28 with AsterixException

use of org.apache.asterix.common.exceptions.AsterixException in project asterixdb by apache.

the class PropertiesAccessor method configure.

private AsterixConfiguration configure(InputStream is, String fileName) throws AsterixException {
    try {
        JAXBContext ctx = JAXBContext.newInstance(AsterixConfiguration.class);
        Unmarshaller unmarshaller = ctx.createUnmarshaller();
        return (AsterixConfiguration) unmarshaller.unmarshal(is);
    } catch (JAXBException e) {
        throw new AsterixException("Failed to read configuration file " + fileName, e);
    }
}
Also used : AsterixException(org.apache.asterix.common.exceptions.AsterixException) AsterixConfiguration(org.apache.asterix.common.configuration.AsterixConfiguration) JAXBException(javax.xml.bind.JAXBException) JAXBContext(javax.xml.bind.JAXBContext) Unmarshaller(javax.xml.bind.Unmarshaller)

Example 29 with AsterixException

use of org.apache.asterix.common.exceptions.AsterixException in project asterixdb by apache.

the class DataflowControllerProvider method getDataflowController.

// TODO: Instead, use a factory just like data source and data parser.
@SuppressWarnings({ "rawtypes", "unchecked" })
public static IDataFlowController getDataflowController(ARecordType recordType, IHyracksTaskContext ctx, int partition, IExternalDataSourceFactory dataSourceFactory, IDataParserFactory dataParserFactory, Map<String, String> configuration, boolean indexingOp, boolean isFeed, FeedLogManager feedLogManager) throws HyracksDataException {
    try {
        switch(dataSourceFactory.getDataSourceType()) {
            case RECORDS:
                IRecordReaderFactory<?> recordReaderFactory = (IRecordReaderFactory<?>) dataSourceFactory;
                IRecordReader<?> recordReader = recordReaderFactory.createRecordReader(ctx, partition);
                IRecordDataParserFactory<?> recordParserFactory = (IRecordDataParserFactory<?>) dataParserFactory;
                IRecordDataParser<?> dataParser = recordParserFactory.createRecordParser(ctx);
                if (indexingOp) {
                    return new IndexingDataFlowController(ctx, DataflowUtils.getTupleForwarder(configuration, feedLogManager), dataParser, recordReader, ((IIndexingDatasource) recordReader).getIndexer());
                } else if (isFeed) {
                    FeedTupleForwarder tupleForwarder = (FeedTupleForwarder) DataflowUtils.getTupleForwarder(configuration, feedLogManager);
                    boolean isChangeFeed = ExternalDataUtils.isChangeFeed(configuration);
                    boolean isRecordWithMeta = ExternalDataUtils.isRecordWithMeta(configuration);
                    if (isRecordWithMeta) {
                        if (isChangeFeed) {
                            int numOfKeys = ExternalDataUtils.getNumberOfKeys(configuration);
                            return new ChangeFeedWithMetaDataFlowController(ctx, tupleForwarder, feedLogManager, numOfKeys + 2, (IRecordWithMetadataParser) dataParser, recordReader);
                        } else {
                            return new FeedWithMetaDataFlowController(ctx, tupleForwarder, feedLogManager, 2, (IRecordWithMetadataParser) dataParser, recordReader);
                        }
                    } else if (isChangeFeed) {
                        int numOfKeys = ExternalDataUtils.getNumberOfKeys(configuration);
                        return new ChangeFeedDataFlowController(ctx, tupleForwarder, feedLogManager, numOfKeys + 1, (IRecordWithPKDataParser) dataParser, recordReader);
                    } else {
                        return new FeedRecordDataFlowController(ctx, tupleForwarder, feedLogManager, 1, dataParser, recordReader);
                    }
                } else {
                    return new RecordDataFlowController(ctx, DataflowUtils.getTupleForwarder(configuration, feedLogManager), dataParser, recordReader, 1);
                }
            case STREAM:
                IInputStreamFactory streamFactory = (IInputStreamFactory) dataSourceFactory;
                AsterixInputStream stream = streamFactory.createInputStream(ctx, partition);
                IStreamDataParserFactory streamParserFactory = (IStreamDataParserFactory) dataParserFactory;
                IStreamDataParser streamParser = streamParserFactory.createInputStreamParser(ctx, partition);
                streamParser.setInputStream(stream);
                if (isFeed) {
                    return new FeedStreamDataFlowController(ctx, (FeedTupleForwarder) DataflowUtils.getTupleForwarder(configuration, feedLogManager), feedLogManager, streamParser, stream);
                } else {
                    return new StreamDataFlowController(ctx, DataflowUtils.getTupleForwarder(configuration, null), streamParser);
                }
            default:
                throw new RuntimeDataException(ErrorCode.PROVIDER_DATAFLOW_CONTROLLER_UNKNOWN_DATA_SOURCE, dataSourceFactory.getDataSourceType());
        }
    } catch (IOException | AsterixException e) {
        throw new HyracksDataException(e);
    }
}
Also used : ChangeFeedDataFlowController(org.apache.asterix.external.dataflow.ChangeFeedDataFlowController) IndexingDataFlowController(org.apache.asterix.external.dataflow.IndexingDataFlowController) IRecordWithMetadataParser(org.apache.asterix.external.api.IRecordWithMetadataParser) AsterixException(org.apache.asterix.common.exceptions.AsterixException) FeedTupleForwarder(org.apache.asterix.external.dataflow.FeedTupleForwarder) ChangeFeedWithMetaDataFlowController(org.apache.asterix.external.dataflow.ChangeFeedWithMetaDataFlowController) FeedWithMetaDataFlowController(org.apache.asterix.external.dataflow.FeedWithMetaDataFlowController) FeedStreamDataFlowController(org.apache.asterix.external.dataflow.FeedStreamDataFlowController) FeedStreamDataFlowController(org.apache.asterix.external.dataflow.FeedStreamDataFlowController) StreamDataFlowController(org.apache.asterix.external.dataflow.StreamDataFlowController) RuntimeDataException(org.apache.asterix.common.exceptions.RuntimeDataException) RecordDataFlowController(org.apache.asterix.external.dataflow.RecordDataFlowController) FeedRecordDataFlowController(org.apache.asterix.external.dataflow.FeedRecordDataFlowController) IStreamDataParser(org.apache.asterix.external.api.IStreamDataParser) IStreamDataParserFactory(org.apache.asterix.external.api.IStreamDataParserFactory) IRecordDataParserFactory(org.apache.asterix.external.api.IRecordDataParserFactory) FeedRecordDataFlowController(org.apache.asterix.external.dataflow.FeedRecordDataFlowController) IInputStreamFactory(org.apache.asterix.external.api.IInputStreamFactory) IOException(java.io.IOException) HyracksDataException(org.apache.hyracks.api.exceptions.HyracksDataException) IRecordReaderFactory(org.apache.asterix.external.api.IRecordReaderFactory) ChangeFeedWithMetaDataFlowController(org.apache.asterix.external.dataflow.ChangeFeedWithMetaDataFlowController) AsterixInputStream(org.apache.asterix.external.api.AsterixInputStream)

Example 30 with AsterixException

use of org.apache.asterix.common.exceptions.AsterixException in project asterixdb by apache.

the class DatasourceFactoryProvider method initFactories.

protected static Map<String, Class> initFactories() throws AsterixException {
    Map<String, Class> factories = new HashMap<>();
    ClassLoader cl = ParserFactoryProvider.class.getClassLoader();
    final Charset encoding = Charset.forName("UTF-8");
    try {
        Enumeration<URL> urls = cl.getResources(RESOURCE);
        for (URL url : Collections.list(urls)) {
            InputStream is = url.openStream();
            String config = IOUtils.toString(is, encoding);
            is.close();
            String[] classNames = config.split("\n");
            for (String className : classNames) {
                if (className.startsWith("#")) {
                    continue;
                }
                final Class<?> clazz = Class.forName(className);
                List<String> formats = ((IRecordReaderFactory) clazz.newInstance()).getRecordReaderNames();
                for (String format : formats) {
                    if (factories.containsKey(format)) {
                        throw new AsterixException(ErrorCode.PROVIDER_DATASOURCE_FACTORY_DUPLICATE_FORMAT_MAPPING, format);
                    }
                    factories.put(format, clazz);
                }
            }
        }
    } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        throw new AsterixException(e);
    }
    return factories;
}
Also used : HashMap(java.util.HashMap) InputStream(java.io.InputStream) Charset(java.nio.charset.Charset) IOException(java.io.IOException) URL(java.net.URL) IRecordReaderFactory(org.apache.asterix.external.api.IRecordReaderFactory) AsterixException(org.apache.asterix.common.exceptions.AsterixException)

Aggregations

AsterixException (org.apache.asterix.common.exceptions.AsterixException)67 IOException (java.io.IOException)27 HyracksDataException (org.apache.hyracks.api.exceptions.HyracksDataException)26 DataOutput (java.io.DataOutput)15 IPointable (org.apache.hyracks.data.std.api.IPointable)15 IFrameTupleReference (org.apache.hyracks.dataflow.common.data.accessors.IFrameTupleReference)15 TypeMismatchException (org.apache.asterix.runtime.exceptions.TypeMismatchException)14 IScalarEvaluator (org.apache.hyracks.algebricks.runtime.base.IScalarEvaluator)14 VoidPointable (org.apache.hyracks.data.std.primitive.VoidPointable)14 ArrayBackedValueStorage (org.apache.hyracks.data.std.util.ArrayBackedValueStorage)14 ATypeTag (org.apache.asterix.om.types.ATypeTag)10 IAType (org.apache.asterix.om.types.IAType)10 ARecordType (org.apache.asterix.om.types.ARecordType)9 IHyracksTaskContext (org.apache.hyracks.api.context.IHyracksTaskContext)9 ISerializerDeserializer (org.apache.hyracks.api.dataflow.value.ISerializerDeserializer)9 AlgebricksException (org.apache.hyracks.algebricks.common.exceptions.AlgebricksException)8 IScalarEvaluatorFactory (org.apache.hyracks.algebricks.runtime.base.IScalarEvaluatorFactory)8 List (java.util.List)7 InputStream (java.io.InputStream)5 CompilationException (org.apache.asterix.common.exceptions.CompilationException)5