entry_query_builder.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. e.changed_at,
  204. f.title as feed_title,
  205. f.feed_url,
  206. f.site_url,
  207. f.checked_at,
  208. f.category_id, c.title as category_title,
  209. f.scraper_rules,
  210. f.rewrite_rules,
  211. f.crawler,
  212. f.user_agent,
  213. f.cookie,
  214. fi.icon_id,
  215. u.timezone
  216. FROM
  217. entries e
  218. LEFT JOIN
  219. feeds f ON f.id=e.feed_id
  220. LEFT JOIN
  221. categories c ON c.id=f.category_id
  222. LEFT JOIN
  223. feed_icons fi ON fi.feed_id=f.id
  224. LEFT JOIN
  225. users u ON u.id=e.user_id
  226. WHERE %s %s
  227. `
  228. condition := e.buildCondition()
  229. sorting := e.buildSorting()
  230. query = fmt.Sprintf(query, condition, sorting)
  231. rows, err := e.store.db.Query(query, e.args...)
  232. if err != nil {
  233. return nil, fmt.Errorf("unable to get entries: %v", err)
  234. }
  235. defer rows.Close()
  236. entries := make(model.Entries, 0)
  237. for rows.Next() {
  238. var entry model.Entry
  239. var iconID sql.NullInt64
  240. var tz string
  241. entry.Feed = &model.Feed{}
  242. entry.Feed.Category = &model.Category{}
  243. entry.Feed.Icon = &model.FeedIcon{}
  244. err := rows.Scan(
  245. &entry.ID,
  246. &entry.UserID,
  247. &entry.FeedID,
  248. &entry.Hash,
  249. &entry.Date,
  250. &entry.Title,
  251. &entry.URL,
  252. &entry.CommentsURL,
  253. &entry.Author,
  254. &entry.ShareCode,
  255. &entry.Content,
  256. &entry.Status,
  257. &entry.Starred,
  258. &entry.ReadingTime,
  259. &entry.CreatedAt,
  260. &entry.ChangedAt,
  261. &entry.Feed.Title,
  262. &entry.Feed.FeedURL,
  263. &entry.Feed.SiteURL,
  264. &entry.Feed.CheckedAt,
  265. &entry.Feed.Category.ID,
  266. &entry.Feed.Category.Title,
  267. &entry.Feed.ScraperRules,
  268. &entry.Feed.RewriteRules,
  269. &entry.Feed.Crawler,
  270. &entry.Feed.UserAgent,
  271. &entry.Feed.Cookie,
  272. &iconID,
  273. &tz,
  274. )
  275. if err != nil {
  276. return nil, fmt.Errorf("unable to fetch entry row: %v", err)
  277. }
  278. if iconID.Valid {
  279. entry.Feed.Icon.IconID = iconID.Int64
  280. } else {
  281. entry.Feed.Icon.IconID = 0
  282. }
  283. // Make sure that timestamp fields contains timezone information (API)
  284. entry.Date = timezone.Convert(tz, entry.Date)
  285. entry.CreatedAt = timezone.Convert(tz, entry.CreatedAt)
  286. entry.ChangedAt = timezone.Convert(tz, entry.ChangedAt)
  287. entry.Feed.CheckedAt = timezone.Convert(tz, entry.Feed.CheckedAt)
  288. entry.Feed.ID = entry.FeedID
  289. entry.Feed.UserID = entry.UserID
  290. entry.Feed.Icon.FeedID = entry.FeedID
  291. entry.Feed.Category.UserID = entry.UserID
  292. entries = append(entries, &entry)
  293. }
  294. return entries, nil
  295. }
  296. // GetEntryIDs returns a list of entry IDs that match the condition.
  297. func (e *EntryQueryBuilder) GetEntryIDs() ([]int64, error) {
  298. query := `SELECT e.id FROM entries e LEFT JOIN feeds f ON f.id=e.feed_id WHERE %s %s`
  299. condition := e.buildCondition()
  300. query = fmt.Sprintf(query, condition, e.buildSorting())
  301. rows, err := e.store.db.Query(query, e.args...)
  302. if err != nil {
  303. return nil, fmt.Errorf("unable to get entries: %v", err)
  304. }
  305. defer rows.Close()
  306. var entryIDs []int64
  307. for rows.Next() {
  308. var entryID int64
  309. err := rows.Scan(&entryID)
  310. if err != nil {
  311. return nil, fmt.Errorf("unable to fetch entry row: %v", err)
  312. }
  313. entryIDs = append(entryIDs, entryID)
  314. }
  315. return entryIDs, nil
  316. }
  317. func (e *EntryQueryBuilder) buildCondition() string {
  318. return strings.Join(e.conditions, " AND ")
  319. }
  320. func (e *EntryQueryBuilder) buildSorting() string {
  321. var parts []string
  322. if e.order != "" {
  323. parts = append(parts, fmt.Sprintf(`ORDER BY %s`, e.order))
  324. }
  325. if e.direction != "" {
  326. parts = append(parts, e.direction)
  327. }
  328. if e.limit > 0 {
  329. parts = append(parts, fmt.Sprintf(`LIMIT %d`, e.limit))
  330. }
  331. if e.offset > 0 {
  332. parts = append(parts, fmt.Sprintf(`OFFSET %d`, e.offset))
  333. }
  334. return strings.Join(parts, " ")
  335. }
  336. // NewEntryQueryBuilder returns a new EntryQueryBuilder.
  337. func NewEntryQueryBuilder(store *Storage, userID int64) *EntryQueryBuilder {
  338. return &EntryQueryBuilder{
  339. store: store,
  340. args: []interface{}{userID},
  341. conditions: []string{"e.user_id = $1"},
  342. }
  343. }
  344. // NewAnonymousQueryBuilder returns a new EntryQueryBuilder suitable for anonymous users.
  345. func NewAnonymousQueryBuilder(store *Storage) *EntryQueryBuilder {
  346. return &EntryQueryBuilder{
  347. store: store,
  348. }
  349. }