entry_query_builder.go 8.9 KB

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