memo.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. package mysql
  2. import (
  3. "context"
  4. "fmt"
  5. "strings"
  6. "github.com/pkg/errors"
  7. "google.golang.org/protobuf/encoding/protojson"
  8. storepb "github.com/usememos/memos/proto/gen/store"
  9. "github.com/usememos/memos/store"
  10. )
  11. func (d *DB) CreateMemo(ctx context.Context, create *store.Memo) (*store.Memo, error) {
  12. fields := []string{"`uid`", "`creator_id`", "`content`", "`visibility`", "`tags`", "`payload`"}
  13. placeholder := []string{"?", "?", "?", "?", "?", "?"}
  14. payload := "{}"
  15. if create.Payload != nil {
  16. payloadBytes, err := protojson.Marshal(create.Payload)
  17. if err != nil {
  18. return nil, err
  19. }
  20. payload = string(payloadBytes)
  21. }
  22. args := []any{create.UID, create.CreatorID, create.Content, create.Visibility, "[]", payload}
  23. stmt := "INSERT INTO `memo` (" + strings.Join(fields, ", ") + ") VALUES (" + strings.Join(placeholder, ", ") + ")"
  24. result, err := d.db.ExecContext(ctx, stmt, args...)
  25. if err != nil {
  26. return nil, err
  27. }
  28. rawID, err := result.LastInsertId()
  29. if err != nil {
  30. return nil, err
  31. }
  32. id := int32(rawID)
  33. memo, err := d.GetMemo(ctx, &store.FindMemo{ID: &id})
  34. if err != nil {
  35. return nil, err
  36. }
  37. if memo == nil {
  38. return nil, errors.Errorf("failed to create memo")
  39. }
  40. return memo, nil
  41. }
  42. func (d *DB) ListMemos(ctx context.Context, find *store.FindMemo) ([]*store.Memo, error) {
  43. where, having, args := []string{"1 = 1"}, []string{"1 = 1"}, []any{}
  44. if v := find.ID; v != nil {
  45. where, args = append(where, "`memo`.`id` = ?"), append(args, *v)
  46. }
  47. if v := find.UID; v != nil {
  48. where, args = append(where, "`memo`.`uid` = ?"), append(args, *v)
  49. }
  50. if v := find.CreatorID; v != nil {
  51. where, args = append(where, "`memo`.`creator_id` = ?"), append(args, *v)
  52. }
  53. if v := find.RowStatus; v != nil {
  54. where, args = append(where, "`memo`.`row_status` = ?"), append(args, *v)
  55. }
  56. if v := find.CreatedTsBefore; v != nil {
  57. where, args = append(where, "UNIX_TIMESTAMP(`memo`.`created_ts`) < ?"), append(args, *v)
  58. }
  59. if v := find.CreatedTsAfter; v != nil {
  60. where, args = append(where, "UNIX_TIMESTAMP(`memo`.`created_ts`) > ?"), append(args, *v)
  61. }
  62. if v := find.UpdatedTsBefore; v != nil {
  63. where, args = append(where, "UNIX_TIMESTAMP(`memo`.`updated_ts`) < ?"), append(args, *v)
  64. }
  65. if v := find.UpdatedTsAfter; v != nil {
  66. where, args = append(where, "UNIX_TIMESTAMP(`memo`.`updated_ts`) > ?"), append(args, *v)
  67. }
  68. if v := find.ContentSearch; len(v) != 0 {
  69. for _, s := range v {
  70. where, args = append(where, "`memo`.`content` LIKE ?"), append(args, "%"+s+"%")
  71. }
  72. }
  73. if v := find.VisibilityList; len(v) != 0 {
  74. placeholder := []string{}
  75. for _, visibility := range v {
  76. placeholder = append(placeholder, "?")
  77. args = append(args, visibility.String())
  78. }
  79. where = append(where, fmt.Sprintf("`memo`.`visibility` in (%s)", strings.Join(placeholder, ",")))
  80. }
  81. if v := find.PayloadFind; v != nil {
  82. if v.Raw != nil {
  83. where, args = append(where, "`memo`.`payload` = ?"), append(args, *v.Raw)
  84. }
  85. if v.Tag != nil {
  86. where, args = append(where, "JSON_CONTAINS(JSON_EXTRACT(`memo`.`payload`, '$.property.tags'), ?)"), append(args, fmt.Sprintf(`["%s"]`, *v.Tag))
  87. }
  88. if v.HasLink {
  89. where = append(where, "JSON_EXTRACT(`memo`.`payload`, '$.property.hasLink') IS TRUE")
  90. }
  91. if v.HasTaskList {
  92. where = append(where, "JSON_EXTRACT(`memo`.`payload`, '$.property.hasTaskList') IS TRUE")
  93. }
  94. if v.HasCode {
  95. where = append(where, "JSON_EXTRACT(`memo`.`payload`, '$.property.hasCode') IS TRUE")
  96. }
  97. if v.HasIncompleteTasks {
  98. where = append(where, "JSON_EXTRACT(`memo`.`payload`, '$.property.hasIncompleteTasks') IS TRUE")
  99. }
  100. }
  101. if find.ExcludeComments {
  102. having = append(having, "`parent_id` IS NULL")
  103. }
  104. orders := []string{}
  105. if find.OrderByPinned {
  106. orders = append(orders, "`pinned` DESC")
  107. }
  108. if find.OrderByUpdatedTs {
  109. orders = append(orders, "`updated_ts` DESC")
  110. } else {
  111. orders = append(orders, "`created_ts` DESC")
  112. }
  113. orders = append(orders, "`id` DESC")
  114. if find.Random {
  115. orders = append(orders, "RAND()")
  116. }
  117. fields := []string{
  118. "`memo`.`id` AS `id`",
  119. "`memo`.`uid` AS `uid`",
  120. "`memo`.`creator_id` AS `creator_id`",
  121. "UNIX_TIMESTAMP(`memo`.`created_ts`) AS `created_ts`",
  122. "UNIX_TIMESTAMP(`memo`.`updated_ts`) AS `updated_ts`",
  123. "`memo`.`row_status` AS `row_status`",
  124. "`memo`.`visibility` AS `visibility`",
  125. "`memo`.`payload` AS `payload`",
  126. "IFNULL(`memo_organizer`.`pinned`, 0) AS `pinned`",
  127. "`memo_relation`.`related_memo_id` AS `parent_id`",
  128. }
  129. if !find.ExcludeContent {
  130. fields = append(fields, "`memo`.`content` AS `content`")
  131. }
  132. query := "SELECT " + strings.Join(fields, ", ") + " FROM `memo` LEFT JOIN `memo_organizer` ON `memo`.`id` = `memo_organizer`.`memo_id` AND `memo`.`creator_id` = `memo_organizer`.`user_id` LEFT JOIN `memo_relation` ON `memo`.`id` = `memo_relation`.`memo_id` AND `memo_relation`.`type` = \"COMMENT\" WHERE " + strings.Join(where, " AND ") + " HAVING " + strings.Join(having, " AND ") + " ORDER BY " + strings.Join(orders, ", ")
  133. if find.Limit != nil {
  134. query = fmt.Sprintf("%s LIMIT %d", query, *find.Limit)
  135. if find.Offset != nil {
  136. query = fmt.Sprintf("%s OFFSET %d", query, *find.Offset)
  137. }
  138. }
  139. rows, err := d.db.QueryContext(ctx, query, args...)
  140. if err != nil {
  141. return nil, err
  142. }
  143. defer rows.Close()
  144. list := make([]*store.Memo, 0)
  145. for rows.Next() {
  146. var memo store.Memo
  147. var payloadBytes []byte
  148. dests := []any{
  149. &memo.ID,
  150. &memo.UID,
  151. &memo.CreatorID,
  152. &memo.CreatedTs,
  153. &memo.UpdatedTs,
  154. &memo.RowStatus,
  155. &memo.Visibility,
  156. &payloadBytes,
  157. &memo.Pinned,
  158. &memo.ParentID,
  159. }
  160. if !find.ExcludeContent {
  161. dests = append(dests, &memo.Content)
  162. }
  163. if err := rows.Scan(dests...); err != nil {
  164. return nil, err
  165. }
  166. payload := &storepb.MemoPayload{}
  167. if err := protojsonUnmarshaler.Unmarshal(payloadBytes, payload); err != nil {
  168. return nil, errors.Wrap(err, "failed to unmarshal payload")
  169. }
  170. memo.Payload = payload
  171. list = append(list, &memo)
  172. }
  173. if err := rows.Err(); err != nil {
  174. return nil, err
  175. }
  176. return list, nil
  177. }
  178. func (d *DB) GetMemo(ctx context.Context, find *store.FindMemo) (*store.Memo, error) {
  179. list, err := d.ListMemos(ctx, find)
  180. if err != nil {
  181. return nil, err
  182. }
  183. if len(list) == 0 {
  184. return nil, nil
  185. }
  186. memo := list[0]
  187. return memo, nil
  188. }
  189. func (d *DB) UpdateMemo(ctx context.Context, update *store.UpdateMemo) error {
  190. set, args := []string{}, []any{}
  191. if v := update.UID; v != nil {
  192. set, args = append(set, "`uid` = ?"), append(args, *v)
  193. }
  194. if v := update.CreatedTs; v != nil {
  195. set, args = append(set, "`created_ts` = FROM_UNIXTIME(?)"), append(args, *v)
  196. }
  197. if v := update.UpdatedTs; v != nil {
  198. set, args = append(set, "`updated_ts` = FROM_UNIXTIME(?)"), append(args, *v)
  199. }
  200. if v := update.RowStatus; v != nil {
  201. set, args = append(set, "`row_status` = ?"), append(args, *v)
  202. }
  203. if v := update.Content; v != nil {
  204. set, args = append(set, "`content` = ?"), append(args, *v)
  205. }
  206. if v := update.Visibility; v != nil {
  207. set, args = append(set, "`visibility` = ?"), append(args, *v)
  208. }
  209. if v := update.Payload; v != nil {
  210. payloadBytes, err := protojson.Marshal(v)
  211. if err != nil {
  212. return err
  213. }
  214. set, args = append(set, "`payload` = ?"), append(args, string(payloadBytes))
  215. }
  216. args = append(args, update.ID)
  217. stmt := "UPDATE `memo` SET " + strings.Join(set, ", ") + " WHERE `id` = ?"
  218. if _, err := d.db.ExecContext(ctx, stmt, args...); err != nil {
  219. return err
  220. }
  221. return nil
  222. }
  223. func (d *DB) DeleteMemo(ctx context.Context, delete *store.DeleteMemo) error {
  224. where, args := []string{"`id` = ?"}, []any{delete.ID}
  225. stmt := "DELETE FROM `memo` WHERE " + strings.Join(where, " AND ")
  226. result, err := d.db.ExecContext(ctx, stmt, args...)
  227. if err != nil {
  228. return err
  229. }
  230. if _, err := result.RowsAffected(); err != nil {
  231. return err
  232. }
  233. return nil
  234. }