entry_query_builder.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. "strings"
  8. "time"
  9. "github.com/lib/pq"
  10. "miniflux.app/v2/internal/model"
  11. "miniflux.app/v2/internal/timezone"
  12. )
  13. // EntryQueryBuilder builds a SQL query to fetch entries.
  14. type EntryQueryBuilder struct {
  15. store *Storage
  16. args []interface{}
  17. conditions []string
  18. sortExpressions []string
  19. limit int
  20. offset int
  21. }
  22. // WithSearchQuery adds full-text search query to the condition.
  23. func (e *EntryQueryBuilder) WithSearchQuery(query string) *EntryQueryBuilder {
  24. if query != "" {
  25. nArgs := len(e.args) + 1
  26. e.conditions = append(e.conditions, fmt.Sprintf("e.document_vectors @@ plainto_tsquery($%d)", nArgs))
  27. e.args = append(e.args, query)
  28. // 0.0000001 = 0.1 / (seconds_in_a_day)
  29. e.WithSorting(
  30. fmt.Sprintf("ts_rank(document_vectors, plainto_tsquery($%d)) - extract (epoch from now() - published_at)::float * 0.0000001", nArgs),
  31. "DESC",
  32. )
  33. }
  34. return e
  35. }
  36. // WithStarred adds starred filter.
  37. func (e *EntryQueryBuilder) WithStarred(starred bool) *EntryQueryBuilder {
  38. if starred {
  39. e.conditions = append(e.conditions, "e.starred is true")
  40. } else {
  41. e.conditions = append(e.conditions, "e.starred is false")
  42. }
  43. return e
  44. }
  45. // BeforeDate adds a condition < published_at
  46. func (e *EntryQueryBuilder) BeforeDate(date time.Time) *EntryQueryBuilder {
  47. e.conditions = append(e.conditions, fmt.Sprintf("e.published_at < $%d", len(e.args)+1))
  48. e.args = append(e.args, date)
  49. return e
  50. }
  51. // AfterDate adds a condition > published_at
  52. func (e *EntryQueryBuilder) AfterDate(date time.Time) *EntryQueryBuilder {
  53. e.conditions = append(e.conditions, fmt.Sprintf("e.published_at > $%d", len(e.args)+1))
  54. e.args = append(e.args, date)
  55. return e
  56. }
  57. // BeforeEntryID adds a condition < entryID.
  58. func (e *EntryQueryBuilder) BeforeEntryID(entryID int64) *EntryQueryBuilder {
  59. if entryID != 0 {
  60. e.conditions = append(e.conditions, fmt.Sprintf("e.id < $%d", len(e.args)+1))
  61. e.args = append(e.args, entryID)
  62. }
  63. return e
  64. }
  65. // AfterEntryID adds a condition > entryID.
  66. func (e *EntryQueryBuilder) AfterEntryID(entryID int64) *EntryQueryBuilder {
  67. if entryID != 0 {
  68. e.conditions = append(e.conditions, fmt.Sprintf("e.id > $%d", len(e.args)+1))
  69. e.args = append(e.args, entryID)
  70. }
  71. return e
  72. }
  73. // WithEntryIDs filter by entry IDs.
  74. func (e *EntryQueryBuilder) WithEntryIDs(entryIDs []int64) *EntryQueryBuilder {
  75. e.conditions = append(e.conditions, fmt.Sprintf("e.id = ANY($%d)", len(e.args)+1))
  76. e.args = append(e.args, pq.Int64Array(entryIDs))
  77. return e
  78. }
  79. // WithEntryID filter by entry ID.
  80. func (e *EntryQueryBuilder) WithEntryID(entryID int64) *EntryQueryBuilder {
  81. if entryID != 0 {
  82. e.conditions = append(e.conditions, fmt.Sprintf("e.id = $%d", len(e.args)+1))
  83. e.args = append(e.args, entryID)
  84. }
  85. return e
  86. }
  87. // WithFeedID filter by feed ID.
  88. func (e *EntryQueryBuilder) WithFeedID(feedID int64) *EntryQueryBuilder {
  89. if feedID > 0 {
  90. e.conditions = append(e.conditions, fmt.Sprintf("e.feed_id = $%d", len(e.args)+1))
  91. e.args = append(e.args, feedID)
  92. }
  93. return e
  94. }
  95. // WithCategoryID filter by category ID.
  96. func (e *EntryQueryBuilder) WithCategoryID(categoryID int64) *EntryQueryBuilder {
  97. if categoryID > 0 {
  98. e.conditions = append(e.conditions, fmt.Sprintf("f.category_id = $%d", len(e.args)+1))
  99. e.args = append(e.args, categoryID)
  100. }
  101. return e
  102. }
  103. // WithStatus filter by entry status.
  104. func (e *EntryQueryBuilder) WithStatus(status string) *EntryQueryBuilder {
  105. if status != "" {
  106. e.conditions = append(e.conditions, fmt.Sprintf("e.status = $%d", len(e.args)+1))
  107. e.args = append(e.args, status)
  108. }
  109. return e
  110. }
  111. // WithStatuses filter by a list of entry statuses.
  112. func (e *EntryQueryBuilder) WithStatuses(statuses []string) *EntryQueryBuilder {
  113. if len(statuses) > 0 {
  114. e.conditions = append(e.conditions, fmt.Sprintf("e.status = ANY($%d)", len(e.args)+1))
  115. e.args = append(e.args, pq.StringArray(statuses))
  116. }
  117. return e
  118. }
  119. // WithTags filter by a list of entry tags.
  120. func (e *EntryQueryBuilder) WithTags(tags []string) *EntryQueryBuilder {
  121. if len(tags) > 0 {
  122. for _, cat := range tags {
  123. e.conditions = append(e.conditions, fmt.Sprintf("$%d = ANY(e.tags)", len(e.args)+1))
  124. e.args = append(e.args, cat)
  125. }
  126. }
  127. return e
  128. }
  129. // WithoutStatus set the entry status that should not be returned.
  130. func (e *EntryQueryBuilder) WithoutStatus(status string) *EntryQueryBuilder {
  131. if status != "" {
  132. e.conditions = append(e.conditions, fmt.Sprintf("e.status <> $%d", len(e.args)+1))
  133. e.args = append(e.args, status)
  134. }
  135. return e
  136. }
  137. // WithShareCode set the entry share code.
  138. func (e *EntryQueryBuilder) WithShareCode(shareCode string) *EntryQueryBuilder {
  139. e.conditions = append(e.conditions, fmt.Sprintf("e.share_code = $%d", len(e.args)+1))
  140. e.args = append(e.args, shareCode)
  141. return e
  142. }
  143. // WithShareCodeNotEmpty adds a filter for non-empty share code.
  144. func (e *EntryQueryBuilder) WithShareCodeNotEmpty() *EntryQueryBuilder {
  145. e.conditions = append(e.conditions, "e.share_code <> ''")
  146. return e
  147. }
  148. // WithSorting add a sort expression.
  149. func (e *EntryQueryBuilder) WithSorting(column, direction string) *EntryQueryBuilder {
  150. e.sortExpressions = append(e.sortExpressions, fmt.Sprintf("%s %s", column, direction))
  151. return e
  152. }
  153. // WithLimit set the limit.
  154. func (e *EntryQueryBuilder) WithLimit(limit int) *EntryQueryBuilder {
  155. if limit > 0 {
  156. e.limit = limit
  157. }
  158. return e
  159. }
  160. // WithOffset set the offset.
  161. func (e *EntryQueryBuilder) WithOffset(offset int) *EntryQueryBuilder {
  162. if offset > 0 {
  163. e.offset = offset
  164. }
  165. return e
  166. }
  167. func (e *EntryQueryBuilder) WithGloballyVisible() *EntryQueryBuilder {
  168. e.conditions = append(e.conditions, "not c.hide_globally")
  169. e.conditions = append(e.conditions, "not f.hide_globally")
  170. return e
  171. }
  172. // CountEntries count the number of entries that match the condition.
  173. func (e *EntryQueryBuilder) CountEntries() (count int, err error) {
  174. query := `
  175. SELECT count(*)
  176. FROM entries e
  177. JOIN feeds f ON f.id = e.feed_id
  178. JOIN categories c ON c.id = f.category_id
  179. WHERE %s
  180. `
  181. condition := e.buildCondition()
  182. err = e.store.db.QueryRow(fmt.Sprintf(query, condition), e.args...).Scan(&count)
  183. if err != nil {
  184. return 0, fmt.Errorf("unable to count entries: %v", err)
  185. }
  186. return count, nil
  187. }
  188. // GetEntry returns a single entry that match the condition.
  189. func (e *EntryQueryBuilder) GetEntry() (*model.Entry, error) {
  190. e.limit = 1
  191. entries, err := e.GetEntries()
  192. if err != nil {
  193. return nil, err
  194. }
  195. if len(entries) != 1 {
  196. return nil, nil
  197. }
  198. entries[0].Enclosures, err = e.store.GetEnclosures(entries[0].ID)
  199. if err != nil {
  200. return nil, err
  201. }
  202. return entries[0], nil
  203. }
  204. // GetEntries returns a list of entries that match the condition.
  205. func (e *EntryQueryBuilder) GetEntries() (model.Entries, error) {
  206. query := `
  207. SELECT
  208. e.id,
  209. e.user_id,
  210. e.feed_id,
  211. e.hash,
  212. e.published_at at time zone u.timezone,
  213. e.title,
  214. e.url,
  215. e.comments_url,
  216. e.author,
  217. e.share_code,
  218. e.content,
  219. e.status,
  220. e.starred,
  221. e.reading_time,
  222. e.created_at,
  223. e.changed_at,
  224. e.tags,
  225. f.title as feed_title,
  226. f.feed_url,
  227. f.site_url,
  228. f.checked_at,
  229. f.category_id, c.title as category_title,
  230. f.scraper_rules,
  231. f.rewrite_rules,
  232. f.crawler,
  233. f.user_agent,
  234. f.cookie,
  235. f.no_media_player,
  236. fi.icon_id,
  237. u.timezone
  238. FROM
  239. entries e
  240. LEFT JOIN
  241. feeds f ON f.id=e.feed_id
  242. LEFT JOIN
  243. categories c ON c.id=f.category_id
  244. LEFT JOIN
  245. feed_icons fi ON fi.feed_id=f.id
  246. LEFT JOIN
  247. users u ON u.id=e.user_id
  248. WHERE %s %s
  249. `
  250. condition := e.buildCondition()
  251. sorting := e.buildSorting()
  252. query = fmt.Sprintf(query, condition, sorting)
  253. rows, err := e.store.db.Query(query, e.args...)
  254. if err != nil {
  255. return nil, fmt.Errorf("unable to get entries: %v", err)
  256. }
  257. defer rows.Close()
  258. entries := make(model.Entries, 0)
  259. for rows.Next() {
  260. var entry model.Entry
  261. var iconID sql.NullInt64
  262. var tz string
  263. entry.Feed = &model.Feed{}
  264. entry.Feed.Category = &model.Category{}
  265. entry.Feed.Icon = &model.FeedIcon{}
  266. err := rows.Scan(
  267. &entry.ID,
  268. &entry.UserID,
  269. &entry.FeedID,
  270. &entry.Hash,
  271. &entry.Date,
  272. &entry.Title,
  273. &entry.URL,
  274. &entry.CommentsURL,
  275. &entry.Author,
  276. &entry.ShareCode,
  277. &entry.Content,
  278. &entry.Status,
  279. &entry.Starred,
  280. &entry.ReadingTime,
  281. &entry.CreatedAt,
  282. &entry.ChangedAt,
  283. pq.Array(&entry.Tags),
  284. &entry.Feed.Title,
  285. &entry.Feed.FeedURL,
  286. &entry.Feed.SiteURL,
  287. &entry.Feed.CheckedAt,
  288. &entry.Feed.Category.ID,
  289. &entry.Feed.Category.Title,
  290. &entry.Feed.ScraperRules,
  291. &entry.Feed.RewriteRules,
  292. &entry.Feed.Crawler,
  293. &entry.Feed.UserAgent,
  294. &entry.Feed.Cookie,
  295. &entry.Feed.NoMediaPlayer,
  296. &iconID,
  297. &tz,
  298. )
  299. if err != nil {
  300. return nil, fmt.Errorf("unable to fetch entry row: %v", err)
  301. }
  302. if iconID.Valid {
  303. entry.Feed.Icon.IconID = iconID.Int64
  304. } else {
  305. entry.Feed.Icon.IconID = 0
  306. }
  307. // Make sure that timestamp fields contains timezone information (API)
  308. entry.Date = timezone.Convert(tz, entry.Date)
  309. entry.CreatedAt = timezone.Convert(tz, entry.CreatedAt)
  310. entry.ChangedAt = timezone.Convert(tz, entry.ChangedAt)
  311. entry.Feed.CheckedAt = timezone.Convert(tz, entry.Feed.CheckedAt)
  312. entry.Feed.ID = entry.FeedID
  313. entry.Feed.UserID = entry.UserID
  314. entry.Feed.Icon.FeedID = entry.FeedID
  315. entry.Feed.Category.UserID = entry.UserID
  316. entries = append(entries, &entry)
  317. }
  318. return entries, nil
  319. }
  320. // GetEntryIDs returns a list of entry IDs that match the condition.
  321. func (e *EntryQueryBuilder) GetEntryIDs() ([]int64, error) {
  322. query := `SELECT e.id FROM entries e LEFT JOIN feeds f ON f.id=e.feed_id WHERE %s %s`
  323. condition := e.buildCondition()
  324. query = fmt.Sprintf(query, condition, e.buildSorting())
  325. rows, err := e.store.db.Query(query, e.args...)
  326. if err != nil {
  327. return nil, fmt.Errorf("unable to get entries: %v", err)
  328. }
  329. defer rows.Close()
  330. var entryIDs []int64
  331. for rows.Next() {
  332. var entryID int64
  333. err := rows.Scan(&entryID)
  334. if err != nil {
  335. return nil, fmt.Errorf("unable to fetch entry row: %v", err)
  336. }
  337. entryIDs = append(entryIDs, entryID)
  338. }
  339. return entryIDs, nil
  340. }
  341. func (e *EntryQueryBuilder) buildCondition() string {
  342. return strings.Join(e.conditions, " AND ")
  343. }
  344. func (e *EntryQueryBuilder) buildSorting() string {
  345. var parts []string
  346. if len(e.sortExpressions) > 0 {
  347. parts = append(parts, fmt.Sprintf(`ORDER BY %s`, strings.Join(e.sortExpressions, ", ")))
  348. }
  349. if e.limit > 0 {
  350. parts = append(parts, fmt.Sprintf(`LIMIT %d`, e.limit))
  351. }
  352. if e.offset > 0 {
  353. parts = append(parts, fmt.Sprintf(`OFFSET %d`, e.offset))
  354. }
  355. return strings.Join(parts, " ")
  356. }
  357. // NewEntryQueryBuilder returns a new EntryQueryBuilder.
  358. func NewEntryQueryBuilder(store *Storage, userID int64) *EntryQueryBuilder {
  359. return &EntryQueryBuilder{
  360. store: store,
  361. args: []interface{}{userID},
  362. conditions: []string{"e.user_id = $1"},
  363. }
  364. }
  365. // NewAnonymousQueryBuilder returns a new EntryQueryBuilder suitable for anonymous users.
  366. func NewAnonymousQueryBuilder(store *Storage) *EntryQueryBuilder {
  367. return &EntryQueryBuilder{
  368. store: store,
  369. }
  370. }