package model import ( "context" "errors" "fmt" "github.com/patrickmn/go-cache" "github.com/spf13/cast" "github.com/zeromicro/go-zero/core/stores/sqlx" "time" ) var _ NhPromoteBindModel = (*customNhPromoteBindModel)(nil) type ( // NhPromoteBindModel is an interface to be customized, add more methods here, // and implement the added methods in customNhPromoteBindModel. NhPromoteBindModel interface { nhPromoteBindModel withSession(session sqlx.Session) NhPromoteBindModel FindRequirePushUser(ctx context.Context, shareUid uint) ([]NhPromoteBind, error) UpdatePushUser(ctx context.Context, id uint) error UpdatePushRole(ctx context.Context, id uint) error UserInviteCount(ctx context.Context, uid uint) (int64, error) } customNhPromoteBindModel struct { *defaultNhPromoteBindModel userInviteCountCache *cache.Cache } ) // NewNhPromoteBindModel returns a model for the database table. func NewNhPromoteBindModel(conn sqlx.SqlConn) NhPromoteBindModel { return &customNhPromoteBindModel{ defaultNhPromoteBindModel: newNhPromoteBindModel(conn), userInviteCountCache: cache.New(time.Minute, time.Second*65), } } func (m *customNhPromoteBindModel) withSession(session sqlx.Session) NhPromoteBindModel { return NewNhPromoteBindModel(sqlx.NewSqlConnFromSession(session)) } func (m *customNhPromoteBindModel) FindRequirePushUser(ctx context.Context, shareUid uint) ([]NhPromoteBind, error) { query := fmt.Sprintf("select %s from %s where `share_uid` = ? and `is_push_user` = 0 limit 100", nhPromoteBindRows, m.table) var resp []NhPromoteBind err := m.conn.QueryRowsCtx(ctx, &resp, query, shareUid) if err != nil && !errors.Is(err, sqlx.ErrNotFound) { return nil, err } return resp, nil } func (m *customNhPromoteBindModel) UpdatePushUser(ctx context.Context, id uint) error { update := fmt.Sprintf("update %s set `is_push_user` = 1 where `id` = ? and `is_push_user` = 0", m.table) result, err := m.conn.ExecCtx(ctx, update, id) if err != nil { return err } row, err := result.RowsAffected() if err != nil { return err } if row == 0 { return ErrNoRowUpdate } return nil } func (m *customNhPromoteBindModel) UpdatePushRole(ctx context.Context, id uint) error { update := fmt.Sprintf("update %s set `is_push_role` = 1 where `id` = ? and `is_push_role` = 0", m.table) result, err := m.conn.ExecCtx(ctx, update, id) if err != nil { return err } row, err := result.RowsAffected() if err != nil { return err } if row == 0 { return ErrNoRowUpdate } return nil } func (m *customNhPromoteBindModel) UserInviteCount(ctx context.Context, uid uint) (int64, error) { key := cast.ToString(uid) v, ok := m.userInviteCountCache.Get(key) if ok { return v.(int64), nil } query := fmt.Sprintf("SELECT COUNT(*) as count FROM %s pb JOIN `nh_twitter` tw ON pb.invited_uid = tw.uid WHERE pb.share_uid = ?", m.table) var count int64 err := m.conn.QueryRowCtx(ctx, &count, query, uid) if err != nil && !errors.Is(err, sqlx.ErrNotFound) { return 0, err } m.userInviteCountCache.SetDefault(key, count) return count, nil }