package model import ( "errors" "github.com/QuantumNous/new-api/common" "gorm.io/gorm" "gorm.io/gorm/clause" ) type UserAssetChannel struct { Id int `json:"id" gorm:"primaryKey"` UserId int `json:"user_id" gorm:"not null;uniqueIndex:idx_user_asset_channel,priority:1"` ChannelType int `json:"channel_type" gorm:"not null;uniqueIndex:idx_user_asset_channel,priority:2"` Group string `json:"group" gorm:"column:group;type:varchar(64);not null;uniqueIndex:idx_user_asset_channel,priority:3"` ChannelId int `json:"channel_id" gorm:"not null"` CreatedAt int64 `json:"created_at"` UpdatedAt int64 `json:"updated_at"` } func (UserAssetChannel) TableName() string { return "user_asset_channels" } func GetUserAssetChannel(userId int, channelType int, group string) (*UserAssetChannel, error) { var binding UserAssetChannel err := DB.Where("user_id = ? AND channel_type = ? AND "+commonGroupCol+" = ?", userId, channelType, group).First(&binding).Error if errors.Is(err, gorm.ErrRecordNotFound) { return nil, nil } if err != nil { return nil, err } return &binding, nil } func BindUserAssetChannel(userId int, channelType int, group string, channelId int) error { return BindUserAssetChannelWithTx(DB, userId, channelType, group, channelId) } func BindUserAssetChannelWithTx(tx *gorm.DB, userId int, channelType int, group string, channelId int) error { now := common.GetTimestamp() binding := UserAssetChannel{ UserId: userId, ChannelType: channelType, Group: group, ChannelId: channelId, CreatedAt: now, UpdatedAt: now, } return tx.Session(&gorm.Session{SkipDefaultTransaction: true}).Clauses(clause.OnConflict{ Columns: []clause.Column{ {Name: "user_id"}, {Name: "channel_type"}, {Name: "group"}, }, DoUpdates: clause.Assignments(map[string]interface{}{ "channel_id": channelId, "updated_at": now, }), }).Create(&binding).Error } func GetUserAssetChannelsByTypes(userId int, channelTypes []int, group string) ([]UserAssetChannel, error) { if len(channelTypes) == 0 { return nil, nil } var bindings []UserAssetChannel err := DB.Where("user_id = ? AND channel_type IN ? AND "+commonGroupCol+" = ?", userId, channelTypes, group). Order("updated_at DESC, id DESC"). Find(&bindings).Error return bindings, err } func DeleteUserAssetChannelsByTypesWithTx(tx *gorm.DB, userId int, channelTypes []int, group string) error { if len(channelTypes) == 0 { return nil } return tx.Session(&gorm.Session{SkipDefaultTransaction: true}).Where("user_id = ? AND channel_type IN ? AND "+commonGroupCol+" = ?", userId, channelTypes, group). Delete(&UserAssetChannel{}).Error } func UnbindUserAssetChannel(userId int, channelType int, group string) error { return DB.Where("user_id = ? AND channel_type = ? AND "+commonGroupCol+" = ?", userId, channelType, group). Delete(&UserAssetChannel{}).Error }