entry.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package storage // import "miniflux.app/v2/internal/storage"
  4. import (
  5. "database/sql"
  6. "errors"
  7. "fmt"
  8. "log/slog"
  9. "time"
  10. "miniflux.app/v2/internal/crypto"
  11. "miniflux.app/v2/internal/model"
  12. "github.com/lib/pq"
  13. )
  14. // ErrEntryTombstoned is returned when an entry cannot be created because its
  15. // (feed_id, hash) pair has a tombstone recording a prior deletion.
  16. var ErrEntryTombstoned = errors.New("store: entry is tombstoned")
  17. // ErrEntryNotFound is returned when the entry does not exist or belongs to another user.
  18. var ErrEntryNotFound = errors.New(`store: entry not found`)
  19. // CountAllEntries returns the number of entries for each status in the database.
  20. func (s *Storage) CountAllEntries() (map[string]int64, error) {
  21. rows, err := s.db.Query(`SELECT status, count(*) FROM entries GROUP BY status`)
  22. if err != nil {
  23. return nil, fmt.Errorf("storage: unable to count entries: %w", err)
  24. }
  25. defer rows.Close()
  26. results := make(map[string]int64)
  27. results[model.EntryStatusUnread] = 0
  28. results[model.EntryStatusRead] = 0
  29. for rows.Next() {
  30. var status string
  31. var count int64
  32. if err := rows.Scan(&status, &count); err != nil {
  33. continue
  34. }
  35. results[status] = count
  36. }
  37. results["total"] = results[model.EntryStatusUnread] + results[model.EntryStatusRead]
  38. return results, nil
  39. }
  40. // UpdateEntryTitleAndContent updates entry title and content.
  41. func (s *Storage) UpdateEntryTitleAndContent(entry *model.Entry) error {
  42. truncatedTitle, truncatedContent := truncateTitleAndContentForTSVectorField(entry.Title, entry.Content)
  43. query := `
  44. UPDATE
  45. entries
  46. SET
  47. title=$1,
  48. content=$2,
  49. reading_time=$3,
  50. document_vectors = setweight(to_tsvector($4), 'A') || setweight(to_tsvector($5), 'B')
  51. WHERE
  52. id=$6 AND user_id=$7
  53. `
  54. if _, err := s.db.Exec(
  55. query,
  56. entry.Title,
  57. entry.Content,
  58. entry.ReadingTime,
  59. truncatedTitle,
  60. truncatedContent,
  61. entry.ID,
  62. entry.UserID); err != nil {
  63. return fmt.Errorf(`store: unable to update entry #%d: %v`, entry.ID, err)
  64. }
  65. return nil
  66. }
  67. // createEntry add a new entry.
  68. func (s *Storage) createEntry(tx *sql.Tx, entry *model.Entry) error {
  69. truncatedTitle, truncatedContent := truncateTitleAndContentForTSVectorField(entry.Title, entry.Content)
  70. // The WHERE NOT EXISTS guard makes the tombstone check atomic with the insert, so a
  71. // concurrent archive committing between an earlier existence check and this statement
  72. // cannot bring a deleted entry back as unread.
  73. query := `
  74. INSERT INTO entries
  75. (
  76. title,
  77. hash,
  78. url,
  79. comments_url,
  80. published_at,
  81. content,
  82. author,
  83. user_id,
  84. feed_id,
  85. reading_time,
  86. changed_at,
  87. document_vectors,
  88. tags,
  89. language
  90. )
  91. SELECT
  92. $1,
  93. $2,
  94. $3,
  95. $4,
  96. $5,
  97. $6,
  98. $7,
  99. $8,
  100. $9,
  101. $10,
  102. now(),
  103. setweight(to_tsvector($11), 'A') || setweight(to_tsvector($12), 'B'),
  104. $13,
  105. $14
  106. WHERE NOT EXISTS (
  107. SELECT 1 FROM entry_tombstones WHERE feed_id=$9 AND hash=$2
  108. )
  109. RETURNING
  110. id, status, created_at, changed_at
  111. `
  112. err := tx.QueryRow(
  113. query,
  114. entry.Title,
  115. entry.Hash,
  116. entry.URL,
  117. entry.CommentsURL,
  118. entry.Date,
  119. entry.Content,
  120. entry.Author,
  121. entry.UserID,
  122. entry.FeedID,
  123. entry.ReadingTime,
  124. truncatedTitle,
  125. truncatedContent,
  126. pq.Array(entry.Tags),
  127. entry.Language,
  128. ).Scan(
  129. &entry.ID,
  130. &entry.Status,
  131. &entry.CreatedAt,
  132. &entry.ChangedAt,
  133. )
  134. if errors.Is(err, sql.ErrNoRows) {
  135. return ErrEntryTombstoned
  136. }
  137. if err != nil {
  138. return fmt.Errorf(`store: unable to create entry %q (feed #%d): %v`, entry.URL, entry.FeedID, err)
  139. }
  140. for _, enclosure := range entry.Enclosures {
  141. enclosure.EntryID = entry.ID
  142. enclosure.UserID = entry.UserID
  143. err := s.createEnclosure(tx, enclosure)
  144. if err != nil {
  145. return err
  146. }
  147. }
  148. return nil
  149. }
  150. // updateEntry updates an entry when a feed is refreshed.
  151. // Note: we do not update the published date because some feeds do not contains any date,
  152. // it default to time.Now() which could change the order of items on the history page.
  153. func (s *Storage) updateEntry(tx *sql.Tx, entry *model.Entry) error {
  154. truncatedTitle, truncatedContent := truncateTitleAndContentForTSVectorField(entry.Title, entry.Content)
  155. query := `
  156. UPDATE
  157. entries
  158. SET
  159. title=$1,
  160. url=$2,
  161. comments_url=$3,
  162. content=$4,
  163. author=$5,
  164. reading_time=$6,
  165. document_vectors = setweight(to_tsvector($7), 'A') || setweight(to_tsvector($8), 'B'),
  166. tags=$12,
  167. language=$13
  168. WHERE
  169. user_id=$9 AND feed_id=$10 AND hash=$11
  170. RETURNING
  171. id
  172. `
  173. err := tx.QueryRow(
  174. query,
  175. entry.Title,
  176. entry.URL,
  177. entry.CommentsURL,
  178. entry.Content,
  179. entry.Author,
  180. entry.ReadingTime,
  181. truncatedTitle,
  182. truncatedContent,
  183. entry.UserID,
  184. entry.FeedID,
  185. entry.Hash,
  186. pq.Array(entry.Tags),
  187. entry.Language,
  188. ).Scan(&entry.ID)
  189. if err != nil {
  190. return fmt.Errorf(`store: unable to update entry %q: %v`, entry.URL, err)
  191. }
  192. for _, enclosure := range entry.Enclosures {
  193. enclosure.UserID = entry.UserID
  194. enclosure.EntryID = entry.ID
  195. }
  196. return s.updateEnclosures(tx, entry)
  197. }
  198. // entryExists checks if an entry already exists based on its hash when refreshing a feed.
  199. func (s *Storage) entryExists(tx *sql.Tx, entry *model.Entry) (bool, error) {
  200. var result bool
  201. // Note: This query uses entries_feed_id_hash_key index (filtering on user_id is not necessary).
  202. err := tx.QueryRow(`SELECT true FROM entries WHERE feed_id=$1 AND hash=$2 LIMIT 1`, entry.FeedID, entry.Hash).Scan(&result)
  203. if err != nil && err != sql.ErrNoRows {
  204. return result, fmt.Errorf(`store: unable to check if entry exists: %v`, err)
  205. }
  206. return result, nil
  207. }
  208. func (s *Storage) getEntryIDByHash(tx *sql.Tx, feedID int64, entryHash string) (int64, error) {
  209. var entryID int64
  210. err := tx.QueryRow(
  211. `SELECT id FROM entries WHERE feed_id=$1 AND hash=$2 LIMIT 1`,
  212. feedID,
  213. entryHash,
  214. ).Scan(&entryID)
  215. if errors.Is(err, sql.ErrNoRows) {
  216. return 0, nil
  217. }
  218. if err != nil {
  219. return 0, fmt.Errorf(`store: unable to fetch entry ID: %v`, err)
  220. }
  221. return entryID, nil
  222. }
  223. // InsertEntryForFeed inserts a single entry into a feed, optionally updating if it already exists.
  224. // Returns true if a new entry was created, false if an existing one was reused.
  225. func (s *Storage) InsertEntryForFeed(userID, feedID int64, entry *model.Entry) (bool, error) {
  226. entry.UserID = userID
  227. entry.FeedID = feedID
  228. tx, err := s.db.Begin()
  229. if err != nil {
  230. return false, fmt.Errorf("store: unable to start transaction: %v", err)
  231. }
  232. defer tx.Rollback()
  233. entryID, err := s.getEntryIDByHash(tx, entry.FeedID, entry.Hash)
  234. if err != nil {
  235. return false, err
  236. }
  237. alreadyExistingEntry := entryID > 0
  238. if alreadyExistingEntry {
  239. entry.ID = entryID
  240. } else {
  241. if err := s.createEntry(tx, entry); err != nil {
  242. return false, err
  243. }
  244. }
  245. if err := tx.Commit(); err != nil {
  246. return false, err
  247. }
  248. return !alreadyExistingEntry, nil
  249. }
  250. func (s *Storage) IsNewEntry(feedID int64, entryHash string) bool {
  251. // An entry is new only if it is neither stored nor tombstoned; otherwise
  252. // callers (such as the crawler) would do expensive work on every refresh
  253. // for items that will be discarded.
  254. query := `
  255. SELECT
  256. EXISTS (
  257. SELECT 1 FROM entries WHERE feed_id=$1 AND hash=$2
  258. ) OR EXISTS (
  259. SELECT 1 FROM entry_tombstones WHERE feed_id=$1 AND hash=$2
  260. )
  261. `
  262. var known bool
  263. s.db.QueryRow(query, feedID, entryHash).Scan(&known)
  264. return !known
  265. }
  266. func (s *Storage) GetReadTime(feedID int64, entryHash string) int {
  267. var result int
  268. // Note: This query uses entries_feed_id_hash_key index
  269. s.db.QueryRow(
  270. `SELECT
  271. reading_time
  272. FROM
  273. entries
  274. WHERE
  275. feed_id=$1 AND
  276. hash=$2
  277. `,
  278. feedID,
  279. entryHash,
  280. ).Scan(&result)
  281. return result
  282. }
  283. // RefreshFeedEntries updates feed entries while refreshing a feed.
  284. func (s *Storage) RefreshFeedEntries(userID, feedID int64, entries model.Entries, updateExistingEntries bool) (newEntries model.Entries, err error) {
  285. for _, entry := range entries {
  286. entry.UserID = userID
  287. entry.FeedID = feedID
  288. tx, err := s.db.Begin()
  289. if err != nil {
  290. return nil, fmt.Errorf(`store: unable to start transaction: %v`, err)
  291. }
  292. entryExists, err := s.entryExists(tx, entry)
  293. if err != nil {
  294. if rollbackErr := tx.Rollback(); rollbackErr != nil {
  295. return nil, fmt.Errorf(`store: unable to rollback transaction: %v (rolled back due to: %v)`, rollbackErr, err)
  296. }
  297. return nil, err
  298. }
  299. if entryExists {
  300. if updateExistingEntries {
  301. err = s.updateEntry(tx, entry)
  302. }
  303. } else {
  304. err = s.createEntry(tx, entry)
  305. switch {
  306. case errors.Is(err, ErrEntryTombstoned):
  307. err = nil
  308. case err == nil:
  309. newEntries = append(newEntries, entry)
  310. }
  311. }
  312. if err != nil {
  313. if rollbackErr := tx.Rollback(); rollbackErr != nil {
  314. return nil, fmt.Errorf(`store: unable to rollback transaction: %v (rolled back due to: %v)`, rollbackErr, err)
  315. }
  316. return nil, err
  317. }
  318. if err := tx.Commit(); err != nil {
  319. return nil, fmt.Errorf(`store: unable to commit transaction: %v`, err)
  320. }
  321. }
  322. return newEntries, nil
  323. }
  324. // ArchiveEntries deletes entries older than the given interval and records tombstones so they are not re-ingested.
  325. func (s *Storage) ArchiveEntries(status string, interval time.Duration, limit int) (int64, error) {
  326. if interval < 0 || limit <= 0 {
  327. return 0, nil
  328. }
  329. query := `
  330. WITH to_delete AS (
  331. SELECT id, feed_id, hash
  332. FROM entries
  333. WHERE
  334. status=$1 AND
  335. starred is false AND
  336. share_code='' AND
  337. created_at < now() - $2::interval
  338. ORDER BY created_at ASC
  339. FOR UPDATE SKIP LOCKED
  340. LIMIT $3
  341. ), deleted AS (
  342. DELETE FROM entries
  343. USING to_delete
  344. WHERE entries.id = to_delete.id
  345. RETURNING entries.feed_id, entries.hash
  346. )
  347. INSERT INTO entry_tombstones (feed_id, hash)
  348. SELECT feed_id, hash FROM deleted WHERE hash <> ''
  349. ON CONFLICT (feed_id, hash) DO NOTHING
  350. `
  351. days := max(int(interval/(24*time.Hour)), 1)
  352. result, err := s.db.Exec(query, status, fmt.Sprintf("%d days", days), limit)
  353. if err != nil {
  354. return 0, fmt.Errorf(`store: unable to archive %s entries: %v`, status, err)
  355. }
  356. count, err := result.RowsAffected()
  357. if err != nil {
  358. return 0, fmt.Errorf(`store: unable to get the number of rows affected: %v`, err)
  359. }
  360. return count, nil
  361. }
  362. // SetEntriesStatus update the status of the given list of entries.
  363. func (s *Storage) SetEntriesStatus(userID int64, entryIDs []int64, status string) error {
  364. query := `
  365. UPDATE
  366. entries
  367. SET
  368. status=$1,
  369. changed_at=now()
  370. WHERE
  371. user_id=$2 AND
  372. id=ANY($3)
  373. `
  374. if _, err := s.db.Exec(query, status, userID, pq.Array(entryIDs)); err != nil {
  375. return fmt.Errorf(`store: unable to update entries statuses %v: %v`, entryIDs, err)
  376. }
  377. return nil
  378. }
  379. // SetEntriesStatusAndCountVisible updates the status of the given entries and returns how many are visible in global views.
  380. func (s *Storage) SetEntriesStatusAndCountVisible(userID int64, entryIDs []int64, status string) (int, error) {
  381. query := `
  382. WITH updated AS (
  383. UPDATE entries
  384. SET
  385. status=$1,
  386. changed_at=now()
  387. WHERE
  388. user_id=$2 AND
  389. id=ANY($3)
  390. RETURNING feed_id
  391. )
  392. SELECT count(*)
  393. FROM updated u
  394. JOIN feeds f ON (f.id = u.feed_id)
  395. JOIN categories c ON (c.id = f.category_id)
  396. WHERE NOT f.hide_globally AND NOT c.hide_globally
  397. `
  398. var visible int
  399. if err := s.db.QueryRow(query, status, userID, pq.Array(entryIDs)).Scan(&visible); err != nil {
  400. return 0, fmt.Errorf(`store: unable to update entries status %v: %v`, entryIDs, err)
  401. }
  402. return visible, nil
  403. }
  404. // SetEntriesStarredState updates the starred state for the given list of entries.
  405. func (s *Storage) SetEntriesStarredState(userID int64, entryIDs []int64, starred bool) error {
  406. query := `UPDATE entries SET starred=$1, changed_at=now() WHERE user_id=$2 AND id=ANY($3)`
  407. if _, err := s.db.Exec(query, starred, userID, pq.Array(entryIDs)); err != nil {
  408. return fmt.Errorf(`store: unable to update the starred state %v: %v`, entryIDs, err)
  409. }
  410. return nil
  411. }
  412. // ToggleStarred toggles entry starred value.
  413. func (s *Storage) ToggleStarred(userID int64, entryID int64) error {
  414. query := `UPDATE entries SET starred = NOT starred, changed_at=now() WHERE user_id=$1 AND id=$2`
  415. result, err := s.db.Exec(query, userID, entryID)
  416. if err != nil {
  417. return fmt.Errorf(`store: unable to toggle starred flag for entry #%d: %v`, entryID, err)
  418. }
  419. count, err := result.RowsAffected()
  420. if err != nil {
  421. return fmt.Errorf(`store: unable to toggle starred flag for entry #%d: %v`, entryID, err)
  422. }
  423. if count == 0 {
  424. return errors.New(`store: nothing has been updated`)
  425. }
  426. return nil
  427. }
  428. // FlushHistory deletes all read entries (non-starred, non-shared) and records tombstones to prevent re-ingestion.
  429. func (s *Storage) FlushHistory(userID int64) error {
  430. query := `
  431. WITH deleted AS (
  432. DELETE FROM entries
  433. WHERE user_id=$1 AND status=$2 AND starred is false AND share_code=''
  434. RETURNING feed_id, hash
  435. )
  436. INSERT INTO entry_tombstones (feed_id, hash)
  437. SELECT feed_id, hash FROM deleted WHERE hash <> ''
  438. ON CONFLICT (feed_id, hash) DO NOTHING
  439. `
  440. if _, err := s.db.Exec(query, userID, model.EntryStatusRead); err != nil {
  441. return fmt.Errorf(`store: unable to flush history: %v`, err)
  442. }
  443. return nil
  444. }
  445. // MarkAllAsRead updates all user entries to the read status.
  446. func (s *Storage) MarkAllAsRead(userID int64) error {
  447. query := `UPDATE entries SET status=$1, changed_at=now() WHERE user_id=$2 AND status=$3`
  448. result, err := s.db.Exec(query, model.EntryStatusRead, userID, model.EntryStatusUnread)
  449. if err != nil {
  450. return fmt.Errorf(`store: unable to mark all entries as read: %v`, err)
  451. }
  452. count, _ := result.RowsAffected()
  453. slog.Debug("Marked all entries as read",
  454. slog.Int64("user_id", userID),
  455. slog.Int64("nb_entries", count),
  456. )
  457. return nil
  458. }
  459. // MarkAllAsReadBeforeDate updates all user entries to the read status before the given date.
  460. func (s *Storage) MarkAllAsReadBeforeDate(userID int64, before time.Time) error {
  461. query := `
  462. UPDATE
  463. entries
  464. SET
  465. status=$1,
  466. changed_at=now()
  467. WHERE
  468. user_id=$2 AND status=$3 AND published_at < $4
  469. `
  470. result, err := s.db.Exec(query, model.EntryStatusRead, userID, model.EntryStatusUnread, before)
  471. if err != nil {
  472. return fmt.Errorf(`store: unable to mark all entries as read before %s: %v`, before.Format(time.RFC3339), err)
  473. }
  474. count, _ := result.RowsAffected()
  475. slog.Debug("Marked all entries as read before date",
  476. slog.Int64("user_id", userID),
  477. slog.Int64("nb_entries", count),
  478. slog.String("before", before.Format(time.RFC3339)),
  479. )
  480. return nil
  481. }
  482. // MarkGloballyVisibleFeedsAsRead marks as read the unread entries that are
  483. // visible in the global unread view, i.e. those belonging to a feed and a
  484. // category that are both not hidden globally.
  485. func (s *Storage) MarkGloballyVisibleFeedsAsRead(userID int64) error {
  486. query := `
  487. UPDATE
  488. entries
  489. SET
  490. status=$1,
  491. changed_at=now()
  492. FROM
  493. feeds
  494. JOIN categories ON (categories.id = feeds.category_id)
  495. WHERE
  496. entries.feed_id = feeds.id
  497. AND entries.user_id=$2
  498. AND entries.status=$3
  499. AND feeds.hide_globally IS FALSE
  500. AND categories.hide_globally IS FALSE
  501. `
  502. result, err := s.db.Exec(query, model.EntryStatusRead, userID, model.EntryStatusUnread)
  503. if err != nil {
  504. return fmt.Errorf(`store: unable to mark globally visible feeds as read: %v`, err)
  505. }
  506. count, _ := result.RowsAffected()
  507. slog.Debug("Marked globally visible feed entries as read",
  508. slog.Int64("user_id", userID),
  509. slog.Int64("nb_entries", count),
  510. )
  511. return nil
  512. }
  513. // MarkFeedAsRead updates all feed entries to the read status.
  514. func (s *Storage) MarkFeedAsRead(userID, feedID int64, before time.Time) error {
  515. query := `
  516. UPDATE
  517. entries
  518. SET
  519. status=$1,
  520. changed_at=now()
  521. WHERE
  522. user_id=$2 AND feed_id=$3 AND status=$4 AND published_at < $5
  523. `
  524. result, err := s.db.Exec(query, model.EntryStatusRead, userID, feedID, model.EntryStatusUnread, before)
  525. if err != nil {
  526. return fmt.Errorf(`store: unable to mark feed entries as read: %v`, err)
  527. }
  528. count, _ := result.RowsAffected()
  529. slog.Debug("Marked feed entries as read",
  530. slog.Int64("user_id", userID),
  531. slog.Int64("feed_id", feedID),
  532. slog.Int64("nb_entries", count),
  533. slog.String("before", before.Format(time.RFC3339)),
  534. )
  535. return nil
  536. }
  537. // MarkCategoryAsRead updates all category entries to the read status.
  538. func (s *Storage) MarkCategoryAsRead(userID, categoryID int64, before time.Time) error {
  539. query := `
  540. UPDATE
  541. entries
  542. SET
  543. status=$1,
  544. changed_at=now()
  545. FROM
  546. feeds
  547. WHERE
  548. feed_id=feeds.id
  549. AND
  550. feeds.user_id=$2
  551. AND
  552. status=$3
  553. AND
  554. published_at < $4
  555. AND
  556. feeds.category_id=$5
  557. `
  558. result, err := s.db.Exec(query, model.EntryStatusRead, userID, model.EntryStatusUnread, before, categoryID)
  559. if err != nil {
  560. return fmt.Errorf(`store: unable to mark category entries as read: %v`, err)
  561. }
  562. count, _ := result.RowsAffected()
  563. slog.Debug("Marked category entries as read",
  564. slog.Int64("user_id", userID),
  565. slog.Int64("category_id", categoryID),
  566. slog.Int64("nb_entries", count),
  567. slog.String("before", before.Format(time.RFC3339)),
  568. )
  569. return nil
  570. }
  571. // EntryShareCode returns the entry share code, generating one if needed, and whether it was created.
  572. func (s *Storage) EntryShareCode(userID int64, entryID int64) (shareCode string, created bool, err error) {
  573. // A single statement keeps concurrent calls from overwriting each other's code.
  574. query := `
  575. UPDATE
  576. entries
  577. SET
  578. share_code = CASE WHEN share_code = '' THEN $1 ELSE share_code END,
  579. changed_at = CASE WHEN share_code = '' THEN now() ELSE changed_at END
  580. WHERE
  581. user_id=$2 AND
  582. id=$3
  583. RETURNING
  584. share_code
  585. `
  586. newShareCode := crypto.GenerateRandomStringHex(20)
  587. err = s.db.QueryRow(query, newShareCode, userID, entryID).Scan(&shareCode)
  588. if errors.Is(err, sql.ErrNoRows) {
  589. err = ErrEntryNotFound
  590. return
  591. } else if err != nil {
  592. err = fmt.Errorf(`store: unable to set share code for entry #%d: %v`, entryID, err)
  593. return
  594. }
  595. created = shareCode == newShareCode
  596. return
  597. }
  598. // UnshareEntry removes the share code for the given entry.
  599. func (s *Storage) UnshareEntry(userID int64, entryID int64) (err error) {
  600. query := `
  601. UPDATE
  602. entries
  603. SET
  604. share_code = '',
  605. changed_at = CASE WHEN share_code <> '' THEN now() ELSE changed_at END
  606. WHERE
  607. user_id=$1 AND
  608. id=$2
  609. `
  610. result, err := s.db.Exec(query, userID, entryID)
  611. if err != nil {
  612. err = fmt.Errorf(`store: unable to remove share code for entry #%d: %v`, entryID, err)
  613. return
  614. }
  615. count, err := result.RowsAffected()
  616. if err != nil {
  617. err = fmt.Errorf(`store: unable to remove share code for entry #%d: %v`, entryID, err)
  618. return
  619. }
  620. if count == 0 {
  621. err = ErrEntryNotFound
  622. return
  623. }
  624. return
  625. }
  626. func truncateTitleAndContentForTSVectorField(title, content string) (string, string) {
  627. // The length of a tsvector (lexemes + positions) must be less than 1 megabyte.
  628. // We don't need to index the entire content, and we need to keep a buffer for the positions.
  629. return truncateStringForTSVectorField(title, 200000), truncateStringForTSVectorField(content, 500000)
  630. }
  631. // truncateStringForTSVectorField truncates a string and don't break UTF-8 characters.
  632. func truncateStringForTSVectorField(s string, maxSize int) string {
  633. if len(s) < maxSize {
  634. return s
  635. }
  636. // Truncate to fit under the limit, ensuring we don't break UTF-8 characters
  637. truncated := s[:maxSize-1]
  638. // Walk backwards to find the last complete UTF-8 character
  639. for i := len(truncated) - 1; i >= 0; i-- {
  640. if (truncated[i] & 0x80) == 0 {
  641. // ASCII character, we can stop here
  642. return truncated[:i+1]
  643. }
  644. if (truncated[i] & 0xC0) == 0xC0 {
  645. // Start of a multi-byte UTF-8 character
  646. return truncated[:i]
  647. }
  648. }
  649. // Fallback: return empty string if we can't find a valid UTF-8 boundary
  650. return ""
  651. }