entry_query_builder.go 13 KB

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