category.go 8.0 KB

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