memo_organizer.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package mysql
  2. import (
  3. "context"
  4. "database/sql"
  5. "strings"
  6. "github.com/usememos/memos/store"
  7. )
  8. func (d *DB) UpsertMemoOrganizer(ctx context.Context, upsert *store.MemoOrganizer) (*store.MemoOrganizer, error) {
  9. stmt := "INSERT INTO `memo_organizer` (`memo_id`, `user_id`, `pinned`) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE `pinned` = ?"
  10. if _, err := d.db.ExecContext(ctx, stmt, upsert.MemoID, upsert.UserID, upsert.Pinned, upsert.Pinned); err != nil {
  11. return nil, err
  12. }
  13. return upsert, nil
  14. }
  15. func (d *DB) ListMemoOrganizer(ctx context.Context, find *store.FindMemoOrganizer) ([]*store.MemoOrganizer, error) {
  16. where, args := []string{"1 = 1"}, []any{}
  17. if find.MemoID != 0 {
  18. where = append(where, "`memo_id` = ?")
  19. args = append(args, find.MemoID)
  20. }
  21. if find.UserID != 0 {
  22. where = append(where, "`user_id` = ?")
  23. args = append(args, find.UserID)
  24. }
  25. query := "SELECT `memo_id`, `user_id`, `pinned` FROM `memo_organizer` WHERE " + strings.Join(where, " AND ")
  26. rows, err := d.db.QueryContext(ctx, query, args...)
  27. if err != nil {
  28. return nil, err
  29. }
  30. defer rows.Close()
  31. list := []*store.MemoOrganizer{}
  32. for rows.Next() {
  33. memoOrganizer := &store.MemoOrganizer{}
  34. if err := rows.Scan(
  35. &memoOrganizer.MemoID,
  36. &memoOrganizer.UserID,
  37. &memoOrganizer.Pinned,
  38. ); err != nil {
  39. return nil, err
  40. }
  41. list = append(list, memoOrganizer)
  42. }
  43. if err := rows.Err(); err != nil {
  44. return nil, err
  45. }
  46. return list, nil
  47. }
  48. func (d *DB) DeleteMemoOrganizer(ctx context.Context, delete *store.DeleteMemoOrganizer) error {
  49. where, args := []string{}, []any{}
  50. if v := delete.MemoID; v != nil {
  51. where, args = append(where, "`memo_id` = ?"), append(args, *v)
  52. }
  53. if v := delete.UserID; v != nil {
  54. where, args = append(where, "`user_id` = ?"), append(args, *v)
  55. }
  56. stmt := "DELETE FROM `memo_organizer` WHERE " + strings.Join(where, " AND ")
  57. if _, err := d.db.ExecContext(ctx, stmt, args...); err != nil {
  58. return err
  59. }
  60. return nil
  61. }
  62. func vacuumMemoOrganizer(ctx context.Context, tx *sql.Tx) error {
  63. stmt := "DELETE FROM `memo_organizer` WHERE `memo_id` NOT IN (SELECT `id` FROM `memo`) OR `user_id` NOT IN (SELECT `id` FROM `user`)"
  64. _, err := tx.ExecContext(ctx, stmt)
  65. if err != nil {
  66. return err
  67. }
  68. return nil
  69. }