services

package
v1.0.10 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 3, 2026 License: GPL-3.0 Imports: 11 Imported by: 0

README

Services 包

这个包提供了 SQL Advisor 工具的核心服务功能,可以被外部 Go 程序引用。

背景

之前这些功能位于 cmd/advisor/internal 包中,由于 Go 语言的 internal 包机制,外部程序无法引用,会报错:

use of internal package advisorTool/cmd/advisor/internal not allowed

现在已迁移到 services 包,可以被任何外部程序正常引用。

功能模块

1. 规则配置 (config.go)

提供 SQL 审核规则的加载和管理功能:

  • LoadRules(configFile, engineType, hasMetadata) - 从配置文件或默认规则加载审核规则
  • GetDefaultRules(engineType, hasMetadata) - 获取指定数据库引擎的默认规则
  • GenerateSampleConfig(engineType) - 生成示例配置文件
2. 结果处理 (result.go)

提供审核结果的转换和处理:

  • ConvertToReviewResults() - 将审核响应转换为 Inception 兼容格式
  • CalculateAffectedRowsForStatements() - 计算 SQL 语句的影响行数
  • SplitSQL() - 分割多条 SQL 语句
  • DBConnectionParams - 数据库连接参数结构
3. 输出格式化 (output.go)

提供多种输出格式支持:

  • OutputResults() - 输出审核结果(支持 JSON 和表格格式)
  • ListAvailableRules() - 列出所有可用的审核规则
4. 元数据获取 (metadata.go)

提供数据库元数据获取功能:

  • FetchDatabaseMetadata() - 从数据库获取 schema 元数据

使用示例

基础用法
package main

import (
    "context"
    "fmt"
    "log"
    
    "advisorTool/pkg/advisor"
    "advisorTool/services"
)

func main() {
    // 1. 加载规则
    rules, err := services.LoadRules("", advisor.EngineMySQL, false)
    if err != nil {
        log.Fatal(err)
    }
    
    // 2. 创建审核请求
    req := &advisor.ReviewRequest{
        Engine:          advisor.EngineMySQL,
        Statement:       "SELECT * FROM users",
        CurrentDatabase: "mydb",
        Rules:           rules,
    }
    
    // 3. 执行审核
    resp, err := advisor.SQLReviewCheck(context.Background(), req)
    if err != nil {
        log.Fatal(err)
    }
    
    // 4. 输出结果
    err = services.OutputResults(resp, req.Statement, req.Engine, "json", nil)
    if err != nil {
        log.Fatal(err)
    }
}
带数据库连接的高级用法
// 设置数据库连接参数
dbParams := &services.DBConnectionParams{
    Host:     "localhost",
    Port:     3306,
    User:     "root",
    Password: "password",
    DbName:   "mydb",
    Charset:  "utf8mb4",
    Timeout:  10,
}

// 获取数据库元数据
metadata, err := services.FetchDatabaseMetadata(advisor.EngineMySQL, dbParams)
if err != nil {
    log.Printf("Warning: %v", err)
} else {
    req.DBSchema = metadata
}

// 执行审核(会包含需要元数据的规则)
resp, err := advisor.SQLReviewCheck(context.Background(), req)
自定义结果处理
// 转换为结构化结果
affectedRowsMap := services.CalculateAffectedRowsForStatements(
    sql, 
    engineType, 
    dbParams,
)

results := services.ConvertToReviewResults(
    resp, 
    sql, 
    engineType, 
    affectedRowsMap,
)

// 自定义处理结果
for _, result := range results {
    if result.ErrorLevel == "2" {
        fmt.Printf("错误: %s\n", result.ErrorMessage)
    }
}

完整示例

参考项目中的示例文件:

  • examples/external_usage_example.go - 外部程序使用示例
  • examples/postgres_library_example.go - PostgreSQL 完整示例
  • cmd/advisor/main.go - CLI 工具实现

支持的数据库

  • MySQL / MariaDB
  • PostgreSQL
  • TiDB
  • OceanBase
  • Oracle
  • SQL Server (MSSQL)
  • Snowflake

输出格式

JSON 格式
[
  {
    "order_id": 1,
    "stage": "CHECKED",
    "error_level": "1",
    "stage_status": "Audit Completed",
    "error_message": "[rule-type] message",
    "sql": "SELECT * FROM users",
    "affected_rows": 0,
    "sequence": "0_0_00000000"
  }
]
表格格式

使用 go-pretty 库输出美观的表格,包含颜色标识和统计信息。

注意事项

  1. 某些规则需要数据库元数据才能运行(如向后兼容性检查)
  2. 计算影响行数功能需要提供有效的数据库连接
  3. 不同数据库引擎支持的规则集不同
  4. 默认规则集已针对各数据库引擎优化

迁移说明

如果你的代码之前使用了 cmd/advisor/internal 包:

旧的导入:

import "advisorTool/cmd/advisor/internal"

新的导入:

import "advisorTool/services"

所有 API 保持不变,只需更改导入路径即可。

Documentation

Overview

Package services provides utilities for the advisor tool that can be imported by external programs.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CalculateAffectedRowsForStatements

func CalculateAffectedRowsForStatements(statement string, engineType advisor.Engine, dbParams *DBConnectionParams) map[int]*AffectedRowsInfo

CalculateAffectedRowsForStatements calculates affected rows for all SQL statements. Returns a map of SQL index to AffectedRowsInfo (count and error).

func FetchDatabaseMetadata

func FetchDatabaseMetadata(engineType advisor.Engine, dbParams *DBConnectionParams) (*advisor.DatabaseSchemaMetadata, error)

FetchDatabaseMetadata fetches database schema metadata from the connected database.

func GenerateSampleConfig

func GenerateSampleConfig(engineType advisor.Engine) string

GenerateSampleConfig generates a sample configuration file for the specified engine.

func GetDbTypeString

func GetDbTypeString(engineType advisor.Engine) string

GetDbTypeString converts Engine type to database type string.

func GetDefaultRules

func GetDefaultRules(engineType advisor.Engine, hasMetadata bool) []*advisor.SQLReviewRule

GetDefaultRules returns default rules based on engine type and whether metadata is available. hasMetadata indicates if database metadata is provided (some rules require it).

func ListAvailableRules

func ListAvailableRules()

ListAvailableRules lists all available SQL review rules.

func LoadRules

func LoadRules(configFile string, engineType advisor.Engine, hasMetadata bool) ([]*advisor.SQLReviewRule, error)

LoadRules loads SQL review rules from a config file or returns default rules.

func OutputResults

func OutputResults(resp *advisor.ReviewResponse, statement string, engineType advisor.Engine, format string, dbParams *DBConnectionParams) error

OutputResults outputs the review results in the specified format.

func SplitSQL

func SplitSQL(statement string) []string

SplitSQL splits SQL statements by semicolon.

Types

type AffectedRowsInfo added in v1.0.8

type AffectedRowsInfo struct {
	Count int
	Error string
}

AffectedRowsInfo holds the count and error information for affected rows calculation.

type DBConnectionParams

type DBConnectionParams struct {
	Host        string
	Port        int
	User        string
	Password    string
	DbName      string
	Charset     string
	ServiceName string
	Sid         string
	SSLMode     string
	Timeout     int
	Schema      string
}

DBConnectionParams holds database connection parameters.

type ReviewConfig

type ReviewConfig struct {
	Name  string             `json:"name" yaml:"name"`
	Rules []*ReviewRuleEntry `json:"rules" yaml:"rules"`
}

ReviewConfig represents a review configuration file.

type ReviewResult

type ReviewResult struct {
	OrderID      int    `json:"order_id"`
	Stage        string `json:"stage"`
	ErrorLevel   string `json:"error_level"`
	StageStatus  string `json:"stage_status"`
	ErrorMessage string `json:"error_message"`
	SQL          string `json:"sql"`
	AffectedRows int    `json:"affected_rows"`
	Sequence     string `json:"sequence"`
	BackupDBName string `json:"backup_dbname"`
	ExecuteTime  string `json:"execute_time"`
	SQLSha1      string `json:"sqlsha1"`
	BackupTime   string `json:"backup_time"`
}

ReviewResult represents the review result in Inception-compatible format.

func ConvertToReviewResults

func ConvertToReviewResults(resp *advisor.ReviewResponse, statement string, engineType advisor.Engine, affectedRowsMap map[int]*AffectedRowsInfo) []ReviewResult

ConvertToReviewResults converts advisor response to Inception-compatible format.

type ReviewRuleEntry

type ReviewRuleEntry struct {
	Type    string `json:"type" yaml:"type"`
	Level   string `json:"level" yaml:"level"`
	Payload string `json:"payload,omitempty" yaml:"payload,omitempty"`
	Engine  string `json:"engine,omitempty" yaml:"engine,omitempty"`
	Comment string `json:"comment,omitempty" yaml:"comment,omitempty"`
}

ReviewRuleEntry represents a single rule entry in the config file.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL