entry_query_builder.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. "database/sql"
  7. "fmt"
  8. "strings"
  9. "time"
  10. "github.com/lib/pq"
  11. "miniflux.app/model"
  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. nArgs := len(e.args) + 1
  28. e.conditions = append(e.conditions, fmt.Sprintf("e.document_vectors @@ plainto_tsquery($%d)", nArgs))
  29. e.args = append(e.args, query)
  30. // 0.0000001 = 0.1 / (seconds_in_a_day)
  31. e.WithOrder(fmt.Sprintf("ts_rank(document_vectors, plainto_tsquery($%d)) - extract (epoch from now() - published_at)::float * 0.0000001", nArgs))
  32. e.WithDirection("DESC")
  33. }
  34. return e
  35. }
  36. // WithStarred adds starred filter.
  37. func (e *EntryQueryBuilder) WithStarred(starred bool) *EntryQueryBuilder {
  38. if starred {
  39. e.conditions = append(e.conditions, "e.starred is true")
  40. } else {
  41. e.conditions = append(e.conditions, "e.starred is false")
  42. }
  43. return e
  44. }
  45. // BeforeDate adds a condition < published_at
  46. func (e *EntryQueryBuilder) BeforeDate(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. // AfterDate adds a condition > published_at
  52. func (e *EntryQueryBuilder) AfterDate(date time.Time) *EntryQueryBuilder {
  53. e.conditions = append(e.conditions, fmt.Sprintf("e.published_at > $%d", len(e.args)+1))
  54. e.args = append(e.args, date)
  55. return e
  56. }
  57. // BeforeEntryID adds a condition < entryID.
  58. func (e *EntryQueryBuilder) BeforeEntryID(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. // AfterEntryID adds a condition > entryID.
  66. func (e *EntryQueryBuilder) AfterEntryID(entryID int64) *EntryQueryBuilder {
  67. if entryID != 0 {
  68. e.conditions = append(e.conditions, fmt.Sprintf("e.id > $%d", len(e.args)+1))
  69. e.args = append(e.args, entryID)
  70. }
  71. return e
  72. }
  73. // WithEntryIDs filter by entry IDs.
  74. func (e *EntryQueryBuilder) WithEntryIDs(entryIDs []int64) *EntryQueryBuilder {
  75. e.conditions = append(e.conditions, fmt.Sprintf("e.id = ANY($%d)", len(e.args)+1))
  76. e.args = append(e.args, pq.Int64Array(entryIDs))
  77. return e
  78. }
  79. // WithEntryID filter by entry ID.
  80. func (e *EntryQueryBuilder) WithEntryID(entryID int64) *EntryQueryBuilder {
  81. if entryID != 0 {
  82. e.conditions = append(e.conditions, fmt.Sprintf("e.id = $%d", len(e.args)+1))
  83. e.args = append(e.args, entryID)
  84. }
  85. return e
  86. }
  87. // WithFeedID filter by feed ID.
  88. func (e *EntryQueryBuilder) WithFeedID(feedID int64) *EntryQueryBuilder {
  89. if feedID > 0 {
  90. e.conditions = append(e.conditions, fmt.Sprintf("e.feed_id = $%d", len(e.args)+1))
  91. e.args = append(e.args, feedID)
  92. }
  93. return e
  94. }
  95. // WithCategoryID filter by category ID.
  96. func (e *EntryQueryBuilder) WithCategoryID(categoryID int64) *EntryQueryBuilder {
  97. if categoryID > 0 {
  98. e.conditions = append(e.conditions, fmt.Sprintf("f.category_id = $%d", len(e.args)+1))
  99. e.args = append(e.args, categoryID)
  100. }
  101. return e
  102. }
  103. // WithStatus filter by entry status.
  104. func (e *EntryQueryBuilder) WithStatus(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. // WithStatuses filter by a list of entry statuses.
  112. func (e *EntryQueryBuilder) WithStatuses(statuses []string) *EntryQueryBuilder {
  113. if len(statuses) > 0 {
  114. e.conditions = append(e.conditions, fmt.Sprintf("e.status = ANY($%d)", len(e.args)+1))
  115. e.args = append(e.args, pq.StringArray(statuses))
  116. }
  117. return e
  118. }
  119. // WithTags filter by a list of entry tags.
  120. func (e *EntryQueryBuilder) WithTags(tags []string) *EntryQueryBuilder {
  121. if len(tags) > 0 {
  122. for _, cat := range tags {
  123. e.conditions = append(e.conditions, fmt.Sprintf("$%d = ANY(e.tags)", len(e.args)+1))
  124. e.args = append(e.args, cat)
  125. }
  126. }
  127. return e
  128. }
  129. // WithoutStatus set the entry status that should not be returned.
  130. func (e *EntryQueryBuilder) WithoutStatus(status string) *EntryQueryBuilder {
  131. if status != "" {
  132. e.conditions = append(e.conditions, fmt.Sprintf("e.status <> $%d", len(e.args)+1))
  133. e.args = append(e.args, status)
  134. }
  135. return e
  136. }
  137. // WithShareCode set the entry share code.
  138. func (e *EntryQueryBuilder) WithShareCode(shareCode string) *EntryQueryBuilder {
  139. e.conditions = append(e.conditions, fmt.Sprintf("e.share_code = $%d", len(e.args)+1))
  140. e.args = append(e.args, shareCode)
  141. return e
  142. }
  143. // WithShareCodeNotEmpty adds a filter for non-empty share code.
  144. func (e *EntryQueryBuilder) WithShareCodeNotEmpty() *EntryQueryBuilder {
  145. e.conditions = append(e.conditions, "e.share_code <> ''")
  146. return e
  147. }
  148. // WithOrder set the sorting order.
  149. func (e *EntryQueryBuilder) WithOrder(order string) *EntryQueryBuilder {
  150. e.order = order
  151. return e
  152. }
  153. // WithDirection set the sorting direction.
  154. func (e *EntryQueryBuilder) WithDirection(direction string) *EntryQueryBuilder {
  155. e.direction = direction
  156. return e
  157. }
  158. // WithLimit set the limit.
  159. func (e *EntryQueryBuilder) WithLimit(limit int) *EntryQueryBuilder {
  160. if limit > 0 {
  161. e.limit = limit
  162. }
  163. return e
  164. }
  165. // WithOffset set the offset.
  166. func (e *EntryQueryBuilder) WithOffset(offset int) *EntryQueryBuilder {
  167. if offset > 0 {
  168. e.offset = offset
  169. }
  170. return e
  171. }
  172. func (e *EntryQueryBuilder) WithGloballyVisible() *EntryQueryBuilder {
  173. e.conditions = append(e.conditions, "not c.hide_globally")
  174. e.conditions = append(e.conditions, "not f.hide_globally")
  175. return e
  176. }
  177. // CountEntries count the number of entries that match the condition.
  178. func (e *EntryQueryBuilder) CountEntries() (count int, err error) {
  179. query := `
  180. SELECT count(*)
  181. FROM entries e
  182. JOIN feeds f ON f.id = e.feed_id
  183. JOIN categories c ON c.id = f.category_id
  184. WHERE %s
  185. `
  186. condition := e.buildCondition()
  187. err = e.store.db.QueryRow(fmt.Sprintf(query, condition), e.args...).Scan(&count)
  188. if err != nil {
  189. return 0, fmt.Errorf("unable to count entries: %v", err)
  190. }
  191. return count, nil
  192. }
  193. // GetEntry returns a single entry that match the condition.
  194. func (e *EntryQueryBuilder) GetEntry() (*model.Entry, error) {
  195. e.limit = 1
  196. entries, err := e.GetEntries()
  197. if err != nil {
  198. return nil, err
  199. }
  200. if len(entries) != 1 {
  201. return nil, nil
  202. }
  203. entries[0].Enclosures, err = e.store.GetEnclosures(entries[0].ID)
  204. if err != nil {
  205. return nil, err
  206. }
  207. return entries[0], nil
  208. }
  209. // GetEntries returns a list of entries that match the condition.
  210. func (e *EntryQueryBuilder) GetEntries() (model.Entries, error) {
  211. query := `
  212. SELECT
  213. e.id,
  214. e.user_id,
  215. e.feed_id,
  216. e.hash,
  217. e.published_at at time zone u.timezone,
  218. e.title,
  219. e.url,
  220. e.comments_url,
  221. e.author,
  222. e.share_code,
  223. e.content,
  224. e.status,
  225. e.starred,
  226. e.reading_time,
  227. e.created_at,
  228. e.changed_at,
  229. e.tags,
  230. f.title as feed_title,
  231. f.feed_url,
  232. f.site_url,
  233. f.checked_at,
  234. f.category_id, c.title as category_title,
  235. f.scraper_rules,
  236. f.rewrite_rules,
  237. f.crawler,
  238. f.user_agent,
  239. f.cookie,
  240. f.no_media_player,
  241. fi.icon_id,
  242. u.timezone
  243. FROM
  244. entries e
  245. LEFT JOIN
  246. feeds f ON f.id=e.feed_id
  247. LEFT JOIN
  248. categories c ON c.id=f.category_id
  249. LEFT JOIN
  250. feed_icons fi ON fi.feed_id=f.id
  251. LEFT JOIN
  252. users u ON u.id=e.user_id
  253. WHERE %s %s
  254. `
  255. condition := e.buildCondition()
  256. sorting := e.buildSorting()
  257. query = fmt.Sprintf(query, condition, sorting)
  258. rows, err := e.store.db.Query(query, e.args...)
  259. if err != nil {
  260. return nil, fmt.Errorf("unable to get entries: %v", err)
  261. }
  262. defer rows.Close()
  263. entries := make(model.Entries, 0)
  264. for rows.Next() {
  265. var entry model.Entry
  266. var iconID sql.NullInt64
  267. var tz string
  268. entry.Feed = &model.Feed{}
  269. entry.Feed.Category = &model.Category{}
  270. entry.Feed.Icon = &model.FeedIcon{}
  271. err := rows.Scan(
  272. &entry.ID,
  273. &entry.UserID,
  274. &entry.FeedID,
  275. &entry.Hash,
  276. &entry.Date,
  277. &entry.Title,
  278. &entry.URL,
  279. &entry.CommentsURL,
  280. &entry.Author,
  281. &entry.ShareCode,
  282. &entry.Content,
  283. &entry.Status,
  284. &entry.Starred,
  285. &entry.ReadingTime,
  286. &entry.CreatedAt,
  287. &entry.ChangedAt,
  288. pq.Array(&entry.Tags),
  289. &entry.Feed.Title,
  290. &entry.Feed.FeedURL,
  291. &entry.Feed.SiteURL,
  292. &entry.Feed.CheckedAt,
  293. &entry.Feed.Category.ID,
  294. &entry.Feed.Category.Title,
  295. &entry.Feed.ScraperRules,
  296. &entry.Feed.RewriteRules,
  297. &entry.Feed.Crawler,
  298. &entry.Feed.UserAgent,
  299. &entry.Feed.Cookie,
  300. &entry.Feed.NoMediaPlayer,
  301. &iconID,
  302. &tz,
  303. )
  304. if err != nil {
  305. return nil, fmt.Errorf("unable to fetch entry row: %v", err)
  306. }
  307. if iconID.Valid {
  308. entry.Feed.Icon.IconID = iconID.Int64
  309. } else {
  310. entry.Feed.Icon.IconID = 0
  311. }
  312. // Make sure that timestamp fields contains timezone information (API)
  313. entry.Date = timezone.Convert(tz, entry.Date)
  314. entry.CreatedAt = timezone.Convert(tz, entry.CreatedAt)
  315. entry.ChangedAt = timezone.Convert(tz, entry.ChangedAt)
  316. entry.Feed.CheckedAt = timezone.Convert(tz, entry.Feed.CheckedAt)
  317. entry.Feed.ID = entry.FeedID
  318. entry.Feed.UserID = entry.UserID
  319. entry.Feed.Icon.FeedID = entry.FeedID
  320. entry.Feed.Category.UserID = entry.UserID
  321. entries = append(entries, &entry)
  322. }
  323. return entries, nil
  324. }
  325. // GetEntryIDs returns a list of entry IDs that match the condition.
  326. func (e *EntryQueryBuilder) GetEntryIDs() ([]int64, error) {
  327. query := `SELECT e.id FROM entries e LEFT JOIN feeds f ON f.id=e.feed_id WHERE %s %s`
  328. condition := e.buildCondition()
  329. query = fmt.Sprintf(query, condition, e.buildSorting())
  330. rows, err := e.store.db.Query(query, e.args...)
  331. if err != nil {
  332. return nil, fmt.Errorf("unable to get entries: %v", err)
  333. }
  334. defer rows.Close()
  335. var entryIDs []int64
  336. for rows.Next() {
  337. var entryID int64
  338. err := rows.Scan(&entryID)
  339. if err != nil {
  340. return nil, fmt.Errorf("unable to fetch entry row: %v", err)
  341. }
  342. entryIDs = append(entryIDs, entryID)
  343. }
  344. return entryIDs, nil
  345. }
  346. func (e *EntryQueryBuilder) buildCondition() string {
  347. return strings.Join(e.conditions, " AND ")
  348. }
  349. func (e *EntryQueryBuilder) buildSorting() string {
  350. var parts []string
  351. if e.order != "" {
  352. parts = append(parts, fmt.Sprintf(`ORDER BY %s`, e.order))
  353. }
  354. if e.direction != "" {
  355. parts = append(parts, e.direction)
  356. }
  357. if e.limit > 0 {
  358. parts = append(parts, fmt.Sprintf(`LIMIT %d`, e.limit))
  359. }
  360. if e.offset > 0 {
  361. parts = append(parts, fmt.Sprintf(`OFFSET %d`, e.offset))
  362. }
  363. return strings.Join(parts, " ")
  364. }
  365. // NewEntryQueryBuilder returns a new EntryQueryBuilder.
  366. func NewEntryQueryBuilder(store *Storage, userID int64) *EntryQueryBuilder {
  367. return &EntryQueryBuilder{
  368. store: store,
  369. args: []interface{}{userID},
  370. conditions: []string{"e.user_id = $1"},
  371. }
  372. }
  373. // NewAnonymousQueryBuilder returns a new EntryQueryBuilder suitable for anonymous users.
  374. func NewAnonymousQueryBuilder(store *Storage) *EntryQueryBuilder {
  375. return &EntryQueryBuilder{
  376. store: store,
  377. }
  378. }