entry_query_builder.go 9.7 KB

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