category.go 7.6 KB

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