entry_query_builder.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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
  5. import (
  6. "fmt"
  7. "strings"
  8. "time"
  9. "github.com/lib/pq"
  10. "github.com/miniflux/miniflux/model"
  11. "github.com/miniflux/miniflux/timer"
  12. "github.com/miniflux/miniflux/timezone"
  13. )
  14. // EntryQueryBuilder builds a SQL query to fetch entries.
  15. type EntryQueryBuilder struct {
  16. store *Storage
  17. args []interface{}
  18. conditions []string
  19. order string
  20. direction string
  21. limit int
  22. offset int
  23. }
  24. // WithStarred adds starred filter.
  25. func (e *EntryQueryBuilder) WithStarred() *EntryQueryBuilder {
  26. e.conditions = append(e.conditions, "e.starred is true")
  27. return e
  28. }
  29. // Before add condition based on the entry date.
  30. func (e *EntryQueryBuilder) Before(date *time.Time) *EntryQueryBuilder {
  31. e.conditions = append(e.conditions, fmt.Sprintf("e.published_at < $%d", len(e.args)+1))
  32. e.args = append(e.args, date)
  33. return e
  34. }
  35. // WithGreaterThanEntryID adds a condition > entryID.
  36. func (e *EntryQueryBuilder) WithGreaterThanEntryID(entryID int64) *EntryQueryBuilder {
  37. if entryID != 0 {
  38. e.conditions = append(e.conditions, fmt.Sprintf("e.id > $%d", len(e.args)+1))
  39. e.args = append(e.args, entryID)
  40. }
  41. return e
  42. }
  43. // WithEntryIDs adds a condition to fetch only the given entry IDs.
  44. func (e *EntryQueryBuilder) WithEntryIDs(entryIDs []int64) *EntryQueryBuilder {
  45. e.conditions = append(e.conditions, fmt.Sprintf("e.id = ANY($%d)", len(e.args)+1))
  46. e.args = append(e.args, pq.Array(entryIDs))
  47. return e
  48. }
  49. // WithEntryID set the entryID.
  50. func (e *EntryQueryBuilder) WithEntryID(entryID int64) *EntryQueryBuilder {
  51. if entryID != 0 {
  52. e.conditions = append(e.conditions, fmt.Sprintf("e.id = $%d", len(e.args)+1))
  53. e.args = append(e.args, entryID)
  54. }
  55. return e
  56. }
  57. // WithFeedID set the feedID.
  58. func (e *EntryQueryBuilder) WithFeedID(feedID int64) *EntryQueryBuilder {
  59. if feedID != 0 {
  60. e.conditions = append(e.conditions, fmt.Sprintf("e.feed_id = $%d", len(e.args)+1))
  61. e.args = append(e.args, feedID)
  62. }
  63. return e
  64. }
  65. // WithCategoryID set the categoryID.
  66. func (e *EntryQueryBuilder) WithCategoryID(categoryID int64) *EntryQueryBuilder {
  67. if categoryID != 0 {
  68. e.conditions = append(e.conditions, fmt.Sprintf("f.category_id = $%d", len(e.args)+1))
  69. e.args = append(e.args, categoryID)
  70. }
  71. return e
  72. }
  73. // WithStatus set the entry status.
  74. func (e *EntryQueryBuilder) WithStatus(status string) *EntryQueryBuilder {
  75. if status != "" {
  76. e.conditions = append(e.conditions, fmt.Sprintf("e.status = $%d", len(e.args)+1))
  77. e.args = append(e.args, status)
  78. }
  79. return e
  80. }
  81. // WithoutStatus set the entry status that should not be returned.
  82. func (e *EntryQueryBuilder) WithoutStatus(status string) *EntryQueryBuilder {
  83. if status != "" {
  84. e.conditions = append(e.conditions, fmt.Sprintf("e.status <> $%d", len(e.args)+1))
  85. e.args = append(e.args, status)
  86. }
  87. return e
  88. }
  89. // WithOrder set the sorting order.
  90. func (e *EntryQueryBuilder) WithOrder(order string) *EntryQueryBuilder {
  91. e.order = order
  92. return e
  93. }
  94. // WithDirection set the sorting direction.
  95. func (e *EntryQueryBuilder) WithDirection(direction string) *EntryQueryBuilder {
  96. e.direction = direction
  97. return e
  98. }
  99. // WithLimit set the limit.
  100. func (e *EntryQueryBuilder) WithLimit(limit int) *EntryQueryBuilder {
  101. e.limit = limit
  102. return e
  103. }
  104. // WithOffset set the offset.
  105. func (e *EntryQueryBuilder) WithOffset(offset int) *EntryQueryBuilder {
  106. e.offset = offset
  107. return e
  108. }
  109. // CountEntries count the number of entries that match the condition.
  110. func (e *EntryQueryBuilder) CountEntries() (count int, err error) {
  111. query := `SELECT count(*) FROM entries e LEFT JOIN feeds f ON f.id=e.feed_id WHERE %s`
  112. condition := e.buildCondition()
  113. defer timer.ExecutionTime(time.Now(), fmt.Sprintf("[EntryQueryBuilder:CountEntries] condition=%s, args=%v", condition, e.args))
  114. err = e.store.db.QueryRow(fmt.Sprintf(query, condition), e.args...).Scan(&count)
  115. if err != nil {
  116. return 0, fmt.Errorf("unable to count entries: %v", err)
  117. }
  118. return count, nil
  119. }
  120. // GetEntry returns a single entry that match the condition.
  121. func (e *EntryQueryBuilder) GetEntry() (*model.Entry, error) {
  122. e.limit = 1
  123. entries, err := e.GetEntries()
  124. if err != nil {
  125. return nil, err
  126. }
  127. if len(entries) != 1 {
  128. return nil, nil
  129. }
  130. entries[0].Enclosures, err = e.store.GetEnclosures(entries[0].ID)
  131. if err != nil {
  132. return nil, err
  133. }
  134. return entries[0], nil
  135. }
  136. // GetEntries returns a list of entries that match the condition.
  137. func (e *EntryQueryBuilder) GetEntries() (model.Entries, error) {
  138. query := `
  139. SELECT
  140. e.id, e.user_id, e.feed_id, e.hash, e.published_at at time zone u.timezone, e.title,
  141. e.url, e.comments_url, e.author, e.content, e.status, e.starred,
  142. f.title as feed_title, f.feed_url, f.site_url, f.checked_at,
  143. f.category_id, c.title as category_title, f.scraper_rules, f.rewrite_rules, f.crawler,
  144. fi.icon_id,
  145. u.timezone
  146. FROM entries e
  147. LEFT JOIN feeds f ON f.id=e.feed_id
  148. LEFT JOIN categories c ON c.id=f.category_id
  149. LEFT JOIN feed_icons fi ON fi.feed_id=f.id
  150. LEFT JOIN users u ON u.id=e.user_id
  151. WHERE %s %s
  152. `
  153. condition := e.buildCondition()
  154. query = fmt.Sprintf(query, condition, e.buildSorting())
  155. // log.Println(query)
  156. defer timer.ExecutionTime(time.Now(), fmt.Sprintf("[EntryQueryBuilder:GetEntries] condition=%s, args=%v", condition, e.args))
  157. rows, err := e.store.db.Query(query, e.args...)
  158. if err != nil {
  159. return nil, fmt.Errorf("unable to get entries: %v", err)
  160. }
  161. defer rows.Close()
  162. entries := make(model.Entries, 0)
  163. for rows.Next() {
  164. var entry model.Entry
  165. var iconID interface{}
  166. var tz string
  167. entry.Feed = &model.Feed{}
  168. entry.Feed.Category = &model.Category{}
  169. entry.Feed.Icon = &model.FeedIcon{}
  170. err := rows.Scan(
  171. &entry.ID,
  172. &entry.UserID,
  173. &entry.FeedID,
  174. &entry.Hash,
  175. &entry.Date,
  176. &entry.Title,
  177. &entry.URL,
  178. &entry.CommentsURL,
  179. &entry.Author,
  180. &entry.Content,
  181. &entry.Status,
  182. &entry.Starred,
  183. &entry.Feed.Title,
  184. &entry.Feed.FeedURL,
  185. &entry.Feed.SiteURL,
  186. &entry.Feed.CheckedAt,
  187. &entry.Feed.Category.ID,
  188. &entry.Feed.Category.Title,
  189. &entry.Feed.ScraperRules,
  190. &entry.Feed.RewriteRules,
  191. &entry.Feed.Crawler,
  192. &iconID,
  193. &tz,
  194. )
  195. if err != nil {
  196. return nil, fmt.Errorf("unable to fetch entry row: %v", err)
  197. }
  198. if iconID == nil {
  199. entry.Feed.Icon.IconID = 0
  200. } else {
  201. entry.Feed.Icon.IconID = iconID.(int64)
  202. }
  203. // Make sure that timestamp fields contains timezone information (API)
  204. entry.Date = timezone.Convert(tz, entry.Date)
  205. entry.Feed.CheckedAt = timezone.Convert(tz, entry.Feed.CheckedAt)
  206. entry.Feed.ID = entry.FeedID
  207. entry.Feed.UserID = entry.UserID
  208. entry.Feed.Icon.FeedID = entry.FeedID
  209. entry.Feed.Category.UserID = entry.UserID
  210. entries = append(entries, &entry)
  211. }
  212. return entries, nil
  213. }
  214. // GetEntryIDs returns a list of entry IDs that match the condition.
  215. func (e *EntryQueryBuilder) GetEntryIDs() ([]int64, error) {
  216. query := `SELECT e.id FROM entries e LEFT JOIN feeds f ON f.id=e.feed_id WHERE %s %s`
  217. condition := e.buildCondition()
  218. query = fmt.Sprintf(query, condition, e.buildSorting())
  219. // log.Println(query)
  220. defer timer.ExecutionTime(time.Now(), fmt.Sprintf("[EntryQueryBuilder:GetEntryIDs] condition=%s, args=%v", condition, e.args))
  221. rows, err := e.store.db.Query(query, e.args...)
  222. if err != nil {
  223. return nil, fmt.Errorf("unable to get entries: %v", err)
  224. }
  225. defer rows.Close()
  226. var entryIDs []int64
  227. for rows.Next() {
  228. var entryID int64
  229. err := rows.Scan(&entryID)
  230. if err != nil {
  231. return nil, fmt.Errorf("unable to fetch entry row: %v", err)
  232. }
  233. entryIDs = append(entryIDs, entryID)
  234. }
  235. return entryIDs, nil
  236. }
  237. func (e *EntryQueryBuilder) buildCondition() string {
  238. return strings.Join(e.conditions, " AND ")
  239. }
  240. func (e *EntryQueryBuilder) buildSorting() string {
  241. var queries []string
  242. if e.order != "" {
  243. queries = append(queries, fmt.Sprintf(`ORDER BY "%s"`, e.order))
  244. }
  245. if e.direction != "" {
  246. queries = append(queries, fmt.Sprintf(`%s`, e.direction))
  247. }
  248. if e.limit != 0 {
  249. queries = append(queries, fmt.Sprintf(`LIMIT %d`, e.limit))
  250. }
  251. if e.offset != 0 {
  252. queries = append(queries, fmt.Sprintf(`OFFSET %d`, e.offset))
  253. }
  254. return strings.Join(queries, " ")
  255. }
  256. // NewEntryQueryBuilder returns a new EntryQueryBuilder.
  257. func NewEntryQueryBuilder(store *Storage, userID int64) *EntryQueryBuilder {
  258. return &EntryQueryBuilder{
  259. store: store,
  260. args: []interface{}{userID},
  261. conditions: []string{"e.user_id = $1"},
  262. }
  263. }