reaction.go 2.0 KB

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