entry_query_builder.go 11 KB

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