Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: simplify Oracle query handling code (#17218)
Danny Xu66542f2a726b
diff --git a/backend/plugin/db/oracle/oracle.go b/backend/plugin/db/oracle/oracle.goindex 43e108f4b0..453fc595c6 100644--- a/backend/plugin/db/oracle/oracle.go+++ b/backend/plugin/db/oracle/oracle.go@@ -9,18 +9,14 @@ import ("log/slog""math/big""strconv"- "strings""time"// Import go-ora Oracle driver.- "github.com/antlr4-go/antlr/v4""github.com/pkg/errors"goora "github.com/sijms/go-ora/v2""google.golang.org/protobuf/types/known/durationpb"- plsql "github.com/bytebase/plsql-parser"-"github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/log"storepb "github.com/bytebase/bytebase/backend/generated-go/store"@@ -322,136 +318,3 @@ func (d *Driver) QueryConn(ctx context.Context, conn *sql.Conn, statement stringreturn results, nil}--// skipAddLimit checks if the statement needs a limit clause.-// For Oracle, we think the statement like "SELECT xxx FROM DUAL" does not need a limit clause.-// More details, xxx can not be a subquery.-func skipAddLimit(stmt string) (bool, error) {- tree, _, err := plsqlparser.ParsePLSQL(stmt)- if err != nil {- return false, err- }-- sqlScript, ok := tree.(*plsql.Sql_scriptContext)- if !ok {- return false, nil- }-- if len(sqlScript.AllSql_plus_command()) > 0 {- return false, nil- }-- if len(sqlScript.AllUnit_statement()) > 1 {- return false, nil- }-- unitStatement := sqlScript.Unit_statement(0)- if unitStatement == nil {- return false, nil- }-- dml := unitStatement.Data_manipulation_language_statements()- if dml == nil {- return false, nil- }-- selectStatement := dml.Select_statement()- if selectStatement == nil {- return false, nil- }-- switch {- case len(selectStatement.AllFor_update_clause()) != 0:- return false, nil- case len(selectStatement.AllOrder_by_clause()) != 0:- return false, nil- case len(selectStatement.AllOffset_clause()) != 0:- return false, nil- case len(selectStatement.AllFetch_clause()) != 0:- return false, nil- default:- // No additional clauses- }-- selectOnly := selectStatement.Select_only_statement()- if selectOnly == nil {- return false, nil- }-- subquery := selectOnly.Subquery()- if subquery == nil {- return false, nil- }-- if len(subquery.AllSubquery_operation_part()) != 0 {- return false, nil- }-- subqueryBasicElements := subquery.Subquery_basic_elements()- if subqueryBasicElements == nil {- return false, nil- }-- if subqueryBasicElements.Subquery() != nil {- return false, nil- }-- queryBlock := subqueryBasicElements.Query_block()- if queryBlock == nil {- return false, nil- }-- switch {- case queryBlock.Subquery_factoring_clause() != nil,- queryBlock.DISTINCT() != nil,- queryBlock.ALL() != nil,- queryBlock.UNIQUE() != nil,- queryBlock.Into_clause() != nil,- queryBlock.Where_clause() != nil,- queryBlock.Hierarchical_query_clause() != nil,- queryBlock.Group_by_clause() != nil,- queryBlock.Model_clause() != nil,- queryBlock.Order_by_clause() != nil,- queryBlock.Fetch_clause() != nil:- return false, nil- default:- // Query block has no special clauses- }-- from := queryBlock.From_clause()- if !strings.EqualFold(from.GetText(), "FROMDUAL") {- return false, nil- }-- selectedList := queryBlock.Selected_list()- if selectedList == nil {- return false, nil- }-- if selectedList.ASTERISK() != nil {- return false, nil- }-- for _, selectedElement := range selectedList.AllSelect_list_elements() {- if selectedElement.Table_wild() != nil {- return false, nil- }-- l := subqueryListener{}- antlr.ParseTreeWalkerDefault.Walk(&l, selectedElement)- if l.hasSubquery {- return false, nil- }- }-- return true, nil-}--type subqueryListener struct {- *plsql.BasePlSqlParserListener- hasSubquery bool-}--func (l *subqueryListener) EnterSubquery(*plsql.SubqueryContext) {- l.hasSubquery = true-}diff --git a/backend/plugin/db/oracle/query.go b/backend/plugin/db/oracle/query.goindex cfb2081c82..849a84ad37 100644--- a/backend/plugin/db/oracle/query.go+++ b/backend/plugin/db/oracle/query.go@@ -24,12 +24,14 @@ import (const dbVersion12 = 12-func makeValueByTypeName(typeName string, _ *sql.ColumnType) any {- // DATE: date.- // TIMESTAMPDTY: timestamp.- // TIMESTAMPTZ_DTY: timestamp with time zone.- // TIMESTAMPLTZ_DTY: timezone with local time zone.+// ========== Type Conversion Functions ==========+// makeValueByTypeName creates appropriate Go types for Oracle column types.+// DATE: date.+// TIMESTAMPDTY: timestamp.+// TIMESTAMPTZ_DTY: timestamp with time zone.+// TIMESTAMPLTZ_DTY: timezone with local time zone.+func makeValueByTypeName(typeName string, _ *sql.ColumnType) any {switch typeName {case "VARCHAR", "TEXT", "UUID":return new(sql.NullString)@@ -92,54 +94,101 @@ func convertValue(typeName string, columnType *sql.ColumnType, value any) *v1pb.}case *sql.NullTime:if raw.Valid {- // The go-ora driver retrieves the database timezone from the wire protocol and appends it to the timestamp.- // To ensure consistency with Oracle Date expectations, we should remove the timezone information.- // https://github.com/sijms/go-ora/blob/2962e725e7a756a667a546fb360ef09afd4c8bd0/v2/parameter.go#L616- _, scale, _ := columnType.DecimalSize()- if typeName == "DATE" || typeName == "TIMESTAMPDTY" {- timeStripped := time.Date(raw.Time.Year(), raw.Time.Month(), raw.Time.Day(), raw.Time.Hour(), raw.Time.Minute(), raw.Time.Second(), raw.Time.Nanosecond(), time.UTC)- return &v1pb.RowValue{- Kind: &v1pb.RowValue_TimestampValue{- TimestampValue: &v1pb.RowValue_Timestamp{- GoogleTimestamp: timestamppb.New(timeStripped),- Accuracy: int32(scale),- },- },- }- }- if typeName == "TIMESTAMPLTZ_DTY" {- s := raw.Time.Format("2006-01-02 15:04:05.000000000")- t, err := time.Parse(time.DateTime, s)- if err != nil {- return util.NullRowValue- }- // This timestamp is not consistent with sqlplus likely due to db and session timezone.- // TODO(d): fix the go-ora library.- return &v1pb.RowValue{- Kind: &v1pb.RowValue_TimestampValue{- TimestampValue: &v1pb.RowValue_Timestamp{- GoogleTimestamp: timestamppb.New(t),- Accuracy: int32(scale),- },- },- }- }- zone, offset := raw.Time.Zone()- return &v1pb.RowValue{- Kind: &v1pb.RowValue_TimestampTzValue{- TimestampTzValue: &v1pb.RowValue_TimestampTZ{- GoogleTimestamp: timestamppb.New(raw.Time),- Zone: zone,- Offset: int32(offset),- Accuracy: int32(scale),- },- },- }+ return convertTimestamp(typeName, columnType, raw.Time)}}return util.NullRowValue}+// convertTimestamp handles Oracle timestamp type conversions.+// The go-ora driver retrieves the database timezone from the wire protocol and appends it to the timestamp.+// To ensure consistency with Oracle Date expectations, we handle different timestamp types appropriately.+// https://github.com/sijms/go-ora/blob/2962e725e7a756a667a546fb360ef09afd4c8bd0/v2/parameter.go#L616+func convertTimestamp(typeName string, columnType *sql.ColumnType, t time.Time) *v1pb.RowValue {+ _, scale, _ := columnType.DecimalSize()++ switch typeName {+ case "DATE", "TIMESTAMPDTY":+ // Strip timezone information for DATE and TIMESTAMP types+ timeStripped := time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.UTC)+ return &v1pb.RowValue{+ Kind: &v1pb.RowValue_TimestampValue{+ TimestampValue: &v1pb.RowValue_Timestamp{+ GoogleTimestamp: timestamppb.New(timeStripped),+ Accuracy: int32(scale),+ },+ },+ }++ case "TIMESTAMPLTZ_DTY":+ // Handle local timezone timestamp+ // This timestamp is not consistent with sqlplus likely due to db and session timezone.+ // TODO(d): fix the go-ora library.+ s := t.Format("2006-01-02 15:04:05.000000000")+ parsedTime, err := time.Parse(time.DateTime, s)+ if err != nil {+ return util.NullRowValue+ }+ return &v1pb.RowValue{+ Kind: &v1pb.RowValue_TimestampValue{+ TimestampValue: &v1pb.RowValue_Timestamp{+ GoogleTimestamp: timestamppb.New(parsedTime),+ Accuracy: int32(scale),+ },+ },+ }++ default:+ // Handle timestamp with timezone+ zone, offset := t.Zone()+ return &v1pb.RowValue{+ Kind: &v1pb.RowValue_TimestampTzValue{+ TimestampTzValue: &v1pb.RowValue_TimestampTZ{+ GoogleTimestamp: timestamppb.New(t),+ Zone: zone,+ Offset: int32(offset),+ Accuracy: int32(scale),+ },+ },+ }+ }+}++// ========== Limit Handling Functions ==========++// addResultLimit adds a limit clause to the statement based on Oracle version+func addResultLimit(stmt string, limit int, engineVersion string) string {+ // Check if we should skip adding limit (e.g., for simple DUAL queries)+ if shouldSkipLimit(stmt) {+ return stmt+ }++ // Determine Oracle version+ if isOracle11gOrEarlier(engineVersion) {+ return addLimitFor11g(stmt, limit)+ }+ return addLimitFor12cAndLater(stmt, limit)+}++// shouldSkipLimit checks if the statement needs a limit clause+func shouldSkipLimit(stmt string) bool {+ ok, err := skipAddLimit(stmt)+ return err == nil && ok+}++// isOracle11gOrEarlier checks if the Oracle version is 11g or earlier+func isOracle11gOrEarlier(engineVersion string) bool {+ versionIdx := strings.Index(engineVersion, ".")+ if versionIdx < 0 {+ return true // Default to 11g behavior for invalid version+ }+ versionNumber, err := strconv.Atoi(engineVersion[:versionIdx])+ if err != nil {+ return true // Default to 11g behavior for parsing errors+ }+ return versionNumber < dbVersion12+}+// addLimitFor11g adds a ROWNUM-based limit for Oracle 11g and earlier versions.// Uses the legacy approach with subquery and ROWNUM.func addLimitFor11g(statement string, limitCount int) string {@@ -198,38 +247,7 @@ func addFetchNextClause(statement string, limitCount int) (string, error) {return res, nil}-// addResultLimit adds a limit clause to the statement based on Oracle version-func addResultLimit(stmt string, limit int, engineVersion string) string {- // Check if we should skip adding limit (e.g., for simple DUAL queries)- if shouldSkipLimit(stmt) {- return stmt- }-- // Determine Oracle version- if isOracle11gOrEarlier(engineVersion) {- return addLimitFor11g(stmt, limit)- }- return addLimitFor12cAndLater(stmt, limit)-}--// isOracle11gOrEarlier checks if the Oracle version is 11g or earlier-func isOracle11gOrEarlier(engineVersion string) bool {- versionIdx := strings.Index(engineVersion, ".")- if versionIdx < 0 {- return true // Default to 11g behavior for invalid version- }- versionNumber, err := strconv.Atoi(engineVersion[:versionIdx])- if err != nil {- return true // Default to 11g behavior for parsing errors- }- return versionNumber < dbVersion12-}--// shouldSkipLimit checks if the statement needs a limit clause-func shouldSkipLimit(stmt string) bool {- ok, err := skipAddLimit(stmt)- return err == nil && ok-}+// ========== PLSQL AST Walker and Rewriter ==========type plsqlRewriter struct {*plsql.BasePlSqlParserListener@@ -288,3 +306,158 @@ func (r *plsqlRewriter) overrideFetchClause(fetchClause plsql.IFetch_clauseConter.rewriter.ReplaceDefault(expression.GetStart().GetTokenIndex(), expression.GetStop().GetTokenIndex(), fmt.Sprintf("%d", limit))}}++// ========== Skip Limit Logic for DUAL Queries ==========++// skipAddLimit checks if the statement needs a limit clause.+// For Oracle, we think the statement like "SELECT xxx FROM DUAL" does not need a limit clause.+// More details, xxx can not be a subquery.+func skipAddLimit(stmt string) (bool, error) {+ tree, _, err := plsqlparser.ParsePLSQL(stmt)+ if err != nil {+ return false, err+ }++ selectStatement := extractSimpleSelectStatement(tree)+ if selectStatement == nil {+ return false, nil+ }++ // Check if select has additional clauses that prevent skipping limit+ if hasAdditionalClauses(selectStatement) {+ return false, nil+ }++ queryBlock := extractQueryBlock(selectStatement)+ if queryBlock == nil {+ return false, nil+ }++ // Check if query block has complex features+ if hasComplexQueryFeatures(queryBlock) {+ return false, nil+ }++ // Must be a simple SELECT FROM DUAL+ if !isFromDual(queryBlock) {+ return false, nil+ }++ // Check selected elements don't contain subqueries+ return !hasSubqueriesInSelection(queryBlock), nil+}++// extractSimpleSelectStatement extracts a simple SELECT statement from the parse tree.+// Returns nil if the tree doesn't represent a simple SELECT.+func extractSimpleSelectStatement(tree antlr.Tree) *plsql.Select_statementContext {+ sqlScript, ok := tree.(*plsql.Sql_scriptContext)+ if !ok {+ return nil+ }++ if len(sqlScript.AllSql_plus_command()) > 0 || len(sqlScript.AllUnit_statement()) != 1 {+ return nil+ }++ unitStatement := sqlScript.Unit_statement(0)+ if unitStatement == nil {+ return nil+ }++ dml := unitStatement.Data_manipulation_language_statements()+ if dml == nil {+ return nil+ }++ if selectStmt := dml.Select_statement(); selectStmt != nil {+ if stmt, ok := selectStmt.(*plsql.Select_statementContext); ok {+ return stmt+ }+ }+ return nil+}++// hasAdditionalClauses checks if a SELECT statement has clauses that prevent limit skipping.+func hasAdditionalClauses(selectStatement *plsql.Select_statementContext) bool {+ return len(selectStatement.AllFor_update_clause()) != 0 ||+ len(selectStatement.AllOrder_by_clause()) != 0 ||+ len(selectStatement.AllOffset_clause()) != 0 ||+ len(selectStatement.AllFetch_clause()) != 0+}++// extractQueryBlock extracts the query block from a SELECT statement.+func extractQueryBlock(selectStatement *plsql.Select_statementContext) *plsql.Query_blockContext {+ selectOnly := selectStatement.Select_only_statement()+ if selectOnly == nil {+ return nil+ }++ subquery := selectOnly.Subquery()+ if subquery == nil || len(subquery.AllSubquery_operation_part()) != 0 {+ return nil+ }++ subqueryBasicElements := subquery.Subquery_basic_elements()+ if subqueryBasicElements == nil || subqueryBasicElements.Subquery() != nil {+ return nil+ }++ if queryBlock := subqueryBasicElements.Query_block(); queryBlock != nil {+ if block, ok := queryBlock.(*plsql.Query_blockContext); ok {+ return block+ }+ }+ return nil+}++// hasComplexQueryFeatures checks if a query block has complex features.+func hasComplexQueryFeatures(queryBlock *plsql.Query_blockContext) bool {+ return queryBlock.Subquery_factoring_clause() != nil ||+ queryBlock.DISTINCT() != nil ||+ queryBlock.ALL() != nil ||+ queryBlock.UNIQUE() != nil ||+ queryBlock.Into_clause() != nil ||+ queryBlock.Where_clause() != nil ||+ queryBlock.Hierarchical_query_clause() != nil ||+ queryBlock.Group_by_clause() != nil ||+ queryBlock.Model_clause() != nil ||+ queryBlock.Order_by_clause() != nil ||+ queryBlock.Fetch_clause() != nil+}++// isFromDual checks if the query is selecting from DUAL table.+func isFromDual(queryBlock *plsql.Query_blockContext) bool {+ from := queryBlock.From_clause()+ return from != nil && strings.EqualFold(from.GetText(), "FROMDUAL")+}++// hasSubqueriesInSelection checks if the selected elements contain subqueries.+func hasSubqueriesInSelection(queryBlock *plsql.Query_blockContext) bool {+ selectedList := queryBlock.Selected_list()+ if selectedList == nil || selectedList.ASTERISK() != nil {+ return true+ }++ for _, selectedElement := range selectedList.AllSelect_list_elements() {+ if selectedElement.Table_wild() != nil {+ return true+ }++ l := subqueryListener{}+ antlr.ParseTreeWalkerDefault.Walk(&l, selectedElement)+ if l.hasSubquery {+ return true+ }+ }++ return false+}++type subqueryListener struct {+ *plsql.BasePlSqlParserListener+ hasSubquery bool+}++func (l *subqueryListener) EnterSubquery(*plsql.SubqueryContext) {+ l.hasSubquery = true+}