user_setting.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package mysql
  2. import (
  3. "context"
  4. "strings"
  5. storepb "github.com/usememos/memos/proto/gen/store"
  6. "github.com/usememos/memos/store"
  7. )
  8. func (d *DB) UpsertUserSetting(ctx context.Context, upsert *store.UserSetting) (*store.UserSetting, error) {
  9. stmt := "INSERT INTO `user_setting` (`user_id`, `key`, `value`) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE `value` = ?"
  10. if _, err := d.db.ExecContext(ctx, stmt, upsert.UserID, upsert.Key.String(), upsert.Value, upsert.Value); err != nil {
  11. return nil, err
  12. }
  13. return upsert, nil
  14. }
  15. func (d *DB) ListUserSettings(ctx context.Context, find *store.FindUserSetting) ([]*store.UserSetting, error) {
  16. where, args := []string{"1 = 1"}, []any{}
  17. if v := find.Key; v != storepb.UserSettingKey_USER_SETTING_KEY_UNSPECIFIED {
  18. where, args = append(where, "`key` = ?"), append(args, v.String())
  19. }
  20. if v := find.UserID; v != nil {
  21. where, args = append(where, "`user_id` = ?"), append(args, *find.UserID)
  22. }
  23. query := "SELECT `user_id`, `key`, `value` FROM `user_setting` WHERE " + strings.Join(where, " AND ")
  24. rows, err := d.db.QueryContext(ctx, query, args...)
  25. if err != nil {
  26. return nil, err
  27. }
  28. defer rows.Close()
  29. userSettingList := make([]*store.UserSetting, 0)
  30. for rows.Next() {
  31. userSetting := &store.UserSetting{}
  32. var keyString string
  33. if err := rows.Scan(
  34. &userSetting.UserID,
  35. &keyString,
  36. &userSetting.Value,
  37. ); err != nil {
  38. return nil, err
  39. }
  40. userSetting.Key = storepb.UserSettingKey(storepb.UserSettingKey_value[keyString])
  41. userSettingList = append(userSettingList, userSetting)
  42. }
  43. if err := rows.Err(); err != nil {
  44. return nil, err
  45. }
  46. return userSettingList, nil
  47. }