package dao

import (
	dbModel "kv_api/model/db"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

func (d *Dao) GetValue(uid, key string) (string, error) {
	kv := &dbModel.KVStorage{}
	err := d.db.Where("`uid` = ? AND `key` = ?", uid, key).First(kv).Error
	if err == gorm.ErrRecordNotFound {
		err = nil
	}
	return kv.Value, err
}

func (d *Dao) SetValue(kv *dbModel.KVStorage) (err error) {
	return d.db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "uid"}, {Name: "key"}},
		DoUpdates: clause.AssignmentColumns([]string{"value"}),
	}).Create(kv).Error
}
