entry_query_builder.go 11 KB

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