category.go 7.8 KB

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