MaterializationAnalysisResult.java

// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.apache.doris.nereids.processor.post.materialize;

import java.util.Objects;
import java.util.Optional;

/** Structured result that keeps expected non-applicability separate from invariant failures. */
public final class MaterializationAnalysisResult<T> {
    /** Expected reasons that a candidate plan is not eligible. */
    public enum NotApplicableReason {
        UNSUPPORTED_OPERATOR,
        UNSUPPORTED_SOURCE,
        UNSUPPORTED_INDEX,
        MISSING_SOURCE_METADATA,
        AMBIGUOUS_LINEAGE,
        NO_DEFERRED_OUTPUT
    }

    private final T value;
    private final NotApplicableReason reason;
    private final String detail;

    private MaterializationAnalysisResult(T value, NotApplicableReason reason, String detail) {
        this.value = value;
        this.reason = reason;
        this.detail = detail;
    }

    public static <T> MaterializationAnalysisResult<T> applicable(T value) {
        return new MaterializationAnalysisResult<>(Objects.requireNonNull(value, "value must not be null"),
                null, "");
    }

    public static <T> MaterializationAnalysisResult<T> notApplicable(
            NotApplicableReason reason, String detail) {
        return new MaterializationAnalysisResult<>(null,
                Objects.requireNonNull(reason, "reason must not be null"),
                Objects.requireNonNull(detail, "detail must not be null"));
    }

    public boolean isApplicable() {
        return value != null;
    }

    public T getValue() {
        if (!isApplicable()) {
            throw new IllegalStateException("analysis is not applicable: " + reason + ": " + detail);
        }
        return value;
    }

    public Optional<NotApplicableReason> getReason() {
        return Optional.ofNullable(reason);
    }

    public String getDetail() {
        return detail;
    }
}