AdminCompactTableCommand.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.trees.plans.commands;

import org.apache.doris.analysis.StmtType;
import org.apache.doris.catalog.Database;
import org.apache.doris.catalog.Env;
import org.apache.doris.catalog.OlapTable;
import org.apache.doris.catalog.Table;
import org.apache.doris.catalog.TabletMeta;
import org.apache.doris.common.AnalysisException;
import org.apache.doris.common.ErrorCode;
import org.apache.doris.common.ErrorReport;
import org.apache.doris.common.UserException;
import org.apache.doris.common.util.Util;
import org.apache.doris.datasource.InternalCatalog;
import org.apache.doris.info.TableRefInfo;
import org.apache.doris.mysql.privilege.PrivPredicate;
import org.apache.doris.nereids.trees.expressions.EqualTo;
import org.apache.doris.nereids.trees.expressions.literal.StringLiteral;
import org.apache.doris.nereids.trees.plans.PlanType;
import org.apache.doris.nereids.trees.plans.visitor.PlanVisitor;
import org.apache.doris.qe.ConnectContext;
import org.apache.doris.qe.StmtExecutor;

import java.util.List;

/**
 * AdminCompactTableCommand
 */
public class AdminCompactTableCommand extends Command implements ForwardWithSync {
    private TableRefInfo tableRefInfo;
    private Long tabletId;
    private EqualTo where;

    /**
     * compact type
     */
    public enum CompactionType {
        CUMULATIVE,
        BASE,
        FULL
    }

    private CompactionType typeFilter;

    public AdminCompactTableCommand(TableRefInfo tableRefInfo, EqualTo where) {
        super(PlanType.ADD_CONSTRAINT_COMMAND);
        this.tableRefInfo = tableRefInfo;
        this.where = where;
    }

    public AdminCompactTableCommand(long tabletId, EqualTo where) {
        super(PlanType.ADD_CONSTRAINT_COMMAND);
        this.tabletId = tabletId;
        this.where = where;
    }

    @Override
    public void run(ConnectContext ctx, StmtExecutor executor) throws Exception {
        validate(ctx);
        String type = getCompactionType();
        if (tabletId != null) {
            ctx.getEnv().compactTablet(tabletId, type);
            return;
        }
        String dbName = tableRefInfo.getTableNameInfo().getDb();
        String tableName = tableRefInfo.getTableNameInfo().getTbl();
        List<String> partitionNames = tableRefInfo.getPartitionNamesInfo().getPartitionNames();
        ctx.getEnv().compactTable(dbName, tableName, type, partitionNames);
    }

    private void validate(ConnectContext ctx) throws UserException {
        if (tabletId != null) {
            validateTablet(ctx);
        } else {
            validateTable(ctx);
        }

        if (where == null) {
            throw new AnalysisException("Compaction type must be specified in"
                + " Where clause like: type = 'BASE/CUMULATIVE/FULL'");
        }

        if (!analyzeWhere()) {
            throw new AnalysisException(
                "Where clause should looks like: type = 'BASE/CUMULATIVE/FULL'");
        }
    }

    private void validateTable(ConnectContext ctx) throws UserException {
        if (!Env.getCurrentEnv().getAccessManager().checkGlobalPriv(ConnectContext.get(), PrivPredicate.ADMIN)) {
            ErrorReport.reportAnalysisException(ErrorCode.ERR_SPECIFIC_ACCESS_DENIED_ERROR, "ADMIN");
        }
        tableRefInfo.analyze(ctx.getNameSpaceContext());
        Util.prohibitExternalCatalog(tableRefInfo.getTableNameInfo().getCtl(), this.getClass().getSimpleName());

        List<String> partitionNames = tableRefInfo.getPartitionNamesInfo().getPartitionNames();
        if (partitionNames != null) {
            if (partitionNames.size() != 1) {
                throw new AnalysisException("Only support single partition for compaction");
            }
        } else {
            throw new AnalysisException("No partition selected for compaction");
        }
    }

    private void validateTablet(ConnectContext ctx) throws UserException {
        TabletMeta tabletMeta = Env.getCurrentInvertedIndex().getTabletMeta(tabletId);
        if (tabletMeta == null) {
            throw new AnalysisException("Unknown tablet: " + tabletId);
        }

        Database db = Env.getCurrentEnv().getInternalCatalog().getDbNullable(tabletMeta.getDbId());
        if (db == null) {
            throw new AnalysisException("Unknown database for tablet: " + tabletId);
        }
        Table table = db.getTableNullable(tabletMeta.getTableId());
        if (!(table instanceof OlapTable)) {
            throw new AnalysisException("Unknown OLAP table for tablet: " + tabletId);
        }

        boolean hasGlobalAdmin = Env.getCurrentEnv().getAccessManager()
                .checkGlobalPriv(ctx, PrivPredicate.ADMIN);
        boolean hasTableAlter = Env.getCurrentEnv().getAccessManager().checkTblPriv(ctx,
                InternalCatalog.INTERNAL_CATALOG_NAME, db.getFullName(), table.getName(), PrivPredicate.ALTER);
        if (!hasGlobalAdmin && !hasTableAlter) {
            ErrorReport.reportAnalysisException(ErrorCode.ERR_SPECIFIC_ACCESS_DENIED_ERROR, "ALTER");
        }
    }

    private boolean analyzeWhere() {
        try {
            typeFilter = CompactionType.valueOf(((StringLiteral) where.right()).getStringValue().toUpperCase());
        } catch (Exception e) {
            return false;
        }

        return typeFilter == CompactionType.CUMULATIVE
                || typeFilter == CompactionType.BASE
                || typeFilter == CompactionType.FULL;
    }

    @Override
    public <R, C> R accept(PlanVisitor<R, C> visitor, C context) {
        return visitor.visitAdminCompactTableCommand(this, context);
    }

    @Override
    public StmtType stmtType() {
        return StmtType.ADMIN;
    }

    private String getCompactionType() {
        switch (typeFilter) {
            case CUMULATIVE:
                return "cumulative";
            case BASE:
                return "base";
            case FULL:
                return "full";
            default:
                throw new IllegalStateException("unexpected compaction type: " + typeFilter);
        }
    }
}