reaction.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package sqlite
  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. placeholder := []string{"?", "?", "?"}
  10. args := []interface{}{upsert.CreatorID, upsert.ContentID, upsert.ReactionType}
  11. stmt := "INSERT INTO `reaction` (" + strings.Join(fields, ", ") + ") VALUES (" + strings.Join(placeholder, ", ") + ") 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 = ?"), append(args, *find.ID)
  25. }
  26. if find.CreatorID != nil {
  27. where, args = append(where, "creator_id = ?"), append(args, *find.CreatorID)
  28. }
  29. if find.ContentID != nil {
  30. where, args = append(where, "content_id = ?"), 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. if err := rows.Scan(
  52. &reaction.ID,
  53. &reaction.CreatedTs,
  54. &reaction.CreatorID,
  55. &reaction.ContentID,
  56. &reaction.ReactionType,
  57. ); err != nil {
  58. return nil, err
  59. }
  60. list = append(list, reaction)
  61. }
  62. if err := rows.Err(); err != nil {
  63. return nil, err
  64. }
  65. return list, nil
  66. }
  67. func (d *DB) DeleteReaction(ctx context.Context, delete *store.DeleteReaction) error {
  68. _, err := d.db.ExecContext(ctx, "DELETE FROM `reaction` WHERE `id` = ?", delete.ID)
  69. return err
  70. }