entry_query_builder.go 8.9 KB

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