category.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package storage // import "miniflux.app/v2/internal/storage"
  4. import (
  5. "database/sql"
  6. "errors"
  7. "fmt"
  8. "github.com/lib/pq"
  9. "miniflux.app/v2/internal/model"
  10. )
  11. // AnotherCategoryExists checks if another category exists with the same title.
  12. func (s *Storage) AnotherCategoryExists(userID, categoryID int64, title string) bool {
  13. var result bool
  14. query := `SELECT true FROM categories WHERE user_id=$1 AND id != $2 AND lower(title)=lower($3) LIMIT 1`
  15. s.db.QueryRow(query, userID, categoryID, title).Scan(&result)
  16. return result
  17. }
  18. // CategoryTitleExists checks if the given category exists into the database.
  19. func (s *Storage) CategoryTitleExists(userID int64, title string) bool {
  20. var result bool
  21. query := `SELECT true FROM categories WHERE user_id=$1 AND lower(title)=lower($2) LIMIT 1`
  22. s.db.QueryRow(query, userID, title).Scan(&result)
  23. return result
  24. }
  25. // CategoryIDExists checks if the given category exists into the database.
  26. func (s *Storage) CategoryIDExists(userID, categoryID int64) bool {
  27. var result bool
  28. query := `SELECT true FROM categories WHERE user_id=$1 AND id=$2 LIMIT 1`
  29. s.db.QueryRow(query, userID, categoryID).Scan(&result)
  30. return result
  31. }
  32. // Category returns a category from the database.
  33. func (s *Storage) Category(userID, categoryID int64) (*model.Category, error) {
  34. var category model.Category
  35. query := `SELECT id, user_id, title, hide_globally FROM categories WHERE user_id=$1 AND id=$2`
  36. err := s.db.QueryRow(query, userID, categoryID).Scan(&category.ID, &category.UserID, &category.Title, &category.HideGlobally)
  37. switch {
  38. case errors.Is(err, sql.ErrNoRows):
  39. return nil, nil
  40. case err != nil:
  41. return nil, fmt.Errorf(`store: unable to fetch category: %v`, err)
  42. default:
  43. return &category, nil
  44. }
  45. }
  46. // FirstCategory returns the first category for the given user.
  47. func (s *Storage) FirstCategory(userID int64) (*model.Category, error) {
  48. query := `SELECT id, user_id, title, hide_globally FROM categories WHERE user_id=$1 ORDER BY title ASC LIMIT 1`
  49. var category model.Category
  50. err := s.db.QueryRow(query, userID).Scan(&category.ID, &category.UserID, &category.Title, &category.HideGlobally)
  51. switch {
  52. case errors.Is(err, sql.ErrNoRows):
  53. return nil, nil
  54. case err != nil:
  55. return nil, fmt.Errorf(`store: unable to fetch category: %v`, err)
  56. default:
  57. return &category, nil
  58. }
  59. }
  60. // CategoryByTitle finds a category by the title.
  61. func (s *Storage) CategoryByTitle(userID int64, title string) (*model.Category, error) {
  62. var category model.Category
  63. query := `SELECT id, user_id, title, hide_globally FROM categories WHERE user_id=$1 AND title=$2`
  64. err := s.db.QueryRow(query, userID, title).Scan(&category.ID, &category.UserID, &category.Title, &category.HideGlobally)
  65. switch {
  66. case errors.Is(err, sql.ErrNoRows):
  67. return nil, nil
  68. case err != nil:
  69. return nil, fmt.Errorf(`store: unable to fetch category: %v`, err)
  70. default:
  71. return &category, nil
  72. }
  73. }
  74. // Categories returns all categories that belongs to the given user.
  75. func (s *Storage) Categories(userID int64) (model.Categories, error) {
  76. query := `SELECT id, user_id, title, hide_globally FROM categories WHERE user_id=$1 ORDER BY title ASC`
  77. rows, err := s.db.Query(query, userID)
  78. if err != nil {
  79. return nil, fmt.Errorf(`store: unable to fetch categories: %v`, err)
  80. }
  81. defer rows.Close()
  82. categories := make(model.Categories, 0)
  83. for rows.Next() {
  84. var category model.Category
  85. if err := rows.Scan(&category.ID, &category.UserID, &category.Title, &category.HideGlobally); err != nil {
  86. return nil, fmt.Errorf(`store: unable to fetch category row: %v`, err)
  87. }
  88. categories = append(categories, category)
  89. }
  90. return categories, nil
  91. }
  92. // CategoriesWithFeedCount returns all categories with the number of feeds, sorted according to sortOrder.
  93. func (s *Storage) CategoriesWithFeedCount(userID int64, sortOrder string) (model.Categories, error) {
  94. query := `
  95. SELECT
  96. c.id,
  97. c.user_id,
  98. c.title,
  99. c.hide_globally,
  100. coalesce(fc.feed_count, 0),
  101. coalesce(uc.unread_count, 0)
  102. FROM categories c
  103. LEFT JOIN (
  104. SELECT category_id, count(*) AS feed_count
  105. FROM feeds
  106. WHERE user_id = $2
  107. GROUP BY category_id
  108. ) fc ON fc.category_id = c.id
  109. LEFT JOIN (
  110. SELECT f.category_id, count(*) AS unread_count
  111. FROM entries e
  112. INNER JOIN feeds f ON f.id = e.feed_id
  113. WHERE e.user_id = $2 AND e.status = $1
  114. GROUP BY f.category_id
  115. ) uc ON uc.category_id = c.id
  116. WHERE
  117. c.user_id=$2
  118. `
  119. if sortOrder == "alphabetical" {
  120. query += `
  121. ORDER BY
  122. c.title ASC
  123. `
  124. } else {
  125. query += `
  126. ORDER BY
  127. coalesce(uc.unread_count, 0) DESC,
  128. c.title ASC
  129. `
  130. }
  131. rows, err := s.db.Query(query, model.EntryStatusUnread, userID)
  132. if err != nil {
  133. return nil, fmt.Errorf(`store: unable to fetch categories: %v`, err)
  134. }
  135. defer rows.Close()
  136. categories := make(model.Categories, 0)
  137. for rows.Next() {
  138. var category model.Category
  139. if err := rows.Scan(&category.ID, &category.UserID, &category.Title, &category.HideGlobally, &category.FeedCount, &category.TotalUnread); err != nil {
  140. return nil, fmt.Errorf(`store: unable to fetch category row: %v`, err)
  141. }
  142. categories = append(categories, category)
  143. }
  144. return categories, nil
  145. }
  146. // CreateCategory creates a new category.
  147. func (s *Storage) CreateCategory(userID int64, request *model.CategoryCreationRequest) (*model.Category, error) {
  148. var category model.Category
  149. query := `
  150. INSERT INTO categories
  151. (user_id, title, hide_globally)
  152. VALUES
  153. ($1, $2, $3)
  154. RETURNING
  155. id,
  156. user_id,
  157. title,
  158. hide_globally
  159. `
  160. err := s.db.QueryRow(
  161. query,
  162. userID,
  163. request.Title,
  164. request.HideGlobally,
  165. ).Scan(
  166. &category.ID,
  167. &category.UserID,
  168. &category.Title,
  169. &category.HideGlobally,
  170. )
  171. if err != nil {
  172. return nil, fmt.Errorf(`store: unable to create category %q for user ID %d: %v`, request.Title, userID, err)
  173. }
  174. return &category, nil
  175. }
  176. // UpdateCategory updates an existing category.
  177. func (s *Storage) UpdateCategory(category *model.Category) error {
  178. query := `UPDATE categories SET title=$1, hide_globally=$2 WHERE id=$3 AND user_id=$4`
  179. _, err := s.db.Exec(
  180. query,
  181. category.Title,
  182. category.HideGlobally,
  183. category.ID,
  184. category.UserID,
  185. )
  186. if err != nil {
  187. return fmt.Errorf(`store: unable to update category: %v`, err)
  188. }
  189. return nil
  190. }
  191. // RemoveCategory deletes a category.
  192. func (s *Storage) RemoveCategory(userID, categoryID int64) error {
  193. query := `DELETE FROM categories WHERE id = $1 AND user_id = $2`
  194. result, err := s.db.Exec(query, categoryID, userID)
  195. if err != nil {
  196. return fmt.Errorf(`store: unable to remove this category: %v`, err)
  197. }
  198. count, err := result.RowsAffected()
  199. if err != nil {
  200. return fmt.Errorf(`store: unable to remove this category: %v`, err)
  201. }
  202. if count == 0 {
  203. return errors.New(`store: no category has been removed`)
  204. }
  205. return nil
  206. }
  207. // RemoveAndReplaceCategoriesByName deletes the given categories, replacing those categories with the user's first
  208. // category on affected feeds.
  209. func (s *Storage) RemoveAndReplaceCategoriesByName(userid int64, titles []string) error {
  210. tx, err := s.db.Begin()
  211. if err != nil {
  212. return errors.New("store: unable to begin transaction")
  213. }
  214. titleParam := pq.Array(titles)
  215. var count int
  216. query := "SELECT count(*) FROM categories WHERE user_id = $1 and title != ANY($2)"
  217. err = tx.QueryRow(query, userid, titleParam).Scan(&count)
  218. if err != nil {
  219. tx.Rollback()
  220. return errors.New("store: unable to retrieve category count")
  221. }
  222. if count < 1 {
  223. tx.Rollback()
  224. return errors.New("store: at least 1 category must remain after deletion")
  225. }
  226. query = `
  227. WITH d_cats AS (SELECT id FROM categories WHERE user_id = $1 AND title = ANY($2))
  228. UPDATE feeds
  229. SET category_id =
  230. (SELECT id
  231. FROM categories
  232. WHERE user_id = $1 AND id NOT IN (SELECT id FROM d_cats)
  233. ORDER BY title ASC
  234. LIMIT 1)
  235. WHERE user_id = $1 AND category_id IN (SELECT id FROM d_cats)
  236. `
  237. _, err = tx.Exec(query, userid, titleParam)
  238. if err != nil {
  239. tx.Rollback()
  240. return fmt.Errorf("store: unable to replace categories: %v", err)
  241. }
  242. query = "DELETE FROM categories WHERE user_id = $1 AND title = ANY($2)"
  243. _, err = tx.Exec(query, userid, titleParam)
  244. if err != nil {
  245. tx.Rollback()
  246. return fmt.Errorf("store: unable to delete categories: %v", err)
  247. }
  248. tx.Commit()
  249. return nil
  250. }