entry_query_builder.go 10 KB

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