Skip to content

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

4.0 KB
Raw Blame
package plsql

import (
	"errors"
	"fmt"
	"reflect"
	"unicode/utf8"

	"github.com/bytebase/omni/oracle/ast"
	oracleparser "github.com/bytebase/omni/oracle/parser"

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

// OmniAST wraps an omni AST node and implements the base.AST interface.
type OmniAST struct {
	// Node is the omni AST node (e.g. *ast.SelectStmt, *ast.CreateTableStmt).
	Node ast.Node
	// Text is the original SQL text of this statement.
	Text string
	// StartPosition is the 1-based position where this statement starts.
	StartPosition *storepb.Position
}

// ASTStartPosition implements base.AST.
func (a *OmniAST) ASTStartPosition() *storepb.Position {
	return a.StartPosition
}

// ParsePLSQL parses SQL using omni's parser and returns an ast.List.
// This is the recommended entry point for new Oracle code that needs omni AST nodes.
func ParsePLSQL(sql string) (*ast.List, error) {
	statements, err := SplitSQL(sql)
	if err != nil {
		return nil, err
	}

	list := &ast.List{}
	for _, statement := range statements {
		if statement.Empty {
			continue
		}
		parsed, err := oracleparser.Parse(statement.Text)
		if err != nil {
			if statement.Range != nil {
				return nil, offsetOracleParseError(err, int(statement.Range.Start))
			}
			return nil, err
		}
		if parsed == nil {
			continue
		}
		if statement.Range != nil {
			offsetOmniLocs(parsed, int(statement.Range.Start))
		}
		list.Items = append(list.Items, parsed.Items...)
	}
	return list, nil
}

func offsetOracleParseError(err error, offset int) error {
	var parseErr *oracleparser.ParseError
	if !errors.As(err, &parseErr) {
		return err
	}
	adjusted := *parseErr
	adjusted.Position += offset
	return &adjusted
}

type omniLocOffsetter int

func offsetOmniLocs(node ast.Node, offset int) {
	if offset == 0 {
		return
	}
	ast.Walk(omniLocOffsetter(offset), node)
}

func (o omniLocOffsetter) Visit(node ast.Node) ast.Visitor {
	if node == nil {
		return nil
	}
	value := reflect.ValueOf(node)
	if value.Kind() != reflect.Pointer || value.IsNil() {
		return o
	}
	elem := value.Elem()
	if elem.Kind() != reflect.Struct {
		return o
	}
	locField := elem.FieldByName("Loc")
	if !locField.IsValid() || !locField.CanSet() || locField.Type() != reflect.TypeOf(ast.Loc{}) {
		return o
	}

	loc, ok := locField.Interface().(ast.Loc)
	if !ok {
		return o
	}
	offset := int(o)
	if loc.Start >= 0 {
		loc.Start += offset
	}
	if loc.End >= 0 {
		loc.End += offset
	}
	locField.Set(reflect.ValueOf(loc))
	return o
}

// GetOmniNode extracts the omni AST node from a base.AST interface.
// Returns the node and true if it is an OmniAST, nil and false otherwise.
func GetOmniNode(a base.AST) (ast.Node, bool) {
	if a == nil {
		return nil, false
	}
	omniAST, ok := a.(*OmniAST)
	if !ok {
		return nil, false
	}
	return omniAST.Node, true
}

// ByteOffsetToRunePosition converts a byte offset in sql to a 1-based line:column
// where column is measured in Unicode code points (runes), matching storepb.Position semantics.
func ByteOffsetToRunePosition(sql string, byteOffset int) *storepb.Position {
	if byteOffset > len(sql) {
		byteOffset = len(sql)
	}

	line := int32(1)
	runeCol := int32(0) // 0-based rune count on current line
	i := 0
	for i < byteOffset {
		r, size := utf8.DecodeRuneInString(sql[i:])
		if r == '\n' {
			line++
			runeCol = 0
		} else {
			runeCol++
		}
		i += size
	}

	return &storepb.Position{
		Line:   line,
		Column: runeCol + 1, // convert to 1-based
	}
}

func convertOmniError(err error, stmt base.Statement) error {
	var parseErr *oracleparser.ParseError
	if !errors.As(err, &parseErr) {
		return err
	}

	pos := ByteOffsetToRunePosition(stmt.Text, parseErr.Position)
	if stmt.Start != nil {
		if pos.Line == 1 {
			pos.Column += stmt.Start.Column - 1
		}
		pos.Line += stmt.Start.Line - 1
	}

	msg := fmt.Sprintf("Syntax error at line %d:%d: %s", pos.Line, pos.Column, parseErr.Message)
	return &base.SyntaxError{
		Position:   pos,
		Message:    msg,
		RawMessage: parseErr.Message,
	}
}