entry_query_builder.go 9.3 KB

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