entry_query_builder.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/lib/pq"
  11. "miniflux.app/v2/internal/model"
  12. "miniflux.app/v2/internal/timezone"
  13. )
  14. // EntryQueryBuilder builds a SQL query to fetch entries.
  15. type EntryQueryBuilder struct {
  16. store *Storage
  17. args []any
  18. conditions []string
  19. sortExpressions []entrySortExpression
  20. limit int
  21. offset int
  22. fetchEnclosures bool
  23. excludeContent bool
  24. }
  25. type entrySortExpression struct {
  26. column string
  27. direction string
  28. expression string
  29. }
  30. // WithEnclosures fetches enclosures for each entry.
  31. func (e *EntryQueryBuilder) WithEnclosures() *EntryQueryBuilder {
  32. e.fetchEnclosures = true
  33. return e
  34. }
  35. // WithoutContent excludes the content column from the query results,
  36. // replacing it with an empty string. This significantly reduces data
  37. // transfer from PostgreSQL on list pages where content is not displayed.
  38. func (e *EntryQueryBuilder) WithoutContent() *EntryQueryBuilder {
  39. e.excludeContent = true
  40. return e
  41. }
  42. // WithSearchQuery adds full-text search query to the condition.
  43. func (e *EntryQueryBuilder) WithSearchQuery(query string) *EntryQueryBuilder {
  44. if query != "" {
  45. nArgs := len(e.args) + 1
  46. e.conditions = append(e.conditions, fmt.Sprintf("e.document_vectors @@ websearch_to_tsquery($%d)", nArgs))
  47. e.args = append(e.args, query)
  48. // 0.0000001 = 0.1 / (seconds_in_a_day)
  49. e.sortExpressions = append(e.sortExpressions, entrySortExpression{
  50. expression: fmt.Sprintf("ts_rank(document_vectors, websearch_to_tsquery($%d)) - extract (epoch from now() - published_at)::float * 0.0000001 DESC", nArgs),
  51. })
  52. }
  53. return e
  54. }
  55. // WithStarred adds starred filter.
  56. func (e *EntryQueryBuilder) WithStarred(starred bool) *EntryQueryBuilder {
  57. if starred {
  58. e.conditions = append(e.conditions, "e.starred is true")
  59. } else {
  60. e.conditions = append(e.conditions, "e.starred is false")
  61. }
  62. return e
  63. }
  64. // BeforeChangedDate adds a condition < changed_at
  65. func (e *EntryQueryBuilder) BeforeChangedDate(date time.Time) *EntryQueryBuilder {
  66. e.conditions = append(e.conditions, "e.changed_at < $"+strconv.Itoa(len(e.args)+1))
  67. e.args = append(e.args, date)
  68. return e
  69. }
  70. // AfterChangedDate adds a condition > changed_at
  71. func (e *EntryQueryBuilder) AfterChangedDate(date time.Time) *EntryQueryBuilder {
  72. e.conditions = append(e.conditions, "e.changed_at > $"+strconv.Itoa(len(e.args)+1))
  73. e.args = append(e.args, date)
  74. return e
  75. }
  76. // BeforePublishedDate adds a condition < published_at
  77. func (e *EntryQueryBuilder) BeforePublishedDate(date time.Time) *EntryQueryBuilder {
  78. e.conditions = append(e.conditions, "e.published_at < $"+strconv.Itoa(len(e.args)+1))
  79. e.args = append(e.args, date)
  80. return e
  81. }
  82. // AfterPublishedDate adds a condition > published_at
  83. func (e *EntryQueryBuilder) AfterPublishedDate(date time.Time) *EntryQueryBuilder {
  84. e.conditions = append(e.conditions, "e.published_at > $"+strconv.Itoa(len(e.args)+1))
  85. e.args = append(e.args, date)
  86. return e
  87. }
  88. // BeforeEntryID adds a condition < entryID.
  89. func (e *EntryQueryBuilder) BeforeEntryID(entryID int64) *EntryQueryBuilder {
  90. if entryID != 0 {
  91. e.conditions = append(e.conditions, "e.id < $"+strconv.Itoa(len(e.args)+1))
  92. e.args = append(e.args, entryID)
  93. }
  94. return e
  95. }
  96. // AfterEntryID adds a condition > entryID.
  97. func (e *EntryQueryBuilder) AfterEntryID(entryID int64) *EntryQueryBuilder {
  98. if entryID != 0 {
  99. e.conditions = append(e.conditions, "e.id > $"+strconv.Itoa(len(e.args)+1))
  100. e.args = append(e.args, entryID)
  101. }
  102. return e
  103. }
  104. // WithEntryIDs filter by entry IDs.
  105. func (e *EntryQueryBuilder) WithEntryIDs(entryIDs ...int64) *EntryQueryBuilder {
  106. if len(entryIDs) == 1 {
  107. e.conditions = append(e.conditions, fmt.Sprintf("e.id = $%d", len(e.args)+1))
  108. e.args = append(e.args, entryIDs[0])
  109. } else if len(entryIDs) > 1 {
  110. e.conditions = append(e.conditions, fmt.Sprintf("e.id = ANY($%d)", len(e.args)+1))
  111. e.args = append(e.args, pq.Int64Array(entryIDs))
  112. }
  113. return e
  114. }
  115. // WithFeedID filter by feed ID.
  116. func (e *EntryQueryBuilder) WithFeedID(feedID int64) *EntryQueryBuilder {
  117. if feedID > 0 {
  118. e.conditions = append(e.conditions, "e.feed_id = $"+strconv.Itoa(len(e.args)+1))
  119. e.args = append(e.args, feedID)
  120. }
  121. return e
  122. }
  123. // WithCategoryID filter by category ID.
  124. func (e *EntryQueryBuilder) WithCategoryID(categoryID int64) *EntryQueryBuilder {
  125. if categoryID > 0 {
  126. e.conditions = append(e.conditions, "f.category_id = $"+strconv.Itoa(len(e.args)+1))
  127. e.args = append(e.args, categoryID)
  128. }
  129. return e
  130. }
  131. // WithStatuses filter by a list of entry statuses.
  132. func (e *EntryQueryBuilder) WithStatuses(statuses ...string) *EntryQueryBuilder {
  133. if len(statuses) == 1 {
  134. e.conditions = append(e.conditions, fmt.Sprintf("e.status = $%d", len(e.args)+1))
  135. e.args = append(e.args, statuses[0])
  136. } else if len(statuses) > 1 {
  137. e.conditions = append(e.conditions, fmt.Sprintf("e.status = ANY($%d)", len(e.args)+1))
  138. e.args = append(e.args, pq.StringArray(statuses))
  139. }
  140. return e
  141. }
  142. // WithTags filter by a list of entry tags.
  143. func (e *EntryQueryBuilder) WithTags(tags ...string) *EntryQueryBuilder {
  144. if len(tags) > 0 {
  145. e.conditions = append(e.conditions, fmt.Sprintf("LOWER(e.tags::text)::text[] @> LOWER($%d::text)::text[]", len(e.args)+1))
  146. e.args = append(e.args, pq.Array(tags))
  147. }
  148. return e
  149. }
  150. // WithoutStatus set the entry status that should not be returned.
  151. func (e *EntryQueryBuilder) WithoutStatus(status string) *EntryQueryBuilder {
  152. if status != "" {
  153. e.conditions = append(e.conditions, "e.status <> $"+strconv.Itoa(len(e.args)+1))
  154. e.args = append(e.args, status)
  155. }
  156. return e
  157. }
  158. // WithShareCode set the entry share code.
  159. func (e *EntryQueryBuilder) WithShareCode(shareCode string) *EntryQueryBuilder {
  160. e.conditions = append(e.conditions, "e.share_code = $"+strconv.Itoa(len(e.args)+1))
  161. e.args = append(e.args, shareCode)
  162. return e
  163. }
  164. // WithShareCodeNotEmpty adds a filter for non-empty share code.
  165. func (e *EntryQueryBuilder) WithShareCodeNotEmpty() *EntryQueryBuilder {
  166. e.conditions = append(e.conditions, "e.share_code <> ''")
  167. return e
  168. }
  169. // WithSorting add a sort expression.
  170. func (e *EntryQueryBuilder) WithSorting(column, direction string) *EntryQueryBuilder {
  171. switch {
  172. case strings.EqualFold(direction, "ASC"):
  173. direction = "ASC"
  174. case strings.EqualFold(direction, "DESC"):
  175. direction = "DESC"
  176. default:
  177. return e
  178. }
  179. e.sortExpressions = append(e.sortExpressions, entrySortExpression{column: column, direction: direction})
  180. return e
  181. }
  182. // WithLimit sets the limit. A non-positive limit is clamped to
  183. // model.MaxEntryLimit so callers cannot request an unbounded result set.
  184. func (e *EntryQueryBuilder) WithLimit(limit int) *EntryQueryBuilder {
  185. return e.WithLimitAndMaximum(limit, model.MaxEntryLimit)
  186. }
  187. // WithLimitAndMaximum sets the limit, capped at the given maximum.
  188. // A non-positive limit is clamped to the maximum.
  189. func (e *EntryQueryBuilder) WithLimitAndMaximum(limit, maximum int) *EntryQueryBuilder {
  190. if limit <= 0 || limit > maximum {
  191. limit = maximum
  192. }
  193. e.limit = limit
  194. return e
  195. }
  196. // WithOffset set the offset.
  197. func (e *EntryQueryBuilder) WithOffset(offset int) *EntryQueryBuilder {
  198. if offset > 0 {
  199. e.offset = offset
  200. }
  201. return e
  202. }
  203. func (e *EntryQueryBuilder) WithGloballyVisible() *EntryQueryBuilder {
  204. e.conditions = append(e.conditions, "c.hide_globally IS FALSE")
  205. e.conditions = append(e.conditions, "f.hide_globally IS FALSE")
  206. return e
  207. }
  208. // CountEntries count the number of entries that match the condition.
  209. func (e *EntryQueryBuilder) CountEntries() (count int, err error) {
  210. query := `
  211. SELECT count(*)
  212. FROM entries e
  213. JOIN feeds f ON f.id = e.feed_id
  214. JOIN categories c ON c.id = f.category_id
  215. WHERE ` + e.buildCondition()
  216. err = e.store.db.QueryRow(query, e.args...).Scan(&count)
  217. if err != nil {
  218. return 0, fmt.Errorf("store: unable to count entries: %v", err)
  219. }
  220. return count, nil
  221. }
  222. // GetEntry returns a single entry that match the condition.
  223. func (e *EntryQueryBuilder) GetEntry() (*model.Entry, error) {
  224. e.limit = 1
  225. entries, err := e.GetEntries()
  226. if err != nil {
  227. return nil, err
  228. }
  229. if len(entries) != 1 {
  230. return nil, nil
  231. }
  232. entries[0].Enclosures, err = e.store.EnclosuresByEntryID(entries[0].ID)
  233. if err != nil {
  234. return nil, err
  235. }
  236. return entries[0], nil
  237. }
  238. // GetEntries returns a list of entries that match the condition.
  239. func (e *EntryQueryBuilder) GetEntries() (model.Entries, error) {
  240. entries, _, err := e.fetchEntries(false)
  241. return entries, err
  242. }
  243. // GetEntriesWithCount returns a list of entries and the total count of matching
  244. // rows, ignoring limit and offset. It uses a window function for non-empty pages
  245. // and falls back to a separate count when the requested offset returns no rows.
  246. func (e *EntryQueryBuilder) GetEntriesWithCount() (model.Entries, int, error) {
  247. entries, total, err := e.fetchEntries(true)
  248. if err != nil {
  249. return nil, 0, err
  250. }
  251. if len(entries) == 0 && e.offset > 0 {
  252. total, err = e.CountEntries()
  253. if err != nil {
  254. return nil, 0, err
  255. }
  256. }
  257. return entries, total, nil
  258. }
  259. // fetchEntries is the shared implementation for GetEntries and GetEntriesWithCount.
  260. // When withCount is true, count(*) OVER() is included in the SELECT and the total
  261. // count of matching rows is returned; otherwise the returned count is 0.
  262. func (e *EntryQueryBuilder) fetchEntries(withCount bool) (model.Entries, int, error) {
  263. sorting, err := e.buildSorting(false)
  264. if err != nil {
  265. return nil, 0, err
  266. }
  267. countColumn := ""
  268. if withCount {
  269. countColumn = "count(*) OVER(),"
  270. }
  271. query := `
  272. SELECT
  273. ` + countColumn + `
  274. e.id,
  275. e.user_id,
  276. e.feed_id,
  277. e.hash,
  278. e.published_at at time zone u.timezone,
  279. e.title,
  280. e.url,
  281. e.comments_url,
  282. e.author,
  283. e.share_code,
  284. ` + e.contentColumn() + `,
  285. e.status,
  286. e.starred,
  287. e.reading_time,
  288. e.created_at,
  289. e.changed_at,
  290. e.tags,
  291. e.language,
  292. f.title as feed_title,
  293. f.feed_url,
  294. f.site_url,
  295. f.description,
  296. f.language,
  297. f.checked_at,
  298. f.category_id,
  299. c.title as category_title,
  300. c.hide_globally as category_hidden,
  301. f.scraper_rules,
  302. f.rewrite_rules,
  303. f.crawler,
  304. f.user_agent,
  305. f.cookie,
  306. f.hide_globally,
  307. f.no_media_player,
  308. f.webhook_url,
  309. fi.icon_id,
  310. i.external_id AS icon_external_id,
  311. u.timezone
  312. FROM
  313. entries e
  314. INNER JOIN
  315. feeds f ON f.id=e.feed_id
  316. INNER JOIN
  317. categories c ON c.id=f.category_id
  318. LEFT JOIN
  319. feed_icons fi ON fi.feed_id=f.id
  320. LEFT JOIN
  321. icons i ON i.id=fi.icon_id
  322. INNER JOIN
  323. users u ON u.id=e.user_id
  324. WHERE ` + e.buildCondition() + " " + sorting
  325. rows, err := e.store.db.Query(query, e.args...)
  326. if err != nil {
  327. return nil, 0, fmt.Errorf("store: unable to get entries: %v", err)
  328. }
  329. defer rows.Close()
  330. size := max(e.limit, 0)
  331. entries := make(model.Entries, 0, size)
  332. entryMap := make(map[int64]*model.Entry, size)
  333. entryIDs := make([]int64, 0, size)
  334. var totalCount int
  335. for rows.Next() {
  336. var iconID sql.NullInt64
  337. var externalIconID sql.NullString
  338. var tz string
  339. entry := model.NewEntry()
  340. dest := []any{
  341. &entry.ID,
  342. &entry.UserID,
  343. &entry.FeedID,
  344. &entry.Hash,
  345. &entry.Date,
  346. &entry.Title,
  347. &entry.URL,
  348. &entry.CommentsURL,
  349. &entry.Author,
  350. &entry.ShareCode,
  351. &entry.Content,
  352. &entry.Status,
  353. &entry.Starred,
  354. &entry.ReadingTime,
  355. &entry.CreatedAt,
  356. &entry.ChangedAt,
  357. pq.Array(&entry.Tags),
  358. &entry.Language,
  359. &entry.Feed.Title,
  360. &entry.Feed.FeedURL,
  361. &entry.Feed.SiteURL,
  362. &entry.Feed.Description,
  363. &entry.Feed.Language,
  364. &entry.Feed.CheckedAt,
  365. &entry.Feed.Category.ID,
  366. &entry.Feed.Category.Title,
  367. &entry.Feed.Category.HideGlobally,
  368. &entry.Feed.ScraperRules,
  369. &entry.Feed.RewriteRules,
  370. &entry.Feed.Crawler,
  371. &entry.Feed.UserAgent,
  372. &entry.Feed.Cookie,
  373. &entry.Feed.HideGlobally,
  374. &entry.Feed.NoMediaPlayer,
  375. &entry.Feed.WebhookURL,
  376. &iconID,
  377. &externalIconID,
  378. &tz,
  379. }
  380. if withCount {
  381. dest = append([]any{&totalCount}, dest...)
  382. }
  383. err := rows.Scan(dest...)
  384. if err != nil {
  385. return nil, 0, fmt.Errorf("store: unable to fetch entry row: %v", err)
  386. }
  387. if iconID.Valid && externalIconID.Valid && externalIconID.String != "" {
  388. entry.Feed.Icon.FeedID = entry.FeedID
  389. entry.Feed.Icon.IconID = iconID.Int64
  390. entry.Feed.Icon.ExternalIconID = externalIconID.String
  391. } else {
  392. entry.Feed.Icon.IconID = 0
  393. }
  394. // Make sure that timestamp fields contain timezone information (API)
  395. entry.Date = timezone.Convert(tz, entry.Date)
  396. entry.CreatedAt = timezone.Convert(tz, entry.CreatedAt)
  397. entry.ChangedAt = timezone.Convert(tz, entry.ChangedAt)
  398. entry.Feed.CheckedAt = timezone.Convert(tz, entry.Feed.CheckedAt)
  399. entry.Feed.ID = entry.FeedID
  400. entry.Feed.UserID = entry.UserID
  401. entry.Feed.Icon.FeedID = entry.FeedID
  402. entry.Feed.Category.UserID = entry.UserID
  403. entries = append(entries, entry)
  404. entryMap[entry.ID] = entry
  405. entryIDs = append(entryIDs, entry.ID)
  406. }
  407. if e.fetchEnclosures && len(entryIDs) > 0 {
  408. enclosures, err := e.store.EnclosuresByEntryIDs(entryIDs)
  409. if err != nil {
  410. return nil, 0, fmt.Errorf("store: unable to fetch enclosures: %w", err)
  411. }
  412. for entryID, entryEnclosures := range enclosures {
  413. if entry, exists := entryMap[entryID]; exists {
  414. entry.Enclosures = entryEnclosures
  415. }
  416. }
  417. }
  418. return entries, totalCount, nil
  419. }
  420. // GetEntryIDs returns a list of entry IDs that match the condition.
  421. func (e *EntryQueryBuilder) GetEntryIDs() ([]int64, error) {
  422. sorting, err := e.buildSorting(true)
  423. if err != nil {
  424. return nil, err
  425. }
  426. query := `
  427. SELECT
  428. e.id
  429. FROM
  430. entries e
  431. LEFT JOIN
  432. feeds f
  433. ON
  434. f.id=e.feed_id
  435. LEFT JOIN
  436. categories c ON c.id=f.category_id
  437. WHERE ` + e.buildCondition() + " " + sorting
  438. rows, err := e.store.db.Query(query, e.args...)
  439. if err != nil {
  440. return nil, fmt.Errorf("store: unable to get entries: %v", err)
  441. }
  442. defer rows.Close()
  443. var entryIDs []int64
  444. for rows.Next() {
  445. var entryID int64
  446. if err := rows.Scan(&entryID); err != nil {
  447. return nil, fmt.Errorf("store: unable to fetch entry row: %v", err)
  448. }
  449. entryIDs = append(entryIDs, entryID)
  450. }
  451. return entryIDs, nil
  452. }
  453. // GetEntryIDsWithCount returns a list of entry IDs and the total count of
  454. // matching rows (ignoring limit/offset). It uses two queries: one to count
  455. // all matching rows and one to fetch the paginated IDs.
  456. func (e *EntryQueryBuilder) GetEntryIDsWithCount() ([]int64, int, error) {
  457. total, err := e.CountEntries()
  458. if err != nil {
  459. return nil, 0, err
  460. }
  461. entryIDs, err := e.GetEntryIDs()
  462. if err != nil {
  463. return nil, 0, err
  464. }
  465. return entryIDs, total, nil
  466. }
  467. func (e *EntryQueryBuilder) contentColumn() string {
  468. if e.excludeContent {
  469. return "'' AS content"
  470. }
  471. return "e.content"
  472. }
  473. func (e *EntryQueryBuilder) buildCondition() string {
  474. return strings.Join(e.conditions, " AND ")
  475. }
  476. func (e *EntryQueryBuilder) buildSorting(entryIDsOnly bool) (string, error) {
  477. sortExpressions := make([]string, 0, len(e.sortExpressions))
  478. for _, sorting := range e.sortExpressions {
  479. if sorting.expression != "" {
  480. sortExpressions = append(sortExpressions, sorting.expression)
  481. continue
  482. }
  483. column := pq.QuoteIdentifier(sorting.column)
  484. if entryIDsOnly {
  485. // ID-only queries cannot rely on the SELECT aliases used by GetEntries.
  486. switch sorting.column {
  487. case "id", "status", "changed_at", "published_at", "created_at", "title", "author":
  488. column = `"e".` + column
  489. case "category_title":
  490. column = `"c"."title"`
  491. case "category_id":
  492. column = `"f".` + column
  493. default:
  494. return "", fmt.Errorf("store: invalid entry ID sorting column: %q", sorting.column)
  495. }
  496. }
  497. sortExpressions = append(sortExpressions, column+" "+sorting.direction)
  498. }
  499. var parts string
  500. if len(sortExpressions) > 0 {
  501. parts += " ORDER BY " + strings.Join(sortExpressions, ", ")
  502. }
  503. if e.limit > 0 {
  504. parts += " LIMIT " + strconv.Itoa(e.limit)
  505. }
  506. if e.offset > 0 {
  507. parts += " OFFSET " + strconv.Itoa(e.offset)
  508. }
  509. return parts, nil
  510. }
  511. // NewEntryQueryBuilder returns a new EntryQueryBuilder.
  512. func (s *Storage) NewEntryQueryBuilder(userID int64) *EntryQueryBuilder {
  513. return &EntryQueryBuilder{
  514. store: s,
  515. args: []any{userID},
  516. conditions: []string{"e.user_id = $1"},
  517. }
  518. }
  519. // NewAnonymousQueryBuilder returns a new EntryQueryBuilder suitable for anonymous users.
  520. func (s *Storage) NewAnonymousQueryBuilder() *EntryQueryBuilder {
  521. return &EntryQueryBuilder{
  522. store: s,
  523. }
  524. }