Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

6.1 KB
Raw Blame
package oceanbase

// Framework code is generated by the generator.

import (
	"context"
	"database/sql"
	"fmt"
	"strings"

	"github.com/bytebase/omni/oceanbase/ast"

	storepb "github.com/bytebase/bytebase/backend/generated-go/store"
	"github.com/bytebase/bytebase/backend/plugin/advisor"
	"github.com/bytebase/bytebase/backend/plugin/advisor/code"
	"github.com/bytebase/bytebase/backend/plugin/parser/base"
	oceanbaseparser "github.com/bytebase/bytebase/backend/plugin/parser/oceanbase"
)

var (
	_ advisor.Advisor = (*DisallowOfflineDdlAdvisor)(nil)
)

func init() {
	advisor.Register(storepb.Engine_OCEANBASE, storepb.SQLReviewRule_STATEMENT_DISALLOW_OFFLINE_DDL, &DisallowOfflineDdlAdvisor{})
}

// DisallowOfflineDdlAdvisor is the advisor checking for disallow Offline DDL.
type DisallowOfflineDdlAdvisor struct {
}

// Check checks for disallow Offline DDL.
func (*DisallowOfflineDdlAdvisor) Check(_ context.Context, checkCtx advisor.Context) ([]*storepb.Advice, error) {
	level, err := advisor.NewStatusBySQLReviewRuleLevel(checkCtx.Rule.Level)
	if err != nil {
		return nil, err
	}

	checker := &disallowOfflineDdlChecker{
		level:     level,
		title:     checkCtx.Rule.Type.String(),
		driver:    checkCtx.Driver,
		currentDB: checkCtx.CurrentDatabase,
	}

	for _, stmt := range checkCtx.ParsedStatements {
		if stmt.AST == nil {
			continue
		}
		node, ok := oceanbaseparser.GetOmniNode(stmt.AST)
		if !ok {
			continue
		}
		checker.checkStatement(stmt.Text, stmt.BaseLine(), node)
	}

	return checker.adviceList, nil
}

type disallowOfflineDdlChecker struct {
	adviceList []*storepb.Advice
	level      storepb.Advice_Status
	title      string
	driver     *sql.DB
	currentDB  string
}

func (checker *disallowOfflineDdlChecker) checkStatement(text string, baseLine int, node ast.Node) {
	switch n := node.(type) {
	case *ast.AlterTableStmt:
		checker.checkAlterTable(text, baseLine, n)
	case *ast.DropTableStmt:
		checker.advice(omniLine(baseLine, text, n.Loc), "Dropping tables")
	case *ast.TruncateStmt:
		checker.advice(omniLine(baseLine, text, n.Loc), "Truncating tables")
	default:
	}
}

func (checker *disallowOfflineDdlChecker) checkAlterTable(text string, baseLine int, stmt *ast.AlterTableStmt) {
	databaseName, tableName := omniTableSchemaAndName(stmt.Table)
	if databaseName == "" {
		databaseName = checker.currentDB
	}
	for _, cmd := range stmt.Commands {
		if cmd == nil {
			continue
		}
		line := omniLine(baseLine, text, cmd.Loc)
		checker.checkAlterTableCmd(line, databaseName, tableName, cmd)
	}
}

func (checker *disallowOfflineDdlChecker) checkAlterTableCmd(line int, databaseName, tableName string, cmd *ast.AlterTableCmd) {
	switch cmd.Type {
	case ast.ATAddColumn:
		if columnType := checker.getSpecialColumnType(cmd.Column); columnType != "" {
			checker.advice(line, fmt.Sprintf("Adding %s columns", columnType))
		}
		for _, column := range cmd.Columns {
			if columnType := checker.getSpecialColumnType(column); columnType != "" {
				checker.advice(line, fmt.Sprintf("Adding %s columns", columnType))
			}
		}
	case ast.ATAddConstraint:
		if cmd.Constraint != nil && cmd.Constraint.Type == ast.ConstrPrimaryKey {
			checker.advice(line, "Adding primary keys")
		}
	case ast.ATModifyColumn:
		if columnType := checker.getSpecialColumnType(cmd.Column); columnType != "" {
			checker.advice(line, fmt.Sprintf("Modifying columns to %s", columnType))
		}
	case ast.ATChangeColumn:
		if columnType := checker.getSpecialColumnType(cmd.Column); columnType != "" {
			checker.advice(line, fmt.Sprintf("Changing columns to %s", columnType))
		}
	case ast.ATDropColumn:
		if checker.isStoredColumn(databaseName, tableName, cmd.Name) {
			checker.advice(line, "Dropping stored generated columns")
		}
	case ast.ATDropConstraint:
		if strings.EqualFold(cmd.Name, "PRIMARY") {
			checker.advice(line, "Dropping primary keys")
		}
	case ast.ATDropPartition:
		checker.advice(line, "Dropping partitions")
	case ast.ATTruncatePartition:
		checker.advice(line, "Truncating partitions")
	case ast.ATAddPartition, ast.ATCoalescePartition, ast.ATReorganizePartition, ast.ATExchangePartition, ast.ATAnalyzePartition, ast.ATCheckPartition, ast.ATOptimizePartition, ast.ATRebuildPartition, ast.ATRepairPartition, ast.ATDiscardPartitionTablespace, ast.ATImportPartitionTablespace, ast.ATRemovePartitioning, ast.ATPartitionBy:
		checker.advice(line, "Modifying partitions")
	case ast.ATConvertCharset:
		checker.advice(line, "Changing charset or collate")
	case ast.ATTableOption:
		if cmd.Option != nil && isCharsetOrCollationOption(cmd.Option) {
			checker.advice(line, "Changing charset or collate")
		}
	default:
	}
}

func isCharsetOrCollationOption(option *ast.TableOption) bool {
	name := strings.ToLower(option.Name)
	return strings.Contains(name, "charset") || strings.Contains(name, "character set") || strings.Contains(name, "collate") || strings.Contains(name, "collation")
}

func (checker *disallowOfflineDdlChecker) isStoredColumn(databaseName, tableName, columnName string) bool {
	if checker.driver == nil || len(databaseName) == 0 || len(tableName) == 0 || len(columnName) == 0 {
		return false
	}

	var result string
	if err := checker.driver.QueryRowContext(context.Background(),
		"SELECT EXTRA FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ?",
		databaseName,
		tableName,
		columnName,
	).Scan(&result); err == nil && strings.Contains(strings.ToLower(result), "stored") {
		return true
	}
	return false
}

func (*disallowOfflineDdlChecker) getSpecialColumnType(column *ast.ColumnDef) string {
	if column == nil {
		return ""
	}
	switch {
	case column.Generated != nil && column.Generated.Stored:
		return "stored generated"
	case column.AutoIncrement:
		return "auto increment"
	case omniColumnHasPrimaryKey(column):
		return "primary key"
	default:
		return ""
	}
}

func (checker *disallowOfflineDdlChecker) advice(line int, operation string) {
	checker.adviceList = append(checker.adviceList, &storepb.Advice{
		Status:        checker.level,
		Code:          code.StatementOfflineDDL.Int32(),
		Title:         checker.title,
		Content:       fmt.Sprintf("%s is an offline DDL operation.", operation),
		StartPosition: base.ConvertANTLRLineToPosition(line),
	})
}