memo_organizer.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package mysql
  2. import (
  3. "context"
  4. "database/sql"
  5. "fmt"
  6. "strings"
  7. "github.com/usememos/memos/store"
  8. )
  9. func (d *DB) UpsertMemoOrganizer(ctx context.Context, upsert *store.MemoOrganizer) (*store.MemoOrganizer, error) {
  10. stmt := `
  11. INSERT INTO memo_organizer (
  12. memo_id,
  13. user_id,
  14. pinned
  15. )
  16. VALUES (?, ?, ?)
  17. ON DUPLICATE KEY UPDATE pinned = ?
  18. `
  19. if _, err := d.db.ExecContext(ctx, stmt, upsert.MemoID, upsert.UserID, upsert.Pinned, upsert.Pinned); err != nil {
  20. return nil, err
  21. }
  22. return upsert, nil
  23. }
  24. func (d *DB) GetMemoOrganizer(ctx context.Context, find *store.FindMemoOrganizer) (*store.MemoOrganizer, error) {
  25. where, args := []string{}, []any{}
  26. if find.MemoID != 0 {
  27. where = append(where, "memo_id = ?")
  28. args = append(args, find.MemoID)
  29. }
  30. if find.UserID != 0 {
  31. where = append(where, "user_id = ?")
  32. args = append(args, find.UserID)
  33. }
  34. query := fmt.Sprintf(`
  35. SELECT
  36. memo_id,
  37. user_id,
  38. pinned
  39. FROM memo_organizer
  40. WHERE %s
  41. `, strings.Join(where, " AND "))
  42. row := d.db.QueryRowContext(ctx, query, args...)
  43. if err := row.Err(); err != nil {
  44. return nil, err
  45. }
  46. if row == nil {
  47. return nil, nil
  48. }
  49. memoOrganizer := &store.MemoOrganizer{}
  50. if err := row.Scan(
  51. &memoOrganizer.MemoID,
  52. &memoOrganizer.UserID,
  53. &memoOrganizer.Pinned,
  54. ); err != nil {
  55. return nil, err
  56. }
  57. return memoOrganizer, nil
  58. }
  59. func (d *DB) DeleteMemoOrganizer(ctx context.Context, delete *store.DeleteMemoOrganizer) error {
  60. where, args := []string{}, []any{}
  61. if v := delete.MemoID; v != nil {
  62. where, args = append(where, "memo_id = ?"), append(args, *v)
  63. }
  64. if v := delete.UserID; v != nil {
  65. where, args = append(where, "user_id = ?"), append(args, *v)
  66. }
  67. stmt := `DELETE FROM memo_organizer WHERE ` + strings.Join(where, " AND ")
  68. if _, err := d.db.ExecContext(ctx, stmt, args...); err != nil {
  69. return err
  70. }
  71. return nil
  72. }
  73. func vacuumMemoOrganizer(ctx context.Context, tx *sql.Tx) error {
  74. stmt := `
  75. DELETE FROM
  76. memo_organizer
  77. WHERE
  78. memo_id NOT IN (
  79. SELECT
  80. id
  81. FROM
  82. memo
  83. )
  84. OR user_id NOT IN (
  85. SELECT
  86. id
  87. FROM
  88. user
  89. )`
  90. _, err := tx.ExecContext(ctx, stmt)
  91. if err != nil {
  92. return err
  93. }
  94. return nil
  95. }