memo_relation.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package mysql
  2. import (
  3. "context"
  4. "strings"
  5. "github.com/usememos/memos/store"
  6. )
  7. func (d *DB) UpsertMemoRelation(ctx context.Context, create *store.MemoRelation) (*store.MemoRelation, error) {
  8. stmt := "INSERT INTO `memo_relation` (`memo_id`, `related_memo_id`, `type`) VALUES (?, ?, ?)"
  9. _, err := d.db.ExecContext(
  10. ctx,
  11. stmt,
  12. create.MemoID,
  13. create.RelatedMemoID,
  14. create.Type,
  15. )
  16. if err != nil {
  17. return nil, err
  18. }
  19. memoRelation := store.MemoRelation{
  20. MemoID: create.MemoID,
  21. RelatedMemoID: create.RelatedMemoID,
  22. Type: create.Type,
  23. }
  24. return &memoRelation, nil
  25. }
  26. func (d *DB) ListMemoRelations(ctx context.Context, find *store.FindMemoRelation) ([]*store.MemoRelation, error) {
  27. where, args := []string{"TRUE"}, []any{}
  28. if find.MemoID != nil {
  29. where, args = append(where, "`memo_id` = ?"), append(args, find.MemoID)
  30. }
  31. if find.RelatedMemoID != nil {
  32. where, args = append(where, "`related_memo_id` = ?"), append(args, find.RelatedMemoID)
  33. }
  34. if find.Type != nil {
  35. where, args = append(where, "`type` = ?"), append(args, find.Type)
  36. }
  37. rows, err := d.db.QueryContext(ctx, "SELECT `memo_id`, `related_memo_id`, `type` FROM `memo_relation` WHERE "+strings.Join(where, " AND "), args...)
  38. if err != nil {
  39. return nil, err
  40. }
  41. defer rows.Close()
  42. list := []*store.MemoRelation{}
  43. for rows.Next() {
  44. memoRelation := &store.MemoRelation{}
  45. if err := rows.Scan(
  46. &memoRelation.MemoID,
  47. &memoRelation.RelatedMemoID,
  48. &memoRelation.Type,
  49. ); err != nil {
  50. return nil, err
  51. }
  52. list = append(list, memoRelation)
  53. }
  54. if err := rows.Err(); err != nil {
  55. return nil, err
  56. }
  57. return list, nil
  58. }
  59. func (d *DB) DeleteMemoRelation(ctx context.Context, delete *store.DeleteMemoRelation) error {
  60. where, args := []string{"TRUE"}, []any{}
  61. if delete.MemoID != nil {
  62. where, args = append(where, "`memo_id` = ?"), append(args, delete.MemoID)
  63. }
  64. if delete.RelatedMemoID != nil {
  65. where, args = append(where, "`related_memo_id` = ?"), append(args, delete.RelatedMemoID)
  66. }
  67. if delete.Type != nil {
  68. where, args = append(where, "`type` = ?"), append(args, delete.Type)
  69. }
  70. stmt := "DELETE FROM `memo_relation` WHERE " + strings.Join(where, " AND ")
  71. result, err := d.db.ExecContext(ctx, stmt, args...)
  72. if err != nil {
  73. return err
  74. }
  75. if _, err = result.RowsAffected(); err != nil {
  76. return err
  77. }
  78. return nil
  79. }