{"record":{"id":"84c86220268fad40","repo":"flipped-aurora/gin-vue-admin","slug":"w-84c862","errorCode":null,"errorMessage":"创建自动代码历史失败: %w","messagePattern":"创建自动代码历史失败: %w","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"server/service/system/auto_code_persistence.go","lineNumber":38,"sourceCode":"\tpackageTemplate string,\n\thistory request.SysAutoHistoryCreate,\n) error {\n\tif db == nil {\n\t\treturn errors.New(\"自动代码数据库未初始化\")\n\t}\n\treturn db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {\n\t\tif err := persistAutoCodeAPIs(tx, info, &history); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := persistAutoCodeMenu(tx, info, packageTemplate, &history); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := persistAutoCodeExportTemplate(tx, info, &history); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tentity := history.Create()\n\t\tif err := tx.Create(&entity).Error; err != nil {\n\t\t\treturn fmt.Errorf(\"创建自动代码历史失败: %w\", err)\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc persistAutoCodeAPIs(tx *gorm.DB, info request.AutoCode, history *request.SysAutoHistoryCreate) error {\n\tif !info.AutoCreateApiToSql || info.OnlyTemplate {\n\t\treturn nil\n\t}\n\tfor _, desired := range info.Apis() {\n\t\tvar existing model.SysApi\n\t\terr := tx.Where(\"path = ? AND method = ?\", desired.Path, desired.Method).First(&existing).Error\n\t\tswitch {\n\t\tcase err == nil:\n\t\t\thistory.ApiIDs = append(history.ApiIDs, existing.ID)\n\t\tcase errors.Is(err, gorm.ErrRecordNotFound):\n\t\t\tif err = tx.Create(&desired).Error; err != nil {\n\t\t\t\treturn fmt.Errorf(\"创建自动代码 API %s %s 失败: %w\", desired.Method, desired.Path, err)","sourceCodeStart":20,"sourceCodeEnd":56,"githubUrl":"https://github.com/flipped-aurora/gin-vue-admin/blob/3136500ef380842b0eb6c4daa87c3f8a47fcf9e0/server/service/system/auto_code_persistence.go#L20-L56","documentation":"This error is returned inside a GORM transaction in server/service/system/auto_code_persistence.go when tx.Create(&entity) fails to insert the assembled auto-code history record. It wraps the GORM error with %w and is returned from the transaction closure, rolling back the whole persistence. It means the history row could not be written: constraint violation, schema drift, invalid FK values, or a database failure.","triggerScenarios":"Running the auto-code history creation flow when the sys_auto_code_history insert fails: DB connection lost mid-transaction, NOT NULL/unique constraint violated by the assembled history entity, ApiIDs/Menu references pointing to nonexistent rows, or invalid column data (over-length/wrong type) from the request payload.","commonSituations":"Migrations out of sync after upgrading (missing table or columns); MySQL strict mode rejecting truncated values; deadlocks or lock wait timeouts under concurrent code generation; referenced API/menu rows deleted before history creation.","solutions":["Log the wrapped error to get the exact DB message (duplicate key, FK constraint, unknown column).","Run AutoMigrate / the project's migration step so sys_auto_code_history and related tables match the model.","Validate the request payload: required fields present, referenced API/menu IDs exist.","Retry the operation if the unwrapped cause is transient (deadlock, lock wait timeout, connection reset).","Check DB connectivity, disk space, and isolation settings if failures are intermittent."],"exampleFix":"// before\nif err := tx.Create(&entity).Error; err != nil {\n    return fmt.Errorf(\"创建自动代码历史失败: %w\", err)\n}\n\n// after\nif err := tx.Create(&entity).Error; err != nil {\n    logger.Error(\"auto history insert failed\", zap.Error(err)) // inspect root cause\n    return fmt.Errorf(\"创建自动代码历史失败: %w\", err)\n}","handlingStrategy":"validation","validationCode":"func canPersistHistory(db *gorm.DB, info request.AutoCode) error {\n    var count int64\n    if err := db.Model(&system.SysAutoCodeHistory{}).Count(&count).Error; err != nil {\n        return fmt.Errorf(\"history table not ready: %w\", err)\n    }\n    for _, apiID := range info.ApiIDs {\n        var n int64\n        if err := db.Model(&system.SysApi{}).Where(\"id = ?\", apiID).Count(&n).Error; err != nil || n == 0 {\n            return fmt.Errorf(\"referenced api id %d missing\", apiID)\n        }\n    }\n    return nil\n}","typeGuard":null,"tryCatchPattern":"err := svc.CreateAutoCodeHistory(info)\nif err != nil {\n    if strings.Contains(fmt.Sprint(errors.Unwrap(err)), \"Duplicate\") {\n        return fmt.Errorf(\"history already recorded for this generation\")\n    }\n    if isTransientDBError(err) { // deadlock / lock timeout / conn reset\n        return retryWithBackoff(3, func() error { return svc.CreateAutoCodeHistory(info) })\n    }\n    return err\n}","preventionTips":["Run AutoMigrate/migrations on every deploy so sys_auto_code_history matches the model.","Validate referenced API/menu IDs exist before entering the persistence transaction.","Use per-request transaction timeouts to avoid long-held locks.","Log the unwrapped DB error for every persistence failure to spot constraint issues early.","Avoid running multiple concurrent codegen jobs against the same package."],"tags":["database","gorm","transaction","persistence"],"backgroundTag":"db-insert-failed","analyzedSha":"3136500ef380842b0eb6c4daa87c3f8a47fcf9e0","analyzedAt":"2026-08-31T13:50:02.721Z","schemaVersion":2},"datasetVersion":"2026-08-31T19:17:28.585Z"}