category.go 7.6 KB

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