4
0

entry_query_builder.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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 adds a condition to fetch only the given 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.Array(entryIDs))
  72. return e
  73. }
  74. // WithEntryID set the entryID.
  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 set the feedID.
  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 set the categoryID.
  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 set the 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. // WithoutStatus set the entry status that should not be returned.
  107. func (e *EntryQueryBuilder) WithoutStatus(status string) *EntryQueryBuilder {
  108. if status != "" {
  109. e.conditions = append(e.conditions, fmt.Sprintf("e.status <> $%d", len(e.args)+1))
  110. e.args = append(e.args, status)
  111. }
  112. return e
  113. }
  114. // WithShareCode set the entry share code.
  115. func (e *EntryQueryBuilder) WithShareCode(shareCode string) *EntryQueryBuilder {
  116. e.conditions = append(e.conditions, fmt.Sprintf("e.share_code = $%d", len(e.args)+1))
  117. e.args = append(e.args, shareCode)
  118. return e
  119. }
  120. // WithShareCodeNotEmpty adds a filter for non-empty share code.
  121. func (e *EntryQueryBuilder) WithShareCodeNotEmpty() *EntryQueryBuilder {
  122. e.conditions = append(e.conditions, "e.share_code <> ''")
  123. return e
  124. }
  125. // WithOrder set the sorting order.
  126. func (e *EntryQueryBuilder) WithOrder(order string) *EntryQueryBuilder {
  127. e.order = order
  128. return e
  129. }
  130. // WithDirection set the sorting direction.
  131. func (e *EntryQueryBuilder) WithDirection(direction string) *EntryQueryBuilder {
  132. e.direction = direction
  133. return e
  134. }
  135. // WithLimit set the limit.
  136. func (e *EntryQueryBuilder) WithLimit(limit int) *EntryQueryBuilder {
  137. e.limit = limit
  138. return e
  139. }
  140. // WithOffset set the offset.
  141. func (e *EntryQueryBuilder) WithOffset(offset int) *EntryQueryBuilder {
  142. e.offset = offset
  143. return e
  144. }
  145. // CountEntries count the number of entries that match the condition.
  146. func (e *EntryQueryBuilder) CountEntries() (count int, err error) {
  147. query := `SELECT count(*) FROM entries e LEFT JOIN feeds f ON f.id=e.feed_id WHERE %s`
  148. condition := e.buildCondition()
  149. err = e.store.db.QueryRow(fmt.Sprintf(query, condition), e.args...).Scan(&count)
  150. if err != nil {
  151. return 0, fmt.Errorf("unable to count entries: %v", err)
  152. }
  153. return count, nil
  154. }
  155. // GetEntry returns a single entry that match the condition.
  156. func (e *EntryQueryBuilder) GetEntry() (*model.Entry, error) {
  157. e.limit = 1
  158. entries, err := e.GetEntries()
  159. if err != nil {
  160. return nil, err
  161. }
  162. if len(entries) != 1 {
  163. return nil, nil
  164. }
  165. entries[0].Enclosures, err = e.store.GetEnclosures(entries[0].ID)
  166. if err != nil {
  167. return nil, err
  168. }
  169. return entries[0], nil
  170. }
  171. // GetEntries returns a list of entries that match the condition.
  172. func (e *EntryQueryBuilder) GetEntries() (model.Entries, error) {
  173. query := `
  174. SELECT
  175. e.id,
  176. e.user_id,
  177. e.feed_id,
  178. e.hash,
  179. e.published_at at time zone u.timezone,
  180. e.title,
  181. e.url,
  182. e.comments_url,
  183. e.author,
  184. e.share_code,
  185. e.content,
  186. e.status,
  187. e.starred,
  188. f.title as feed_title,
  189. f.feed_url,
  190. f.site_url,
  191. f.checked_at,
  192. f.category_id, c.title as category_title,
  193. f.scraper_rules,
  194. f.rewrite_rules,
  195. f.crawler,
  196. f.user_agent,
  197. fi.icon_id,
  198. u.timezone
  199. FROM
  200. entries e
  201. LEFT JOIN
  202. feeds f ON f.id=e.feed_id
  203. LEFT JOIN
  204. categories c ON c.id=f.category_id
  205. LEFT JOIN
  206. feed_icons fi ON fi.feed_id=f.id
  207. LEFT JOIN
  208. users u ON u.id=e.user_id
  209. WHERE %s %s
  210. `
  211. condition := e.buildCondition()
  212. sorting := e.buildSorting()
  213. query = fmt.Sprintf(query, condition, sorting)
  214. rows, err := e.store.db.Query(query, e.args...)
  215. if err != nil {
  216. return nil, fmt.Errorf("unable to get entries: %v", err)
  217. }
  218. defer rows.Close()
  219. entries := make(model.Entries, 0)
  220. for rows.Next() {
  221. var entry model.Entry
  222. var iconID interface{}
  223. var tz string
  224. entry.Feed = &model.Feed{}
  225. entry.Feed.Category = &model.Category{}
  226. entry.Feed.Icon = &model.FeedIcon{}
  227. err := rows.Scan(
  228. &entry.ID,
  229. &entry.UserID,
  230. &entry.FeedID,
  231. &entry.Hash,
  232. &entry.Date,
  233. &entry.Title,
  234. &entry.URL,
  235. &entry.CommentsURL,
  236. &entry.Author,
  237. &entry.ShareCode,
  238. &entry.Content,
  239. &entry.Status,
  240. &entry.Starred,
  241. &entry.Feed.Title,
  242. &entry.Feed.FeedURL,
  243. &entry.Feed.SiteURL,
  244. &entry.Feed.CheckedAt,
  245. &entry.Feed.Category.ID,
  246. &entry.Feed.Category.Title,
  247. &entry.Feed.ScraperRules,
  248. &entry.Feed.RewriteRules,
  249. &entry.Feed.Crawler,
  250. &entry.Feed.UserAgent,
  251. &iconID,
  252. &tz,
  253. )
  254. if err != nil {
  255. return nil, fmt.Errorf("unable to fetch entry row: %v", err)
  256. }
  257. if iconID == nil {
  258. entry.Feed.Icon.IconID = 0
  259. } else {
  260. entry.Feed.Icon.IconID = iconID.(int64)
  261. }
  262. // Make sure that timestamp fields contains timezone information (API)
  263. entry.Date = timezone.Convert(tz, entry.Date)
  264. entry.Feed.CheckedAt = timezone.Convert(tz, entry.Feed.CheckedAt)
  265. entry.Feed.ID = entry.FeedID
  266. entry.Feed.UserID = entry.UserID
  267. entry.Feed.Icon.FeedID = entry.FeedID
  268. entry.Feed.Category.UserID = entry.UserID
  269. entries = append(entries, &entry)
  270. }
  271. return entries, nil
  272. }
  273. // GetEntryIDs returns a list of entry IDs that match the condition.
  274. func (e *EntryQueryBuilder) GetEntryIDs() ([]int64, error) {
  275. query := `SELECT e.id FROM entries e LEFT JOIN feeds f ON f.id=e.feed_id WHERE %s %s`
  276. condition := e.buildCondition()
  277. query = fmt.Sprintf(query, condition, e.buildSorting())
  278. rows, err := e.store.db.Query(query, e.args...)
  279. if err != nil {
  280. return nil, fmt.Errorf("unable to get entries: %v", err)
  281. }
  282. defer rows.Close()
  283. var entryIDs []int64
  284. for rows.Next() {
  285. var entryID int64
  286. err := rows.Scan(&entryID)
  287. if err != nil {
  288. return nil, fmt.Errorf("unable to fetch entry row: %v", err)
  289. }
  290. entryIDs = append(entryIDs, entryID)
  291. }
  292. return entryIDs, nil
  293. }
  294. func (e *EntryQueryBuilder) buildCondition() string {
  295. return strings.Join(e.conditions, " AND ")
  296. }
  297. func (e *EntryQueryBuilder) buildSorting() string {
  298. var parts []string
  299. if e.order != "" {
  300. parts = append(parts, fmt.Sprintf(`ORDER BY %s`, e.order))
  301. }
  302. if e.direction != "" {
  303. parts = append(parts, fmt.Sprintf(`%s`, e.direction))
  304. }
  305. if e.limit != 0 {
  306. parts = append(parts, fmt.Sprintf(`LIMIT %d`, e.limit))
  307. }
  308. if e.offset != 0 {
  309. parts = append(parts, fmt.Sprintf(`OFFSET %d`, e.offset))
  310. }
  311. return strings.Join(parts, " ")
  312. }
  313. // NewEntryQueryBuilder returns a new EntryQueryBuilder.
  314. func NewEntryQueryBuilder(store *Storage, userID int64) *EntryQueryBuilder {
  315. return &EntryQueryBuilder{
  316. store: store,
  317. args: []interface{}{userID},
  318. conditions: []string{"e.user_id = $1"},
  319. }
  320. }
  321. // NewAnonymousQueryBuilder returns a new EntryQueryBuilder suitable for anonymous users.
  322. func NewAnonymousQueryBuilder(store *Storage) *EntryQueryBuilder {
  323. return &EntryQueryBuilder{
  324. store: store,
  325. }
  326. }