-
Notifications
You must be signed in to change notification settings - Fork 214
Feat/multi format audit report export #3238
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
LordofAvernus
wants to merge
14
commits into
main
Choose a base branch
from
feat/multi-format-audit-report-export
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 8 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
0d80d29
feat(utils): add report export format enums, data models, and generat…
LordofAvernus 768df70
feat(utils): implement CSV report generator with unit tests
LordofAvernus 47500f7
feat(utils): implement HTML report generator with template and unit t…
LordofAvernus 19ac482
feat(utils): implement CE format dispatch for ExportAuditReport
LordofAvernus 6eb0a3c
feat(api): refactor DownloadTaskSQLReportFile to support multi-format…
LordofAvernus b490691
docs(swagger): add export_format query parameter to sql_report endpoint
LordofAvernus a01d8a0
fix(report): fix BUG-001,003,005,007 in multi-format export (CE part)
LordofAvernus 8f6d839
fix(utils): return error for unsupported export format instead of CSV…
LordofAvernus 2d973a0
refactor(auditreport): move report export to server and apply review …
LordofAvernus 0fc0407
refactor(report): optimize SQL list initialization in BuildAuditRepor…
LordofAvernus 52697f8
feat(auditreport): move report ExportFormat to server layer
LordofAvernus e76654f
fix(report): unify report timestamps and simplify level distribution
LordofAvernus 502ad1a
docs(api): add export_format enum for sql_report endpoint
LordofAvernus 2c3d81f
ci: update checkout, setup-go and golangci-lint-action
LordofAvernus File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,241 @@ | ||
| package v1 | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "sort" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/actiontech/sqle/sqle/locale" | ||
| "github.com/actiontech/sqle/sqle/model" | ||
| "github.com/actiontech/sqle/sqle/server" | ||
| "github.com/actiontech/sqle/sqle/utils" | ||
| ) | ||
|
|
||
| // BuildAuditReportData 从 Task 和数据库查询构建报告数据。 | ||
| // 该函数放在 controller 层而非 utils 层,因为 utils 被 model 引用, | ||
| // 若 utils 反向引用 model 会产生循环依赖。 | ||
| func BuildAuditReportData(task *model.Task, s *model.Storage, noDuplicate bool, ctx context.Context) (*utils.AuditReportData, error) { | ||
| // 1. 获取 SQL 列表 | ||
| data := map[string]interface{}{ | ||
| "task_id": fmt.Sprintf("%d", task.ID), | ||
| "no_duplicate": noDuplicate, | ||
| } | ||
|
|
||
| taskSQLsDetail, _, err := s.GetTaskSQLsByReq(data) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("get task SQLs failed: %w", err) | ||
| } | ||
|
|
||
| // 2. 获取回滚 SQL 映射 | ||
| rollbackSqlMap, err := server.BackupService{}.GetRollbackSqlsMap(task.ID) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("get rollback SQLs failed: %w", err) | ||
| } | ||
|
|
||
| // 3. 构建 SQL 列表和统计数据 | ||
| levelDist := make(map[string]int) | ||
| ruleHits := make(map[string]int) | ||
| var sqlList []utils.AuditSQLItem | ||
| var problemSQLs []utils.AuditSQLItem | ||
|
|
||
| for _, td := range taskSQLsDetail { | ||
| // 构造临时 ExecuteSQL 对象以复用状态描述方法 | ||
| tempSQL := &model.ExecuteSQL{ | ||
| AuditResults: td.AuditResults, | ||
| AuditStatus: td.AuditStatus, | ||
| } | ||
| tempSQL.ExecStatus = td.ExecStatus | ||
|
|
||
| // 提取规则名称和审核建议 | ||
| ruleName, suggestion := extractRuleInfo(td.AuditResults, ctx) | ||
|
|
||
| item := utils.AuditSQLItem{ | ||
| Number: td.Number, | ||
| SQL: td.ExecSQL, | ||
| AuditLevel: td.AuditLevel, | ||
| AuditStatus: tempSQL.GetAuditStatusDesc(ctx), | ||
| AuditResult: tempSQL.GetAuditResultDesc(ctx), | ||
| ExecStatus: tempSQL.GetExecStatusDesc(ctx), | ||
| ExecResult: td.ExecResult, | ||
| RollbackSQL: strings.Join(rollbackSqlMap[td.Id], "\n"), | ||
| Description: td.Description, | ||
| RuleName: ruleName, | ||
| Suggestion: suggestion, | ||
| } | ||
| sqlList = append(sqlList, item) | ||
|
|
||
| // 统计等级分布 | ||
| level := td.AuditLevel | ||
| if level == "" { | ||
| level = "normal" | ||
| } | ||
| levelDist[level]++ | ||
|
|
||
| // 区分问题 SQL(AuditLevel 不是 normal 且不为空) | ||
| if level != "normal" { | ||
| problemSQLs = append(problemSQLs, item) | ||
| } | ||
|
|
||
| // 统计规则命中 | ||
| for _, ar := range td.AuditResults { | ||
| if ar.RuleName != "" { | ||
| ruleHits[ar.RuleName]++ | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // 4. 构建国际化标签(当前使用 locale 包提供的 i18n 标签) | ||
| labels := buildReportLabels(ctx) | ||
|
|
||
| // 5. 构建审核时间 | ||
| auditTime := time.Now().Format("2006-01-02 15:04:05") | ||
| if task.CreatedAt.Year() > 1 { | ||
| auditTime = task.CreatedAt.Format("2006-01-02 15:04:05") | ||
| } | ||
|
|
||
| instanceName := task.InstanceName() | ||
| if instanceName == "" { | ||
| instanceName = "unknown" | ||
| } | ||
|
|
||
| return &utils.AuditReportData{ | ||
| TaskID: uint64(task.ID), | ||
| Title: locale.Bundle.LocalizeMsgByCtx(ctx, locale.ReportLabelTitle), | ||
| InstanceName: instanceName, | ||
| Schema: task.Schema, | ||
| GeneratedAt: time.Now(), | ||
| Lang: locale.Bundle.GetLangTagFromCtx(ctx).String(), | ||
| LogoBase64: "", | ||
| Summary: utils.AuditSummary{ | ||
| AuditTime: auditTime, | ||
| InstanceName: instanceName, | ||
| Schema: task.Schema, | ||
| TotalSQL: len(sqlList), | ||
| PassRate: task.PassRate * 100, | ||
| Score: task.Score, | ||
| AuditLevel: task.AuditLevel, | ||
| }, | ||
| Statistics: utils.AuditStatistics{ | ||
| LevelDistribution: toLevelCounts(levelDist), | ||
| RuleHits: toRuleHits(ruleHits), | ||
| }, | ||
| SQLList: sqlList, | ||
| ProblemSQLs: problemSQLs, | ||
| Labels: labels, | ||
| }, nil | ||
| } | ||
|
|
||
| // extractRuleInfo 从审核结果中提取规则名称和审核建议。 | ||
| // 如果有多条规则命中,使用逗号分隔拼接。 | ||
| func extractRuleInfo(auditResults model.AuditResults, ctx context.Context) (ruleName string, suggestion string) { | ||
| if len(auditResults) == 0 { | ||
| return "", "" | ||
| } | ||
|
|
||
| lang := locale.Bundle.GetLangTagFromCtx(ctx) | ||
| var ruleNames []string | ||
| var suggestions []string | ||
|
|
||
| for _, ar := range auditResults { | ||
| if ar.RuleName != "" { | ||
| ruleNames = append(ruleNames, ar.RuleName) | ||
| } | ||
| msg := ar.GetAuditMsgByLangTag(lang) | ||
| if msg != "" { | ||
| suggestions = append(suggestions, msg) | ||
| } | ||
| } | ||
|
|
||
| return strings.Join(ruleNames, ", "), strings.Join(suggestions, "; ") | ||
| } | ||
|
|
||
| // toLevelCounts 将等级分布 map 转换为有序的 LevelCount 切片。 | ||
| // 按 error > warn > notice > normal 顺序排列。 | ||
| func toLevelCounts(dist map[string]int) []utils.LevelCount { | ||
| if len(dist) == 0 { | ||
| return []utils.LevelCount{} | ||
| } | ||
|
|
||
| levelOrder := map[string]int{ | ||
| "error": 0, | ||
| "warn": 1, | ||
| "notice": 2, | ||
| "normal": 3, | ||
| } | ||
|
|
||
| result := make([]utils.LevelCount, 0, len(dist)) | ||
| for level, count := range dist { | ||
| result = append(result, utils.LevelCount{ | ||
| Level: level, | ||
| Count: count, | ||
| }) | ||
| } | ||
|
|
||
| sort.Slice(result, func(i, j int) bool { | ||
| oi, ok := levelOrder[result[i].Level] | ||
| if !ok { | ||
| oi = 99 | ||
| } | ||
| oj, ok := levelOrder[result[j].Level] | ||
| if !ok { | ||
| oj = 99 | ||
| } | ||
| return oi < oj | ||
| }) | ||
|
|
||
| return result | ||
| } | ||
|
|
||
| // toRuleHits 将规则命中 map 转换为按命中次数降序排列的 RuleHit 切片。 | ||
| func toRuleHits(hits map[string]int) []utils.RuleHit { | ||
| if len(hits) == 0 { | ||
| return []utils.RuleHit{} | ||
| } | ||
|
|
||
| result := make([]utils.RuleHit, 0, len(hits)) | ||
| for name, count := range hits { | ||
| result = append(result, utils.RuleHit{ | ||
| RuleName: name, | ||
| HitCount: count, | ||
| }) | ||
| } | ||
|
|
||
| sort.Slice(result, func(i, j int) bool { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 这里排序是合理的,在界面上规则顺序保持一致,提高影响用户体验 |
||
| return result[i].HitCount > result[j].HitCount | ||
| }) | ||
|
|
||
| return result | ||
| } | ||
|
|
||
| // buildReportLabels 构建报告中使用的国际化标签。 | ||
| // 当前版本使用 locale 包已有的国际化消息和硬编码中文标签, | ||
| // 后续阶段 8 将接入 go-i18n 框架实现完整国际化。 | ||
| func buildReportLabels(ctx context.Context) utils.ReportLabels { | ||
| return utils.ReportLabels{ | ||
| AuditSummary: locale.Bundle.LocalizeMsgByCtx(ctx, locale.ReportLabelAuditSummary), | ||
| ResultStatistics: locale.Bundle.LocalizeMsgByCtx(ctx, locale.ReportLabelResultStatistics), | ||
| ProblemSQLList: locale.Bundle.LocalizeMsgByCtx(ctx, locale.ReportLabelProblemSQLList), | ||
| RuleHitStatistics: locale.Bundle.LocalizeMsgByCtx(ctx, locale.ReportLabelRuleHitStatistics), | ||
| AuditTime: locale.Bundle.LocalizeMsgByCtx(ctx, locale.ReportLabelAuditTime), | ||
| DataSource: locale.Bundle.LocalizeMsgByCtx(ctx, locale.ReportLabelDataSource), | ||
| Schema: locale.Bundle.LocalizeMsgByCtx(ctx, locale.ReportLabelSchema), | ||
| TotalSQL: locale.Bundle.LocalizeMsgByCtx(ctx, locale.ReportLabelTotalSQL), | ||
| PassRate: locale.Bundle.LocalizeMsgByCtx(ctx, locale.ReportLabelPassRate), | ||
| Score: locale.Bundle.LocalizeMsgByCtx(ctx, locale.ReportLabelScore), | ||
| AuditLevel: locale.Bundle.LocalizeMsgByCtx(ctx, locale.ReportLabelAuditLevel), | ||
| Number: locale.Bundle.LocalizeMsgByCtx(ctx, locale.TaskSQLReportIndex), | ||
| SQL: locale.Bundle.LocalizeMsgByCtx(ctx, locale.TaskSQLReportSQL), | ||
| AuditStatus: locale.Bundle.LocalizeMsgByCtx(ctx, locale.TaskSQLReportAuditStatus), | ||
| AuditResult: locale.Bundle.LocalizeMsgByCtx(ctx, locale.TaskSQLReportAuditResult), | ||
| ExecStatus: locale.Bundle.LocalizeMsgByCtx(ctx, locale.TaskSQLReportExecStatus), | ||
| ExecResult: locale.Bundle.LocalizeMsgByCtx(ctx, locale.TaskSQLReportExecResult), | ||
| RollbackSQL: locale.Bundle.LocalizeMsgByCtx(ctx, locale.TaskSQLReportRollbackSQL), | ||
| RuleName: locale.Bundle.LocalizeMsgByCtx(ctx, locale.ReportLabelRuleName), | ||
| Description: locale.Bundle.LocalizeMsgByCtx(ctx, locale.TaskSQLReportDescription), | ||
| Suggestion: locale.Bundle.LocalizeMsgByCtx(ctx, locale.ReportLabelSuggestion), | ||
| Count: locale.Bundle.LocalizeMsgByCtx(ctx, locale.ReportLabelCount), | ||
| HitCount: locale.Bundle.LocalizeMsgByCtx(ctx, locale.ReportLabelHitCount), | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
应该定义一个FilterOption 结构体,明确能用哪些参数进行筛选