reaction.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package postgres
  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) UpsertReaction(ctx context.Context, upsert *store.Reaction) (*store.Reaction, error) {
  9. fields := []string{"creator_id", "content_id", "reaction_type"}
  10. args := []interface{}{upsert.CreatorID, upsert.ContentID, upsert.ReactionType.String()}
  11. stmt := "INSERT INTO reaction (" + strings.Join(fields, ", ") + ") VALUES (" + placeholders(len(args)) + ") RETURNING id, created_ts"
  12. if err := d.db.QueryRowContext(ctx, stmt, args...).Scan(
  13. &upsert.ID,
  14. &upsert.CreatedTs,
  15. ); err != nil {
  16. return nil, err
  17. }
  18. reaction := upsert
  19. return reaction, nil
  20. }
  21. func (d *DB) ListReactions(ctx context.Context, find *store.FindReaction) ([]*store.Reaction, error) {
  22. where, args := []string{"1 = 1"}, []interface{}{}
  23. if find.ID != nil {
  24. where, args = append(where, "id = "+placeholder(len(args)+1)), append(args, *find.ID)
  25. }
  26. if find.CreatorID != nil {
  27. where, args = append(where, "creator_id = "+placeholder(len(args)+1)), append(args, *find.CreatorID)
  28. }
  29. if find.ContentID != nil {
  30. where, args = append(where, "content_id = "+placeholder(len(args)+1)), append(args, *find.ContentID)
  31. }
  32. rows, err := d.db.QueryContext(ctx, `
  33. SELECT
  34. id,
  35. created_ts,
  36. creator_id,
  37. content_id,
  38. reaction_type
  39. FROM reaction
  40. WHERE `+strings.Join(where, " AND ")+`
  41. ORDER BY id ASC`,
  42. args...,
  43. )
  44. if err != nil {
  45. return nil, err
  46. }
  47. defer rows.Close()
  48. list := []*store.Reaction{}
  49. for rows.Next() {
  50. reaction := &store.Reaction{}
  51. var reactionType string
  52. if err := rows.Scan(
  53. &reaction.ID,
  54. &reaction.CreatedTs,
  55. &reaction.CreatorID,
  56. &reaction.ContentID,
  57. &reactionType,
  58. ); err != nil {
  59. return nil, err
  60. }
  61. reaction.ReactionType = storepb.ReactionType(storepb.ReactionType_value[reactionType])
  62. list = append(list, reaction)
  63. }
  64. if err := rows.Err(); err != nil {
  65. return nil, err
  66. }
  67. return list, nil
  68. }
  69. func (d *DB) DeleteReaction(ctx context.Context, delete *store.DeleteReaction) error {
  70. _, err := d.db.ExecContext(ctx, "DELETE FROM reaction WHERE id = $1", delete.ID)
  71. return err
  72. }