flipped-aurora/gin-vue-admin · error

sys_users表数据初始化失败!

Error message

sys_users表数据初始化失败!

What it means

Thrown by the user initializer (initUser.InitializeData) when inserting the default seed users (admin 9528 etc.) into sys_users fails. It wraps the GORM error with the table name. Note the function continues to attach Authorities; this specific error concerns only the initial user-row Create.

Source

Thrown at server/source/system/user.go:79

			Password:    adminPassword,
			NickName:    "Mr.奇淼",
			HeaderImg:   "https://qmplusimg.henrongyi.top/gva_header.jpg",
			AuthorityId: 888,
			Phone:       "17611111111",
			Email:       "333333333@qq.com",
		},
		{
			UUID:        uuid.New(),
			Username:    "a303176530",
			Password:    password,
			NickName:    "用户1",
			HeaderImg:   "https://qmplusimg.henrongyi.top/1572075907logo.png",
			AuthorityId: 9528,
			Phone:       "17611111111",
			Email:       "333333333@qq.com"},
	}
	if err = db.Create(&entities).Error; err != nil {
		return ctx, errors.Wrap(err, sysModel.SysUser{}.TableName()+"表数据初始化失败!")
	}
	next = context.WithValue(ctx, i.InitializerName(), entities)
	authorityEntities, ok := ctx.Value(new(initAuthority).InitializerName()).([]sysModel.SysAuthority)
	if !ok {
		return next, errors.Wrap(system.ErrMissingDependentContext, "创建 [用户-权限] 关联失败, 未找到权限表初始化数据")
	}
	if err = db.Model(&entities[0]).Association("Authorities").Replace(authorityEntities); err != nil {
		return next, err
	}
	if err = db.Model(&entities[1]).Association("Authorities").Replace(authorityEntities[:1]); err != nil {
		return next, err
	}
	return next, err
}

func (i *initUser) DataInserted(ctx context.Context) bool {
	db, ok := ctx.Value("db").(*gorm.DB)
	if !ok {

View on GitHub (pinned to 3136500ef3)

Solutions

  1. Inspect the wrapped GORM cause — duplicate key means users already exist and init can be skipped
  2. AutoMigrate SysUser (and authority/user-association tables) before running the initializer
  3. Guard with DataInserted(ctx) / the system init flag so seeding happens only on a fresh DB
  4. Delete the conflicting sys_users rows (or recreate the DB) and re-run init
  5. Verify DB credentials and that the connection is writable

Example fix

// before: second boot re-seeds and hits duplicate user
ctx, err = initUser{}.InitializeData(ctx)
// after: only seed on fresh DB
if !(initUser{}).DataInserted(ctx) {
    if err := db.AutoMigrate(&sysModel.SysUser{}); err != nil { return err }
    ctx, err = initUser{}.InitializeData(ctx)
}
Defensive patterns

Strategy: validation

Validate before calling

if !db.Migrator().HasTable(&sysModel.SysUser{}) {
    if err := db.AutoMigrate(&sysModel.SysUser{}); err != nil { return err }
}
var count int64
if err := db.Model(&sysModel.SysUser{}).Count(&count).Error; err != nil { return err }
if count > 0 { return nil } // users already seeded (e.g. admin 9528)

Type guard

func hasDB(ctx context.Context) (*gorm.DB, bool) {
    db, ok := ctx.Value("db").(*gorm.DB)
    return db, ok && db != nil
}

Try / catch

ctx, err = initUser{}.InitializeData(ctx)
if err != nil {
    if strings.Contains(err.Error(), "sys_users表数据初始化失败") {
        log.Printf("user seed failed, likely duplicate admin: cause=%v", errors.Cause(err))
    }
    return err
}

Prevention

When it happens

Trigger: db.Create(&entities) fails: sys_users not migrated, duplicate username/authority unique conflict from prior seeding, NOT NULL or column-type violation, password-hash column length exceeded, or DB connectivity loss.

Common situations: Running init twice on the same DB (user admin already exists → unique violation); partial seed from a crashed init left some user rows; schema drift after upgrade (new NOT NULL columns without defaults); DB in read-only mode.

Related errors


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