entry_query_builder.go 11 KB

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