resource.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. package store
  2. import (
  3. "context"
  4. "database/sql"
  5. "fmt"
  6. "sort"
  7. "strings"
  8. "github.com/usememos/memos/api"
  9. "github.com/usememos/memos/common"
  10. )
  11. // resourceRaw is the store model for an Resource.
  12. // Fields have exactly the same meanings as Resource.
  13. type resourceRaw struct {
  14. ID int
  15. // Standard fields
  16. CreatorID int
  17. CreatedTs int64
  18. UpdatedTs int64
  19. // Domain specific fields
  20. Filename string
  21. Blob []byte
  22. Type string
  23. Size int64
  24. }
  25. func (raw *resourceRaw) toResource() *api.Resource {
  26. return &api.Resource{
  27. ID: raw.ID,
  28. // Standard fields
  29. CreatorID: raw.CreatorID,
  30. CreatedTs: raw.CreatedTs,
  31. UpdatedTs: raw.UpdatedTs,
  32. // Domain specific fields
  33. Filename: raw.Filename,
  34. Blob: raw.Blob,
  35. Type: raw.Type,
  36. Size: raw.Size,
  37. }
  38. }
  39. func (s *Store) ComposeMemoResourceList(ctx context.Context, memo *api.Memo) error {
  40. resourceList, err := s.FindResourceList(ctx, &api.ResourceFind{
  41. MemoID: &memo.ID,
  42. })
  43. if err != nil {
  44. return err
  45. }
  46. for _, resource := range resourceList {
  47. memoResource, err := s.FindMemoResource(ctx, &api.MemoResourceFind{
  48. MemoID: &memo.ID,
  49. ResourceID: &resource.ID,
  50. })
  51. if err != nil {
  52. return err
  53. }
  54. resource.CreatedTs = memoResource.CreatedTs
  55. resource.UpdatedTs = memoResource.UpdatedTs
  56. }
  57. sort.Slice(resourceList, func(i, j int) bool {
  58. if resourceList[i].CreatedTs != resourceList[j].CreatedTs {
  59. return resourceList[i].CreatedTs < resourceList[j].CreatedTs
  60. }
  61. return resourceList[i].ID < resourceList[j].ID
  62. })
  63. memo.ResourceList = resourceList
  64. return nil
  65. }
  66. func (s *Store) CreateResource(ctx context.Context, create *api.ResourceCreate) (*api.Resource, error) {
  67. tx, err := s.db.BeginTx(ctx, nil)
  68. if err != nil {
  69. return nil, FormatError(err)
  70. }
  71. defer tx.Rollback()
  72. resourceRaw, err := createResource(ctx, tx, create)
  73. if err != nil {
  74. return nil, err
  75. }
  76. if err := tx.Commit(); err != nil {
  77. return nil, FormatError(err)
  78. }
  79. if err := s.cache.UpsertCache(api.ResourceCache, resourceRaw.ID, resourceRaw); err != nil {
  80. return nil, err
  81. }
  82. resource := resourceRaw.toResource()
  83. return resource, nil
  84. }
  85. func (s *Store) FindResourceList(ctx context.Context, find *api.ResourceFind) ([]*api.Resource, error) {
  86. tx, err := s.db.BeginTx(ctx, nil)
  87. if err != nil {
  88. return nil, FormatError(err)
  89. }
  90. defer tx.Rollback()
  91. resourceRawList, err := findResourceList(ctx, tx, find)
  92. if err != nil {
  93. return nil, err
  94. }
  95. resourceList := []*api.Resource{}
  96. for _, raw := range resourceRawList {
  97. resourceList = append(resourceList, raw.toResource())
  98. }
  99. return resourceList, nil
  100. }
  101. func (s *Store) FindResource(ctx context.Context, find *api.ResourceFind) (*api.Resource, error) {
  102. if find.ID != nil {
  103. resourceRaw := &resourceRaw{}
  104. has, err := s.cache.FindCache(api.ResourceCache, *find.ID, resourceRaw)
  105. if err != nil {
  106. return nil, err
  107. }
  108. if has {
  109. return resourceRaw.toResource(), nil
  110. }
  111. }
  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 := findResourceList(ctx, tx, find)
  118. if err != nil {
  119. return nil, err
  120. }
  121. if len(list) == 0 {
  122. return nil, &common.Error{Code: common.NotFound, Err: fmt.Errorf("not found")}
  123. }
  124. resourceRaw := list[0]
  125. if err := s.cache.UpsertCache(api.ResourceCache, resourceRaw.ID, resourceRaw); err != nil {
  126. return nil, err
  127. }
  128. resource := resourceRaw.toResource()
  129. return resource, nil
  130. }
  131. func (s *Store) DeleteResource(ctx context.Context, delete *api.ResourceDelete) error {
  132. tx, err := s.db.BeginTx(ctx, nil)
  133. if err != nil {
  134. return FormatError(err)
  135. }
  136. defer tx.Rollback()
  137. if err := deleteResource(ctx, tx, delete); err != nil {
  138. return err
  139. }
  140. if err := vacuum(ctx, tx); err != nil {
  141. return err
  142. }
  143. if err := tx.Commit(); err != nil {
  144. return FormatError(err)
  145. }
  146. s.cache.DeleteCache(api.ResourceCache, delete.ID)
  147. return nil
  148. }
  149. func (s *Store) PatchResource(ctx context.Context, patch *api.ResourcePatch) (*api.Resource, error) {
  150. tx, err := s.db.BeginTx(ctx, nil)
  151. if err != nil {
  152. return nil, FormatError(err)
  153. }
  154. defer tx.Rollback()
  155. resourceRaw, err := patchResource(ctx, tx, patch)
  156. if err != nil {
  157. return nil, err
  158. }
  159. if err := tx.Commit(); err != nil {
  160. return nil, FormatError(err)
  161. }
  162. if err := s.cache.UpsertCache(api.ResourceCache, resourceRaw.ID, resourceRaw); err != nil {
  163. return nil, err
  164. }
  165. resource := resourceRaw.toResource()
  166. return resource, nil
  167. }
  168. func createResource(ctx context.Context, tx *sql.Tx, create *api.ResourceCreate) (*resourceRaw, error) {
  169. query := `
  170. INSERT INTO resource (
  171. filename,
  172. blob,
  173. type,
  174. size,
  175. creator_id
  176. )
  177. VALUES (?, ?, ?, ?, ?)
  178. RETURNING id, filename, blob, type, size, creator_id, created_ts, updated_ts
  179. `
  180. var resourceRaw resourceRaw
  181. if err := tx.QueryRowContext(ctx, query, create.Filename, create.Blob, create.Type, create.Size, create.CreatorID).Scan(
  182. &resourceRaw.ID,
  183. &resourceRaw.Filename,
  184. &resourceRaw.Blob,
  185. &resourceRaw.Type,
  186. &resourceRaw.Size,
  187. &resourceRaw.CreatorID,
  188. &resourceRaw.CreatedTs,
  189. &resourceRaw.UpdatedTs,
  190. ); err != nil {
  191. return nil, FormatError(err)
  192. }
  193. return &resourceRaw, nil
  194. }
  195. func patchResource(ctx context.Context, tx *sql.Tx, patch *api.ResourcePatch) (*resourceRaw, error) {
  196. set, args := []string{}, []interface{}{}
  197. if v := patch.UpdatedTs; v != nil {
  198. set, args = append(set, "updated_ts = ?"), append(args, *v)
  199. }
  200. if v := patch.Filename; v != nil {
  201. set, args = append(set, "filename = ?"), append(args, *v)
  202. }
  203. args = append(args, patch.ID)
  204. query := `
  205. UPDATE resource
  206. SET ` + strings.Join(set, ", ") + `
  207. WHERE id = ?
  208. RETURNING id, filename, blob, type, size, creator_id, created_ts, updated_ts
  209. `
  210. var resourceRaw resourceRaw
  211. if err := tx.QueryRowContext(ctx, query, args...).Scan(
  212. &resourceRaw.ID,
  213. &resourceRaw.Filename,
  214. &resourceRaw.Blob,
  215. &resourceRaw.Type,
  216. &resourceRaw.Size,
  217. &resourceRaw.CreatorID,
  218. &resourceRaw.CreatedTs,
  219. &resourceRaw.UpdatedTs,
  220. ); err != nil {
  221. return nil, FormatError(err)
  222. }
  223. return &resourceRaw, nil
  224. }
  225. func findResourceList(ctx context.Context, tx *sql.Tx, find *api.ResourceFind) ([]*resourceRaw, error) {
  226. where, args := []string{"1 = 1"}, []interface{}{}
  227. if v := find.ID; v != nil {
  228. where, args = append(where, "id = ?"), append(args, *v)
  229. }
  230. if v := find.CreatorID; v != nil {
  231. where, args = append(where, "creator_id = ?"), append(args, *v)
  232. }
  233. if v := find.Filename; v != nil {
  234. where, args = append(where, "filename = ?"), append(args, *v)
  235. }
  236. if v := find.MemoID; v != nil {
  237. where, args = append(where, "id in (SELECT resource_id FROM memo_resource WHERE memo_id = ?)"), append(args, *v)
  238. }
  239. query := `
  240. SELECT
  241. id,
  242. filename,
  243. blob,
  244. type,
  245. size,
  246. creator_id,
  247. created_ts,
  248. updated_ts
  249. FROM resource
  250. WHERE ` + strings.Join(where, " AND ") + `
  251. ORDER BY id DESC
  252. `
  253. rows, err := tx.QueryContext(ctx, query, args...)
  254. if err != nil {
  255. return nil, FormatError(err)
  256. }
  257. defer rows.Close()
  258. resourceRawList := make([]*resourceRaw, 0)
  259. for rows.Next() {
  260. var resourceRaw resourceRaw
  261. if err := rows.Scan(
  262. &resourceRaw.ID,
  263. &resourceRaw.Filename,
  264. &resourceRaw.Blob,
  265. &resourceRaw.Type,
  266. &resourceRaw.Size,
  267. &resourceRaw.CreatorID,
  268. &resourceRaw.CreatedTs,
  269. &resourceRaw.UpdatedTs,
  270. ); err != nil {
  271. return nil, FormatError(err)
  272. }
  273. resourceRawList = append(resourceRawList, &resourceRaw)
  274. }
  275. if err := rows.Err(); err != nil {
  276. return nil, FormatError(err)
  277. }
  278. return resourceRawList, nil
  279. }
  280. func deleteResource(ctx context.Context, tx *sql.Tx, delete *api.ResourceDelete) error {
  281. where, args := []string{"id = ?"}, []interface{}{delete.ID}
  282. stmt := `DELETE FROM resource WHERE ` + strings.Join(where, " AND ")
  283. result, err := tx.ExecContext(ctx, stmt, args...)
  284. if err != nil {
  285. return FormatError(err)
  286. }
  287. rows, _ := result.RowsAffected()
  288. if rows == 0 {
  289. return &common.Error{Code: common.NotFound, Err: fmt.Errorf("resource not found")}
  290. }
  291. return nil
  292. }
  293. func vacuumResource(ctx context.Context, tx *sql.Tx) error {
  294. stmt := `
  295. DELETE FROM
  296. resource
  297. WHERE
  298. creator_id NOT IN (
  299. SELECT
  300. id
  301. FROM
  302. user
  303. )`
  304. _, err := tx.ExecContext(ctx, stmt)
  305. if err != nil {
  306. return FormatError(err)
  307. }
  308. return nil
  309. }