resource.go 9.3 KB

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