reaction.go 2.1 KB

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