Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: remove unused code (#15558)
Danny Xuba538642b0dc
diff --git a/backend/api/lsp/fs.go b/backend/api/lsp/fs.goindex 68f0e3c199..f976c8b5d1 100644--- a/backend/api/lsp/fs.go+++ b/backend/api/lsp/fs.go@@ -123,10 +123,3 @@ func isFileSystemRequest(method string) bool {return false}}--// Reset resets the file system with lock.-func (fs *MemFS) Reset() {- fs.mu.Lock()- defer fs.mu.Unlock()- fs.m = make(map[string][]byte)-}diff --git a/backend/api/v1/common.go b/backend/api/v1/common.goindex 7474078529..2e3648d688 100644--- a/backend/api/v1/common.go+++ b/backend/api/v1/common.go@@ -5,7 +5,6 @@ import ("regexp""strings"- "github.com/google/cel-go/cel""github.com/pkg/errors""golang.org/x/exp/ebnf""google.golang.org/grpc/codes"@@ -46,44 +45,6 @@ func isValidResourceID(resourceID string) bool {return resourceIDMatcher.MatchString(resourceID)}-const filterExample = `project == "projects/abc"`--// getProjectFilter will parse the simple filter such as `project = "projects/abc"` to "projects/abc" .-func getProjectFilter(filter string) (string, error) {- retErr := errors.Errorf("invalid filter %q, example %q", filter, filterExample)- e, err := cel.NewEnv(cel.Variable("project", cel.StringType))- if err != nil {- return "", err- }- ast, issues := e.Compile(filter)- if issues != nil {- return "", status.Error(codes.InvalidArgument, issues.String())- }- parsedExpr, err := cel.AstToParsedExpr(ast)- if err != nil {- return "", retErr- }- expr := parsedExpr.Expr- callExpr := expr.GetCallExpr()- if callExpr == nil {- return "", retErr- }- if callExpr.Function != "_==_" {- return "", retErr- }- if len(callExpr.Args) != 2 {- return "", retErr- }- if callExpr.Args[0].GetIdentExpr() == nil || callExpr.Args[0].GetIdentExpr().Name != "project" {- return "", retErr- }- constExpr := callExpr.Args[1].GetConstExpr()- if constExpr == nil {- return "", retErr- }- return constExpr.GetStringValue(), nil-}-// getEBNFTokens will parse the simple filter such as `project = "abc" | "def".` to {project: ["abc", "def"]} .func getEBNFTokens(filter, filterKey string) ([]string, error) {grammar, err := ebnf.Parse("", strings.NewReader(filter))diff --git a/backend/api/v1/common_test.go b/backend/api/v1/common_test.goindex c4337d2d84..529fdc465f 100644--- a/backend/api/v1/common_test.go+++ b/backend/api/v1/common_test.go@@ -39,45 +39,6 @@ func TestIsValidResourceID(t *testing.T) {}}-func TestGetProjectFilter(t *testing.T) {- tests := []struct {- filter string- want string- wantErr bool- }{- {- filter: "",- want: "",- wantErr: true,- },- {- filter: `project == "projects/abc"`,- want: "projects/abc",- wantErr: false,- },- {- filter: `project== "projects/abc"`,- want: "projects/abc",- wantErr: false,- },- {- filter: `project== "projects/abc".`,- want: "",- wantErr: true,- },- }-- for _, test := range tests {- value, err := getProjectFilter(test.filter)- if test.wantErr {- require.Error(t, err)- } else {- require.NoError(t, err)- require.Equal(t, test.want, value)- }- }-}-func TestGetEBNFTokens(t *testing.T) {testCases := []struct {input stringdiff --git a/backend/api/v1/sql_service.go b/backend/api/v1/sql_service.goindex 5736ef8a72..cfaefec0f6 100644--- a/backend/api/v1/sql_service.go+++ b/backend/api/v1/sql_service.go@@ -8,7 +8,6 @@ import ("fmt""io""regexp"- "strconv""strings""time"@@ -1773,21 +1772,6 @@ func (*SQLService) Pretty(_ context.Context, request *v1pb.PrettyRequest) (*v1pb}, nil}-func getOffsetAndOriginTable(backupTable string) (int, string, error) {- if backupTable == "" {- return 0, "", nil- }- parts := strings.Split(backupTable, "_")- if len(parts) < 4 {- return 0, "", status.Errorf(codes.InvalidArgument, "invalid backup table format: %s", backupTable)- }- offset, err := strconv.Atoi(parts[2])- if err != nil {- return 0, "", status.Errorf(codes.InvalidArgument, "invalid offset: %s", parts[0])- }- return offset, strings.Join(parts[3:], "_"), nil-}-func checkAndGetDataSourceQueriable(ctx context.Context, storeInstance *store.Store, database *store.DatabaseMessage, dataSourceID string) (*storepb.DataSource, error) {instance, err := storeInstance.GetInstanceV2(ctx, &store.FindInstanceMessage{ResourceID: &database.InstanceID})if err != nil {diff --git a/backend/api/v1/sql_service_test.go b/backend/api/v1/sql_service_test.godeleted file mode 100644index e5c1b737c1..0000000000--- a/backend/api/v1/sql_service_test.go+++ /dev/null@@ -1,39 +0,0 @@-package v1--import (- "testing"-- "github.com/stretchr/testify/assert"-)--func TestGetOffsetAndOriginTable(t *testing.T) {- tests := []struct {- input string- offset int- tableName string- }{- {- input: "_20240614164851_0_TEST_table1",- offset: 0,- tableName: "TEST_table1",- },- {- input: "_20240614164851_11_TEST",- offset: 11,- tableName: "TEST",- },- {- input: "_20240614164851_8_TEST_input_table1",- offset: 8,- tableName: "TEST_input_table1",- },- }- a := assert.New(t)-- for _, test := range tests {- offset, tabaleName, err := getOffsetAndOriginTable(test.input)- a.NoError(err)- a.Equal(test.offset, offset)- a.Equal(test.tableName, tabaleName)- }-}diff --git a/backend/common/feature_flag.go b/backend/common/feature_flag.godeleted file mode 100644index d5ddd4498a..0000000000--- a/backend/common/feature_flag.go+++ /dev/null@@ -1,25 +0,0 @@-package common--// Have a single place to track all ongoing feature development that requires code to work with both-// old and new schecma. We need to gate the feature to make the code be compatible with both dev-// schema (having the schema change) and prod schema (not having the schema change yet).-//-// Step 1: Declare a feature-//-// Step 2: Gate the feature when the relevant schema hasn't been applied to prod yet-//-// if common.FeatureFlag(common.FeatureFlagNoop) {-// <<New feature code work with the new schema>>-// } else {-// <<Old code work with the old schema>>-// }-//-// Step 3: Remove the feature and gate--// FeatureFlagType is the feature flag type.-type FeatureFlagType string--const (- // FeatureFlagNoop is a noop feature flag for demonstration purpose.- FeatureFlagNoop FeatureFlagType = "bb.feature-flag.noop"-)diff --git a/backend/common/feature_flag_dev.go b/backend/common/feature_flag_dev.godeleted file mode 100644index 32d541d5f4..0000000000--- a/backend/common/feature_flag_dev.go+++ /dev/null@@ -1,9 +0,0 @@-//go:build !release--package common--// FeatureFlag in dev build always returns true.-// Because dev schema always has the latest change and is compatible with the new feature code.-func FeatureFlag(_ FeatureFlagType) bool {- return true-}diff --git a/backend/common/feature_flag_prod.go b/backend/common/feature_flag_prod.godeleted file mode 100644index 6e282601d9..0000000000--- a/backend/common/feature_flag_prod.go+++ /dev/null@@ -1,10 +0,0 @@-//go:build release--package common--// FeatureFlag in release build always returns false.-// Because we would remove the FeatureFlag check entirely after the schema change for the feature-// is rolled out to prod.-func FeatureFlag(_ FeatureFlagType) bool {- return false-}diff --git a/backend/common/mock.go b/backend/common/mock.godeleted file mode 100644index 1d6d1cb6b5..0000000000--- a/backend/common/mock.go+++ /dev/null@@ -1,15 +0,0 @@-package common--import (- "net/http"-)--// MockRoundTripper is a helper to mock http.RoundTripper.-type MockRoundTripper struct {- MockRoundTrip func(r *http.Request) (*http.Response, error)-}--// RoundTrip is the interface for doing mock RoundTrip.-func (m *MockRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {- return m.MockRoundTrip(r)-}diff --git a/backend/common/resource_name.go b/backend/common/resource_name.goindex 90076f1ae5..dffa07fb48 100644--- a/backend/common/resource_name.go+++ b/backend/common/resource_name.go@@ -2,7 +2,6 @@ package commonimport ("fmt"- "regexp""strconv""strings"@@ -98,14 +97,6 @@ func GetProjectIDWebhookID(name string) (string, string, error) {return tokens[0], tokens[1], nil}-func GetProjectIDDeploymentConfigID(name string) (string, string, error) {- tokens, err := GetNameParentTokens(name, ProjectNamePrefix, DeploymentConfigPrefix)- if err != nil {- return "", "", err- }- return tokens[0], tokens[1], nil-}-func GetProjectIDChangelistID(name string) (string, string, error) {tokens, err := GetNameParentTokens(name, ProjectNamePrefix, ChangelistsPrefix)if err != nil {@@ -127,15 +118,6 @@ func GetUIDFromName(name, prefix string) (int, error) {return uid, nil}-// TrimSuffixAndGetProjectID trims the suffix from the name and returns the project ID.-func TrimSuffixAndGetProjectID(name string, suffix string) (string, error) {- trimmed, err := TrimSuffix(name, suffix)- if err != nil {- return "", err- }- return GetProjectID(trimmed)-}-// TrimSuffixAndGetInstanceDatabaseID trims the suffix from the name and returns the instance ID and database ID.func TrimSuffixAndGetInstanceDatabaseID(name string, suffix string) (string, string, error) {trimmed, err := TrimSuffix(name, suffix)@@ -164,16 +146,6 @@ func GetInstanceID(name string) (string, error) {return tokens[0], nil}-// GetInstanceRoleID returns the instance ID and instance role name from a resource name.-func GetInstanceRoleID(name string) (string, string, error) {- // the instance request should be instances/{instance-id}/roles/{role-name}- tokens, err := GetNameParentTokens(name, InstanceNamePrefix, InstanceRolePrefix)- if err != nil {- return "", "", err- }- return tokens[0], tokens[1], nil-}-// GetInstanceDatabaseID returns the instance ID and database ID from a resource name.func GetInstanceDatabaseID(name string) (string, string, error) {// the instance request should be instances/{instance-id}/databases/{database-id}@@ -309,19 +281,6 @@ func GetIssueID(name string) (int, error) {return issueID, nil}-// GetTaskID returns the task ID from a resource name.-func GetTaskID(name string) (int, error) {- tokens, err := GetNameParentTokens(name, ProjectNamePrefix, RolloutPrefix, StagePrefix, TaskPrefix)- if err != nil {- return 0, err- }- taskID, err := strconv.Atoi(tokens[3])- if err != nil {- return 0, errors.Errorf("invalid task ID %q", tokens[1])- }- return taskID, nil-}-// GetProjectIDPlanID returns the project ID and plan ID from a resource name.func GetProjectIDPlanID(name string) (string, int64, error) {tokens, err := GetNameParentTokens(name, ProjectNamePrefix, PlanPrefix)@@ -555,17 +514,6 @@ func GetProjectReleaseUIDFile(name string) (string, int64, string, error) {return tokens[0], releaseUID, tokens[2], nil}-var branchRegexp = regexp.MustCompile("^projects/([^/]+)/branches/(.+)$")--// GetProjectAndBranchID returns the project and branch ID from a resource name.-func GetProjectAndBranchID(name string) (string, string, error) {- matches := branchRegexp.FindStringSubmatch(name)- if len(matches) != 3 {- return "", "", errors.Errorf("invalid branch name %q", name)- }- return matches[1], matches[2], nil-}-// GetGroupEmail returns the group email.func GetGroupEmail(name string) (string, error) {tokens, err := GetNameParentTokens(name, GroupPrefix)@@ -608,10 +556,6 @@ func FormatProject(id string) string {return fmt.Sprintf("%s%s", ProjectNamePrefix, id)}-func FormatDeploymentConfig(parent string) string {- return fmt.Sprintf("%s/%s%s", parent, DeploymentConfigPrefix, "default")-}-func FormatUserEmail(email string) string {return fmt.Sprintf("%s%s", UserNamePrefix, email)}@@ -668,10 +612,6 @@ func FormatTaskRun(projectID string, pipelineUID, stageUID, taskUID, taskRunUIDreturn fmt.Sprintf("%s/%s%d", FormatTask(projectID, pipelineUID, stageUID, taskUID), TaskRunPrefix, taskRunUID)}-func FormatBranchResourceID(projectID string, branchID string) string {- return fmt.Sprintf("%s/%s%s", FormatProject(projectID), BranchPrefix, branchID)-}-func FormatReleaseName(projectID string, releaseUID int64) string {return fmt.Sprintf("%s/%s%d", FormatProject(projectID), ReleaseNamePrefix, releaseUID)}diff --git a/backend/common/resource_name_test.go b/backend/common/resource_name_test.goindex 5a75efa9c8..e58dfd4290 100644--- a/backend/common/resource_name_test.go+++ b/backend/common/resource_name_test.go@@ -15,18 +15,6 @@ func TestGetInstanceDatabaseID(t *testing.T) {require.Error(t, err)}-func TestGetProjectAndBranchID(t *testing.T) {- projectID, branchID, err := GetProjectAndBranchID("projects/aaa/branches/feat/hello")- require.NoError(t, err)- require.Equal(t, "aaa", projectID)- require.Equal(t, "feat/hello", branchID)-- projectID, branchID, err = GetProjectAndBranchID("projects/new-project/branches/vv")- require.NoError(t, err)- require.Equal(t, "new-project", projectID)- require.Equal(t, "vv", branchID)-}-func TestGetSchemaTableName(t *testing.T) {schema, table, err := GetSchemaTableName("schemas/a/tables/b")require.NoError(t, err)diff --git a/backend/common/util.go b/backend/common/util.goindex c0da421463..a04635f972 100644--- a/backend/common/util.go+++ b/backend/common/util.go@@ -6,7 +6,6 @@ import ("fmt""math/big""path"- "path/filepath""strconv""strings""unicode/utf8"@@ -132,11 +131,6 @@ func TruncateStringWithDescription(str string) string {return str}-// GetBinlogAbsDir gets the binary log directory for an instance.-func GetBinlogAbsDir(dataDir string, instanceID int) string {- return filepath.Join(dataDir, "backup", "instance", fmt.Sprintf("%d", instanceID))-}-// Obfuscate obfuscates a string with a seed string.func Obfuscate(src, seed string) string {srcBytes, seedBytes := []byte(src), []byte(seed)diff --git a/backend/legacyapi/api.go b/backend/legacyapi/api.godeleted file mode 100644index b1eb1e6bd5..0000000000--- a/backend/legacyapi/api.go+++ /dev/null@@ -1,22 +0,0 @@-// Package api provides the definition of all APIs.-package api--// RowStatus is the status for a row.-type RowStatus string--const (- // Normal is the status for a normal row.- Normal RowStatus = "NORMAL"- // Archived is the status for an archived row.- Archived RowStatus = "ARCHIVED"-)--// SortOrder is the sort order for the returned list.-type SortOrder string--const (- // ASC is the sort order to return in ascending order.- ASC SortOrder = "ASC"- // DESC is the sort order to return in descending order.- DESC SortOrder = "DESC"-)diff --git a/backend/legacyapi/external_approval.go b/backend/legacyapi/external_approval.godeleted file mode 100644index d0c74bb7db..0000000000--- a/backend/legacyapi/external_approval.go+++ /dev/null@@ -1,11 +0,0 @@-package api--// ExternalApprovalType is the type of the ExternalApproval.-type ExternalApprovalType string--const (- // ExternalApprovalTypeFeishu is the ExternalApproval from feishu.- ExternalApprovalTypeFeishu ExternalApprovalType = "bb.plugin.app.feishu"- // ExternalApprovalTypeRelay is the ExternalApproval from relay.- ExternalApprovalTypeRelay ExternalApprovalType = "bb.plugin.app.relay"-)diff --git a/backend/legacyapi/label.go b/backend/legacyapi/label.godeleted file mode 100644index 8d6667fa58..0000000000--- a/backend/legacyapi/label.go+++ /dev/null@@ -1,12 +0,0 @@-package api--const (- // EnvironmentLabelKey is the reserved key for environment.- EnvironmentLabelKey string = "environment"- // TenantLabelKey is the label key for tenant.- TenantLabelKey = "tenant"-- // DatabaseLabelSizeMax is the maximum size of database labels.- DatabaseLabelSizeMax = 4- labelLengthMax = 63-)diff --git a/backend/legacyapi/member.go b/backend/legacyapi/member.goindex c2239c2599..cdf9efc85b 100644--- a/backend/legacyapi/member.go+++ b/backend/legacyapi/member.go@@ -1,17 +1,5 @@package api-// MemberStatus is the status of an member.-type MemberStatus string--const (- // Unknown is the member status for UNKNOWN.- Unknown MemberStatus = "UNKNOWN"- // Invited is the member status for INVITED.- Invited MemberStatus = "INVITED"- // Active is the member status for ACTIVE.- Active MemberStatus = "ACTIVE"-)-// Role is the type of a role.type Role stringdiff --git a/backend/legacyapi/project.go b/backend/legacyapi/project.goindex 2153c2325a..e04e300cfb 100644--- a/backend/legacyapi/project.go+++ b/backend/legacyapi/project.go@@ -11,6 +11,4 @@ const (// This can be mutated by the user. But for now this is only used by onboarding flow to create// a prod instance after first signup, so it's safe to refer it.DefaultProdEnvironmentID = "prod"- // DefaultProdEnvironmentUID is the initial resource UID for the prod environment.- DefaultProdEnvironmentUID = 102)diff --git a/backend/legacyapi/task.go b/backend/legacyapi/task.goindex 86fd8c5ee5..1e173aed17 100644--- a/backend/legacyapi/task.go+++ b/backend/legacyapi/task.go@@ -1,25 +1,5 @@package api-// TaskStatus is the status of a task.-type TaskStatus string--const (- // TaskPending is the task status for PENDING.- TaskPending TaskStatus = "PENDING"- // TaskPendingApproval is the task status for PENDING_APPROVAL.- TaskPendingApproval TaskStatus = "PENDING_APPROVAL"- // TaskRunning is the task status for RUNNING.- TaskRunning TaskStatus = "RUNNING"- // TaskDone is the task status for DONE.- TaskDone TaskStatus = "DONE"- // TaskFailed is the task status for FAILED.- TaskFailed TaskStatus = "FAILED"- // TaskCanceled is the task status for CANCELED.- TaskCanceled TaskStatus = "CANCELED"- // TaskSkipped is the task status for SKIPPED.- TaskSkipped TaskStatus = "SKIPPED"-)-// TaskType is the type of a task.type TaskType stringdiff --git a/backend/metric/metric.go b/backend/metric/metric.goindex a097f6c97d..1447da5a88 100644--- a/backend/metric/metric.go+++ b/backend/metric/metric.go@@ -2,7 +2,6 @@package metricimport (- api "github.com/bytebase/bytebase/backend/legacyapi""github.com/bytebase/bytebase/backend/plugin/metric"storepb "github.com/bytebase/bytebase/proto/generated-go/store")@@ -18,20 +17,12 @@ const (UserCountMetricName metric.Name = "bb.user.count"// OpenAPIMetricName is the metric name for OpenAPI.OpenAPIMetricName metric.Name = "bb.api.call"- // SQLAdviseAPIMetricName is the metric name for SQL check API.- SQLAdviseAPIMetricName metric.Name = "bb.api.sql.advise"- // SubscriptionTrialMetricName is the metric name for trial.- SubscriptionTrialMetricName metric.Name = "bb.subscription.trial"// PrincipalRegistrationMetricName is the metric name for the principal registration event.PrincipalRegistrationMetricName metric.Name = "bb.principal.registration"// PrincipalLoginMetricName is the metric name for principal login event.PrincipalLoginMetricName metric.Name = "bb.principal.login"// IssueCreateMetricName is the metric name for issue creation event.IssueCreateMetricName metric.Name = "bb.issue.create"- // SQLEditorExecutionMetricName is the metric name for SQL Editor execution event.- SQLEditorExecutionMetricName metric.Name = "bb.sql-editor.execute"- // PrincipalCreateMetricName is the metric name for principal creation event.- PrincipalCreateMetricName metric.Name = "bb.principal.create"// APIRequestMetricName is the metric name for api request.APIRequestMetricName metric.Name = "bb.api.request"// InstanceCreateMetricName is the metric name for instance creation event.@@ -54,33 +45,3 @@ type IssueCountMetric struct {type ProjectCountMetric struct {Count int}--// PolicyCountMetric is the API message for policy count metric.-type PolicyCountMetric struct {- Type api.PolicyType- Value string- EnvironmentName string- Count int-}--// TaskCountMetric is the API message for task count metric.-type TaskCountMetric struct {- Type api.TaskType- Status api.TaskStatus- Count int-}--// SheetCountMetric is the API message for sheet count metric.-type SheetCountMetric struct {- Visibility string- Count int-}--// MemberCountMetric is the API message for member count metric.-type MemberCountMetric struct {- Count int- Role api.Role- Status api.MemberStatus- RowStatus api.RowStatus- Type api.PrincipalType-}diff --git a/backend/plugin/advisor/catalog/catalog.go b/backend/plugin/advisor/catalog/catalog.goindex bfb9204541..9cbe461631 100644--- a/backend/plugin/advisor/catalog/catalog.go+++ b/backend/plugin/advisor/catalog/catalog.go@@ -36,10 +36,3 @@ func NewCatalog(ctx context.Context, s *store.Store, instanceID, databaseName stfunc (c *Catalog) GetFinder() *Finder {return c.Finder}--// NewEmptyCatalog creates a new empty database catalog.-func NewEmptyCatalog(engineType storepb.Engine) (*Catalog, error) {- return &Catalog{- NewEmptyFinder(&FinderContext{CheckIntegrity: false, EngineType: engineType, IgnoreCaseSensitive: false}),- }, nil-}diff --git a/backend/plugin/advisor/catalog/walk_through.go b/backend/plugin/advisor/catalog/walk_through.goindex f935945287..06b7610708 100644--- a/backend/plugin/advisor/catalog/walk_through.go+++ b/backend/plugin/advisor/catalog/walk_through.go@@ -135,22 +135,6 @@ type WalkThroughError struct {Payload any}-// NewParseError returns a new ErrorTypeParseError.-func NewParseError(content string) *WalkThroughError {- return &WalkThroughError{- Type: ErrorTypeParseError,- Content: content,- }-}--// NewSetLineError returns a new ErrorTypeParseError.-func NewSetLineError(content string) *WalkThroughError {- return &WalkThroughError{- Type: ErrorTypeSetLineError,- Content: content,- }-}-// NewRelationExistsError returns a new ErrorTypeRelationExists.func NewRelationExistsError(relationName string, schemaName string) *WalkThroughError {return &WalkThroughError{diff --git a/backend/plugin/advisor/mssql/advisor_procedure_disallow_create_or_alter.go b/backend/plugin/advisor/mssql/advisor_procedure_disallow_create_or_alter.goindex 89c6c6ed1e..5079a45bdc 100644--- a/backend/plugin/advisor/mssql/advisor_procedure_disallow_create_or_alter.go+++ b/backend/plugin/advisor/mssql/advisor_procedure_disallow_create_or_alter.go@@ -12,7 +12,7 @@ import ()func init() {- advisor.Register(storepb.Engine_MSSQL, advisor.MSSQLProcedureDisallowCreateOrAlter, &FunctionDisallowCreateOrAlterAdvisor{})+ advisor.Register(storepb.Engine_MSSQL, advisor.MSSQLProcedureDisallowCreateOrAlter, &ProcedureDisallowCreateOrAlterAdvisor{})}type ProcedureDisallowCreateOrAlterAdvisor struct{}@@ -46,10 +46,10 @@ func (*ProcedureDisallowCreateOrAlterAdvisor) Check(_ context.Context, checkCtxreturn checker.adviceList, nil}-func (checker *FunctionDisallowCreateOrAlterChecker) EnterCreate_or_alter_procedure(ctx *parser.Create_or_alter_procedureContext) {+func (checker *ProcedureDisallowCreateOrAlterChecker) EnterCreate_or_alter_procedure(ctx *parser.Create_or_alter_procedureContext) {checker.adviceList = append(checker.adviceList, &storepb.Advice{Status: checker.level,- Code: advisor.DisallowCreateFunction.Int32(),+ Code: advisor.DisallowCreateProcedure.Int32(),Title: checker.title,Content: "Creating or altering procedures is prohibited",StartPosition: &storepb.Position{diff --git a/backend/plugin/advisor/mssql/test/column_maximum_varchar_length.yaml b/backend/plugin/advisor/mssql/test/column_maximum_varchar_length.yamlindex 1be47f4835..d8b29472ff 100644--- a/backend/plugin/advisor/mssql/test/column_maximum_varchar_length.yaml+++ b/backend/plugin/advisor/mssql/test/column_maximum_varchar_length.yaml@@ -7,7 +7,6 @@code: 422title: column.maximum-varchar-lengthcontent: The maximum varchar length is 2560.- detail: ""startposition:line: 1column: 0@@ -19,7 +18,6 @@code: 422title: column.maximum-varchar-lengthcontent: The maximum varchar length is 2560.- detail: ""startposition:line: 1column: 0@@ -31,7 +29,6 @@code: 422title: column.maximum-varchar-lengthcontent: The maximum varchar length is 2560.- detail: ""startposition:line: 1column: 0diff --git a/backend/plugin/advisor/mssql/test/column_no_null.yaml b/backend/plugin/advisor/mssql/test/column_no_null.yamlindex ebec8f7010..f27972f7b8 100644--- a/backend/plugin/advisor/mssql/test/column_no_null.yaml+++ b/backend/plugin/advisor/mssql/test/column_no_null.yaml@@ -11,7 +11,6 @@code: 402title: column.no-nullcontent: Column [age] is nullable, which is not allowed.- detail: ""startposition:line: 4column: 0@@ -20,7 +19,6 @@code: 402title: column.no-nullcontent: Column [address] is nullable, which is not allowed.- detail: ""startposition:line: 5column: 0@@ -39,7 +37,6 @@code: 402title: column.no-nullcontent: Column [address] is nullable, which is not allowed.- detail: ""startposition:line: 5column: 0@@ -51,7 +48,6 @@code: 402title: column.no-nullcontent: Column [name] is nullable, which is not allowed.- detail: ""startposition:line: 1column: 0@@ -65,7 +61,6 @@code: 402title: column.no-nullcontent: Column [age] is nullable, which is not allowed.- detail: ""startposition:line: 1column: 0@@ -77,7 +72,6 @@code: 402title: column.no-nullcontent: Column [age] is nullable, which is not allowed.- detail: ""startposition:line: 1column: 0diff --git a/backend/plugin/advisor/mssql/test/column_required.yaml b/backend/plugin/advisor/mssql/test/column_required.yamlindex 98ad3c3268..540cfb56c3 100644--- a/backend/plugin/advisor/mssql/test/column_required.yaml+++ b/backend/plugin/advisor/mssql/test/column_required.yaml@@ -18,7 +18,6 @@code: 401title: column.requiredcontent: Table t missing required column "created_ts"- detail: ""startposition:line: 1column: 0@@ -27,7 +26,6 @@code: 401title: column.requiredcontent: Table t missing required column "creator_id"- detail: ""startposition:line: 1column: 0@@ -36,7 +34,6 @@code: 401title: column.requiredcontent: Table t missing required column "id"- detail: ""startposition:line: 1column: 0@@ -45,7 +42,6 @@code: 401title: column.requiredcontent: Table t missing required column "updated_ts"- detail: ""startposition:line: 1column: 0@@ -54,7 +50,6 @@code: 401title: column.requiredcontent: Table t missing required column "updater_id"- detail: ""startposition:line: 1column: 0@@ -72,7 +67,6 @@code: 401title: column.requiredcontent: Table t missing required column "updated_ts"- detail: ""startposition:line: 1column: 0@@ -84,7 +78,6 @@code: 401title: column.requiredcontent: Table t missing required column "created_ts"- detail: ""startposition:line: 1column: 0@@ -96,7 +89,6 @@code: 401title: column.requiredcontent: Table t missing required column "creator_id"- detail: ""startposition:line: 1column: 0diff --git a/backend/plugin/advisor/mssql/test/column_type_disallow_list.yaml b/backend/plugin/advisor/mssql/test/column_type_disallow_list.yamlindex 743805953a..7f03c6b56f 100644--- a/backend/plugin/advisor/mssql/test/column_type_disallow_list.yaml+++ b/backend/plugin/advisor/mssql/test/column_type_disallow_list.yaml@@ -10,7 +10,6 @@code: 411title: column.type-disallow-listcontent: Column type JSON is disallowed- detail: ""startposition:line: 4column: 0diff --git a/backend/plugin/advisor/mssql/test/index_not_redundant.yaml b/backend/plugin/advisor/mssql/test/index_not_redundant.yamlindex b28b72ff77..3e217c8945 100644--- a/backend/plugin/advisor/mssql/test/index_not_redundant.yaml+++ b/backend/plugin/advisor/mssql/test/index_not_redundant.yaml@@ -5,7 +5,6 @@code: 817title: index.not-redundantcontent: Redundant indexes with the same prefix ('idx_0' and 'test_index') in 'dbo.pokes' is not allowed- detail: ""startposition:line: 1column: 0@@ -19,7 +18,6 @@code: 817title: index.not-redundantcontent: Redundant indexes with the same prefix ('idx_0' and 'test_index') in 'dbo.pokes' is not allowed- detail: ""startposition:line: 1column: 0diff --git a/backend/plugin/advisor/mssql/test/naming_identifier_no_keyword.yaml b/backend/plugin/advisor/mssql/test/naming_identifier_no_keyword.yamlindex d7fa567818..444cf7168b 100644--- a/backend/plugin/advisor/mssql/test/naming_identifier_no_keyword.yaml+++ b/backend/plugin/advisor/mssql/test/naming_identifier_no_keyword.yaml@@ -7,7 +7,6 @@code: 308title: naming.identifier.no-keywordcontent: Identifier [exec] is a keyword identifier and should be avoided.- detail: ""startposition:line: 1column: 0@@ -16,7 +15,6 @@code: 308title: naming.identifier.no-keywordcontent: Identifier [fillfactor] is a keyword identifier and should be avoided.- detail: ""startposition:line: 1column: 0@@ -25,7 +23,6 @@code: 308title: naming.identifier.no-keywordcontent: Identifier [add] is a keyword identifier and should be avoided.- detail: ""startposition:line: 2column: 0@@ -34,7 +31,6 @@code: 308title: naming.identifier.no-keywordcontent: Identifier [fillfactor] is a keyword identifier and should be avoided.- detail: ""startposition:line: 2column: 0diff --git a/backend/plugin/advisor/mssql/test/naming_table.yaml b/backend/plugin/advisor/mssql/test/naming_table.yamlindex d3926dd5b4..3751f755a1 100644--- a/backend/plugin/advisor/mssql/test/naming_table.yaml+++ b/backend/plugin/advisor/mssql/test/naming_table.yaml@@ -7,7 +7,6 @@code: 301title: naming.tablecontent: '[\\] mismatches table naming convention, naming format should be "^[A-Z]([_A-Za-z])*$"'- detail: ""startposition:line: 1column: 0@@ -19,7 +18,6 @@code: 301title: naming.tablecontent: all_lowercase mismatches table naming convention, naming format should be "^[A-Z]([_A-Za-z])*$"- detail: ""startposition:line: 1column: 0@@ -35,7 +33,6 @@code: 301title: naming.tablecontent: salesTerr mismatches table naming convention, naming format should be "^[A-Z]([_A-Za-z])*$"- detail: ""startposition:line: 1column: 0diff --git a/backend/plugin/advisor/mssql/test/naming_table_no_keyword.yaml b/backend/plugin/advisor/mssql/test/naming_table_no_keyword.yamlindex a61878f6cd..c2f7b7b653 100644--- a/backend/plugin/advisor/mssql/test/naming_table_no_keyword.yaml+++ b/backend/plugin/advisor/mssql/test/naming_table_no_keyword.yaml@@ -5,7 +5,6 @@code: 308title: naming.table.no-keywordcontent: Table name [fillfactor] is a reserved keyword and should be avoided.- detail: ""startposition:line: 1column: 0@@ -17,7 +16,6 @@code: 308title: naming.table.no-keywordcontent: Table name [fillfactor] is a reserved keyword and should be avoided.- detail: ""startposition:line: 1column: 0diff --git a/backend/plugin/advisor/mssql/test/schema_backward_compatibility.yaml b/backend/plugin/advisor/mssql/test/schema_backward_compatibility.yamlindex 947b6561d9..3d73bf4d99 100644--- a/backend/plugin/advisor/mssql/test/schema_backward_compatibility.yaml+++ b/backend/plugin/advisor/mssql/test/schema_backward_compatibility.yaml@@ -5,7 +5,6 @@code: 102title: schema.backward-compatibilitycontent: sp_rename may cause incompatibility with the existing data and code, and break scripts and stored procedures.- detail: ""startposition:line: 1column: 0@@ -17,7 +16,6 @@code: 112title: schema.backward-compatibilitycontent: Drop table master.dbo.MyTable may cause incompatibility with the existing data and code- detail: ""startposition:line: 1column: 0@@ -33,7 +31,6 @@code: 112title: schema.backward-compatibilitycontent: Drop schema master.myschema may cause incompatibility with the existing data and code- detail: ""startposition:line: 1column: 0@@ -49,7 +46,6 @@code: 112title: schema.backward-compatibilitycontent: Drop database mydb may cause incompatibility with the existing data and code- detail: ""startposition:line: 1column: 0@@ -74,7 +70,6 @@code: 112title: schema.backward-compatibilitycontent: Drop column mycolumnone, mycolumntwo may cause incompatibility with the existing data and code- detail: ""startposition:line: 1column: 0@@ -83,7 +78,6 @@code: 111title: schema.backward-compatibilitycontent: Alter COLUMN mycolumnone may cause incompatibility with the existing data and code- detail: ""startposition:line: 2column: 0@@ -92,7 +86,6 @@code: 106title: schema.backward-compatibilitycontent: Add PRIMARY KEY may cause incompatibility with the existing data and code- detail: ""startposition:line: 3column: 0@@ -101,7 +94,6 @@code: 107title: schema.backward-compatibilitycontent: Add UNIQUE KEY may cause incompatibility with the existing data and code- detail: ""startposition:line: 4column: 0@@ -110,7 +102,6 @@code: 109title: schema.backward-compatibilitycontent: Add CHECK may cause incompatibility with the existing data and code- detail: ""startposition:line: 5column: 0@@ -119,7 +110,6 @@code: 108title: schema.backward-compatibilitycontent: Add CHECK WITH NO CHECK may cause incompatibility with the existing data and code- detail: ""startposition:line: 6column: 0@@ -128,7 +118,6 @@code: 108title: schema.backward-compatibilitycontent: Add FOREIGN KEY WITH NO CHECK may cause incompatibility with the existing data and code- detail: ""startposition:line: 8column: 0@@ -140,7 +129,6 @@code: 102title: schema.backward-compatibilitycontent: sp_rename may cause incompatibility with the existing data and code, and break scripts and stored procedures.- detail: ""startposition:line: 1column: 0@@ -152,7 +140,6 @@code: 102title: schema.backward-compatibilitycontent: sp_rename may cause incompatibility with the existing data and code, and break scripts and stored procedures.- detail: ""startposition:line: 1column: 0diff --git a/backend/plugin/advisor/mssql/test/statement_disallow_cross_db_queries.yaml b/backend/plugin/advisor/mssql/test/statement_disallow_cross_db_queries.yamlindex 9de88ba1b0..68d04ea013 100644--- a/backend/plugin/advisor/mssql/test/statement_disallow_cross_db_queries.yaml+++ b/backend/plugin/advisor/mssql/test/statement_disallow_cross_db_queries.yaml@@ -10,7 +10,6 @@code: 233title: statement.disallow-cross-db-queriescontent: 'Cross database queries (target databse: ''master2'', current database: ''master'') are prohibited'- detail: ""startposition:line: 1column: 0@@ -24,7 +23,6 @@code: 233title: statement.disallow-cross-db-queriescontent: 'Cross database queries (target databse: ''master'', current database: ''master2'') are prohibited'- detail: ""startposition:line: 2column: 0diff --git a/backend/plugin/advisor/mssql/test/statement_disallow_mix_in_ddl.yaml b/backend/plugin/advisor/mssql/test/statement_disallow_mix_in_ddl.yamlindex 971e866a37..1faca79076 100644--- a/backend/plugin/advisor/mssql/test/statement_disallow_mix_in_ddl.yaml+++ b/backend/plugin/advisor/mssql/test/statement_disallow_mix_in_ddl.yaml@@ -5,7 +5,6 @@code: 227title: statement.disallow-mix-in-ddlcontent: Alter schema can only run DDL- detail: ""startposition:line: 1column: 0@@ -17,7 +16,6 @@code: 227title: statement.disallow-mix-in-ddlcontent: Alter schema can only run DDL- detail: ""startposition:line: 1column: 0@@ -29,7 +27,6 @@code: 227title: statement.disallow-mix-in-ddlcontent: Alter schema can only run DDL- detail: ""startposition:line: 1column: 0@@ -38,7 +35,6 @@code: 227title: statement.disallow-mix-in-ddlcontent: Alter schema can only run DDL- detail: ""startposition:line: 1column: 0diff --git a/backend/plugin/advisor/mssql/test/statement_disallow_mix_in_dml.yaml b/backend/plugin/advisor/mssql/test/statement_disallow_mix_in_dml.yamlindex 71eb18b3cf..f48c4bddf2 100644--- a/backend/plugin/advisor/mssql/test/statement_disallow_mix_in_dml.yaml+++ b/backend/plugin/advisor/mssql/test/statement_disallow_mix_in_dml.yaml@@ -9,7 +9,6 @@code: 227title: statement.disallow-mix-in-dmlcontent: Data change can only run DML- detail: ""startposition:line: 1column: 0diff --git a/backend/plugin/advisor/mssql/test/statement_select_no_select_all.yaml b/backend/plugin/advisor/mssql/test/statement_select_no_select_all.yamlindex 0548a580f9..d9bc264725 100644--- a/backend/plugin/advisor/mssql/test/statement_select_no_select_all.yaml+++ b/backend/plugin/advisor/mssql/test/statement_select_no_select_all.yaml@@ -5,7 +5,6 @@code: 203title: statement.select.no-select-allcontent: Avoid using SELECT *.- detail: ""startposition:line: 1column: 0@@ -19,7 +18,6 @@code: 203title: statement.select.no-select-allcontent: Avoid using SELECT *.- detail: ""startposition:line: 1column: 0@@ -31,7 +29,6 @@code: 203title: statement.select.no-select-allcontent: Avoid using SELECT *.- detail: ""startposition:line: 1column: 0diff --git a/backend/plugin/advisor/mssql/test/statement_where_disallow_functions_and_calculations.yaml b/backend/plugin/advisor/mssql/test/statement_where_disallow_functions_and_calculations.yamlindex e564f4a5c6..ca25d7c0c6 100644--- a/backend/plugin/advisor/mssql/test/statement_where_disallow_functions_and_calculations.yaml+++ b/backend/plugin/advisor/mssql/test/statement_where_disallow_functions_and_calculations.yaml@@ -9,7 +9,6 @@code: 234title: statement.where.disallow-functions-and-calculationscontent: Performing calculations in 'WHERE' clause is not allowed- detail: ""startposition:line: 2column: 0@@ -18,7 +17,6 @@code: 234title: statement.where.disallow-functions-and-calculationscontent: Performing calculations in 'WHERE' clause is not allowed- detail: ""startposition:line: 4column: 0@@ -32,7 +30,6 @@code: 234title: statement.where.disallow-functions-and-calculationscontent: Performing calculations in 'WHERE' clause is not allowed- detail: ""startposition:line: 1column: 0@@ -41,7 +38,6 @@code: 234title: statement.where.disallow-functions-and-calculationscontent: Calling function 'AVG(bar)' in 'WHERE' clause is not allowed- detail: ""startposition:line: 2column: 0@@ -61,7 +57,6 @@code: 234title: statement.where.disallow-functions-and-calculationscontent: Calling function 'AVG(a)' in 'WHERE' clause is not allowed- detail: ""startposition:line: 1column: 0diff --git a/backend/plugin/advisor/mssql/test/statement_where_require_select.yaml b/backend/plugin/advisor/mssql/test/statement_where_require_select.yamlindex ffd98ae3c6..0021236256 100644--- a/backend/plugin/advisor/mssql/test/statement_where_require_select.yaml+++ b/backend/plugin/advisor/mssql/test/statement_where_require_select.yaml@@ -5,7 +5,6 @@code: 202title: statement.where.require.selectcontent: WHERE clause is required for SELETE statement.- detail: ""startposition:line: 1column: 0@@ -22,7 +21,6 @@code: 202title: statement.where.require.selectcontent: WHERE clause is required for SELETE statement.- detail: ""startposition:line: 2column: 0@@ -31,7 +29,6 @@code: 202title: statement.where.require.selectcontent: WHERE clause is required for SELETE statement.- detail: ""startposition:line: 3column: 0diff --git a/backend/plugin/advisor/mssql/test/statement_where_require_update_delete.yaml b/backend/plugin/advisor/mssql/test/statement_where_require_update_delete.yamlindex 67ca71c1de..47dafb33c7 100644--- a/backend/plugin/advisor/mssql/test/statement_where_require_update_delete.yaml+++ b/backend/plugin/advisor/mssql/test/statement_where_require_update_delete.yaml@@ -5,7 +5,6 @@code: 202title: statement.where.require.update-deletecontent: WHERE clause is required for UPDATE statement.- detail: ""startposition:line: 1column: 0@@ -19,7 +18,6 @@code: 202title: statement.where.require.update-deletecontent: WHERE clause is required for DELETE statement.- detail: ""startposition:line: 1column: 0diff --git a/backend/plugin/advisor/mssql/test/system_function_disallow_create.yaml b/backend/plugin/advisor/mssql/test/system_function_disallow_create.yamlindex 851b078be4..d720349df3 100644--- a/backend/plugin/advisor/mssql/test/system_function_disallow_create.yaml+++ b/backend/plugin/advisor/mssql/test/system_function_disallow_create.yaml@@ -19,7 +19,6 @@code: 1701title: system.function.disallow-createcontent: Creating or altering functions is prohibited- detail: ""startposition:line: 1column: 0diff --git a/backend/plugin/advisor/mssql/test/system_procedure_disallow_create.yaml b/backend/plugin/advisor/mssql/test/system_procedure_disallow_create.yamlindex d677574320..cfc91b9909 100644--- a/backend/plugin/advisor/mssql/test/system_procedure_disallow_create.yaml+++ b/backend/plugin/advisor/mssql/test/system_procedure_disallow_create.yaml@@ -20,10 +20,9 @@changeType: 0want:- status: 2- code: 1701+ code: 1401title: system.procedure.disallow-createcontent: Creating or altering procedures is prohibited- detail: ""startposition:line: 1column: 0diff --git a/backend/plugin/advisor/mssql/test/table_disallow_ddl.yaml b/backend/plugin/advisor/mssql/test/table_disallow_ddl.yamlindex ed9b7a0f0c..ccab9b0a88 100644--- a/backend/plugin/advisor/mssql/test/table_disallow_ddl.yaml+++ b/backend/plugin/advisor/mssql/test/table_disallow_ddl.yaml@@ -13,7 +13,6 @@code: 613title: table.disallow-ddlcontent: DDL is disallowed on table MySchema.Identifier.- detail: ""startposition:line: 5column: 0diff --git a/backend/plugin/advisor/mssql/test/table_disallow_dml.yaml b/backend/plugin/advisor/mssql/test/table_disallow_dml.yamlindex 829f392a8d..5f09ec71e3 100644--- a/backend/plugin/advisor/mssql/test/table_disallow_dml.yaml+++ b/backend/plugin/advisor/mssql/test/table_disallow_dml.yaml@@ -8,7 +8,6 @@code: 614title: table.disallow-dmlcontent: DML is disallowed on table MySchema.Identifier.- detail: ""startposition:line: 1column: 0@@ -22,7 +21,6 @@code: 614title: table.disallow-dmlcontent: DML is disallowed on table MySchema.Identifier.- detail: ""startposition:line: 2column: 0@@ -34,7 +32,6 @@code: 614title: table.disallow-dmlcontent: DML is disallowed on table MySchema.Identifier.- detail: ""startposition:line: 1column: 0@@ -46,7 +43,6 @@code: 614title: table.disallow-dmlcontent: DML is disallowed on table MySchema.Identifier.- detail: ""startposition:line: 1column: 0@@ -58,7 +54,6 @@code: 614title: table.disallow-dmlcontent: DML is disallowed on table MySchema.Identifier.- detail: ""startposition:line: 1column: 0diff --git a/backend/plugin/advisor/mssql/test/table_drop_naming_convention.yaml b/backend/plugin/advisor/mssql/test/table_drop_naming_convention.yamlindex 3a6cb28c72..14e58ca54e 100644--- a/backend/plugin/advisor/mssql/test/table_drop_naming_convention.yaml+++ b/backend/plugin/advisor/mssql/test/table_drop_naming_convention.yaml@@ -7,7 +7,6 @@code: 603title: table.drop-naming-conventioncontent: '[foo] mismatches drop table naming convention, naming format should be "_delete$"'- detail: ""startposition:line: 1column: 0@@ -19,7 +18,6 @@code: 603title: table.drop-naming-conventioncontent: '[foo] mismatches drop table naming convention, naming format should be "_delete$"'- detail: ""startposition:line: 1column: 0diff --git a/backend/plugin/advisor/mssql/test/table_no_foreign_key.yaml b/backend/plugin/advisor/mssql/test/table_no_foreign_key.yamlindex 798652a80a..f526d0084f 100644--- a/backend/plugin/advisor/mssql/test/table_no_foreign_key.yaml+++ b/backend/plugin/advisor/mssql/test/table_no_foreign_key.yaml@@ -11,7 +11,6 @@code: 602title: table.no-foreign-keycontent: FOREIGN KEY is not allowed in the table MyTable.- detail: ""startposition:line: 3column: 0@@ -30,7 +29,6 @@code: 602title: table.no-foreign-keycontent: FOREIGN KEY is not allowed in the table Customer.- detail: ""startposition:line: 6column: 0@@ -49,7 +47,6 @@code: 602title: table.no-foreign-keycontent: FOREIGN KEY is not allowed in the table Customer.- detail: ""startposition:line: 7column: 0diff --git a/backend/plugin/advisor/mssql/test/table_require_pk.yaml b/backend/plugin/advisor/mssql/test/table_require_pk.yamlindex 70770e7009..597b87e809 100644--- a/backend/plugin/advisor/mssql/test/table_require_pk.yaml+++ b/backend/plugin/advisor/mssql/test/table_require_pk.yaml@@ -9,7 +9,6 @@code: 601title: table.require-pkcontent: Table MySchema.MyTable requires PRIMARY KEY.- detail: ""startposition:line: 1column: 0diff --git a/backend/plugin/app/relay/relay_client.go b/backend/plugin/app/relay/relay_client.godeleted file mode 100644index cc548efcc7..0000000000--- a/backend/plugin/app/relay/relay_client.go+++ /dev/null@@ -1,129 +0,0 @@-// Package relay is the client sending requests to relay server for external approvals.-package relay--import (- "bytes"- "encoding/json"- "fmt"- "net/http"- "strings"- "time"-- "github.com/pkg/errors"-)--// Client is the client for relay.-type Client struct {- client *http.Client-}--// NewClient returns a client.-func NewClient() *Client {- return &Client{- client: &http.Client{- Timeout: 5 * time.Second,- },- }-}--// CreatePayload is the message to create external approval.-type CreatePayload struct {- IssueID string `json:"issueId"`- Creator string `json:"creator"`- Title string `json:"title"`- Description string `json:"description"`- Project string `json:"project"`- Statement string `json:"statement"`- CreateTime time.Time `json:"createTime"`-}--// Status is the status of the external approval.-type Status string--const (- // StatusApproved means that the external approval is approved.- StatusApproved Status = "APPROVED"- // StatusRejected means that the external approval is rejected.- StatusRejected Status = "REJECTED"-)--// ResponsePayload is the response message to for external approval.-type ResponsePayload struct {- ID string `json:"id"`- Status Status `json:"status"`-}--// Create sends a message to create external approval.-func (c *Client) Create(relayEndpoint string, payload *CreatePayload) (string, error) {- out, err := json.Marshal(&payload)- if err != nil {- return "", err- }- req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/approval", relayEndpoint), bytes.NewBuffer(out))- if err != nil {- return "", err- }- resp, err := c.client.Do(req)- if err != nil {- return "", err- }- defer resp.Body.Close()- if resp.StatusCode != http.StatusOK {- return "", errors.Errorf("failed to create external approval with status %v", resp.Status)- }- responseBody := &ResponsePayload{}- err = json.NewDecoder(resp.Body).Decode(responseBody)- if err != nil {- return "", err- }- return responseBody.ID, nil-}--// UpdatePayload is the message to update external approval.-type UpdatePayload struct {- Title string `json:"title"`- Statement string `json:"statement"`-}--// UpdateApproval sends a message to update the external approval.-func (c *Client) UpdateApproval(relayEndpoint string, id string, payload *UpdatePayload) error {- out, err := json.Marshal(&payload)- if err != nil {- return err- }- req, err := http.NewRequest(http.MethodPatch, fmt.Sprintf("%s/approval/%s", relayEndpoint, id), bytes.NewBuffer(out))- if err != nil {- return err- }- resp, err := c.client.Do(req)- if err != nil {- return err- }- defer resp.Body.Close()- if resp.StatusCode != http.StatusOK {- return errors.Errorf("failed to create external approval with status %v", resp.Status)- }- return nil-}--// GetApproval gets the approval of an external approval.-func (c *Client) GetApproval(relayEndpoint string, id string) (*ResponsePayload, error) {- req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/approval/%s", relayEndpoint, id), strings.NewReader(""))- if err != nil {- return nil, err- }- resp, err := c.client.Do(req)- if err != nil {- return nil, err- }- defer resp.Body.Close()- if resp.StatusCode != http.StatusOK {- return nil, errors.Errorf("failed to get external approval status with status %v", resp.Status)- }- responseBody := &ResponsePayload{}- err = json.NewDecoder(resp.Body).Decode(responseBody)- if err != nil {- return nil, err- }- return responseBody, nil-}diff --git a/backend/plugin/db/util/ssh.go b/backend/plugin/db/util/ssh.goindex fc6174da76..ce302322a1 100644--- a/backend/plugin/db/util/ssh.go+++ b/backend/plugin/db/util/ssh.go@@ -2,8 +2,6 @@ package utilimport ("fmt"- "io"- "log/slog""net""os""time"@@ -11,7 +9,6 @@ import ("golang.org/x/crypto/ssh""golang.org/x/crypto/ssh/agent"- "github.com/bytebase/bytebase/backend/common/log"storepb "github.com/bytebase/bytebase/proto/generated-go/store")@@ -55,69 +52,6 @@ func GetSSHClient(ds *storepb.DataSource) (*ssh.Client, error) {return sshConn, nil}-// ProxyConnection proxies the connection between ssh client and listener.-func ProxyConnection(sshClient *ssh.Client, listener net.Listener, databaseAddr string) {- // Accept incoming connections.- for {- conn, err := listener.Accept()- if err != nil {- return- }-- // Create a new connection to the target server.- targetConn, err := sshClient.Dial("tcp", databaseAddr)- if err != nil {- return- }-- // Copy data from the incoming connection to the target connection.- go func() {- defer conn.Close()- defer targetConn.Close()-- for {- buf := make([]byte, 1024)- n, err := conn.Read(buf)- if err != nil {- if err != io.EOF {- slog.Error("proxy source read error", log.BBError(err))- }- return- }-- _, err = targetConn.Write(buf[:n])- if err != nil {- slog.Error("proxy source write error", log.BBError(err))- return- }- }- }()-- // Copy data from the target connection to the incoming connection.- go func() {- defer conn.Close()- defer targetConn.Close()-- for {- buf := make([]byte, 1024)- n, err := targetConn.Read(buf)- if err != nil {- if err != io.EOF {- slog.Error("proxy target read error", log.BBError(err))- }- return- }-- _, err = conn.Write(buf[:n])- if err != nil {- slog.Error("proxy target write error", log.BBError(err))- return- }- }- }()- }-}-const sshPortSize = 100// PortFIFO is the fifo for SSH client port queue.diff --git a/backend/plugin/parser/base/masking.go b/backend/plugin/parser/base/masking.godeleted file mode 100644index 2139d44158..0000000000--- a/backend/plugin/parser/base/masking.go+++ /dev/null@@ -1,113 +0,0 @@-package base--import (- "github.com/bytebase/bytebase/backend/component/masker"-)--// DatabaseSchema is the database schema using to extract sensitive fields.-type DatabaseSchema struct {- Name string- SchemaList []SchemaSchema-}--// SchemaSchema is the schema of the schema using to extract sensitive fields.-type SchemaSchema struct {- Name string- TableList []TableSchema- ViewList []ViewSchema-}--// ViewSchema is the view schema using to extract sensitive fields.-type ViewSchema struct {- Name string- Definition string-}--// TableSchema is the table schema using to extract sensitive fields.-type TableSchema struct {- Name string- ColumnList []ColumnInfo-}--// ColumnInfo is the column info using to extract sensitive fields.-type ColumnInfo struct {- Name string- MaskingAttributes MaskingAttributes-}--// SensitiveField is the struct about SELECT fields.-type SensitiveField struct {- Name string- MaskingAttributes MaskingAttributes-}--// FieldInfo is the masking field info.-type FieldInfo struct {- Name string- Table string- Schema string- Database string- MaskingAttributes MaskingAttributes-}--// MaskingAttributes contain the masking related attributes on the column, likes MaskingLevel.-type MaskingAttributes struct {- Masker masker.Masker-}--// TransmittedBy transmits the masking attributes from other to self.-// If two masker is not equal, self will be set to default full masker.-func (m *MaskingAttributes) TransmittedBy(other MaskingAttributes) (changed bool) {- changed = false- defaultMasker := masker.NewDefaultFullMasker()- if !m.Masker.Equal(other.Masker) && !m.Masker.Equal(defaultMasker) {- m.Masker = defaultMasker- changed = true- }- return changed-}--// TransmittedByInExpression transmits the masking attributes from other to self.-// If anyone of the masker is not none masker, both masker will be set to default full masker.-// It should be used in expression computing only.-func (m *MaskingAttributes) TransmittedByInExpression(other MaskingAttributes) (changed bool) {- changed = false- _, selfIsNoneMasker := m.Masker.(*masker.NoneMasker)- _, otherIsNoneMasker := other.Masker.(*masker.NoneMasker)- // Any none masker will be replaced with default full masker in expr computing.- if (!selfIsNoneMasker) || (!otherIsNoneMasker) {- m.Masker = masker.NewDefaultFullMasker()- changed = true- }- return changed-}--// IsNeverChangeInTransmission returns true if the masking attributes would never change in transmission, it can be used to do the quit early optimization.-func (m *MaskingAttributes) IsNeverChangeInTransmission() bool {- _, ok := m.Masker.(*masker.FullMasker)- return ok-}--// Clone clones the masking attributes.-func (m *MaskingAttributes) Clone() MaskingAttributes {- return MaskingAttributes{- Masker: m.Masker,- }-}--// NewMaskingAttributes creates a new masking attributes.-func NewMaskingAttributes(masker masker.Masker) MaskingAttributes {- return MaskingAttributes{- Masker: masker,- }-}--// NewDefaultMaskingAttributes creates a new masking attributes with default masking level.-func NewDefaultMaskingAttributes() MaskingAttributes {- return NewMaskingAttributes(masker.NewNoneMasker())-}--// NewEmptyMaskingAttributes creates a new masking attributes with empty masking level.-func NewEmptyMaskingAttributes() MaskingAttributes {- return NewMaskingAttributes(masker.NewNoneMasker())-}diff --git a/backend/plugin/parser/mysql/equal.go b/backend/plugin/parser/mysql/equal.godeleted file mode 100644index 32af338fdd..0000000000--- a/backend/plugin/parser/mysql/equal.go+++ /dev/null@@ -1,126 +0,0 @@-package mysql--import (- "github.com/antlr4-go/antlr/v4"- parser "github.com/bytebase/mysql-parser"- "github.com/pkg/errors"-)--// IsViewTailEqual returns true if the two view tails are equal.-func IsViewTailEqual(a, b parser.IViewTailContext) bool {- return a.GetText() == b.GetText()-}--type isViewTailEqualViewStmtListener struct {- *parser.BaseMySQLParserListener-- target parser.IViewTailContext- equal bool- err error-}--func (l *isViewTailEqualViewStmtListener) EnterCreateView(ctx *parser.CreateViewContext) {- if l.err != nil {- return- }- p := ctx.GetParent()- if _, ok := p.(*parser.CreateStatementContext); !ok {- l.err = errors.New("Expecting CreateStatementContext as parent")- return- }- pp := p.GetParent()- if _, ok := pp.(*parser.SimpleStatementContext); !ok {- l.err = errors.New("Expecting SimpleStatementContext as parent")- return- }- ppp := pp.GetParent()- if _, ok := ppp.(*parser.QueryContext); !ok {- l.err = errors.New("Expecting QueryContext as parent")- return- }-- if IsViewTailEqual(l.target, ctx.ViewTail()) {- l.equal = true- }-}--// IsViewTailEqualCreateViewStmt returns true if the view tail is equal to the view statement.-func IsViewTailEqualCreateViewStmt(a parser.IViewTailContext, b string) (bool, error) {- parseResults, err := ParseMySQL(b)- if err != nil {- return false, err- }- if len(parseResults) != 1 {- return false, errors.Errorf("Expecting one statement, but got %d", len(parseResults))- }-- stmt := parseResults[0]- listener := &isViewTailEqualViewStmtListener{- target: a,- }- antlr.ParseTreeWalkerDefault.Walk(listener, stmt.Tree)- if listener.err != nil {- return false, listener.err- }-- return listener.equal, nil-}--// IsCompoundStmtEqual returns true if the two compound statements are equal.-func IsCompoundStmtEqual(a, b parser.ICompoundStatementContext) bool {- return a.GetText() == b.GetText()-}--type isCompoundEqualFuncStmtListener struct {- *parser.BaseMySQLParserListener-- target parser.ICompoundStatementContext- equal bool- err error-}--func (l *isCompoundEqualFuncStmtListener) EnterCreateFunction(ctx *parser.CreateFunctionContext) {- if l.err != nil {- return- }- p := ctx.GetParent()- if _, ok := p.(*parser.CreateStatementContext); !ok {- l.err = errors.New("Expecting CreateFunctionStatementContext as parent")- return- }- pp := p.GetParent()- if _, ok := pp.(*parser.SimpleStatementContext); !ok {- l.err = errors.New("Expecting SimpleStatementContext as parent")- return- }- ppp := pp.GetParent()- if _, ok := ppp.(*parser.QueryContext); !ok {- l.err = errors.New("Expecting QueryContext as parent")- return- }-- if IsCompoundStmtEqual(l.target, ctx.CompoundStatement()) {- l.equal = true- }-}--// IsCompoundEqualCreateFuncStmt returns true if the compound statement is equal to the create function statement.-func IsCompoundEqualCreateFuncStmt(a parser.ICompoundStatementContext, b string) (bool, error) {- parseResults, err := ParseMySQL(b)- if err != nil {- return false, err- }- if len(parseResults) != 1 {- return false, errors.Errorf("Expecting one statement, but got %d", len(parseResults))- }-- stmt := parseResults[0]- listener := &isCompoundEqualFuncStmtListener{- target: a,- }- antlr.ParseTreeWalkerDefault.Walk(listener, stmt.Tree)- if listener.err != nil {- return false, listener.err- }- return listener.equal, nil-}diff --git a/backend/plugin/parser/mysql/fingerprint.go b/backend/plugin/parser/mysql/fingerprint.godeleted file mode 100644index bc37584f16..0000000000--- a/backend/plugin/parser/mysql/fingerprint.go+++ /dev/null@@ -1,173 +0,0 @@-package mysql--import (- "bytes"- "regexp"- "strings"-- "github.com/pkg/errors"-)--// GetFingerprint gets mysql query fingerprint.-// From https://github.com/percona/percona-toolkit/blob/af686fe186d1fca4c4392c8fa75c31a00c8fb273/bin/pt-query-digest#L2930-func GetFingerprint(query string) (string, error) {- // Match SQL queries generated by mysqldump command.- if matched, _ := regexp.MatchString(`\ASELECT /\*!40001 SQL_NO_CACHE \*/ \* FROM `, query); matched {- return "mysqldump", nil- }- // Match SQL queries generated by Percona Toolkit.- if matched, _ := regexp.MatchString(`/\*\w+\.\w+:[0-9]/[0-9]\*/`, query); matched {- return "percona-toolkit", nil- }- // Match administrator commands.- if matched, _ := regexp.MatchString(`\Aadministrator command: `, query); matched {- return query, nil- }- // Match stored procedure call statements.- if matched, _ := regexp.MatchString(`\A\s*(call\s+\S+)\(`, query); matched {- return strings.ToLower(regexp.MustCompile(`\A\s*(call\s+\S+)\(`).FindStringSubmatch(query)[1]), nil- }- // Match INSERT INTO or REPLACE INTO statements.- if beginning := regexp.MustCompile(`(?i)((?:INSERT|REPLACE)(?: IGNORE)?\s+INTO.+?VALUES\s*\(.*?\))\s*,\s*\(`).FindStringSubmatch(query); len(beginning) > 0 {- query = beginning[1]- }-- // Match multi-line comments and single-line comments, and remove them.- mlcRe := regexp.MustCompile(`(?s)/\*.*?\*/`)- olcRe := regexp.MustCompile(`(?m)--.*$`)- query = mlcRe.ReplaceAllString(query, "")- query = olcRe.ReplaceAllString(query, "")-- // Replace the database name in USE statements with a question mark (?).- query = regexp.MustCompile(`(?i)\Ause \S+\z`).ReplaceAllString(query, "use ?")-- // Replace escape characters and special characters in SQL queries with a question mark (?).- query = regexp.MustCompile(`([^\\])(\\')`).ReplaceAllString(query, "$1")- query = regexp.MustCompile(`([^\\])(\\")`).ReplaceAllString(query, "$1")- query = regexp.MustCompile(`\\\\`).ReplaceAllString(query, "")- query = regexp.MustCompile(`\\'`).ReplaceAllString(query, "")- query = regexp.MustCompile(`\\"`).ReplaceAllString(query, "")- query = regexp.MustCompile(`([^\\])(".*?[^\\]?")`).ReplaceAllString(query, "$1?")- query = regexp.MustCompile(`([^\\])('.*?[^\\]?')`).ReplaceAllString(query, "$1?")-- // Replace boolean values in SQL queries with a question mark (?).- query = regexp.MustCompile(`\bfalse\b|\btrue\b`).ReplaceAllString(query, "?")-- // Replace MD5 values in SQL queries with a question mark (?).- if matched, _ := regexp.MatchString(`([._-])[a-f0-9]{32}`, query); matched {- query = regexp.MustCompile(`([._-])[a-f0-9]{32}`).ReplaceAllString(query, "$1?")- }-- // Replace numbers in SQL queries with a question mark (?).- if matched, _ := regexp.MatchString(`\b[0-9+-][0-9a-f.xb+-]*`, query); matched {- query = regexp.MustCompile(`\b[0-9+-][0-9a-f.xb+-]*`).ReplaceAllString(query, "?")- }-- // Replace special characters in SQL queries with a question mark (?).- if matched, _ := regexp.MatchString(`[xb+-]\?`, query); matched {- query = regexp.MustCompile(`[xb+-]\?`).ReplaceAllString(query, "?")- } else {- query = regexp.MustCompile(`[xb.+-]\?`).ReplaceAllString(query, "?")- }-- // Remove spaces and line breaks in SQL queries.- query = strings.TrimSpace(query)- query = regexp.MustCompile(`\s+`).ReplaceAllString(query, " ")- query = strings.ToLower(query)-- // Replace NULL values in SQL queries with a question mark (?).- query = regexp.MustCompile(`\bnull\b`).ReplaceAllString(query, "?")-- // Replace IN and VALUES clauses in SQL queries with a question mark (?).- query = regexp.MustCompile(`\b(in|values?)(?:[\s,]*\([\s?,]*\))+`).ReplaceAllString(query, "$1(?+)")-- var err error- query, err = collapseUnion(query)- if err != nil {- return "", err- }-- // Replace numbers in the LIMIT clause of SQL queries with a question mark (?).- query = regexp.MustCompile(`\blimit \?(?:, ?\?| offset \?)?`).ReplaceAllString(query, "limit ?")-- // Remove ASC sorting in SQL queries.- if matched, _ := regexp.MatchString(`\border by `, query); matched {- ascRegexp := regexp.MustCompile(`(.+?)\s+asc`)- for {- if matched := ascRegexp.MatchString(query); matched {- query = ascRegexp.ReplaceAllString(query, "$1")- } else {- break- }- }- }-- return query, nil-}--func collapseUnion(query string) (string, error) {- // The origin perl code is:- // $query =~ s{ # Collapse UNION- // \b(select\s.*?)(?:(\sunion(?:\sall)?)\s\1)+- // }- // {$1 /*repeat$2*/}xg;- // But Golang doesn't support \1(back-reference).- // So we use the following code to replace it.- unionRegexp := regexp.MustCompile(`\s(union all|union)\s`)- parts := unionRegexp.Split(query, -1)- if len(parts) == 1 {- return query, nil- }- // Add a sentinel node to the end of the slice.- // Because we remove all comments before, so all parts are different from sentinel node.- parts = append(parts, "/*Sentinel Node*/")- separators := unionRegexp.FindAllString(query, -1)- if len(parts) != len(separators)+2 {- return "", errors.Errorf("find %d parts, but %d separators", len(parts)-1, len(separators))- }- start := 0- var buf bytes.Buffer- if _, err := buf.WriteString(parts[start]); err != nil {- return "", err- }- for i, part := range parts {- if i == 0 {- continue- }- if part == parts[start] {- continue- }- if i == start+1 {- // The i-th part is not equal to the front part.- if i == len(parts)-1 {- // The i-th part is the sentinel node.- break- }- if _, err := buf.WriteString(separators[i-1]); err != nil {- return "", err- }- } else {- // deal with the same parts[start, i-1] and start < i-1.- if _, err := buf.WriteString(" /*repeat"); err != nil {- return "", err- }- // Write the last separator between the same parts[start, i-1].- // In other words, the last separator is the separator between the i-th part and the (i-1)-th part.- // So the index of the last separator is (i-1)-1.- if _, err := buf.WriteString(separators[(i-1)-1]); err != nil {- return "", err- }- if _, err := buf.WriteString("*/"); err != nil {- return "", err- }- }- start = i- // Don't write the sentinel node.- if i != len(parts)-1 {- if _, err := buf.WriteString(parts[start]); err != nil {- return "", err- }- }- }- return buf.String(), nil-}diff --git a/backend/plugin/parser/mysql/fingerprint_test.go b/backend/plugin/parser/mysql/fingerprint_test.godeleted file mode 100644index 72efc8e1f3..0000000000--- a/backend/plugin/parser/mysql/fingerprint_test.go+++ /dev/null@@ -1,119 +0,0 @@-package mysql--import (- "testing"-- "github.com/stretchr/testify/require"-)--func TestGetMySQLFingerprint(t *testing.T) {- tests := []struct {- stmt string- want string- }{- {- stmt: "SELECT * FROM `mytable` UNION SELECT a, b FROM `mytable`",- want: "select * from `mytable` union select a, b from `mytable`",- },- {- stmt: "-- this is comment\nSELECT * FROM `mytable`",- want: "select * from `mytable`",- },- // Test mysqldump query.- {- stmt: "SELECT /*!40001 SQL_NO_CACHE */ * FROM `mytable`",- want: "mysqldump",- },- // Test Percona Toolkit query.- {- stmt: "/*foo.bar:1/2*/ SELECT * FROM `mytable`",- want: "percona-toolkit",- },- // Test administrator command.- {- stmt: "administrator command: SHOW STATUS",- want: "administrator command: SHOW STATUS",- },- // Test stored procedure call statement.- {- stmt: "CALL my_stored_procedure(?, ?)",- want: "call my_stored_procedure(?, ?)",- },- // Test INSERT INTO statement.- {- stmt: "INSERT INTO `mytable` (`id`, `name`) VALUES (1, 'John'), (2, 'Doe')",- want: "insert into `mytable` (`id`, `name`) values(?+)",- },- // Test REPLACE INTO statement.- {- stmt: "REPLACE INTO `mytable` (`id`, `name`) VALUES (1, 'John'), (2, 'Doe')",- want: "replace into `mytable` (`id`, `name`) values(?+)",- },- // Test multi-line comment.- {- stmt: "SELECT * FROM `mytable` /* WHERE `id` = 1 */",- want: "select * from `mytable`",- },- // Test single-line comment.- {- stmt: "SELECT * FROM `mytable` -- WHERE `id` = 1",- want: "select * from `mytable`",- },- // Test USE statement.- {- stmt: "USE `mydatabase`",- want: "use ?",- },- // Test escape characters in SQL query.- {- stmt: "SELECT 'It\\'s raining' FROM `mytable`",- want: "select ? from `mytable`",- },- // Test special characters in SQL query.- {- stmt: "SELECT 'Hello, \"world\"!' FROM `mytable`",- want: "select ? from `mytable`",- },- // Test boolean values in SQL query.- {- stmt: "SELECT * FROM `mytable` WHERE `is_active` = true",- want: "select * from `mytable` where `is_active` = ?",- },- // Test MD5 values in SQL query.- {- stmt: "SELECT * FROM `mytable` WHERE `password` = '5f4dcc3b5aa765d61d8327deb882cf99'",- want: "select * from `mytable` where `password` = ?",- },- // Test numbers in SQL query.- {- stmt: "SELECT * FROM `mytable` WHERE `id` = 123",- want: "select * from `mytable` where `id` = ?",- },- // Test special characters in SQL query.- {- stmt: "SELECT * FROM `mytable` WHERE `id` IN (1, 2, 3)",- want: "select * from `mytable` where `id` in(?+)",- },- // Test repeated clauses in SQL query.- {- stmt: "SELECT * FROM `mytable` WHERE `id` = 1 UNION SELECT * FROM `mytable` WHERE `id` = 2 UNION ALL SELECT * FROM `mytable` WHERE `id` = 3",- want: "select * from `mytable` where `id` = ? /*repeat union all */",- },- // Test LIMIT clause in SQL query.- {- stmt: "SELECT * FROM `mytable` LIMIT 10",- want: "select * from `mytable` limit ?",- },- // Test ASC sorting in SQL query.- {- stmt: "SELECT * FROM `mytable` ORDER BY `id` ASC, `name` DESC",- want: "select * from `mytable` order by `id`, `name` desc",- },- }-- for _, test := range tests {- res, err := GetFingerprint(test.stmt)- require.NoError(t, err, test.stmt)- require.Equal(t, test.want, res, test.stmt)- }-}diff --git a/backend/plugin/parser/mysql/utils.go b/backend/plugin/parser/mysql/utils.godeleted file mode 100644index 7a3537420b..0000000000--- a/backend/plugin/parser/mysql/utils.go+++ /dev/null@@ -1,28 +0,0 @@-package mysql--import "fmt"--// PartitionDefaultNameGenerator is the name generator of MySQL partition, which use the default clause.-// The behavior of this generator should be compatible with MySQL.-// - If do not specify the `parentName`, the default partition name series is "p0", "p1", "p2", ...-// - Otherwise, the default partition name series is "parentNamesp0", "parentNamesp1", "parentNamesp2", ...-type PartitionDefaultNameGenerator struct {- parentName string- count int-}--func NewPartitionDefaultNameGenerator(parentName string) *PartitionDefaultNameGenerator {- return &PartitionDefaultNameGenerator{- parentName: parentName,- count: -1,- }-}--func (g *PartitionDefaultNameGenerator) Next() string {- g.count++-- if g.parentName == "" {- return fmt.Sprintf("p%d", g.count)- }- return fmt.Sprintf("%ssp%d", g.parentName, g.count)-}diff --git a/backend/plugin/parser/pg/pg.go b/backend/plugin/parser/pg/pg.goindex e158d34b8e..49c184836b 100644--- a/backend/plugin/parser/pg/pg.go+++ b/backend/plugin/parser/pg/pg.go@@ -6,8 +6,6 @@ import ("github.com/antlr4-go/antlr/v4"parser "github.com/bytebase/postgresql-parser"- "github.com/pkg/errors"-"github.com/bytebase/bytebase/backend/plugin/parser/base")@@ -88,39 +86,6 @@ func normalizePostgreSQLName(ctx parser.INameContext) string {return ""}-func NormalizePostgreSQLFuncName(ctx parser.IFunc_nameContext) []string {- if ctx == nil {- return nil- }-- switch {- case ctx.Builtin_function_name() != nil:- return []string{strings.ToLower(ctx.Builtin_function_name().GetText())}- case ctx.Type_function_name() != nil:- return []string{NormalizePostgreSQLTypeFunctionName(ctx.Type_function_name())}- case ctx.Colid() != nil:- var result []string- result = append(result, NormalizePostgreSQLColid(ctx.Colid()))- result = append(result, normalizePostgreSQLIndirection(ctx.Indirection())...)- return result- default:- return []string{strings.ToLower(ctx.GetText())}- }-}--func NormalizePostgreSQLTypeFunctionName(ctx parser.IType_function_nameContext) string {- if ctx == nil {- return ""- }-- switch {- case ctx.Identifier() != nil:- return normalizePostgreSQLIdentifier(ctx.Identifier())- default:- return strings.ToLower(ctx.GetText())- }-}-// NormalizePostgreSQLAnyName normalizes the given any name.func NormalizePostgreSQLAnyName(ctx parser.IAny_nameContext) []string {if ctx == nil {@@ -138,59 +103,6 @@ func NormalizePostgreSQLAnyName(ctx parser.IAny_nameContext) []string {return result}-func normalizePostgreSQLStringListAsTableName(list []string) (string, string, error) {- switch len(list) {- case 2:- return list[0], list[1], nil- case 1:- return "", list[0], nil- case 0:- return "", "", nil- default:- return "", "", errors.Errorf("Invalid table name: %v", list)- }-}--// NormalizePostgreSQLAnyNameAsTableName normalizes the given any name as table name.-func NormalizePostgreSQLAnyNameAsTableName(ctx parser.IAny_nameContext) (string, string, error) {- if ctx == nil {- return "", "", nil- }-- list := NormalizePostgreSQLAnyName(ctx)- return normalizePostgreSQLStringListAsTableName(list)-}--// NormalizePostgreSQLAnyNameAsColumnName normalizes the given any name as column name.-func NormalizePostgreSQLAnyNameAsColumnName(ctx parser.IAny_nameContext) (string, string, string, error) {- if ctx == nil {- return "", "", "", nil- }-- list := NormalizePostgreSQLAnyName(ctx)-- switch len(list) {- case 3:- return list[0], list[1], list[2], nil- case 2:- return "", list[0], list[1], nil- case 1:- return "", "", list[0], nil- default:- return "", "", "", errors.Errorf("Invalid column name: %v", list)- }-}--// NormalizePostgreSQLQualifiedNameAsTableName normalizes the given qualified name as table name.-func NormalizePostgreSQLQualifiedNameAsTableName(ctx parser.IQualified_nameContext) (string, string, error) {- if ctx == nil {- return "", "", nil- }-- list := NormalizePostgreSQLQualifiedName(ctx)- return normalizePostgreSQLStringListAsTableName(list)-}-// ParsePostgreSQLStatement parses the given SQL and returns the AST tree.func NormalizePostgreSQLQualifiedName(ctx parser.IQualified_nameContext) []string {if ctx == nil {diff --git a/backend/plugin/parser/plsql/plsql.go b/backend/plugin/parser/plsql/plsql.goindex a7409b2e88..4f2f3d0c38 100644--- a/backend/plugin/parser/plsql/plsql.go+++ b/backend/plugin/parser/plsql/plsql.go@@ -225,14 +225,6 @@ func NormalizeTableName(tableName parser.ITable_nameContext) string {return NormalizeIdentifierContext(tableName.Identifier())}-func NormalizeGeneralElement(element parser.IGeneral_elementContext) []string {- var result []string- for _, child := range element.AllGeneral_element_part() {- result = append(result, NormalizeIDExpression(child.Id_expression()))- }- return result-}-// EquivalentType returns true if the given type is equivalent to the given text.func EquivalentType(tp parser.IDatatypeContext, text string) (bool, error) {tree, _, err := ParsePLSQL(fmt.Sprintf(`CREATE TABLE t(a %s);`, text))diff --git a/backend/plugin/parser/sql/ast/data_type.go b/backend/plugin/parser/sql/ast/data_type.goindex eca115c10e..2e4457da4b 100644--- a/backend/plugin/parser/sql/ast/data_type.go+++ b/backend/plugin/parser/sql/ast/data_type.go@@ -55,15 +55,12 @@ type UserDefinedType interface {DataTypeTypeName() *TypeNameDef- userDefinedTypeInterface()}type userDefinedType struct {dataType}-func (*userDefinedType) userDefinedTypeInterface() {}-// TypeName implements the UserDefinedType interface.func (*userDefinedType) TypeName() *TypeNameDef {return &TypeNameDef{}diff --git a/backend/plugin/parser/tidb/normalize.go b/backend/plugin/parser/tidb/normalize.goindex e5fa93716c..6518e6e52c 100644--- a/backend/plugin/parser/tidb/normalize.go+++ b/backend/plugin/parser/tidb/normalize.go@@ -1,73 +1,9 @@package tidbimport (- "strings"-parser "github.com/bytebase/tidb-parser")-// NormalizeTiDBTableName normalizes the given table name.-func NormalizeTiDBTableName(ctx parser.ITableNameContext) (string, string) {- if ctx.QualifiedIdentifier() != nil {- return normalizeTiDBQualifiedIdentifier(ctx.QualifiedIdentifier())- }- if ctx.DotIdentifier() != nil {- return "", NormalizeTiDBIdentifier(ctx.DotIdentifier().Identifier())- }- return "", ""-}--// NormalizeTiDBTableRef normalizes the given table reference.-func NormalizeTiDBTableRef(ctx parser.ITableRefContext) (string, string) {- if ctx.QualifiedIdentifier() != nil {- return normalizeTiDBQualifiedIdentifier(ctx.QualifiedIdentifier())- }- if ctx.DotIdentifier() != nil {- return "", NormalizeTiDBIdentifier(ctx.DotIdentifier().Identifier())- }- return "", ""-}--// NormalizeTiDBColumnName normalizes the given column name.-func NormalizeTiDBColumnName(ctx parser.IColumnNameContext) (string, string, string) {- if ctx.Identifier() != nil {- return "", "", NormalizeTiDBIdentifier(ctx.Identifier())- }- return NormalizeTiDBFieldIdentifier(ctx.FieldIdentifier())-}--// NormalizeTiDBFieldIdentifier normalizes the given field identifier.-func NormalizeTiDBFieldIdentifier(ctx parser.IFieldIdentifierContext) (string, string, string) {- list := []string{}- if ctx.QualifiedIdentifier() != nil {- id1, id2 := normalizeTiDBQualifiedIdentifier(ctx.QualifiedIdentifier())- list = append(list, id1, id2)- }-- if ctx.DotIdentifier() != nil {- list = append(list, NormalizeTiDBIdentifier(ctx.DotIdentifier().Identifier()))- }-- for len(list) < 3 {- list = append([]string{""}, list...)- }-- return list[0], list[1], list[2]-}--func normalizeTiDBQualifiedIdentifier(qualifiedIdentifier parser.IQualifiedIdentifierContext) (string, string) {- list := []string{NormalizeTiDBIdentifier(qualifiedIdentifier.Identifier())}- if qualifiedIdentifier.DotIdentifier() != nil {- list = append(list, NormalizeTiDBIdentifier(qualifiedIdentifier.DotIdentifier().Identifier()))- }-- if len(list) == 1 {- list = append([]string{""}, list...)- }-- return list[0], list[1]-}-// NormalizeTiDBIdentifier normalizes the given identifier.func NormalizeTiDBIdentifier(identifier parser.IIdentifierContext) string {if identifier.PureIdentifier() != nil {@@ -90,253 +26,3 @@ func NormalizeTiDBTextOrIdentifier(ctx parser.ITextOrIdentifierContext) string {// remove the quotations.return textString[1 : len(textString)-1]}--// NormalizeTiDBTextStringLiteral normalize the given TextStringLiteral.-func NormalizeTiDBTextLiteral(ctx parser.ITextLiteralContext) string {- textString := ctx.GetText()- // remove the quotations.- return textString[1 : len(textString)-1]-}--// NormalizeTiDBTextStringLiteral normalize the given TextStringLiteral.-func NormalizeTiDBTextStringLiteral(ctx parser.ITextStringLiteralContext) string {- textString := ctx.GetText()- // remove the quotations.- return textString[1 : len(textString)-1]-}--// NormalizeTiDBSignedStringLiteral normalize the given SignedLiteral.-func NormalizeTiDBSignedLiteral(ctx parser.ISignedLiteralContext) string {- textString := ctx.GetText()- if (strings.HasPrefix(textString, "'") && strings.HasSuffix(textString, "'")) || (strings.HasPrefix(textString, "\"") && strings.HasSuffix(textString, "\"")) {- textString = textString[1 : len(textString)-1]- }- return textString-}--// NormalizeTiDBSelectAlias normalizes the given select alias.-func NormalizeTiDBSelectAlias(selectAlias parser.ISelectAliasContext) string {- if selectAlias.Identifier() != nil {- return NormalizeTiDBIdentifier(selectAlias.Identifier())- }- textString := selectAlias.TextStringLiteral().GetText()- return textString[1 : len(textString)-1]-}--// NormalizeTiDBIdentifierList normalizes the given identifier list.-func NormalizeTiDBIdentifierList(ctx parser.IIdentifierListContext) []string {- var result []string- for _, identifier := range ctx.AllIdentifier() {- result = append(result, NormalizeTiDBIdentifier(identifier))- }- return result-}--// NormalizeTiDBViewName normalizes the given view name.-func NormalizeTiDBViewName(ctx parser.IViewNameContext) (string, string) {- if ctx.QualifiedIdentifier() != nil {- return normalizeTiDBQualifiedIdentifier(ctx.QualifiedIdentifier())- }- if ctx.DotIdentifier() != nil {- return "", NormalizeTiDBIdentifier(ctx.DotIdentifier().Identifier())- }- return "", ""-}--// NormalizeTiDBEventName normalizes the given event name.-func NormalizeTiDBEventName(ctx parser.IEventNameContext) (string, string) {- if ctx.QualifiedIdentifier() != nil {- return normalizeTiDBQualifiedIdentifier(ctx.QualifiedIdentifier())- }- return "", ""-}--// NormalizeTiDBTriggerName normalizes the given trigger name.-func NormalizeTiDBTriggerName(ctx parser.ITriggerNameContext) (string, string) {- if ctx.QualifiedIdentifier() != nil {- return normalizeTiDBQualifiedIdentifier(ctx.QualifiedIdentifier())- }- return "", ""-}--// NormalizeTiDBFunctionName normalizes the given function name.-func NormalizeTiDBFunctionName(ctx parser.IFunctionNameContext) (string, string) {- if ctx.QualifiedIdentifier() != nil {- return normalizeTiDBQualifiedIdentifier(ctx.QualifiedIdentifier())- }- return "", ""-}--// NormalizeTiDBProcedureName normalizes the given procedure name.-func NormalizeTiDBProcedureName(ctx parser.IProcedureNameContext) (string, string) {- if ctx.QualifiedIdentifier() != nil {- return normalizeTiDBQualifiedIdentifier(ctx.QualifiedIdentifier())- }- return "", ""-}--// NormalizeTiDBSchemaRef normalize the given schemaRef.-func NormalizeTiDBSchemaRef(ctx parser.ISchemaRefContext) string {- if ctx.Identifier() != nil {- return NormalizeTiDBIdentifier(ctx.Identifier())- }- return ""-}--// NormalizeTiDBSchemaRef normalize the given schemaName.-func NormalizeTiDBSchemaName(ctx parser.ISchemaNameContext) string {- if ctx.Identifier() != nil {- return NormalizeTiDBIdentifier(ctx.Identifier())- }- return ""-}--// NormalizeTiDBKeyListVariants normalize the given keyListVariants.-func NormalizeKeyListVariants(ctx parser.IKeyListVariantsContext) []string {- if ctx.KeyList() != nil {- return NormalizeKeyList(ctx.KeyList())- }- if ctx.KeyListWithExpression() != nil {- return NormalizeKeyListWithExpression(ctx.KeyListWithExpression())- }- return nil-}--// NormalizeTiDBKeyList normalize the given keyList.-func NormalizeKeyList(ctx parser.IKeyListContext) []string {- var result []string- for _, key := range ctx.AllKeyPart() {- keyText := NormalizeTiDBIdentifier(key.Identifier())- result = append(result, keyText)- }- return result-}--// NormalizeTiDBKeyListWithExpression normalize the given keyListWithExpression.-func NormalizeKeyListWithExpression(ctx parser.IKeyListWithExpressionContext) []string {- var result []string- for _, key := range ctx.AllKeyPartOrExpression() {- if key.KeyPart() != nil {- keyText := NormalizeTiDBIdentifier(key.KeyPart().Identifier())- result = append(result, keyText)- } else if key.ExprWithParentheses() != nil {- keyText := key.GetParser().GetTokenStream().GetTextFromRuleContext(key.ExprWithParentheses())- result = append(result, keyText)- }- }- return result-}--// NormalizeTiDBIndexName normalize the given IndexName.-func NormalizeIndexName(ctx parser.IIndexNameContext) string {- if ctx.Identifier() != nil {- return NormalizeTiDBIdentifier(ctx.Identifier())- }- return ""-}--// NormalizeTiDBIndexName normalize the given IndeRef.-func NormalizeIndexRef(ctx parser.IIndexRefContext) (string, string, string) {- if ctx.FieldIdentifier() != nil {- return NormalizeTiDBFieldIdentifier(ctx.FieldIdentifier())- }- return "", "", ""-}--// NormalizeTiDBIdentifierListWithParentheses normalize the given IdentififerListWithparentheses.-func NormalizeIdentifierListWithParentheses(ctx parser.IIdentifierListWithParenthesesContext) []string {- if ctx.IdentifierList() != nil {- return NormalizeTiDBIdentifierList(ctx.IdentifierList())- }- return nil-}--// NormalizeTiDBConstraintName normalize the given IConstraintName.-func NormalizeConstraintName(ctx parser.IConstraintNameContext) string {- if ctx.Identifier() != nil {- return NormalizeTiDBIdentifier(ctx.Identifier())- }- return ""-}--// NormalizeTiDBColumnInternalRef noamalizes the given columnInternalRef.-func NormalizeTiDBColumnInternalRef(ctx parser.IColumnInternalRefContext) string {- if ctx.Identifier() != nil {- return NormalizeTiDBIdentifier(ctx.Identifier())- }- return ""-}--// NormalizeTiDBCharsetName noamalizes the given charset name.-func NormalizeTiDBCharsetName(ctx parser.ICharsetNameContext) string {- switch {- case ctx.TextOrIdentifier() != nil:- return NormalizeTiDBTextOrIdentifier(ctx.TextOrIdentifier())- case ctx.DEFAULT_SYMBOL() != nil:- return "DEFAULT"- case ctx.BINARY_SYMBOL() != nil:- return "BINARY"- }- return ""-}--// NormalizeTiDBCollationName noamalizes the given collation name.-func NormalizeTiDBCollationName(ctx parser.ICollationNameContext) string {- switch {- case ctx.TextOrIdentifier() != nil:- return NormalizeTiDBTextOrIdentifier(ctx.TextOrIdentifier())- case ctx.DEFAULT_SYMBOL() != nil:- return "DEFAULT"- case ctx.BINARY_SYMBOL() != nil:- return "BINARY"- }- return ""-}--// NormalizeTiDBDataType noamalizes the given dataType.-// campact for tidb parser compatibility.-// eg: varchar(5).-// compact is true, return varchar.-// compact is false, return varchar(5).-func NormalizeTiDBDataType(ctx parser.IDataTypeContext, compact bool) string {- if !compact {- return ctx.GetParser().GetTokenStream().GetTextFromRuleContext(ctx)- }- switch ctx.GetType_().GetTokenType() {- case parser.TiDBParserDOUBLE_SYMBOL:- if ctx.PRECISION_SYMBOL() != nil {- return "double precision"- }- return "double"- case parser.TiDBParserCHAR_SYMBOL:- if ctx.VARYING_SYMBOL() != nil {- return "char varying"- }- return "char"- default:- return strings.ToLower(ctx.GetType_().GetText())- }-}--// GetCharSetName get charset name from DataTypeContext.-func GetCharSetName(ctx parser.IDataTypeContext) string {- if ctx.CharsetWithOptBinary() == nil {- return ""- }- charset := NormalizeTiDBCharsetName(ctx.CharsetWithOptBinary().CharsetName())- return charset-}--// IsTimeType check if the dataType is time type.-func IsTimeType(ctx parser.IDataTypeContext) bool {- if ctx.GetType_() == nil {- return false- }-- switch ctx.GetType_().GetTokenType() {- case parser.TiDBParserDATETIME_SYMBOL, parser.TiDBParserTIMESTAMP_SYMBOL:- return true- default:- return false- }-}diff --git a/backend/plugin/parser/tidb/split.go b/backend/plugin/parser/tidb/split.goindex 57c0b87c25..8330b8391d 100644--- a/backend/plugin/parser/tidb/split.go+++ b/backend/plugin/parser/tidb/split.go@@ -24,17 +24,6 @@ func SplitSQL(statement string) ([]base.SingleSQL, error) {return list, nil}-// SplitSQLKeepEmptyBlocks splits the given SQL statement into multiple SQL statements.-// TODO: remove SplitSQL, and rename this to SplitSQL.-func SplitSQLKeepEmptyBlocks(statement string) ([]base.SingleSQL, error) {- t := tokenizer.NewTokenizer(statement, tokenizer.KeepEmptyBlocks())- list, err := t.SplitTiDBMultiSQL()- if err != nil {- return nil, err- }- return list, nil-}-func hasDelimiterStatement(stream *antlr.CommonTokenStream) bool {tokens := stream.GetAllTokens()for _, token := range tokens {diff --git a/backend/plugin/parser/tidb/util.go b/backend/plugin/parser/tidb/util.goindex 20ec45b45e..2f283a6a84 100644--- a/backend/plugin/parser/tidb/util.go+++ b/backend/plugin/parser/tidb/util.go@@ -1,8 +1,6 @@package tidbimport (- "fmt"-tidbast "github.com/pingcap/tidb/pkg/parser/ast")@@ -31,24 +29,3 @@ func extractFieldName(in *tidbast.SelectField) string {}return ""}--type PartitionDefaultNameGenerator struct {- parentName string- count int-}--func NewPartitionDefaultNameGenerator(parentName string) *PartitionDefaultNameGenerator {- return &PartitionDefaultNameGenerator{- parentName: parentName,- count: -1,- }-}--func (g *PartitionDefaultNameGenerator) Next() string {- g.count++-- if g.parentName == "" {- return fmt.Sprintf("p%d", g.count)- }- return fmt.Sprintf("%ssp%d", g.parentName, g.count)-}diff --git a/backend/plugin/parser/tokenizer/tokenizer.go b/backend/plugin/parser/tokenizer/tokenizer.goindex de606938c9..c469e4efc5 100644--- a/backend/plugin/parser/tokenizer/tokenizer.go+++ b/backend/plugin/parser/tokenizer/tokenizer.go@@ -108,17 +108,6 @@ func NewTokenizer(statement string, options ...Option) *Tokenizer {return t}-func NewStreamTokenizer(src io.Reader, f func(string) error) *Tokenizer {- t := &Tokenizer{- cursor: 0,- line: 1,- reader: bufio.NewReader(src),- f: f,- }- t.scan()- return t-}-func (t *Tokenizer) SetLineForMySQLCreateTableStmt(node *tidbast.CreateTableStmt, firstLine int) error {// We assume that the parser will parse the columns and table constraints according to the order of the raw SQL statements// and the identifiers don't equal any keywords in CREATE TABLE statements.diff --git a/backend/plugin/parser/tsql/batch/batch.go b/backend/plugin/parser/tsql/batch/batch.goindex f1ca287bbc..fa10088f56 100644--- a/backend/plugin/parser/tsql/batch/batch.go+++ b/backend/plugin/parser/tsql/batch/batch.go@@ -19,16 +19,10 @@ const ()type Command interface {- // isCommand is a dummy method to prevent users from implementing the Command interface.- isCommand()// String returns the string representation of the command.String() string}-type baseCommand struct{}--func (*baseCommand) isCommand() {}-var (// lineEnd is the slice to use when appending a line.lineEnd = []rune("\n")@@ -45,7 +39,6 @@ var (// GoCommand signals the end of a batch of Transact-SQL statements to the SQL Server Utilities.// https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-go?view=sql-server-ver16type GoCommand struct {- baseCommand// Count is a positive integer, the batch preceding the GO command will execute the specified number of times.// The default value of Count is 1.Count uintdiff --git a/backend/runner/utils/sdl_utils.go b/backend/runner/utils/sdl_utils.godeleted file mode 100644index 670c8048d5..0000000000--- a/backend/runner/utils/sdl_utils.go+++ /dev/null@@ -1,70 +0,0 @@-// Package utils is the package for runner utils.-package utils--import (- "bytes"- "context"-- "github.com/pkg/errors"-- "github.com/bytebase/bytebase/backend/component/dbfactory"-- "github.com/bytebase/bytebase/backend/plugin/db"- "github.com/bytebase/bytebase/backend/plugin/parser/base"- "github.com/bytebase/bytebase/backend/plugin/parser/sql/transform"- "github.com/bytebase/bytebase/backend/store"- storepb "github.com/bytebase/bytebase/proto/generated-go/store"-)--// ComputeDatabaseSchemaDiff computes the diff between current database schema-// and the given schema. It returns an empty string if there is no applicable-// diff.-func ComputeDatabaseSchemaDiff(ctx context.Context, instance *store.InstanceMessage, database *store.DatabaseMessage, dbFactory *dbfactory.DBFactory, newSchema string) (string, error) {- driver, err := dbFactory.GetAdminDatabaseDriver(ctx, instance, database, db.ConnectionContext{})- if err != nil {- return "", errors.Wrap(err, "get admin driver")- }- defer func() {- _ = driver.Close(ctx)- }()-- // Use new driver to sync the schema to avoid the session state change, such as SET ROLE in PostgreSQL.- syncDriver, err := dbFactory.GetAdminDatabaseDriver(ctx, instance, database, db.ConnectionContext{})- if err != nil {- return "", errors.Wrap(err, "get sync driver")- }- defer syncDriver.Close(ctx)- dbSchema, err := syncDriver.SyncDBSchema(ctx)- if err != nil {- return "", errors.Wrap(err, "sync database schema")- }-- var schema bytes.Buffer- err = driver.Dump(ctx, &schema, dbSchema)- if err != nil {- return "", errors.Wrap(err, "dump old schema")- }-- var engine storepb.Engine- switch instance.Metadata.GetEngine() {- case storepb.Engine_POSTGRES, storepb.Engine_RISINGWAVE:- engine = storepb.Engine_POSTGRES- case storepb.Engine_MYSQL, storepb.Engine_TIDB, storepb.Engine_MARIADB, storepb.Engine_OCEANBASE:- engine = storepb.Engine_MYSQL- default:- return "", errors.Errorf("unsupported database engine %q", instance.Metadata.GetEngine())- }-- sdlFormat, err := transform.SchemaTransform(engine, schema.String())- if err != nil {- return "", errors.Wrapf(err, "failed to transform SDL format")- }- diff, err := base.SchemaDiff(engine, base.DiffContext{- IgnoreCaseSensitive: !store.IsObjectCaseSensitive(instance),- StrictMode: true,- }, sdlFormat, newSchema)- if err != nil {- return "", errors.Wrapf(err, "compute schema diff")- }- return diff, nil-}diff --git a/backend/store/stats.go b/backend/store/stats.goindex e3b271791e..b32ba333cb 100644--- a/backend/store/stats.go+++ b/backend/store/stats.go@@ -187,79 +187,3 @@ func (s *Store) CountInstanceGroupByEngineAndEnvironmentID(ctx context.Context)}return res, nil}--// CountTaskGroupByTypeAndStatus counts the number of TaskGroup and group by TaskType.-// Used for the metric collector.-func (s *Store) CountTaskGroupByTypeAndStatus(ctx context.Context) ([]*metric.TaskCountMetric, error) {- tx, err := s.db.BeginTx(ctx, nil)- if err != nil {- return nil, err- }- defer tx.Rollback()-- rows, err := tx.QueryContext(ctx, `- SELECT type, status, COUNT(*)- FROM task- WHERE id > 102- GROUP BY type, status`,- )- if err != nil {- return nil, err- }- defer rows.Close()-- var res []*metric.TaskCountMetric- for rows.Next() {- var metric metric.TaskCountMetric- if err := rows.Scan(&metric.Type, &metric.Status, &metric.Count); err != nil {- return nil, err- }- res = append(res, &metric)- }- if err := rows.Err(); err != nil {- return nil, err- }- if err := tx.Commit(); err != nil {- return nil, err- }- return res, nil-}--// CountSheetGroupByRowstatusVisibilitySourceAndType counts the number of sheets group by visibility, source and type.-// Used by the metric collector.-func (s *Store) CountSheetGroupByRowstatusVisibilitySourceAndType(ctx context.Context) ([]*metric.SheetCountMetric, error) {- tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})- if err != nil {- return nil, err- }- defer tx.Rollback()-- rows, err := tx.QueryContext(ctx, `- SELECT visibility, COUNT(*) AS count- FROM worksheet- GROUP BY visibility`)- if err != nil {- return nil, err- }- defer rows.Close()-- var res []*metric.SheetCountMetric- for rows.Next() {- var sheetCount metric.SheetCountMetric- if err := rows.Scan(- &sheetCount.Visibility,- &sheetCount.Count,- ); err != nil {- return nil, err- }- res = append(res, &sheetCount)- }- if err := rows.Err(); err != nil {- return nil, err- }- if err := tx.Commit(); err != nil {- return nil, err- }-- return res, nil-}diff --git a/backend/utils/utils.go b/backend/utils/utils.goindex 7d1d3cb0eb..2ad58e081e 100644--- a/backend/utils/utils.go+++ b/backend/utils/utils.go@@ -4,7 +4,6 @@ package utilsimport ("context""fmt"- "io""reflect""regexp""strconv"@@ -12,11 +11,6 @@ import ("unicode""github.com/pkg/errors"- "golang.org/x/text/encoding"- "golang.org/x/text/encoding/charmap"- "golang.org/x/text/encoding/simplifiedchinese"- textunicode "golang.org/x/text/encoding/unicode"- "golang.org/x/text/transform""google.golang.org/genproto/googleapis/type/expr""google.golang.org/grpc/codes""google.golang.org/grpc/status"@@ -283,30 +277,6 @@ func Uniq[T comparable](array []T) []T {return res}-// ConvertBytesToUTF8String tries to decode a byte slice into a UTF-8 string using common encodings.-func ConvertBytesToUTF8String(data []byte) (string, error) {- encodings := []encoding.Encoding{- textunicode.UTF8,- simplifiedchinese.GBK,- textunicode.UTF16(textunicode.LittleEndian, textunicode.UseBOM),- textunicode.UTF16(textunicode.BigEndian, textunicode.UseBOM),- charmap.ISO8859_1,- }-- for _, enc := range encodings {- reader := transform.NewReader(strings.NewReader(string(data)), enc.NewDecoder())- decoded, err := io.ReadAll(reader)- if err == nil && isUtf8(decoded) {- return string(decoded), nil- }- }- return "", errors.New("failed to decode the byte slice into a UTF-8 string")-}--func isUtf8(data []byte) bool {- return !strings.Contains(string(data), string(unicode.ReplacementChar))-}-// IsSpaceOrSemicolon checks if the rune is a space or a semicolon.func IsSpaceOrSemicolon(r rune) bool {if ok := unicode.IsSpace(r); ok {diff --git a/backend/utils/utils_test.go b/backend/utils/utils_test.goindex fe568b233e..b5e69cbef5 100644--- a/backend/utils/utils_test.go+++ b/backend/utils/utils_test.go@@ -63,41 +63,6 @@ func TestGetRenderedStatement(t *testing.T) {}}-func TestConvertBytesToUTF8String(t *testing.T) {- tests := []struct {- input []byte- expected string- }{- {- input: []byte{},- expected: "",- },- {- input: []byte("hello"),- expected: "hello",- },- {- input: []byte("你好"),- expected: "你好",- },- {- input: []byte("Hello 世界 😊"),- expected: "Hello 世界 😊",- },- {- // string: SELECT "�ݱ�˼"- input: []byte{83, 69, 76, 69, 67, 84, 32, 34, 176, 221, 177, 180, 203, 188, 34},- expected: "SELECT \"拜贝思\"",- },- }-- for _, test := range tests {- actual, err := ConvertBytesToUTF8String(test.input)- assert.NoError(t, err)- assert.Equal(t, test.expected, actual)- }-}-func TestCheckDatabaseGroupMatch(t *testing.T) {tests := []struct {expression string