阅15
gorm快速上手
初始化
在基础设施包(pkg)中,创建对应的模块,比如postgres模块。然后定义一个初始化的New函数
goimport ( "gorm.io/driver/postgres" "gorm.io/gorm" "fmt" "log" ) func New(dsn string) (*gorm.DB,error) { db,err := gorm.Open(postgres.Open(dsn),&gorm.Config{}) if err != nil { return nil,fmt.Errorf("failed to connect to PostgresSQL:%W",err) } log.Println("✅ Connected to PostgreSQL") return db,nil }
在主包中引入
gotype Server struct { cfg *config.Config engine *gin.Engine closers []func() messageSvc *service.MessageService db *gorm.DB rdb *rawredis.Client kafkaProducer *backendkafka.Producer eventBroker *consumer.EventBroker redisEventBus *consumer.RedisEventBus // 跨實例事件總線 jwtMgr *jwtpkg.Manager userRepo *repository.UserRepository } func New(cfg *config.Config) (*Server, error) { s := &Server{cfg: cfg} // 基礎設施 if err := s.initPostgres(); err != nil { return nil, err } ... return s, nil } func (s *Server) initPostgres() error { db, err := postgres.New(s.cfg.PostgresURL) if err != nil { return err } log.Println("✅ PostgreSQL connected") s.db = db s.closers = append(s.closers, func() { if sqlDB, err := db.DB(); err == nil { _ = sqlDB.Close() } }) if err := migration.Migrate(db); err != nil { return err } if err := migration.CreatePartitionedTables(db); err != nil { return err } if err := migration.SeedData(db); err != nil { return err } if err := migration.CreateIndexes(db); err != nil { return err } return nil }
模型定义
ORM,通过一般通过建立对象关系模型的抽象来操作底层的sql,一般都需要建对应的model层,gorm也不例外。
在internal/model下面建立对应的模型文件。
下面以user为例子:
gopackage model import ( "database/sql/driver" "encoding/json" "time" ) type User struct { ID string `gorm:"primaryKey;type:uuid;default:gen_random_uuid()" json:"id"` TenantID string `gorm:"index" json:"tenant_id"` Username string `gorm:"uniqueIndex:idx_tenant_username" json:"username"` Email string `gorm:"index" json:"email"` Phone string `json:phone,omitempty` Avatar string `json:phone,omitempty` DisplayName string `json:"display_name,omitempty"` Role string `json:"role"` Status string `json:"status"` RoleID string `json:"role_id,omitempty"` Password string `json:"-"` IsSystem bool `gorm:"default:false",json:"is_system"` ExtraData JOSNBMAP `gorm:"type:jsonb" json:"extra_data,omitempty"` CreateAt time.Time `json:create_at` UpdateAt time.Time `json.update_at` } func (User) TableName()string{ return "users" } func (u *User) Scan(value interface{})error{ return json.Unmarshal(value.([]byte),u) } func (u User) Value()(driver.Value,error){ return json.Marshal(u) }
Value()是序列化,为了在gorm创建和更新等操作时,序列化数据结构(结构体)为json数据,保存到数据库。Scan(value)是为了反序列化,当gorm在从数据库查询到数据后,底层调用Scan方法,将数据库的数据转为符合定义的数据结构(结构体)
增删改查
一般数据库操作都会放到一个相关的repository层去做统一查询和操作数据库。
gopackage repository import ( "context" "errors" "github.com/jeff/sky-chat/backend/internal/model" "gorm.io/gorm" ) // UserRepository 用戶數據訪問層 type UserRepository struct { db *gorm.DB } // NewUserRepository 創建用戶倉庫 func NewUserRepository(db *gorm.DB) *UserRepository { return &UserRepository{db: db} } // Create 創建用戶 func (r *UserRepository) Create(ctx context.Context, user *model.User) error { return r.db.WithContext(ctx).Create(user).Error } // FindByID 根據 ID 獲取用戶 func (r *UserRepository) FindByID(ctx context.Context, id string) (*model.User, error) { var user model.User if err := r.db.WithContext(ctx).Where("id = ?", id).First(&user).Error; err != nil { return nil, err } return &user, nil } // ListByIDs 批量查詢用戶(保留 id -> user 映射),用於會話列表解析對端顯示名,避免 N+1。 func (r *UserRepository) ListByIDs(ctx context.Context, ids []string) ([]*model.User, error) { if len(ids) == 0 { return []*model.User{}, nil } var users []*model.User if err := r.db.WithContext(ctx).Where("id IN ?", ids).Find(&users).Error; err != nil { return nil, err } return users, nil } // DisplayNameOf 取用戶顯示名:display_name 优先,缺省退回 username。 func DisplayNameOf(u *model.User) string { if u == nil { return "" } if u.DisplayName != "" { return u.DisplayName } return u.Username } // FindByUsername 根據用戶名(+租戶)查詢 func (r *UserRepository) FindByUsername(ctx context.Context, tenantID, username string) (*model.User, error) { var user model.User if err := r.db.WithContext(ctx). Where("username = ? AND tenant_id = ?", username, tenantID). First(&user).Error; err != nil { return nil, err } return &user, nil } // GetProfile 獲取用戶擴展資料;不存在返回 nil 而非錯誤 func (r *UserRepository) GetProfile(ctx context.Context, userID string) (*model.UserProfile, error) { var p model.UserProfile if err := r.db.WithContext(ctx).Where("user_id = ?", userID).First(&p).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, nil } return nil, err } return &p, nil } // UpsertProfile 新建或更新用戶擴展資料(1:1) func (r *UserRepository) UpsertProfile(ctx context.Context, p *model.UserProfile) error { if err := r.db.WithContext(ctx).Create(p).Error; err != nil { // 已存在則更新 return r.db.WithContext(ctx). Where("user_id = ?", p.UserID). Omit("id", "user_id", "created_at"). Save(p).Error } return nil } // List 分頁查詢用戶(關鍵字 / 狀態過濾) func (r *UserRepository) List(ctx context.Context, tenantID, keyword, status string, page, pageSize int) ([]*model.User, int64, error) { q := r.db.WithContext(ctx).Model(&model.User{}).Where("tenant_id = ?", tenantID) if keyword != "" { like := "%" + keyword + "%" q = q.Where("username ILIKE ? OR display_name ILIKE ? OR email ILIKE ? OR phone ILIKE ?", like, like, like, like) } if status != "" { q = q.Where("status = ?", status) } var total int64 if err := q.Count(&total).Error; err != nil { return nil, 0, err } var users []*model.User if err := q. Order("created_at DESC"). Offset((page - 1) * pageSize). Limit(pageSize). Find(&users).Error; err != nil { return nil, 0, err } return users, total, nil } // UpdateFields 按字段更新用戶(見 auth_service 的 upsert 模式) func (r *UserRepository) UpdateFields(ctx context.Context, id string, fields map[string]any) error { return r.db.WithContext(ctx).Model(&model.User{}).Where("id = ?", id).Updates(fields).Error } // Delete 刪除用戶並清理關聯數據(角色綁定、擴展資料) func (r *UserRepository) Delete(ctx context.Context, id string) error { return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { if err := tx.Where("user_id = ?", id).Delete(&model.UserRole{}).Error; err != nil { return err } if err := tx.Where("user_id = ?", id).Delete(&model.UserProfile{}).Error; err != nil { return err } return tx.Where("id = ?", id).Delete(&model.User{}).Error }) } // UpdatePassword 更新用戶密碼(存 bcrypt hash) func (r *UserRepository) UpdatePassword(ctx context.Context, id, hash string) error { return r.UpdateFields(ctx, id, map[string]any{"password": hash}) } // SetStatus 啟用 / 禁用 / 拉黑用戶 func (r *UserRepository) SetStatus(ctx context.Context, id, status string) error { return r.UpdateFields(ctx, id, map[string]any{"status": status}) } // ListRoleIDs 返回用戶已綁定的角色 ID 列表 func (r *UserRepository) ListRoleIDs(ctx context.Context, userID string) ([]string, error) { var ids []string err := r.db.WithContext(ctx). Model(&model.UserRole{}). Where("user_id = ?", userID). Pluck("role_id", &ids).Error return ids, err } // AssignRoles 覆蓋式分配用戶角色 func (r *UserRepository) AssignRoles(ctx context.Context, userID string, roleIDs []string) error { return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { if err := tx.Where("user_id = ?", userID).Delete(&model.UserRole{}).Error; err != nil { return err } for _, rid := range roleIDs { if err := tx.Create(&model.UserRole{UserID: userID, RoleID: rid}).Error; err != nil { return err } } return nil }) } // BindRoles 為新建用戶一次性綁定角色 func (r *UserRepository) BindRoles(ctx context.Context, userID string, roleIDs []string) error { for _, rid := range roleIDs { if err := r.db.WithContext(ctx).Create(&model.UserRole{UserID: userID, RoleID: rid}).Error; err != nil { return err } } return nil } // ListPermissionCodes 返回用戶全部角色所綁定的權限碼(去重),用於前端路由/按鈕權限校驗。 func (r *UserRepository) ListPermissionCodes(ctx context.Context, userID string) ([]string, error) { var codes []string err := r.db.WithContext(ctx). Model(&model.Permission{}). Select("DISTINCT permissions.code"). Joins("JOIN role_permissions rp ON rp.permission_id = permissions.id"). Joins("JOIN user_roles ur ON ur.role_id = rp.role_id"). Where("ur.user_id = ?", userID). Scan(&codes).Error return codes, err }
加载中...