memo_organizer.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package sqlite
  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 CONFLICT(memo_id, user_id) DO UPDATE
  18. SET
  19. pinned = EXCLUDED.pinned
  20. `
  21. if _, err := d.db.ExecContext(ctx, stmt, upsert.MemoID, upsert.UserID, upsert.Pinned); err != nil {
  22. return nil, err
  23. }
  24. return upsert, nil
  25. }
  26. func (d *DB) GetMemoOrganizer(ctx context.Context, find *store.FindMemoOrganizer) (*store.MemoOrganizer, error) {
  27. where, args := []string{}, []any{}
  28. if find.MemoID != 0 {
  29. where = append(where, "memo_id = ?")
  30. args = append(args, find.MemoID)
  31. }
  32. if find.UserID != 0 {
  33. where = append(where, "user_id = ?")
  34. args = append(args, find.UserID)
  35. }
  36. query := fmt.Sprintf(`
  37. SELECT
  38. memo_id,
  39. user_id,
  40. pinned
  41. FROM memo_organizer
  42. WHERE %s
  43. `, strings.Join(where, " AND "))
  44. row := d.db.QueryRowContext(ctx, query, args...)
  45. if err := row.Err(); err != nil {
  46. return nil, err
  47. }
  48. if row == nil {
  49. return nil, nil
  50. }
  51. memoOrganizer := &store.MemoOrganizer{}
  52. if err := row.Scan(
  53. &memoOrganizer.MemoID,
  54. &memoOrganizer.UserID,
  55. &memoOrganizer.Pinned,
  56. ); err != nil {
  57. return nil, err
  58. }
  59. return memoOrganizer, nil
  60. }
  61. func (d *DB) DeleteMemoOrganizer(ctx context.Context, delete *store.DeleteMemoOrganizer) error {
  62. where, args := []string{}, []any{}
  63. if v := delete.MemoID; v != nil {
  64. where, args = append(where, "memo_id = ?"), append(args, *v)
  65. }
  66. if v := delete.UserID; v != nil {
  67. where, args = append(where, "user_id = ?"), append(args, *v)
  68. }
  69. stmt := `DELETE FROM memo_organizer WHERE ` + strings.Join(where, " AND ")
  70. if _, err := d.db.ExecContext(ctx, stmt, args...); err != nil {
  71. return err
  72. }
  73. return nil
  74. }
  75. func vacuumMemoOrganizer(ctx context.Context, tx *sql.Tx) error {
  76. stmt := `
  77. DELETE FROM
  78. memo_organizer
  79. WHERE
  80. memo_id NOT IN (
  81. SELECT
  82. id
  83. FROM
  84. memo
  85. )
  86. OR user_id NOT IN (
  87. SELECT
  88. id
  89. FROM
  90. user
  91. )`
  92. _, err := tx.ExecContext(ctx, stmt)
  93. if err != nil {
  94. return err
  95. }
  96. return nil
  97. }