memo.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. package mysql
  2. import (
  3. "context"
  4. "database/sql"
  5. "fmt"
  6. "strings"
  7. "github.com/pkg/errors"
  8. "github.com/usememos/memos/common/util"
  9. "github.com/usememos/memos/store"
  10. )
  11. func (d *DB) CreateMemo(ctx context.Context, create *store.Memo) (*store.Memo, error) {
  12. fields := []string{"`creator_id`", "`content`", "`visibility`"}
  13. placeholder := []string{"?", "?", "?"}
  14. args := []any{create.CreatorID, create.Content, create.Visibility}
  15. if create.ID != 0 {
  16. fields = append(fields, "`id`")
  17. placeholder = append(placeholder, "?")
  18. args = append(args, create.ID)
  19. }
  20. if create.CreatedTs != 0 {
  21. fields = append(fields, "`created_ts`")
  22. placeholder = append(placeholder, "FROM_UNIXTIME(?)")
  23. args = append(args, create.CreatedTs)
  24. }
  25. if create.UpdatedTs != 0 {
  26. fields = append(fields, "`updated_ts`")
  27. placeholder = append(placeholder, "FROM_UNIXTIME(?)")
  28. args = append(args, create.UpdatedTs)
  29. }
  30. if create.RowStatus != "" {
  31. fields = append(fields, "`row_status`")
  32. placeholder = append(placeholder, "?")
  33. args = append(args, create.RowStatus)
  34. }
  35. stmt := "INSERT INTO memo (" + strings.Join(fields, ", ") + ") VALUES (" + strings.Join(placeholder, ", ") + ")"
  36. result, err := d.db.ExecContext(ctx, stmt, args...)
  37. if err != nil {
  38. return nil, err
  39. }
  40. rawID, err := result.LastInsertId()
  41. if err != nil {
  42. return nil, err
  43. }
  44. id := int32(rawID)
  45. memo, err := d.GetMemo(ctx, &store.FindMemo{ID: &id})
  46. if err != nil {
  47. return nil, err
  48. }
  49. if memo == nil {
  50. return nil, errors.Errorf("failed to create memo")
  51. }
  52. return memo, nil
  53. }
  54. func (d *DB) ListMemos(ctx context.Context, find *store.FindMemo) ([]*store.Memo, error) {
  55. where, args := []string{"1 = 1"}, []any{}
  56. if v := find.ID; v != nil {
  57. where, args = append(where, "`memo`.`id` = ?"), append(args, *v)
  58. }
  59. if v := find.CreatorID; v != nil {
  60. where, args = append(where, "`memo`.`creator_id` = ?"), append(args, *v)
  61. }
  62. if v := find.RowStatus; v != nil {
  63. where, args = append(where, "`memo`.`row_status` = ?"), append(args, *v)
  64. }
  65. if v := find.CreatedTsBefore; v != nil {
  66. where, args = append(where, "UNIX_TIMESTAMP(`memo`.`created_ts`) < ?"), append(args, *v)
  67. }
  68. if v := find.CreatedTsAfter; v != nil {
  69. where, args = append(where, "UNIX_TIMESTAMP(`memo`.`created_ts`) > ?"), append(args, *v)
  70. }
  71. if v := find.Pinned; v != nil {
  72. where = append(where, "`memo_organizer`.`pinned` = 1")
  73. }
  74. if v := find.ContentSearch; len(v) != 0 {
  75. for _, s := range v {
  76. where, args = append(where, "`memo`.`content` LIKE ?"), append(args, "%"+s+"%")
  77. }
  78. }
  79. if v := find.VisibilityList; len(v) != 0 {
  80. list := []string{}
  81. for _, visibility := range v {
  82. list = append(list, "?")
  83. args = append(args, visibility)
  84. }
  85. where = append(where, fmt.Sprintf("`memo`.`visibility` in (%s)", strings.Join(list, ",")))
  86. }
  87. orders := []string{"`pinned` DESC"}
  88. if find.OrderByUpdatedTs {
  89. orders = append(orders, "`updated_ts` DESC")
  90. } else {
  91. orders = append(orders, "`created_ts` DESC")
  92. }
  93. orders = append(orders, "`id` DESC")
  94. query := "SELECT `memo`.`id` AS `id`, `memo`.`creator_id` AS `creator_id`, UNIX_TIMESTAMP(`memo`.`created_ts`) AS `created_ts`, UNIX_TIMESTAMP(`memo`.`updated_ts`) AS `updated_ts`, `memo`.`row_status` AS `row_status`, `memo`.`content` AS `content`, `memo`.`visibility` AS `visibility`, MAX(CASE WHEN `memo_organizer`.`pinned` = 1 THEN 1 ELSE 0 END) AS `pinned`, GROUP_CONCAT(`resource`.`id`) AS `resource_id_list`, (SELECT GROUP_CONCAT(`memo_id`,':',`related_memo_id`,':',`type`) FROM `memo_relation` WHERE `memo_relation`.`memo_id` = `memo`.`id` OR `memo_relation`.`related_memo_id` = `memo`.`id` ) AS `relation_list` FROM `memo` LEFT JOIN `memo_organizer` ON `memo`.`id` = `memo_organizer`.`memo_id` LEFT JOIN `resource` ON `memo`.`id` = `resource`.`memo_id` WHERE " + strings.Join(where, " AND ") + " GROUP BY `memo`.`id` ORDER BY " + strings.Join(orders, ", ")
  95. if find.Limit != nil {
  96. query = fmt.Sprintf("%s LIMIT %d", query, *find.Limit)
  97. if find.Offset != nil {
  98. query = fmt.Sprintf("%s OFFSET %d", query, *find.Offset)
  99. }
  100. }
  101. rows, err := d.db.QueryContext(ctx, query, args...)
  102. if err != nil {
  103. return nil, err
  104. }
  105. defer rows.Close()
  106. list := make([]*store.Memo, 0)
  107. for rows.Next() {
  108. var memo store.Memo
  109. var memoResourceIDList sql.NullString
  110. var memoRelationList sql.NullString
  111. if err := rows.Scan(
  112. &memo.ID,
  113. &memo.CreatorID,
  114. &memo.CreatedTs,
  115. &memo.UpdatedTs,
  116. &memo.RowStatus,
  117. &memo.Content,
  118. &memo.Visibility,
  119. &memo.Pinned,
  120. &memoResourceIDList,
  121. &memoRelationList,
  122. ); err != nil {
  123. return nil, err
  124. }
  125. if memoResourceIDList.Valid {
  126. idStringList := strings.Split(memoResourceIDList.String, ",")
  127. memo.ResourceIDList = make([]int32, 0, len(idStringList))
  128. for _, idString := range idStringList {
  129. id, err := util.ConvertStringToInt32(idString)
  130. if err != nil {
  131. return nil, err
  132. }
  133. memo.ResourceIDList = append(memo.ResourceIDList, id)
  134. }
  135. }
  136. if memoRelationList.Valid {
  137. memo.RelationList = make([]*store.MemoRelation, 0)
  138. relatedMemoTypeList := strings.Split(memoRelationList.String, ",")
  139. for _, relatedMemoType := range relatedMemoTypeList {
  140. relatedMemoTypeList := strings.Split(relatedMemoType, ":")
  141. if len(relatedMemoTypeList) != 3 {
  142. return nil, errors.Errorf("invalid relation format")
  143. }
  144. memoID, err := util.ConvertStringToInt32(relatedMemoTypeList[0])
  145. if err != nil {
  146. return nil, err
  147. }
  148. relatedMemoID, err := util.ConvertStringToInt32(relatedMemoTypeList[1])
  149. if err != nil {
  150. return nil, err
  151. }
  152. relationType := store.MemoRelationType(relatedMemoTypeList[2])
  153. memo.RelationList = append(memo.RelationList, &store.MemoRelation{
  154. MemoID: memoID,
  155. RelatedMemoID: relatedMemoID,
  156. Type: relationType,
  157. })
  158. // Set the first parent ID if relation type is comment.
  159. if memo.ParentID == nil && memoID == memo.ID && relationType == store.MemoRelationComment {
  160. memo.ParentID = &relatedMemoID
  161. }
  162. }
  163. }
  164. list = append(list, &memo)
  165. }
  166. if err := rows.Err(); err != nil {
  167. return nil, err
  168. }
  169. return list, nil
  170. }
  171. func (d *DB) GetMemo(ctx context.Context, find *store.FindMemo) (*store.Memo, error) {
  172. list, err := d.ListMemos(ctx, find)
  173. if err != nil {
  174. return nil, err
  175. }
  176. if len(list) == 0 {
  177. return nil, nil
  178. }
  179. memo := list[0]
  180. return memo, nil
  181. }
  182. func (d *DB) UpdateMemo(ctx context.Context, update *store.UpdateMemo) error {
  183. set, args := []string{}, []any{}
  184. if v := update.CreatedTs; v != nil {
  185. set, args = append(set, "`created_ts` = FROM_UNIXTIME(?)"), append(args, *v)
  186. }
  187. if v := update.UpdatedTs; v != nil {
  188. set, args = append(set, "`updated_ts` = FROM_UNIXTIME(?)"), append(args, *v)
  189. }
  190. if v := update.RowStatus; v != nil {
  191. set, args = append(set, "`row_status` = ?"), append(args, *v)
  192. }
  193. if v := update.Content; v != nil {
  194. set, args = append(set, "`content` = ?"), append(args, *v)
  195. }
  196. if v := update.Visibility; v != nil {
  197. set, args = append(set, "`visibility` = ?"), append(args, *v)
  198. }
  199. args = append(args, update.ID)
  200. stmt := "UPDATE `memo` SET " + strings.Join(set, ", ") + " WHERE `id` = ?"
  201. if _, err := d.db.ExecContext(ctx, stmt, args...); err != nil {
  202. return err
  203. }
  204. return nil
  205. }
  206. func (d *DB) DeleteMemo(ctx context.Context, delete *store.DeleteMemo) error {
  207. where, args := []string{"`id` = ?"}, []any{delete.ID}
  208. stmt := "DELETE FROM `memo` WHERE " + strings.Join(where, " AND ")
  209. result, err := d.db.ExecContext(ctx, stmt, args...)
  210. if err != nil {
  211. return err
  212. }
  213. if _, err := result.RowsAffected(); err != nil {
  214. return err
  215. }
  216. if err := d.Vacuum(ctx); err != nil {
  217. // Prevent linter warning.
  218. return err
  219. }
  220. return nil
  221. }
  222. func (d *DB) FindMemosVisibilityList(ctx context.Context, memoIDs []int32) ([]store.Visibility, error) {
  223. args := make([]any, 0, len(memoIDs))
  224. list := make([]string, 0, len(memoIDs))
  225. for _, memoID := range memoIDs {
  226. args = append(args, memoID)
  227. list = append(list, "?")
  228. }
  229. where := fmt.Sprintf("`id` in (%s)", strings.Join(list, ","))
  230. query := "SELECT DISTINCT(`visibility`) FROM `memo` WHERE " + where
  231. rows, err := d.db.QueryContext(ctx, query, args...)
  232. if err != nil {
  233. return nil, err
  234. }
  235. defer rows.Close()
  236. visibilityList := make([]store.Visibility, 0)
  237. for rows.Next() {
  238. var visibility store.Visibility
  239. if err := rows.Scan(&visibility); err != nil {
  240. return nil, err
  241. }
  242. visibilityList = append(visibilityList, visibility)
  243. }
  244. if err := rows.Err(); err != nil {
  245. return nil, err
  246. }
  247. return visibilityList, nil
  248. }
  249. func vacuumMemo(ctx context.Context, tx *sql.Tx) error {
  250. stmt := "DELETE FROM `memo` WHERE `creator_id` NOT IN (SELECT `id` FROM `user`)"
  251. _, err := tx.ExecContext(ctx, stmt)
  252. if err != nil {
  253. return err
  254. }
  255. return nil
  256. }