entry_query_builder.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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. order string
  20. direction string
  21. limit int
  22. offset int
  23. }
  24. // WithSearchQuery adds full-text search query to the condition.
  25. func (e *EntryQueryBuilder) WithSearchQuery(query string) *EntryQueryBuilder {
  26. if query != "" {
  27. nArgs := len(e.args) + 1
  28. e.conditions = append(e.conditions, fmt.Sprintf("e.document_vectors @@ plainto_tsquery($%d)", nArgs))
  29. e.args = append(e.args, query)
  30. // 0.0000001 = 0.1 / (seconds_in_a_day)
  31. e.WithOrder(fmt.Sprintf("ts_rank(document_vectors, plainto_tsquery($%d)) - extract (epoch from now() - published_at)::float * 0.0000001", nArgs))
  32. e.WithDirection("DESC")
  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. // WithOrder set the sorting order.
  149. func (e *EntryQueryBuilder) WithOrder(order string) *EntryQueryBuilder {
  150. e.order = order
  151. return e
  152. }
  153. // WithDirection set the sorting direction.
  154. func (e *EntryQueryBuilder) WithDirection(direction string) *EntryQueryBuilder {
  155. e.direction = direction
  156. return e
  157. }
  158. // WithLimit set the limit.
  159. func (e *EntryQueryBuilder) WithLimit(limit int) *EntryQueryBuilder {
  160. if limit > 0 {
  161. e.limit = limit
  162. }
  163. return e
  164. }
  165. // WithOffset set the offset.
  166. func (e *EntryQueryBuilder) WithOffset(offset int) *EntryQueryBuilder {
  167. if offset > 0 {
  168. e.offset = offset
  169. }
  170. return e
  171. }
  172. func (e *EntryQueryBuilder) WithGloballyVisible() *EntryQueryBuilder {
  173. e.conditions = append(e.conditions, "not c.hide_globally")
  174. e.conditions = append(e.conditions, "not f.hide_globally")
  175. return e
  176. }
  177. // CountEntries count the number of entries that match the condition.
  178. func (e *EntryQueryBuilder) CountEntries() (count int, err error) {
  179. query := `
  180. SELECT count(*)
  181. FROM entries e
  182. JOIN feeds f ON f.id = e.feed_id
  183. JOIN categories c ON c.id = f.category_id
  184. WHERE %s
  185. `
  186. condition := e.buildCondition()
  187. err = e.store.db.QueryRow(fmt.Sprintf(query, condition), e.args...).Scan(&count)
  188. if err != nil {
  189. return 0, fmt.Errorf("unable to count entries: %v", err)
  190. }
  191. return count, nil
  192. }
  193. // GetEntry returns a single entry that match the condition.
  194. func (e *EntryQueryBuilder) GetEntry() (*model.Entry, error) {
  195. e.limit = 1
  196. entries, err := e.GetEntries()
  197. if err != nil {
  198. return nil, err
  199. }
  200. if len(entries) != 1 {
  201. return nil, nil
  202. }
  203. entries[0].Enclosures, err = e.store.GetEnclosures(entries[0].ID)
  204. if err != nil {
  205. return nil, err
  206. }
  207. return entries[0], nil
  208. }
  209. // GetEntries returns a list of entries that match the condition.
  210. func (e *EntryQueryBuilder) GetEntries() (model.Entries, error) {
  211. query := `
  212. SELECT
  213. e.id,
  214. e.user_id,
  215. e.feed_id,
  216. e.hash,
  217. e.published_at at time zone u.timezone,
  218. e.title,
  219. e.url,
  220. e.comments_url,
  221. e.author,
  222. e.share_code,
  223. e.content,
  224. e.status,
  225. e.starred,
  226. e.reading_time,
  227. e.created_at,
  228. e.changed_at,
  229. e.tags,
  230. f.title as feed_title,
  231. f.feed_url,
  232. f.site_url,
  233. f.checked_at,
  234. f.category_id, c.title as category_title,
  235. f.scraper_rules,
  236. f.rewrite_rules,
  237. f.crawler,
  238. f.user_agent,
  239. f.cookie,
  240. fi.icon_id,
  241. u.timezone
  242. FROM
  243. entries e
  244. LEFT JOIN
  245. feeds f ON f.id=e.feed_id
  246. LEFT JOIN
  247. categories c ON c.id=f.category_id
  248. LEFT JOIN
  249. feed_icons fi ON fi.feed_id=f.id
  250. LEFT JOIN
  251. users u ON u.id=e.user_id
  252. WHERE %s %s
  253. `
  254. condition := e.buildCondition()
  255. sorting := e.buildSorting()
  256. query = fmt.Sprintf(query, condition, sorting)
  257. rows, err := e.store.db.Query(query, e.args...)
  258. if err != nil {
  259. return nil, fmt.Errorf("unable to get entries: %v", err)
  260. }
  261. defer rows.Close()
  262. entries := make(model.Entries, 0)
  263. for rows.Next() {
  264. var entry model.Entry
  265. var iconID sql.NullInt64
  266. var tz string
  267. entry.Feed = &model.Feed{}
  268. entry.Feed.Category = &model.Category{}
  269. entry.Feed.Icon = &model.FeedIcon{}
  270. err := rows.Scan(
  271. &entry.ID,
  272. &entry.UserID,
  273. &entry.FeedID,
  274. &entry.Hash,
  275. &entry.Date,
  276. &entry.Title,
  277. &entry.URL,
  278. &entry.CommentsURL,
  279. &entry.Author,
  280. &entry.ShareCode,
  281. &entry.Content,
  282. &entry.Status,
  283. &entry.Starred,
  284. &entry.ReadingTime,
  285. &entry.CreatedAt,
  286. &entry.ChangedAt,
  287. pq.Array(&entry.Tags),
  288. &entry.Feed.Title,
  289. &entry.Feed.FeedURL,
  290. &entry.Feed.SiteURL,
  291. &entry.Feed.CheckedAt,
  292. &entry.Feed.Category.ID,
  293. &entry.Feed.Category.Title,
  294. &entry.Feed.ScraperRules,
  295. &entry.Feed.RewriteRules,
  296. &entry.Feed.Crawler,
  297. &entry.Feed.UserAgent,
  298. &entry.Feed.Cookie,
  299. &iconID,
  300. &tz,
  301. )
  302. if err != nil {
  303. return nil, fmt.Errorf("unable to fetch entry row: %v", err)
  304. }
  305. if iconID.Valid {
  306. entry.Feed.Icon.IconID = iconID.Int64
  307. } else {
  308. entry.Feed.Icon.IconID = 0
  309. }
  310. // Make sure that timestamp fields contains timezone information (API)
  311. entry.Date = timezone.Convert(tz, entry.Date)
  312. entry.CreatedAt = timezone.Convert(tz, entry.CreatedAt)
  313. entry.ChangedAt = timezone.Convert(tz, entry.ChangedAt)
  314. entry.Feed.CheckedAt = timezone.Convert(tz, entry.Feed.CheckedAt)
  315. entry.Feed.ID = entry.FeedID
  316. entry.Feed.UserID = entry.UserID
  317. entry.Feed.Icon.FeedID = entry.FeedID
  318. entry.Feed.Category.UserID = entry.UserID
  319. entries = append(entries, &entry)
  320. }
  321. return entries, nil
  322. }
  323. // GetEntryIDs returns a list of entry IDs that match the condition.
  324. func (e *EntryQueryBuilder) GetEntryIDs() ([]int64, error) {
  325. query := `SELECT e.id FROM entries e LEFT JOIN feeds f ON f.id=e.feed_id WHERE %s %s`
  326. condition := e.buildCondition()
  327. query = fmt.Sprintf(query, condition, e.buildSorting())
  328. rows, err := e.store.db.Query(query, e.args...)
  329. if err != nil {
  330. return nil, fmt.Errorf("unable to get entries: %v", err)
  331. }
  332. defer rows.Close()
  333. var entryIDs []int64
  334. for rows.Next() {
  335. var entryID int64
  336. err := rows.Scan(&entryID)
  337. if err != nil {
  338. return nil, fmt.Errorf("unable to fetch entry row: %v", err)
  339. }
  340. entryIDs = append(entryIDs, entryID)
  341. }
  342. return entryIDs, nil
  343. }
  344. func (e *EntryQueryBuilder) buildCondition() string {
  345. return strings.Join(e.conditions, " AND ")
  346. }
  347. func (e *EntryQueryBuilder) buildSorting() string {
  348. var parts []string
  349. if e.order != "" {
  350. parts = append(parts, fmt.Sprintf(`ORDER BY %s`, e.order))
  351. }
  352. if e.direction != "" {
  353. parts = append(parts, e.direction)
  354. }
  355. if e.limit > 0 {
  356. parts = append(parts, fmt.Sprintf(`LIMIT %d`, e.limit))
  357. }
  358. if e.offset > 0 {
  359. parts = append(parts, fmt.Sprintf(`OFFSET %d`, e.offset))
  360. }
  361. return strings.Join(parts, " ")
  362. }
  363. // NewEntryQueryBuilder returns a new EntryQueryBuilder.
  364. func NewEntryQueryBuilder(store *Storage, userID int64) *EntryQueryBuilder {
  365. return &EntryQueryBuilder{
  366. store: store,
  367. args: []interface{}{userID},
  368. conditions: []string{"e.user_id = $1"},
  369. }
  370. }
  371. // NewAnonymousQueryBuilder returns a new EntryQueryBuilder suitable for anonymous users.
  372. func NewAnonymousQueryBuilder(store *Storage) *EntryQueryBuilder {
  373. return &EntryQueryBuilder{
  374. store: store,
  375. }
  376. }