entry_query_builder.go 14 KB

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