entry_query_builder.go 15 KB

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