entry_query_builder.go 11 KB

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