resource.go 8.9 KB

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