memo.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. package store
  2. import (
  3. "context"
  4. "database/sql"
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "github.com/usememos/memos/common"
  10. )
  11. // Visibility is the type of a visibility.
  12. type Visibility string
  13. const (
  14. // Public is the PUBLIC visibility.
  15. Public Visibility = "PUBLIC"
  16. // Protected is the PROTECTED visibility.
  17. Protected Visibility = "PROTECTED"
  18. // Private is the PRIVATE visibility.
  19. Private Visibility = "PRIVATE"
  20. )
  21. func (v Visibility) String() string {
  22. switch v {
  23. case Public:
  24. return "PUBLIC"
  25. case Protected:
  26. return "PROTECTED"
  27. case Private:
  28. return "PRIVATE"
  29. }
  30. return "PRIVATE"
  31. }
  32. type MemoMessage struct {
  33. ID int
  34. // Standard fields
  35. RowStatus RowStatus
  36. CreatorID int
  37. CreatedTs int64
  38. UpdatedTs int64
  39. // Domain specific fields
  40. Content string
  41. Visibility Visibility
  42. // Composed fields
  43. Pinned bool
  44. ResourceIDList []int
  45. RelationList []*MemoRelationMessage
  46. }
  47. type FindMemoMessage struct {
  48. ID *int
  49. // Standard fields
  50. RowStatus *RowStatus
  51. CreatorID *int
  52. // Domain specific fields
  53. Pinned *bool
  54. ContentSearch []string
  55. VisibilityList []Visibility
  56. // Pagination
  57. Limit *int
  58. Offset *int
  59. }
  60. type UpdateMemoMessage struct {
  61. ID int
  62. CreatedTs *int64
  63. UpdatedTs *int64
  64. RowStatus *RowStatus
  65. Content *string
  66. Visibility *Visibility
  67. }
  68. type DeleteMemoMessage struct {
  69. ID int
  70. }
  71. func (s *Store) CreateMemo(ctx context.Context, create *MemoMessage) (*MemoMessage, error) {
  72. tx, err := s.db.BeginTx(ctx, nil)
  73. if err != nil {
  74. return nil, FormatError(err)
  75. }
  76. defer tx.Rollback()
  77. if create.CreatedTs == 0 {
  78. create.CreatedTs = time.Now().Unix()
  79. }
  80. query := `
  81. INSERT INTO memo (
  82. creator_id,
  83. created_ts,
  84. content,
  85. visibility
  86. )
  87. VALUES (?, ?, ?, ?)
  88. RETURNING id, created_ts, updated_ts, row_status
  89. `
  90. if err := tx.QueryRowContext(
  91. ctx,
  92. query,
  93. create.CreatorID,
  94. create.CreatedTs,
  95. create.Content,
  96. create.Visibility,
  97. ).Scan(
  98. &create.ID,
  99. &create.CreatedTs,
  100. &create.UpdatedTs,
  101. &create.RowStatus,
  102. ); err != nil {
  103. return nil, FormatError(err)
  104. }
  105. if err := tx.Commit(); err != nil {
  106. return nil, FormatError(err)
  107. }
  108. memoMessage := create
  109. return memoMessage, nil
  110. }
  111. func (s *Store) ListMemos(ctx context.Context, find *FindMemoMessage) ([]*MemoMessage, error) {
  112. tx, err := s.db.BeginTx(ctx, nil)
  113. if err != nil {
  114. return nil, FormatError(err)
  115. }
  116. defer tx.Rollback()
  117. list, err := listMemos(ctx, tx, find)
  118. if err != nil {
  119. return nil, err
  120. }
  121. return list, nil
  122. }
  123. func (s *Store) GetMemo(ctx context.Context, find *FindMemoMessage) (*MemoMessage, error) {
  124. tx, err := s.db.BeginTx(ctx, nil)
  125. if err != nil {
  126. return nil, FormatError(err)
  127. }
  128. defer tx.Rollback()
  129. list, err := listMemos(ctx, tx, find)
  130. if err != nil {
  131. return nil, err
  132. }
  133. if len(list) == 0 {
  134. return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("memo not found")}
  135. }
  136. memoMessage := list[0]
  137. return memoMessage, nil
  138. }
  139. func (s *Store) UpdateMemo(ctx context.Context, update *UpdateMemoMessage) error {
  140. tx, err := s.db.BeginTx(ctx, nil)
  141. if err != nil {
  142. return err
  143. }
  144. defer tx.Rollback()
  145. set, args := []string{}, []any{}
  146. if v := update.CreatedTs; v != nil {
  147. set, args = append(set, "created_ts = ?"), append(args, *v)
  148. }
  149. if v := update.UpdatedTs; v != nil {
  150. set, args = append(set, "updated_ts = ?"), append(args, *v)
  151. }
  152. if v := update.RowStatus; v != nil {
  153. set, args = append(set, "row_status = ?"), append(args, *v)
  154. }
  155. if v := update.Content; v != nil {
  156. set, args = append(set, "content = ?"), append(args, *v)
  157. }
  158. if v := update.Visibility; v != nil {
  159. set, args = append(set, "visibility = ?"), append(args, *v)
  160. }
  161. args = append(args, update.ID)
  162. query := `
  163. UPDATE memo
  164. SET ` + strings.Join(set, ", ") + `
  165. WHERE id = ?
  166. `
  167. if _, err := tx.ExecContext(ctx, query, args...); err != nil {
  168. return err
  169. }
  170. err = tx.Commit()
  171. return err
  172. }
  173. func (s *Store) DeleteMemo(ctx context.Context, delete *DeleteMemoMessage) error {
  174. tx, err := s.db.BeginTx(ctx, nil)
  175. if err != nil {
  176. return FormatError(err)
  177. }
  178. defer tx.Rollback()
  179. where, args := []string{"id = ?"}, []any{delete.ID}
  180. stmt := `DELETE FROM memo WHERE ` + strings.Join(where, " AND ")
  181. result, err := tx.ExecContext(ctx, stmt, args...)
  182. if err != nil {
  183. return FormatError(err)
  184. }
  185. rows, err := result.RowsAffected()
  186. if err != nil {
  187. return err
  188. }
  189. if rows == 0 {
  190. return &common.Error{Code: common.NotFound, Err: fmt.Errorf("idp not found")}
  191. }
  192. if err := s.vacuumImpl(ctx, tx); err != nil {
  193. return err
  194. }
  195. err = tx.Commit()
  196. return err
  197. }
  198. func listMemos(ctx context.Context, tx *sql.Tx, find *FindMemoMessage) ([]*MemoMessage, error) {
  199. where, args := []string{"1 = 1"}, []any{}
  200. if v := find.ID; v != nil {
  201. where, args = append(where, "memo.id = ?"), append(args, *v)
  202. }
  203. if v := find.CreatorID; v != nil {
  204. where, args = append(where, "memo.creator_id = ?"), append(args, *v)
  205. }
  206. if v := find.RowStatus; v != nil {
  207. where, args = append(where, "memo.row_status = ?"), append(args, *v)
  208. }
  209. if v := find.Pinned; v != nil {
  210. where = append(where, "memo_organizer.pinned = 1")
  211. }
  212. if v := find.ContentSearch; len(v) != 0 {
  213. for _, s := range v {
  214. where, args = append(where, "memo.content LIKE ?"), append(args, "%"+s+"%")
  215. }
  216. }
  217. if v := find.VisibilityList; len(v) != 0 {
  218. list := []string{}
  219. for _, visibility := range v {
  220. list = append(list, fmt.Sprintf("$%d", len(args)+1))
  221. args = append(args, visibility)
  222. }
  223. where = append(where, fmt.Sprintf("memo.visibility in (%s)", strings.Join(list, ",")))
  224. }
  225. query := `
  226. SELECT
  227. memo.id AS id,
  228. memo.creator_id AS creator_id,
  229. memo.created_ts AS created_ts,
  230. memo.updated_ts AS updated_ts,
  231. memo.row_status AS row_status,
  232. memo.content AS content,
  233. memo.visibility AS visibility,
  234. CASE WHEN memo_organizer.pinned = 1 THEN 1 ELSE 0 END AS pinned,
  235. GROUP_CONCAT(memo_resource.resource_id) AS resource_id_list,
  236. (
  237. SELECT
  238. GROUP_CONCAT(related_memo_id || ':' || type)
  239. FROM
  240. memo_relation
  241. WHERE
  242. memo_relation.memo_id = memo.id
  243. GROUP BY
  244. memo_relation.memo_id
  245. ) AS relation_list
  246. FROM
  247. memo
  248. LEFT JOIN
  249. memo_organizer ON memo.id = memo_organizer.memo_id
  250. LEFT JOIN
  251. memo_resource ON memo.id = memo_resource.memo_id
  252. WHERE ` + strings.Join(where, " AND ") + `
  253. GROUP BY memo.id
  254. ORDER BY pinned DESC, memo.created_ts DESC
  255. `
  256. if find.Limit != nil {
  257. query = fmt.Sprintf("%s LIMIT %d", query, *find.Limit)
  258. if find.Offset != nil {
  259. query = fmt.Sprintf("%s OFFSET %d", query, *find.Offset)
  260. }
  261. }
  262. rows, err := tx.QueryContext(ctx, query, args...)
  263. if err != nil {
  264. return nil, FormatError(err)
  265. }
  266. defer rows.Close()
  267. memoMessageList := make([]*MemoMessage, 0)
  268. for rows.Next() {
  269. var memoMessage MemoMessage
  270. var memoResourceIDList sql.NullString
  271. var memoRelationList sql.NullString
  272. if err := rows.Scan(
  273. &memoMessage.ID,
  274. &memoMessage.CreatorID,
  275. &memoMessage.CreatedTs,
  276. &memoMessage.UpdatedTs,
  277. &memoMessage.RowStatus,
  278. &memoMessage.Content,
  279. &memoMessage.Visibility,
  280. &memoMessage.Pinned,
  281. &memoResourceIDList,
  282. &memoRelationList,
  283. ); err != nil {
  284. return nil, FormatError(err)
  285. }
  286. if memoResourceIDList.Valid {
  287. idStringList := strings.Split(memoResourceIDList.String, ",")
  288. memoMessage.ResourceIDList = make([]int, 0, len(idStringList))
  289. for _, idString := range idStringList {
  290. id, err := strconv.Atoi(idString)
  291. if err != nil {
  292. return nil, FormatError(err)
  293. }
  294. memoMessage.ResourceIDList = append(memoMessage.ResourceIDList, id)
  295. }
  296. }
  297. if memoRelationList.Valid {
  298. memoMessage.RelationList = make([]*MemoRelationMessage, 0)
  299. relatedMemoTypeList := strings.Split(memoRelationList.String, ",")
  300. for _, relatedMemoType := range relatedMemoTypeList {
  301. relatedMemoTypeList := strings.Split(relatedMemoType, ":")
  302. if len(relatedMemoTypeList) != 2 {
  303. return nil, &common.Error{Code: common.Invalid, Err: fmt.Errorf("invalid relation format")}
  304. }
  305. relatedMemoID, err := strconv.Atoi(relatedMemoTypeList[0])
  306. if err != nil {
  307. return nil, FormatError(err)
  308. }
  309. memoMessage.RelationList = append(memoMessage.RelationList, &MemoRelationMessage{
  310. MemoID: memoMessage.ID,
  311. RelatedMemoID: relatedMemoID,
  312. Type: MemoRelationType(relatedMemoTypeList[1]),
  313. })
  314. }
  315. }
  316. memoMessageList = append(memoMessageList, &memoMessage)
  317. }
  318. if err := rows.Err(); err != nil {
  319. return nil, FormatError(err)
  320. }
  321. return memoMessageList, nil
  322. }
  323. func vacuumMemo(ctx context.Context, tx *sql.Tx) error {
  324. stmt := `
  325. DELETE FROM
  326. memo
  327. WHERE
  328. creator_id NOT IN (
  329. SELECT
  330. id
  331. FROM
  332. user
  333. )`
  334. _, err := tx.ExecContext(ctx, stmt)
  335. if err != nil {
  336. return FormatError(err)
  337. }
  338. return nil
  339. }