entry_query_builder.go 10 KB

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