entry_query_builder.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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. // WithEntryID filter by entry ID.
  111. func (e *EntryQueryBuilder) WithEntryID(entryID int64) *EntryQueryBuilder {
  112. if entryID != 0 {
  113. e.conditions = append(e.conditions, "e.id = $"+strconv.Itoa(len(e.args)+1))
  114. e.args = append(e.args, entryID)
  115. }
  116. return e
  117. }
  118. // WithFeedID filter by feed ID.
  119. func (e *EntryQueryBuilder) WithFeedID(feedID int64) *EntryQueryBuilder {
  120. if feedID > 0 {
  121. e.conditions = append(e.conditions, "e.feed_id = $"+strconv.Itoa(len(e.args)+1))
  122. e.args = append(e.args, feedID)
  123. }
  124. return e
  125. }
  126. // WithCategoryID filter by category ID.
  127. func (e *EntryQueryBuilder) WithCategoryID(categoryID int64) *EntryQueryBuilder {
  128. if categoryID > 0 {
  129. e.conditions = append(e.conditions, "f.category_id = $"+strconv.Itoa(len(e.args)+1))
  130. e.args = append(e.args, categoryID)
  131. }
  132. return e
  133. }
  134. // WithStatus filter by entry status.
  135. func (e *EntryQueryBuilder) WithStatus(status string) *EntryQueryBuilder {
  136. if status != "" {
  137. e.conditions = append(e.conditions, "e.status = $"+strconv.Itoa(len(e.args)+1))
  138. e.args = append(e.args, status)
  139. }
  140. return e
  141. }
  142. // WithStatuses filter by a list of entry statuses.
  143. func (e *EntryQueryBuilder) WithStatuses(statuses []string) *EntryQueryBuilder {
  144. if len(statuses) == 1 {
  145. e.conditions = append(e.conditions, fmt.Sprintf("e.status = $%d", len(e.args)+1))
  146. e.args = append(e.args, statuses[0])
  147. } else if len(statuses) > 1 {
  148. e.conditions = append(e.conditions, fmt.Sprintf("e.status = ANY($%d)", len(e.args)+1))
  149. e.args = append(e.args, pq.StringArray(statuses))
  150. }
  151. return e
  152. }
  153. // WithTags filter by a list of entry tags.
  154. func (e *EntryQueryBuilder) WithTags(tags []string) *EntryQueryBuilder {
  155. if len(tags) > 0 {
  156. for _, cat := range tags {
  157. e.conditions = append(e.conditions, fmt.Sprintf("LOWER($%d) = ANY(LOWER(e.tags::text)::text[])", len(e.args)+1))
  158. e.args = append(e.args, cat)
  159. }
  160. }
  161. return e
  162. }
  163. // WithoutStatus set the entry status that should not be returned.
  164. func (e *EntryQueryBuilder) WithoutStatus(status string) *EntryQueryBuilder {
  165. if status != "" {
  166. e.conditions = append(e.conditions, "e.status <> $"+strconv.Itoa(len(e.args)+1))
  167. e.args = append(e.args, status)
  168. }
  169. return e
  170. }
  171. // WithShareCode set the entry share code.
  172. func (e *EntryQueryBuilder) WithShareCode(shareCode string) *EntryQueryBuilder {
  173. e.conditions = append(e.conditions, "e.share_code = $"+strconv.Itoa(len(e.args)+1))
  174. e.args = append(e.args, shareCode)
  175. return e
  176. }
  177. // WithShareCodeNotEmpty adds a filter for non-empty share code.
  178. func (e *EntryQueryBuilder) WithShareCodeNotEmpty() *EntryQueryBuilder {
  179. e.conditions = append(e.conditions, "e.share_code <> ''")
  180. return e
  181. }
  182. // WithSorting add a sort expression.
  183. func (e *EntryQueryBuilder) WithSorting(column, direction string) *EntryQueryBuilder {
  184. switch {
  185. case strings.EqualFold(direction, "ASC"):
  186. e.sortExpressions = append(e.sortExpressions, pq.QuoteIdentifier(column)+" ASC")
  187. case strings.EqualFold(direction, "DESC"):
  188. e.sortExpressions = append(e.sortExpressions, pq.QuoteIdentifier(column)+" DESC")
  189. }
  190. return e
  191. }
  192. // WithLimit set the limit.
  193. func (e *EntryQueryBuilder) WithLimit(limit int) *EntryQueryBuilder {
  194. if limit > 0 {
  195. e.limit = min(limit, model.MaxEntryLimit)
  196. }
  197. return e
  198. }
  199. // WithOffset set the offset.
  200. func (e *EntryQueryBuilder) WithOffset(offset int) *EntryQueryBuilder {
  201. if offset > 0 {
  202. e.offset = offset
  203. }
  204. return e
  205. }
  206. func (e *EntryQueryBuilder) WithGloballyVisible() *EntryQueryBuilder {
  207. e.conditions = append(e.conditions, "c.hide_globally IS FALSE")
  208. e.conditions = append(e.conditions, "f.hide_globally IS FALSE")
  209. return e
  210. }
  211. // CountEntries count the number of entries that match the condition.
  212. func (e *EntryQueryBuilder) CountEntries() (count int, err error) {
  213. query := `
  214. SELECT count(*)
  215. FROM entries e
  216. JOIN feeds f ON f.id = e.feed_id
  217. JOIN categories c ON c.id = f.category_id
  218. WHERE ` + e.buildCondition()
  219. err = e.store.db.QueryRow(query, e.args...).Scan(&count)
  220. if err != nil {
  221. return 0, fmt.Errorf("store: unable to count entries: %v", err)
  222. }
  223. return count, nil
  224. }
  225. // GetEntry returns a single entry that match the condition.
  226. func (e *EntryQueryBuilder) GetEntry() (*model.Entry, error) {
  227. e.limit = 1
  228. entries, err := e.GetEntries()
  229. if err != nil {
  230. return nil, err
  231. }
  232. if len(entries) != 1 {
  233. return nil, nil
  234. }
  235. entries[0].Enclosures, err = e.store.GetEnclosures(entries[0].ID)
  236. if err != nil {
  237. return nil, err
  238. }
  239. return entries[0], nil
  240. }
  241. // GetEntries returns a list of entries that match the condition.
  242. func (e *EntryQueryBuilder) GetEntries() (model.Entries, error) {
  243. entries, _, err := e.fetchEntries(false)
  244. return entries, err
  245. }
  246. // GetEntriesWithCount returns a list of entries and the total count of matching
  247. // rows (ignoring limit/offset) in a single query using a window function.
  248. // This avoids a separate CountEntries() round-trip.
  249. func (e *EntryQueryBuilder) GetEntriesWithCount() (model.Entries, int, error) {
  250. return e.fetchEntries(true)
  251. }
  252. // fetchEntries is the shared implementation for GetEntries and GetEntriesWithCount.
  253. // When withCount is true, count(*) OVER() is included in the SELECT and the total
  254. // count of matching rows is returned; otherwise the returned count is 0.
  255. func (e *EntryQueryBuilder) fetchEntries(withCount bool) (model.Entries, int, error) {
  256. countColumn := ""
  257. if withCount {
  258. countColumn = "count(*) OVER(),"
  259. }
  260. query := `
  261. SELECT
  262. ` + countColumn + `
  263. e.id,
  264. e.user_id,
  265. e.feed_id,
  266. e.hash,
  267. e.published_at at time zone u.timezone,
  268. e.title,
  269. e.url,
  270. e.comments_url,
  271. e.author,
  272. e.share_code,
  273. ` + e.contentColumn() + `,
  274. e.status,
  275. e.starred,
  276. e.reading_time,
  277. e.created_at,
  278. e.changed_at,
  279. e.tags,
  280. f.title as feed_title,
  281. f.feed_url,
  282. f.site_url,
  283. f.description,
  284. f.checked_at,
  285. f.category_id,
  286. c.title as category_title,
  287. c.hide_globally as category_hidden,
  288. f.scraper_rules,
  289. f.rewrite_rules,
  290. f.crawler,
  291. f.user_agent,
  292. f.cookie,
  293. f.hide_globally,
  294. f.no_media_player,
  295. f.webhook_url,
  296. fi.icon_id,
  297. i.external_id AS icon_external_id,
  298. u.timezone
  299. FROM
  300. entries e
  301. LEFT JOIN
  302. feeds f ON f.id=e.feed_id
  303. LEFT JOIN
  304. categories c ON c.id=f.category_id
  305. LEFT JOIN
  306. feed_icons fi ON fi.feed_id=f.id
  307. LEFT JOIN
  308. icons i ON i.id=fi.icon_id
  309. LEFT JOIN
  310. users u ON u.id=e.user_id
  311. WHERE ` + e.buildCondition() + " " + e.buildSorting()
  312. rows, err := e.store.db.Query(query, e.args...)
  313. if err != nil {
  314. return nil, 0, fmt.Errorf("store: unable to get entries: %v", err)
  315. }
  316. defer rows.Close()
  317. size := max(e.limit, 0)
  318. entries := make(model.Entries, 0, size)
  319. entryMap := make(map[int64]*model.Entry, size)
  320. entryIDs := make([]int64, 0, size)
  321. var totalCount int
  322. for rows.Next() {
  323. var iconID sql.NullInt64
  324. var externalIconID sql.NullString
  325. var tz string
  326. entry := model.NewEntry()
  327. dest := []any{
  328. &entry.ID,
  329. &entry.UserID,
  330. &entry.FeedID,
  331. &entry.Hash,
  332. &entry.Date,
  333. &entry.Title,
  334. &entry.URL,
  335. &entry.CommentsURL,
  336. &entry.Author,
  337. &entry.ShareCode,
  338. &entry.Content,
  339. &entry.Status,
  340. &entry.Starred,
  341. &entry.ReadingTime,
  342. &entry.CreatedAt,
  343. &entry.ChangedAt,
  344. pq.Array(&entry.Tags),
  345. &entry.Feed.Title,
  346. &entry.Feed.FeedURL,
  347. &entry.Feed.SiteURL,
  348. &entry.Feed.Description,
  349. &entry.Feed.CheckedAt,
  350. &entry.Feed.Category.ID,
  351. &entry.Feed.Category.Title,
  352. &entry.Feed.Category.HideGlobally,
  353. &entry.Feed.ScraperRules,
  354. &entry.Feed.RewriteRules,
  355. &entry.Feed.Crawler,
  356. &entry.Feed.UserAgent,
  357. &entry.Feed.Cookie,
  358. &entry.Feed.HideGlobally,
  359. &entry.Feed.NoMediaPlayer,
  360. &entry.Feed.WebhookURL,
  361. &iconID,
  362. &externalIconID,
  363. &tz,
  364. }
  365. if withCount {
  366. dest = append([]any{&totalCount}, dest...)
  367. }
  368. err := rows.Scan(dest...)
  369. if err != nil {
  370. return nil, 0, fmt.Errorf("store: unable to fetch entry row: %v", err)
  371. }
  372. if iconID.Valid && externalIconID.Valid && externalIconID.String != "" {
  373. entry.Feed.Icon.FeedID = entry.FeedID
  374. entry.Feed.Icon.IconID = iconID.Int64
  375. entry.Feed.Icon.ExternalIconID = externalIconID.String
  376. } else {
  377. entry.Feed.Icon.IconID = 0
  378. }
  379. // Make sure that timestamp fields contain timezone information (API)
  380. entry.Date = timezone.Convert(tz, entry.Date)
  381. entry.CreatedAt = timezone.Convert(tz, entry.CreatedAt)
  382. entry.ChangedAt = timezone.Convert(tz, entry.ChangedAt)
  383. entry.Feed.CheckedAt = timezone.Convert(tz, entry.Feed.CheckedAt)
  384. entry.Feed.ID = entry.FeedID
  385. entry.Feed.UserID = entry.UserID
  386. entry.Feed.Icon.FeedID = entry.FeedID
  387. entry.Feed.Category.UserID = entry.UserID
  388. entries = append(entries, entry)
  389. entryMap[entry.ID] = entry
  390. entryIDs = append(entryIDs, entry.ID)
  391. }
  392. if e.fetchEnclosures && len(entryIDs) > 0 {
  393. enclosures, err := e.store.GetEnclosuresForEntries(entryIDs)
  394. if err != nil {
  395. return nil, 0, fmt.Errorf("store: unable to fetch enclosures: %w", err)
  396. }
  397. for entryID, entryEnclosures := range enclosures {
  398. if entry, exists := entryMap[entryID]; exists {
  399. entry.Enclosures = entryEnclosures
  400. }
  401. }
  402. }
  403. return entries, totalCount, nil
  404. }
  405. // GetEntryIDs returns a list of entry IDs that match the condition.
  406. func (e *EntryQueryBuilder) GetEntryIDs() ([]int64, error) {
  407. query := `
  408. SELECT
  409. e.id
  410. FROM
  411. entries e
  412. LEFT JOIN
  413. feeds f
  414. ON
  415. f.id=e.feed_id
  416. WHERE ` + e.buildCondition() + " " + e.buildSorting()
  417. rows, err := e.store.db.Query(query, e.args...)
  418. if err != nil {
  419. return nil, fmt.Errorf("store: unable to get entries: %v", err)
  420. }
  421. defer rows.Close()
  422. var entryIDs []int64
  423. for rows.Next() {
  424. var entryID int64
  425. err := rows.Scan(&entryID)
  426. if err != nil {
  427. return nil, fmt.Errorf("store: unable to fetch entry row: %v", err)
  428. }
  429. entryIDs = append(entryIDs, entryID)
  430. }
  431. return entryIDs, nil
  432. }
  433. func (e *EntryQueryBuilder) contentColumn() string {
  434. if e.excludeContent {
  435. return "'' AS content"
  436. }
  437. return "e.content"
  438. }
  439. func (e *EntryQueryBuilder) buildCondition() string {
  440. return strings.Join(e.conditions, " AND ")
  441. }
  442. func (e *EntryQueryBuilder) buildSorting() string {
  443. var parts string
  444. if len(e.sortExpressions) > 0 {
  445. parts += " ORDER BY " + strings.Join(e.sortExpressions, ", ")
  446. }
  447. if e.limit > 0 {
  448. parts += " LIMIT " + strconv.Itoa(e.limit)
  449. }
  450. if e.offset > 0 {
  451. parts += " OFFSET " + strconv.Itoa(e.offset)
  452. }
  453. return parts
  454. }
  455. // NewEntryQueryBuilder returns a new EntryQueryBuilder.
  456. func NewEntryQueryBuilder(store *Storage, userID int64) *EntryQueryBuilder {
  457. return &EntryQueryBuilder{
  458. store: store,
  459. args: []any{userID},
  460. conditions: []string{"e.user_id = $1"},
  461. }
  462. }
  463. // NewAnonymousQueryBuilder returns a new EntryQueryBuilder suitable for anonymous users.
  464. func NewAnonymousQueryBuilder(store *Storage) *EntryQueryBuilder {
  465. return &EntryQueryBuilder{
  466. store: store,
  467. }
  468. }