user_setting.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package sqlite
  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 := `
  10. INSERT INTO user_setting (
  11. user_id, key, value
  12. )
  13. VALUES (?, ?, ?)
  14. ON CONFLICT(user_id, key) DO UPDATE
  15. SET value = EXCLUDED.value
  16. `
  17. if _, err := d.db.ExecContext(ctx, stmt, upsert.UserID, upsert.Key.String(), upsert.Value); err != nil {
  18. return nil, err
  19. }
  20. return upsert, nil
  21. }
  22. func (d *DB) ListUserSettings(ctx context.Context, find *store.FindUserSetting) ([]*store.UserSetting, error) {
  23. where, args := []string{"1 = 1"}, []any{}
  24. if v := find.Key; v != storepb.UserSettingKey_USER_SETTING_KEY_UNSPECIFIED {
  25. where, args = append(where, "key = ?"), append(args, v.String())
  26. }
  27. if v := find.UserID; v != nil {
  28. where, args = append(where, "user_id = ?"), append(args, *find.UserID)
  29. }
  30. query := `
  31. SELECT
  32. user_id,
  33. key,
  34. value
  35. FROM user_setting
  36. WHERE ` + strings.Join(where, " AND ")
  37. rows, err := d.db.QueryContext(ctx, query, args...)
  38. if err != nil {
  39. return nil, err
  40. }
  41. defer rows.Close()
  42. userSettingList := make([]*store.UserSetting, 0)
  43. for rows.Next() {
  44. userSetting := &store.UserSetting{}
  45. var keyString string
  46. if err := rows.Scan(
  47. &userSetting.UserID,
  48. &keyString,
  49. &userSetting.Value,
  50. ); err != nil {
  51. return nil, err
  52. }
  53. userSetting.Key = storepb.UserSettingKey(storepb.UserSettingKey_value[keyString])
  54. userSettingList = append(userSettingList, userSetting)
  55. }
  56. if err := rows.Err(); err != nil {
  57. return nil, err
  58. }
  59. return userSettingList, nil
  60. }