entry_query_builder.go 13 KB

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