entry_query_builder.go 12 KB

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