category.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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 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 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 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. (SELECT count(*) FROM feeds WHERE feeds.category_id=c.id) AS count,
  101. (SELECT count(*)
  102. FROM feeds
  103. JOIN entries ON (feeds.id = entries.feed_id)
  104. WHERE feeds.category_id = c.id AND entries.status = $1) AS count_unread
  105. FROM categories c
  106. WHERE
  107. user_id=$2
  108. `
  109. if sortOrder == "alphabetical" {
  110. query += `
  111. ORDER BY
  112. c.title ASC
  113. `
  114. } else {
  115. query += `
  116. ORDER BY
  117. count_unread DESC,
  118. c.title ASC
  119. `
  120. }
  121. rows, err := s.db.Query(query, model.EntryStatusUnread, userID)
  122. if err != nil {
  123. return nil, fmt.Errorf(`store: unable to fetch categories: %v`, err)
  124. }
  125. defer rows.Close()
  126. categories := make(model.Categories, 0)
  127. for rows.Next() {
  128. var category model.Category
  129. if err := rows.Scan(&category.ID, &category.UserID, &category.Title, &category.HideGlobally, &category.FeedCount, &category.TotalUnread); err != nil {
  130. return nil, fmt.Errorf(`store: unable to fetch category row: %v`, err)
  131. }
  132. categories = append(categories, category)
  133. }
  134. return categories, nil
  135. }
  136. // CreateCategory creates a new category.
  137. func (s *Storage) CreateCategory(userID int64, request *model.CategoryCreationRequest) (*model.Category, error) {
  138. var category model.Category
  139. query := `
  140. INSERT INTO categories
  141. (user_id, title, hide_globally)
  142. VALUES
  143. ($1, $2, $3)
  144. RETURNING
  145. id,
  146. user_id,
  147. title,
  148. hide_globally
  149. `
  150. err := s.db.QueryRow(
  151. query,
  152. userID,
  153. request.Title,
  154. request.HideGlobally,
  155. ).Scan(
  156. &category.ID,
  157. &category.UserID,
  158. &category.Title,
  159. &category.HideGlobally,
  160. )
  161. if err != nil {
  162. return nil, fmt.Errorf(`store: unable to create category %q for user ID %d: %v`, request.Title, userID, err)
  163. }
  164. return &category, nil
  165. }
  166. // UpdateCategory updates an existing category.
  167. func (s *Storage) UpdateCategory(category *model.Category) error {
  168. query := `UPDATE categories SET title=$1, hide_globally=$2 WHERE id=$3 AND user_id=$4`
  169. _, err := s.db.Exec(
  170. query,
  171. category.Title,
  172. category.HideGlobally,
  173. category.ID,
  174. category.UserID,
  175. )
  176. if err != nil {
  177. return fmt.Errorf(`store: unable to update category: %v`, err)
  178. }
  179. return nil
  180. }
  181. // RemoveCategory deletes a category.
  182. func (s *Storage) RemoveCategory(userID, categoryID int64) error {
  183. query := `DELETE FROM categories WHERE id = $1 AND user_id = $2`
  184. result, err := s.db.Exec(query, categoryID, userID)
  185. if err != nil {
  186. return fmt.Errorf(`store: unable to remove this category: %v`, err)
  187. }
  188. count, err := result.RowsAffected()
  189. if err != nil {
  190. return fmt.Errorf(`store: unable to remove this category: %v`, err)
  191. }
  192. if count == 0 {
  193. return errors.New(`store: no category has been removed`)
  194. }
  195. return nil
  196. }
  197. // RemoveAndReplaceCategoriesByName deletes the given categories, replacing those categories with the user's first
  198. // category on affected feeds.
  199. func (s *Storage) RemoveAndReplaceCategoriesByName(userid int64, titles []string) error {
  200. tx, err := s.db.Begin()
  201. if err != nil {
  202. return errors.New("store: unable to begin transaction")
  203. }
  204. titleParam := pq.Array(titles)
  205. var count int
  206. query := "SELECT count(*) FROM categories WHERE user_id = $1 and title != ANY($2)"
  207. err = tx.QueryRow(query, userid, titleParam).Scan(&count)
  208. if err != nil {
  209. tx.Rollback()
  210. return errors.New("store: unable to retrieve category count")
  211. }
  212. if count < 1 {
  213. tx.Rollback()
  214. return errors.New("store: at least 1 category must remain after deletion")
  215. }
  216. query = `
  217. WITH d_cats AS (SELECT id FROM categories WHERE user_id = $1 AND title = ANY($2))
  218. UPDATE feeds
  219. SET category_id =
  220. (SELECT id
  221. FROM categories
  222. WHERE user_id = $1 AND id NOT IN (SELECT id FROM d_cats)
  223. ORDER BY title ASC
  224. LIMIT 1)
  225. WHERE user_id = $1 AND category_id IN (SELECT id FROM d_cats)
  226. `
  227. _, err = tx.Exec(query, userid, titleParam)
  228. if err != nil {
  229. tx.Rollback()
  230. return fmt.Errorf("store: unable to replace categories: %v", err)
  231. }
  232. query = "DELETE FROM categories WHERE user_id = $1 AND title = ANY($2)"
  233. _, err = tx.Exec(query, userid, titleParam)
  234. if err != nil {
  235. tx.Rollback()
  236. return fmt.Errorf("store: unable to delete categories: %v", err)
  237. }
  238. tx.Commit()
  239. return nil
  240. }