pg_notification_dao.go 1.5 KB
package dao

import (
	"fmt"
	"github.com/go-pg/pg"
	pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
	"time"
)

type NotificationDao struct {
	transactionContext *pgTransaction.TransactionContext
}

func (dao *NotificationDao) ReadAllUnReadSentNotification(receiverId int64, notificationType int) (int, error) {
	tx := dao.transactionContext.PgTx
	if notificationType == 0 {
		result, err := tx.Query(
			pg.Scan(),
			`UPDATE sent_notifications SET is_read=?, read_time=? WHERE receiver @> '{"uid":?}' AND is_read=false`,
			true, time.Now(), receiverId)
		if err != nil {
			return 0, err
		} else {
			return result.RowsAffected(), nil
		}
	} else {
		result, err := tx.Query(
			pg.Scan(),
			`UPDATE sent_notifications SET is_read=?, read_time=? WHERE  notification_id IN ( SELECT sent_notification.notification_id FROM sent_notifications AS sent_notification LEFT JOIN notifications AS notification ON notification.id = sent_notification.notification_id WHERE sent_notification.receiver @> '{"uid":?}' AND sent_notification.is_read=false AND notification.notification_type=?)`,
			true, time.Now(), receiverId, notificationType)
		if err != nil {
			return 0, err
		} else {
			return result.RowsAffected(), nil
		}
	}
}

func NewNotificationDao(transactionContext *pgTransaction.TransactionContext) (*NotificationDao, error) {
	if transactionContext == nil {
		return nil, fmt.Errorf("transactionContext参数不能为nil")
	} else {
		return &NotificationDao{
			transactionContext: transactionContext,
		}, nil
	}
}