memo.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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 len(v.TagSearch) != 0 {
  86. for _, tag := range v.TagSearch {
  87. where, args = append(where, "(JSON_CONTAINS(JSON_EXTRACT(`memo`.`payload`, '$.property.tags'), ?) OR JSON_CONTAINS(JSON_EXTRACT(`memo`.`payload`, '$.property.tags'), ?))"), append(args, fmt.Sprintf(`"%s"`, tag), fmt.Sprintf(`"%s/"`, tag))
  88. }
  89. }
  90. if v.HasLink {
  91. where = append(where, "JSON_EXTRACT(`memo`.`payload`, '$.property.hasLink') IS TRUE")
  92. }
  93. if v.HasTaskList {
  94. where = append(where, "JSON_EXTRACT(`memo`.`payload`, '$.property.hasTaskList') IS TRUE")
  95. }
  96. if v.HasCode {
  97. where = append(where, "JSON_EXTRACT(`memo`.`payload`, '$.property.hasCode') IS TRUE")
  98. }
  99. if v.HasIncompleteTasks {
  100. where = append(where, "JSON_EXTRACT(`memo`.`payload`, '$.property.hasIncompleteTasks') IS TRUE")
  101. }
  102. }
  103. if find.ExcludeComments {
  104. having = append(having, "`parent_id` IS NULL")
  105. }
  106. orders := []string{}
  107. if find.OrderByPinned {
  108. orders = append(orders, "`pinned` DESC")
  109. }
  110. order := "DESC"
  111. if find.OrderByTimeAsc {
  112. order = "ASC"
  113. }
  114. if find.OrderByUpdatedTs {
  115. orders = append(orders, "`updated_ts` "+order)
  116. } else {
  117. orders = append(orders, "`created_ts` "+order)
  118. }
  119. orders = append(orders, "`id` "+order)
  120. if find.Random {
  121. orders = append(orders, "RAND()")
  122. }
  123. fields := []string{
  124. "`memo`.`id` AS `id`",
  125. "`memo`.`uid` AS `uid`",
  126. "`memo`.`creator_id` AS `creator_id`",
  127. "UNIX_TIMESTAMP(`memo`.`created_ts`) AS `created_ts`",
  128. "UNIX_TIMESTAMP(`memo`.`updated_ts`) AS `updated_ts`",
  129. "`memo`.`row_status` AS `row_status`",
  130. "`memo`.`visibility` AS `visibility`",
  131. "`memo`.`payload` AS `payload`",
  132. "IFNULL(`memo_organizer`.`pinned`, 0) AS `pinned`",
  133. "`memo_relation`.`related_memo_id` AS `parent_id`",
  134. }
  135. if !find.ExcludeContent {
  136. fields = append(fields, "`memo`.`content` AS `content`")
  137. }
  138. query := "SELECT " + strings.Join(fields, ", ") + " FROM `memo`" + " " +
  139. "LEFT JOIN `memo_organizer` ON `memo`.`id` = `memo_organizer`.`memo_id` AND `memo`.`creator_id` = `memo_organizer`.`user_id`" + " " +
  140. "LEFT JOIN `memo_relation` ON `memo`.`id` = `memo_relation`.`memo_id` AND `memo_relation`.`type` = 'COMMENT'" + " " +
  141. "WHERE " + strings.Join(where, " AND ") + " " +
  142. "HAVING " + strings.Join(having, " AND ") + " " +
  143. "ORDER BY " + strings.Join(orders, ", ")
  144. if find.Limit != nil {
  145. query = fmt.Sprintf("%s LIMIT %d", query, *find.Limit)
  146. if find.Offset != nil {
  147. query = fmt.Sprintf("%s OFFSET %d", query, *find.Offset)
  148. }
  149. }
  150. rows, err := d.db.QueryContext(ctx, query, args...)
  151. if err != nil {
  152. return nil, err
  153. }
  154. defer rows.Close()
  155. list := make([]*store.Memo, 0)
  156. for rows.Next() {
  157. var memo store.Memo
  158. var payloadBytes []byte
  159. dests := []any{
  160. &memo.ID,
  161. &memo.UID,
  162. &memo.CreatorID,
  163. &memo.CreatedTs,
  164. &memo.UpdatedTs,
  165. &memo.RowStatus,
  166. &memo.Visibility,
  167. &payloadBytes,
  168. &memo.Pinned,
  169. &memo.ParentID,
  170. }
  171. if !find.ExcludeContent {
  172. dests = append(dests, &memo.Content)
  173. }
  174. if err := rows.Scan(dests...); err != nil {
  175. return nil, err
  176. }
  177. payload := &storepb.MemoPayload{}
  178. if err := protojsonUnmarshaler.Unmarshal(payloadBytes, payload); err != nil {
  179. return nil, errors.Wrap(err, "failed to unmarshal payload")
  180. }
  181. memo.Payload = payload
  182. list = append(list, &memo)
  183. }
  184. if err := rows.Err(); err != nil {
  185. return nil, err
  186. }
  187. return list, nil
  188. }
  189. func (d *DB) GetMemo(ctx context.Context, find *store.FindMemo) (*store.Memo, error) {
  190. list, err := d.ListMemos(ctx, find)
  191. if err != nil {
  192. return nil, err
  193. }
  194. if len(list) == 0 {
  195. return nil, nil
  196. }
  197. memo := list[0]
  198. return memo, nil
  199. }
  200. func (d *DB) UpdateMemo(ctx context.Context, update *store.UpdateMemo) error {
  201. set, args := []string{}, []any{}
  202. if v := update.UID; v != nil {
  203. set, args = append(set, "`uid` = ?"), append(args, *v)
  204. }
  205. if v := update.CreatedTs; v != nil {
  206. set, args = append(set, "`created_ts` = FROM_UNIXTIME(?)"), append(args, *v)
  207. }
  208. if v := update.UpdatedTs; v != nil {
  209. set, args = append(set, "`updated_ts` = FROM_UNIXTIME(?)"), append(args, *v)
  210. }
  211. if v := update.RowStatus; v != nil {
  212. set, args = append(set, "`row_status` = ?"), append(args, *v)
  213. }
  214. if v := update.Content; v != nil {
  215. set, args = append(set, "`content` = ?"), append(args, *v)
  216. }
  217. if v := update.Visibility; v != nil {
  218. set, args = append(set, "`visibility` = ?"), append(args, *v)
  219. }
  220. if v := update.Payload; v != nil {
  221. payloadBytes, err := protojson.Marshal(v)
  222. if err != nil {
  223. return err
  224. }
  225. set, args = append(set, "`payload` = ?"), append(args, string(payloadBytes))
  226. }
  227. args = append(args, update.ID)
  228. stmt := "UPDATE `memo` SET " + strings.Join(set, ", ") + " WHERE `id` = ?"
  229. if _, err := d.db.ExecContext(ctx, stmt, args...); err != nil {
  230. return err
  231. }
  232. return nil
  233. }
  234. func (d *DB) DeleteMemo(ctx context.Context, delete *store.DeleteMemo) error {
  235. where, args := []string{"`id` = ?"}, []any{delete.ID}
  236. stmt := "DELETE FROM `memo` WHERE " + strings.Join(where, " AND ")
  237. result, err := d.db.ExecContext(ctx, stmt, args...)
  238. if err != nil {
  239. return err
  240. }
  241. if _, err := result.RowsAffected(); err != nil {
  242. return err
  243. }
  244. return nil
  245. }