memos/store/db/mysql/user_setting.go

57 lines
1.6 KiB
Go
Raw Normal View History

package mysql
import (
"context"
"strings"
storepb "github.com/usememos/memos/proto/gen/store"
"github.com/usememos/memos/store"
)
2024-04-13 02:08:35 +08:00
func (d *DB) UpsertUserSetting(ctx context.Context, upsert *store.UserSetting) (*store.UserSetting, error) {
2023-10-07 22:56:12 +08:00
stmt := "INSERT INTO `user_setting` (`user_id`, `key`, `value`) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE `value` = ?"
2024-04-13 02:08:35 +08:00
if _, err := d.db.ExecContext(ctx, stmt, upsert.UserID, upsert.Key.String(), upsert.Value, upsert.Value); err != nil {
return nil, err
}
return upsert, nil
}
2024-04-13 02:08:35 +08:00
func (d *DB) ListUserSettings(ctx context.Context, find *store.FindUserSetting) ([]*store.UserSetting, error) {
where, args := []string{"1 = 1"}, []any{}
if v := find.Key; v != storepb.UserSettingKey_USER_SETTING_KEY_UNSPECIFIED {
2023-10-07 22:56:12 +08:00
where, args = append(where, "`key` = ?"), append(args, v.String())
}
if v := find.UserID; v != nil {
2023-10-07 22:56:12 +08:00
where, args = append(where, "`user_id` = ?"), append(args, *find.UserID)
}
2023-10-07 22:56:12 +08:00
query := "SELECT `user_id`, `key`, `value` FROM `user_setting` WHERE " + strings.Join(where, " AND ")
rows, err := d.db.QueryContext(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
2024-04-13 02:08:35 +08:00
userSettingList := make([]*store.UserSetting, 0)
for rows.Next() {
2024-04-13 02:08:35 +08:00
userSetting := &store.UserSetting{}
var keyString string
if err := rows.Scan(
2024-04-13 02:08:35 +08:00
&userSetting.UserID,
&keyString,
2024-04-13 02:08:35 +08:00
&userSetting.Value,
); err != nil {
return nil, err
}
userSetting.Key = storepb.UserSettingKey(storepb.UserSettingKey_value[keyString])
userSettingList = append(userSettingList, userSetting)
}
if err := rows.Err(); err != nil {
return nil, err
}
return userSettingList, nil
}