entry_query_builder.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. // 0.0000001 = 0.1 / (seconds_in_a_day)
  30. e.WithOrder(fmt.Sprintf("ts_rank(document_vectors, plainto_tsquery($%d)) - extract (epoch from now() - published_at)::float * 0.0000001", nArgs))
  31. e.WithDirection("DESC")
  32. }
  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 filter by 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.Int64Array(entryIDs))
  72. return e
  73. }
  74. // WithEntryID filter by entry ID.
  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 filter by feed ID.
  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 filter by category ID.
  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 filter by 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. // WithStatuses filter by a list of entry statuses.
  107. func (e *EntryQueryBuilder) WithStatuses(statuses []string) *EntryQueryBuilder {
  108. if len(statuses) > 0 {
  109. e.conditions = append(e.conditions, fmt.Sprintf("e.status = ANY($%d)", len(e.args)+1))
  110. e.args = append(e.args, pq.StringArray(statuses))
  111. }
  112. return e
  113. }
  114. // WithoutStatus set the entry status that should not be returned.
  115. func (e *EntryQueryBuilder) WithoutStatus(status string) *EntryQueryBuilder {
  116. if status != "" {
  117. e.conditions = append(e.conditions, fmt.Sprintf("e.status <> $%d", len(e.args)+1))
  118. e.args = append(e.args, status)
  119. }
  120. return e
  121. }
  122. // WithShareCode set the entry share code.
  123. func (e *EntryQueryBuilder) WithShareCode(shareCode string) *EntryQueryBuilder {
  124. e.conditions = append(e.conditions, fmt.Sprintf("e.share_code = $%d", len(e.args)+1))
  125. e.args = append(e.args, shareCode)
  126. return e
  127. }
  128. // WithShareCodeNotEmpty adds a filter for non-empty share code.
  129. func (e *EntryQueryBuilder) WithShareCodeNotEmpty() *EntryQueryBuilder {
  130. e.conditions = append(e.conditions, "e.share_code <> ''")
  131. return e
  132. }
  133. // WithOrder set the sorting order.
  134. func (e *EntryQueryBuilder) WithOrder(order string) *EntryQueryBuilder {
  135. e.order = order
  136. return e
  137. }
  138. // WithDirection set the sorting direction.
  139. func (e *EntryQueryBuilder) WithDirection(direction string) *EntryQueryBuilder {
  140. e.direction = direction
  141. return e
  142. }
  143. // WithLimit set the limit.
  144. func (e *EntryQueryBuilder) WithLimit(limit int) *EntryQueryBuilder {
  145. if limit > 0 {
  146. e.limit = limit
  147. }
  148. return e
  149. }
  150. // WithOffset set the offset.
  151. func (e *EntryQueryBuilder) WithOffset(offset int) *EntryQueryBuilder {
  152. if offset > 0 {
  153. e.offset = offset
  154. }
  155. return e
  156. }
  157. // CountEntries count the number of entries that match the condition.
  158. func (e *EntryQueryBuilder) CountEntries() (count int, err error) {
  159. query := `SELECT count(*) FROM entries e LEFT JOIN feeds f ON f.id=e.feed_id WHERE %s`
  160. condition := e.buildCondition()
  161. err = e.store.db.QueryRow(fmt.Sprintf(query, condition), e.args...).Scan(&count)
  162. if err != nil {
  163. return 0, fmt.Errorf("unable to count entries: %v", err)
  164. }
  165. return count, nil
  166. }
  167. // GetEntry returns a single entry that match the condition.
  168. func (e *EntryQueryBuilder) GetEntry() (*model.Entry, error) {
  169. e.limit = 1
  170. entries, err := e.GetEntries()
  171. if err != nil {
  172. return nil, err
  173. }
  174. if len(entries) != 1 {
  175. return nil, nil
  176. }
  177. entries[0].Enclosures, err = e.store.GetEnclosures(entries[0].ID)
  178. if err != nil {
  179. return nil, err
  180. }
  181. return entries[0], nil
  182. }
  183. // GetEntries returns a list of entries that match the condition.
  184. func (e *EntryQueryBuilder) GetEntries() (model.Entries, error) {
  185. query := `
  186. SELECT
  187. e.id,
  188. e.user_id,
  189. e.feed_id,
  190. e.hash,
  191. e.published_at at time zone u.timezone,
  192. e.title,
  193. e.url,
  194. e.comments_url,
  195. e.author,
  196. e.share_code,
  197. e.content,
  198. e.status,
  199. e.starred,
  200. e.reading_time,
  201. e.created_at,
  202. f.title as feed_title,
  203. f.feed_url,
  204. f.site_url,
  205. f.checked_at,
  206. f.category_id, c.title as category_title,
  207. f.scraper_rules,
  208. f.rewrite_rules,
  209. f.crawler,
  210. f.user_agent,
  211. fi.icon_id,
  212. u.timezone
  213. FROM
  214. entries e
  215. LEFT JOIN
  216. feeds f ON f.id=e.feed_id
  217. LEFT JOIN
  218. categories c ON c.id=f.category_id
  219. LEFT JOIN
  220. feed_icons fi ON fi.feed_id=f.id
  221. LEFT JOIN
  222. users u ON u.id=e.user_id
  223. WHERE %s %s
  224. `
  225. condition := e.buildCondition()
  226. sorting := e.buildSorting()
  227. query = fmt.Sprintf(query, condition, sorting)
  228. rows, err := e.store.db.Query(query, e.args...)
  229. if err != nil {
  230. return nil, fmt.Errorf("unable to get entries: %v", err)
  231. }
  232. defer rows.Close()
  233. entries := make(model.Entries, 0)
  234. for rows.Next() {
  235. var entry model.Entry
  236. var iconID interface{}
  237. var tz string
  238. entry.Feed = &model.Feed{}
  239. entry.Feed.Category = &model.Category{}
  240. entry.Feed.Icon = &model.FeedIcon{}
  241. err := rows.Scan(
  242. &entry.ID,
  243. &entry.UserID,
  244. &entry.FeedID,
  245. &entry.Hash,
  246. &entry.Date,
  247. &entry.Title,
  248. &entry.URL,
  249. &entry.CommentsURL,
  250. &entry.Author,
  251. &entry.ShareCode,
  252. &entry.Content,
  253. &entry.Status,
  254. &entry.Starred,
  255. &entry.ReadingTime,
  256. &entry.CreatedAt,
  257. &entry.Feed.Title,
  258. &entry.Feed.FeedURL,
  259. &entry.Feed.SiteURL,
  260. &entry.Feed.CheckedAt,
  261. &entry.Feed.Category.ID,
  262. &entry.Feed.Category.Title,
  263. &entry.Feed.ScraperRules,
  264. &entry.Feed.RewriteRules,
  265. &entry.Feed.Crawler,
  266. &entry.Feed.UserAgent,
  267. &iconID,
  268. &tz,
  269. )
  270. if err != nil {
  271. return nil, fmt.Errorf("unable to fetch entry row: %v", err)
  272. }
  273. if iconID == nil {
  274. entry.Feed.Icon.IconID = 0
  275. } else {
  276. entry.Feed.Icon.IconID = iconID.(int64)
  277. }
  278. // Make sure that timestamp fields contains timezone information (API)
  279. entry.Date = timezone.Convert(tz, entry.Date)
  280. entry.CreatedAt = timezone.Convert(tz, entry.CreatedAt)
  281. entry.Feed.CheckedAt = timezone.Convert(tz, entry.Feed.CheckedAt)
  282. entry.Feed.ID = entry.FeedID
  283. entry.Feed.UserID = entry.UserID
  284. entry.Feed.Icon.FeedID = entry.FeedID
  285. entry.Feed.Category.UserID = entry.UserID
  286. entries = append(entries, &entry)
  287. }
  288. return entries, nil
  289. }
  290. // GetEntryIDs returns a list of entry IDs that match the condition.
  291. func (e *EntryQueryBuilder) GetEntryIDs() ([]int64, error) {
  292. query := `SELECT e.id FROM entries e LEFT JOIN feeds f ON f.id=e.feed_id WHERE %s %s`
  293. condition := e.buildCondition()
  294. query = fmt.Sprintf(query, condition, e.buildSorting())
  295. rows, err := e.store.db.Query(query, e.args...)
  296. if err != nil {
  297. return nil, fmt.Errorf("unable to get entries: %v", err)
  298. }
  299. defer rows.Close()
  300. var entryIDs []int64
  301. for rows.Next() {
  302. var entryID int64
  303. err := rows.Scan(&entryID)
  304. if err != nil {
  305. return nil, fmt.Errorf("unable to fetch entry row: %v", err)
  306. }
  307. entryIDs = append(entryIDs, entryID)
  308. }
  309. return entryIDs, nil
  310. }
  311. func (e *EntryQueryBuilder) buildCondition() string {
  312. return strings.Join(e.conditions, " AND ")
  313. }
  314. func (e *EntryQueryBuilder) buildSorting() string {
  315. var parts []string
  316. if e.order != "" {
  317. parts = append(parts, fmt.Sprintf(`ORDER BY %s`, e.order))
  318. }
  319. if e.direction != "" {
  320. parts = append(parts, fmt.Sprintf(`%s`, e.direction))
  321. }
  322. if e.limit > 0 {
  323. parts = append(parts, fmt.Sprintf(`LIMIT %d`, e.limit))
  324. }
  325. if e.offset > 0 {
  326. parts = append(parts, fmt.Sprintf(`OFFSET %d`, e.offset))
  327. }
  328. return strings.Join(parts, " ")
  329. }
  330. // NewEntryQueryBuilder returns a new EntryQueryBuilder.
  331. func NewEntryQueryBuilder(store *Storage, userID int64) *EntryQueryBuilder {
  332. return &EntryQueryBuilder{
  333. store: store,
  334. args: []interface{}{userID},
  335. conditions: []string{"e.user_id = $1"},
  336. }
  337. }
  338. // NewAnonymousQueryBuilder returns a new EntryQueryBuilder suitable for anonymous users.
  339. func NewAnonymousQueryBuilder(store *Storage) *EntryQueryBuilder {
  340. return &EntryQueryBuilder{
  341. store: store,
  342. }
  343. }