entry_query_builder.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. nArgs := len(e.args) + 1
  27. e.conditions = append(e.conditions, fmt.Sprintf("e.document_vectors @@ plainto_tsquery($%d)", nArgs))
  28. e.args = append(e.args, query)
  29. e.WithOrder(fmt.Sprintf("ts_rank(document_vectors, plainto_tsquery($%d))", nArgs))
  30. e.WithDirection("DESC")
  31. }
  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,
  164. e.user_id,
  165. e.feed_id,
  166. e.hash,
  167. e.published_at at time zone u.timezone,
  168. e.title,
  169. e.url,
  170. e.comments_url,
  171. e.author,
  172. e.content,
  173. e.status,
  174. e.starred,
  175. f.title as feed_title,
  176. f.feed_url,
  177. f.site_url,
  178. f.checked_at,
  179. f.category_id, c.title as category_title,
  180. f.scraper_rules,
  181. f.rewrite_rules,
  182. f.crawler,
  183. f.user_agent,
  184. fi.icon_id,
  185. u.timezone
  186. FROM
  187. entries e
  188. LEFT JOIN
  189. feeds f ON f.id=e.feed_id
  190. LEFT JOIN
  191. categories c ON c.id=f.category_id
  192. LEFT JOIN
  193. feed_icons fi ON fi.feed_id=f.id
  194. LEFT JOIN
  195. users u ON u.id=e.user_id
  196. WHERE %s %s
  197. `
  198. condition := e.buildCondition()
  199. sorting := e.buildSorting()
  200. query = fmt.Sprintf(query, condition, sorting)
  201. rows, err := e.store.db.Query(query, e.args...)
  202. if err != nil {
  203. return nil, fmt.Errorf("unable to get entries: %v", err)
  204. }
  205. defer rows.Close()
  206. entries := make(model.Entries, 0)
  207. for rows.Next() {
  208. var entry model.Entry
  209. var iconID interface{}
  210. var tz string
  211. entry.Feed = &model.Feed{}
  212. entry.Feed.Category = &model.Category{}
  213. entry.Feed.Icon = &model.FeedIcon{}
  214. err := rows.Scan(
  215. &entry.ID,
  216. &entry.UserID,
  217. &entry.FeedID,
  218. &entry.Hash,
  219. &entry.Date,
  220. &entry.Title,
  221. &entry.URL,
  222. &entry.CommentsURL,
  223. &entry.Author,
  224. &entry.Content,
  225. &entry.Status,
  226. &entry.Starred,
  227. &entry.Feed.Title,
  228. &entry.Feed.FeedURL,
  229. &entry.Feed.SiteURL,
  230. &entry.Feed.CheckedAt,
  231. &entry.Feed.Category.ID,
  232. &entry.Feed.Category.Title,
  233. &entry.Feed.ScraperRules,
  234. &entry.Feed.RewriteRules,
  235. &entry.Feed.Crawler,
  236. &entry.Feed.UserAgent,
  237. &iconID,
  238. &tz,
  239. )
  240. if err != nil {
  241. return nil, fmt.Errorf("unable to fetch entry row: %v", err)
  242. }
  243. if iconID == nil {
  244. entry.Feed.Icon.IconID = 0
  245. } else {
  246. entry.Feed.Icon.IconID = iconID.(int64)
  247. }
  248. // Make sure that timestamp fields contains timezone information (API)
  249. entry.Date = timezone.Convert(tz, entry.Date)
  250. entry.Feed.CheckedAt = timezone.Convert(tz, entry.Feed.CheckedAt)
  251. entry.Feed.ID = entry.FeedID
  252. entry.Feed.UserID = entry.UserID
  253. entry.Feed.Icon.FeedID = entry.FeedID
  254. entry.Feed.Category.UserID = entry.UserID
  255. entries = append(entries, &entry)
  256. }
  257. return entries, nil
  258. }
  259. // GetEntryIDs returns a list of entry IDs that match the condition.
  260. func (e *EntryQueryBuilder) GetEntryIDs() ([]int64, error) {
  261. query := `SELECT e.id FROM entries e LEFT JOIN feeds f ON f.id=e.feed_id WHERE %s %s`
  262. condition := e.buildCondition()
  263. query = fmt.Sprintf(query, condition, e.buildSorting())
  264. rows, err := e.store.db.Query(query, e.args...)
  265. if err != nil {
  266. return nil, fmt.Errorf("unable to get entries: %v", err)
  267. }
  268. defer rows.Close()
  269. var entryIDs []int64
  270. for rows.Next() {
  271. var entryID int64
  272. err := rows.Scan(&entryID)
  273. if err != nil {
  274. return nil, fmt.Errorf("unable to fetch entry row: %v", err)
  275. }
  276. entryIDs = append(entryIDs, entryID)
  277. }
  278. return entryIDs, nil
  279. }
  280. func (e *EntryQueryBuilder) buildCondition() string {
  281. return strings.Join(e.conditions, " AND ")
  282. }
  283. func (e *EntryQueryBuilder) buildSorting() string {
  284. var parts []string
  285. if e.order != "" {
  286. parts = append(parts, fmt.Sprintf(`ORDER BY %s`, e.order))
  287. }
  288. if e.direction != "" {
  289. parts = append(parts, fmt.Sprintf(`%s`, e.direction))
  290. }
  291. if e.limit != 0 {
  292. parts = append(parts, fmt.Sprintf(`LIMIT %d`, e.limit))
  293. }
  294. if e.offset != 0 {
  295. parts = append(parts, fmt.Sprintf(`OFFSET %d`, e.offset))
  296. }
  297. return strings.Join(parts, " ")
  298. }
  299. // NewEntryQueryBuilder returns a new EntryQueryBuilder.
  300. func NewEntryQueryBuilder(store *Storage, userID int64) *EntryQueryBuilder {
  301. return &EntryQueryBuilder{
  302. store: store,
  303. args: []interface{}{userID},
  304. conditions: []string{"e.user_id = $1"},
  305. }
  306. }