entry_query_builder.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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/timer"
  12. "miniflux.app/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. // WithSearchQuery adds full-text search query to the condition.
  25. func (e *EntryQueryBuilder) WithSearchQuery(query string) *EntryQueryBuilder {
  26. if query != "" {
  27. e.conditions = append(e.conditions, fmt.Sprintf("e.document_vectors @@ plainto_tsquery($%d)", len(e.args)+1))
  28. e.args = append(e.args, query)
  29. }
  30. return e
  31. }
  32. // WithStarred adds starred filter.
  33. func (e *EntryQueryBuilder) WithStarred() *EntryQueryBuilder {
  34. e.conditions = append(e.conditions, "e.starred is true")
  35. return e
  36. }
  37. // BeforeDate adds a condition < published_at
  38. func (e *EntryQueryBuilder) BeforeDate(date time.Time) *EntryQueryBuilder {
  39. e.conditions = append(e.conditions, fmt.Sprintf("e.published_at < $%d", len(e.args)+1))
  40. e.args = append(e.args, date)
  41. return e
  42. }
  43. // AfterDate adds a condition > published_at
  44. func (e *EntryQueryBuilder) AfterDate(date time.Time) *EntryQueryBuilder {
  45. e.conditions = append(e.conditions, fmt.Sprintf("e.published_at > $%d", len(e.args)+1))
  46. e.args = append(e.args, date)
  47. return e
  48. }
  49. // BeforeEntryID adds a condition < entryID.
  50. func (e *EntryQueryBuilder) BeforeEntryID(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. // AfterEntryID adds a condition > entryID.
  58. func (e *EntryQueryBuilder) AfterEntryID(entryID int64) *EntryQueryBuilder {
  59. if entryID != 0 {
  60. e.conditions = append(e.conditions, fmt.Sprintf("e.id > $%d", len(e.args)+1))
  61. e.args = append(e.args, entryID)
  62. }
  63. return e
  64. }
  65. // WithEntryIDs adds a condition to fetch only the given entry IDs.
  66. func (e *EntryQueryBuilder) WithEntryIDs(entryIDs []int64) *EntryQueryBuilder {
  67. e.conditions = append(e.conditions, fmt.Sprintf("e.id = ANY($%d)", len(e.args)+1))
  68. e.args = append(e.args, pq.Array(entryIDs))
  69. return e
  70. }
  71. // WithEntryID set the entryID.
  72. func (e *EntryQueryBuilder) WithEntryID(entryID int64) *EntryQueryBuilder {
  73. if entryID != 0 {
  74. e.conditions = append(e.conditions, fmt.Sprintf("e.id = $%d", len(e.args)+1))
  75. e.args = append(e.args, entryID)
  76. }
  77. return e
  78. }
  79. // WithFeedID set the feedID.
  80. func (e *EntryQueryBuilder) WithFeedID(feedID int64) *EntryQueryBuilder {
  81. if feedID != 0 {
  82. e.conditions = append(e.conditions, fmt.Sprintf("e.feed_id = $%d", len(e.args)+1))
  83. e.args = append(e.args, feedID)
  84. }
  85. return e
  86. }
  87. // WithCategoryID set the categoryID.
  88. func (e *EntryQueryBuilder) WithCategoryID(categoryID int64) *EntryQueryBuilder {
  89. if categoryID != 0 {
  90. e.conditions = append(e.conditions, fmt.Sprintf("f.category_id = $%d", len(e.args)+1))
  91. e.args = append(e.args, categoryID)
  92. }
  93. return e
  94. }
  95. // WithStatus set the entry status.
  96. func (e *EntryQueryBuilder) WithStatus(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. // WithoutStatus set the entry status that should not be returned.
  104. func (e *EntryQueryBuilder) WithoutStatus(status string) *EntryQueryBuilder {
  105. if status != "" {
  106. e.conditions = append(e.conditions, fmt.Sprintf("e.status <> $%d", len(e.args)+1))
  107. e.args = append(e.args, status)
  108. }
  109. return e
  110. }
  111. // WithOrder set the sorting order.
  112. func (e *EntryQueryBuilder) WithOrder(order string) *EntryQueryBuilder {
  113. e.order = order
  114. return e
  115. }
  116. // WithDirection set the sorting direction.
  117. func (e *EntryQueryBuilder) WithDirection(direction string) *EntryQueryBuilder {
  118. e.direction = direction
  119. return e
  120. }
  121. // WithLimit set the limit.
  122. func (e *EntryQueryBuilder) WithLimit(limit int) *EntryQueryBuilder {
  123. e.limit = limit
  124. return e
  125. }
  126. // WithOffset set the offset.
  127. func (e *EntryQueryBuilder) WithOffset(offset int) *EntryQueryBuilder {
  128. e.offset = offset
  129. return e
  130. }
  131. // CountEntries count the number of entries that match the condition.
  132. func (e *EntryQueryBuilder) CountEntries() (count int, err error) {
  133. query := `SELECT count(*) FROM entries e LEFT JOIN feeds f ON f.id=e.feed_id WHERE %s`
  134. condition := e.buildCondition()
  135. defer timer.ExecutionTime(time.Now(), fmt.Sprintf("[EntryQueryBuilder:CountEntries] %s, args=%v", condition, e.args))
  136. err = e.store.db.QueryRow(fmt.Sprintf(query, condition), e.args...).Scan(&count)
  137. if err != nil {
  138. return 0, fmt.Errorf("unable to count entries: %v", err)
  139. }
  140. return count, nil
  141. }
  142. // GetEntry returns a single entry that match the condition.
  143. func (e *EntryQueryBuilder) GetEntry() (*model.Entry, error) {
  144. e.limit = 1
  145. entries, err := e.GetEntries()
  146. if err != nil {
  147. return nil, err
  148. }
  149. if len(entries) != 1 {
  150. return nil, nil
  151. }
  152. entries[0].Enclosures, err = e.store.GetEnclosures(entries[0].ID)
  153. if err != nil {
  154. return nil, err
  155. }
  156. return entries[0], nil
  157. }
  158. // GetEntries returns a list of entries that match the condition.
  159. func (e *EntryQueryBuilder) GetEntries() (model.Entries, error) {
  160. query := `
  161. SELECT
  162. e.id, e.user_id, e.feed_id, e.hash, e.published_at at time zone u.timezone, e.title,
  163. e.url, e.comments_url, e.author, e.content, e.status, e.starred,
  164. f.title as feed_title, f.feed_url, f.site_url, f.checked_at,
  165. f.category_id, c.title as category_title, f.scraper_rules, f.rewrite_rules, f.crawler, f.user_agent,
  166. fi.icon_id,
  167. u.timezone
  168. FROM entries e
  169. LEFT JOIN feeds f ON f.id=e.feed_id
  170. LEFT JOIN categories c ON c.id=f.category_id
  171. LEFT JOIN feed_icons fi ON fi.feed_id=f.id
  172. LEFT JOIN users u ON u.id=e.user_id
  173. WHERE %s %s
  174. `
  175. condition := e.buildCondition()
  176. sorting := e.buildSorting()
  177. query = fmt.Sprintf(query, condition, sorting)
  178. defer timer.ExecutionTime(time.Now(), fmt.Sprintf("[EntryQueryBuilder:GetEntries] %s, args=%v, sorting=%s", condition, e.args, 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. // log.Println(query)
  243. defer timer.ExecutionTime(time.Now(), fmt.Sprintf("[EntryQueryBuilder:GetEntryIDs] condition=%s, args=%v", condition, e.args))
  244. rows, err := e.store.db.Query(query, e.args...)
  245. if err != nil {
  246. return nil, fmt.Errorf("unable to get entries: %v", err)
  247. }
  248. defer rows.Close()
  249. var entryIDs []int64
  250. for rows.Next() {
  251. var entryID int64
  252. err := rows.Scan(&entryID)
  253. if err != nil {
  254. return nil, fmt.Errorf("unable to fetch entry row: %v", err)
  255. }
  256. entryIDs = append(entryIDs, entryID)
  257. }
  258. return entryIDs, nil
  259. }
  260. func (e *EntryQueryBuilder) buildCondition() string {
  261. return strings.Join(e.conditions, " AND ")
  262. }
  263. func (e *EntryQueryBuilder) buildSorting() string {
  264. var parts []string
  265. if e.order != "" {
  266. parts = append(parts, fmt.Sprintf(`ORDER BY "%s"`, e.order))
  267. }
  268. if e.direction != "" {
  269. parts = append(parts, fmt.Sprintf(`%s`, e.direction))
  270. }
  271. if e.limit != 0 {
  272. parts = append(parts, fmt.Sprintf(`LIMIT %d`, e.limit))
  273. }
  274. if e.offset != 0 {
  275. parts = append(parts, fmt.Sprintf(`OFFSET %d`, e.offset))
  276. }
  277. return strings.Join(parts, " ")
  278. }
  279. // NewEntryQueryBuilder returns a new EntryQueryBuilder.
  280. func NewEntryQueryBuilder(store *Storage, userID int64) *EntryQueryBuilder {
  281. return &EntryQueryBuilder{
  282. store: store,
  283. args: []interface{}{userID},
  284. conditions: []string{"e.user_id = $1"},
  285. }
  286. }