flipped-aurora/gin-vue-admin · error

创建自动代码历史失败: %w

Error message

创建自动代码历史失败: %w

What it means

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.

Source

Thrown at server/service/system/auto_code_persistence.go:38

	packageTemplate string,
	history request.SysAutoHistoryCreate,
) error {
	if db == nil {
		return errors.New("自动代码数据库未初始化")
	}
	return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		if err := persistAutoCodeAPIs(tx, info, &history); err != nil {
			return err
		}
		if err := persistAutoCodeMenu(tx, info, packageTemplate, &history); err != nil {
			return err
		}
		if err := persistAutoCodeExportTemplate(tx, info, &history); err != nil {
			return err
		}
		entity := history.Create()
		if err := tx.Create(&entity).Error; err != nil {
			return fmt.Errorf("创建自动代码历史失败: %w", err)
		}
		return nil
	})
}

func persistAutoCodeAPIs(tx *gorm.DB, info request.AutoCode, history *request.SysAutoHistoryCreate) error {
	if !info.AutoCreateApiToSql || info.OnlyTemplate {
		return nil
	}
	for _, desired := range info.Apis() {
		var existing model.SysApi
		err := tx.Where("path = ? AND method = ?", desired.Path, desired.Method).First(&existing).Error
		switch {
		case err == nil:
			history.ApiIDs = append(history.ApiIDs, existing.ID)
		case errors.Is(err, gorm.ErrRecordNotFound):
			if err = tx.Create(&desired).Error; err != nil {
				return fmt.Errorf("创建自动代码 API %s %s 失败: %w", desired.Method, desired.Path, err)

View on GitHub (pinned to 3136500ef3)

Solutions

  1. Log the wrapped error to get the exact DB message (duplicate key, FK constraint, unknown column).
  2. Run AutoMigrate / the project's migration step so sys_auto_code_history and related tables match the model.
  3. Validate the request payload: required fields present, referenced API/menu IDs exist.
  4. Retry the operation if the unwrapped cause is transient (deadlock, lock wait timeout, connection reset).
  5. Check DB connectivity, disk space, and isolation settings if failures are intermittent.

Example fix

// before
if err := tx.Create(&entity).Error; err != nil {
    return fmt.Errorf("创建自动代码历史失败: %w", err)
}

// after
if err := tx.Create(&entity).Error; err != nil {
    logger.Error("auto history insert failed", zap.Error(err)) // inspect root cause
    return fmt.Errorf("创建自动代码历史失败: %w", err)
}
Defensive patterns

Strategy: validation

Validate before calling

func canPersistHistory(db *gorm.DB, info request.AutoCode) error {
    var count int64
    if err := db.Model(&system.SysAutoCodeHistory{}).Count(&count).Error; err != nil {
        return fmt.Errorf("history table not ready: %w", err)
    }
    for _, apiID := range info.ApiIDs {
        var n int64
        if err := db.Model(&system.SysApi{}).Where("id = ?", apiID).Count(&n).Error; err != nil || n == 0 {
            return fmt.Errorf("referenced api id %d missing", apiID)
        }
    }
    return nil
}

Try / catch

err := svc.CreateAutoCodeHistory(info)
if err != nil {
    if strings.Contains(fmt.Sprint(errors.Unwrap(err)), "Duplicate") {
        return fmt.Errorf("history already recorded for this generation")
    }
    if isTransientDBError(err) { // deadlock / lock timeout / conn reset
        return retryWithBackoff(3, func() error { return svc.CreateAutoCodeHistory(info) })
    }
    return err
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of flipped-aurora/gin-vue-admin@3136500ef3 (2026-08-31). Data as JSON: /api/errors/84c86220268fad40. Report an issue: GitHub.