You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

dataset.go 9.8 kB

5 years ago
5 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
3 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. package models
  2. import (
  3. "errors"
  4. "fmt"
  5. "sort"
  6. "code.gitea.io/gitea/modules/timeutil"
  7. "xorm.io/builder"
  8. )
  9. const (
  10. DatasetStatusPrivate int32 = iota
  11. DatasetStatusPublic
  12. DatasetStatusDeleted
  13. )
  14. type Dataset struct {
  15. ID int64 `xorm:"pk autoincr"`
  16. Title string `xorm:"INDEX NOT NULL"`
  17. Status int32 `xorm:"INDEX"` // normal_private: 0, pulbic: 1, is_delete: 2
  18. Category string
  19. Description string `xorm:"TEXT"`
  20. DownloadTimes int64
  21. NumStars int `xorm:"INDEX NOT NULL DEFAULT 0"`
  22. License string
  23. Task string
  24. ReleaseID int64 `xorm:"INDEX"`
  25. UserID int64 `xorm:"INDEX"`
  26. RepoID int64 `xorm:"INDEX"`
  27. Repo *Repository `xorm:"-"`
  28. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  29. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  30. User *User `xorm:"-"`
  31. Attachments []*Attachment `xorm:"-"`
  32. }
  33. func (d *Dataset) IsPrivate() bool {
  34. switch d.Status {
  35. case DatasetStatusPrivate:
  36. return true
  37. case DatasetStatusPublic:
  38. return false
  39. case DatasetStatusDeleted:
  40. return false
  41. default:
  42. return false
  43. }
  44. }
  45. type DatasetList []*Dataset
  46. func (datasets DatasetList) loadAttributes(e Engine) error {
  47. if len(datasets) == 0 {
  48. return nil
  49. }
  50. set := make(map[int64]struct{})
  51. datasetIDs := make([]int64, len(datasets))
  52. for i := range datasets {
  53. set[datasets[i].UserID] = struct{}{}
  54. set[datasets[i].RepoID] = struct{}{}
  55. datasetIDs[i] = datasets[i].ID
  56. }
  57. // Load owners.
  58. users := make(map[int64]*User, len(set))
  59. repos := make(map[int64]*Repository, len(set))
  60. if err := e.
  61. Where("id > 0").
  62. In("id", keysInt64(set)).
  63. Find(&users); err != nil {
  64. return fmt.Errorf("find users: %v", err)
  65. }
  66. if err := e.
  67. Where("id > 0").
  68. In("id", keysInt64(set)).
  69. Find(&repos); err != nil {
  70. return fmt.Errorf("find repos: %v", err)
  71. }
  72. for i := range datasets {
  73. datasets[i].User = users[datasets[i].UserID]
  74. datasets[i].Repo = repos[datasets[i].RepoID]
  75. }
  76. return nil
  77. }
  78. type SearchDatasetOptions struct {
  79. Keyword string
  80. OwnerID int64
  81. RepoID int64
  82. IncludePublic bool
  83. Category string
  84. Task string
  85. License string
  86. ListOptions
  87. SearchOrderBy
  88. IsOwner bool
  89. }
  90. func CreateDataset(dataset *Dataset) (err error) {
  91. if _, err = x.Insert(dataset); err != nil {
  92. return err
  93. }
  94. return nil
  95. }
  96. func SearchDataset(opts *SearchDatasetOptions) (DatasetList, int64, error) {
  97. cond := SearchDatasetCondition(opts)
  98. return SearchDatasetByCondition(opts, cond)
  99. }
  100. func SearchDatasetCondition(opts *SearchDatasetOptions) builder.Cond {
  101. var cond = builder.NewCond()
  102. cond = cond.And(builder.Neq{"dataset.status": DatasetStatusDeleted})
  103. if len(opts.Keyword) > 0 {
  104. cond = cond.And(builder.Like{"dataset.title", opts.Keyword})
  105. }
  106. if len(opts.Category) > 0 {
  107. cond = cond.And(builder.Eq{"dataset.category": opts.Category})
  108. }
  109. if len(opts.Task) > 0 {
  110. cond = cond.And(builder.Eq{"dataset.task": opts.Task})
  111. }
  112. if len(opts.License) > 0 {
  113. cond = cond.And(builder.Eq{"dataset.license": opts.License})
  114. }
  115. if opts.RepoID > 0 {
  116. cond = cond.And(builder.Eq{"dataset.repo_id": opts.RepoID})
  117. }
  118. if opts.IncludePublic {
  119. cond = cond.And(builder.Eq{"dataset.status": DatasetStatusPublic})
  120. cond = cond.And(builder.Eq{"attachment.is_private": false})
  121. if opts.OwnerID > 0 {
  122. if len(opts.Keyword) == 0 {
  123. cond = cond.Or(builder.Eq{"repository.owner_id": opts.OwnerID})
  124. } else {
  125. subCon := builder.NewCond()
  126. subCon = subCon.And(builder.Eq{"repository.owner_id": opts.OwnerID}, builder.Like{"dataset.title", opts.Keyword})
  127. cond = cond.Or(subCon)
  128. }
  129. }
  130. } else if opts.OwnerID > 0 {
  131. cond = cond.And(builder.Eq{"repository.owner_id": opts.OwnerID})
  132. if !opts.IsOwner {
  133. cond = cond.And(builder.Eq{"dataset.status": DatasetStatusPublic})
  134. cond = cond.And(builder.Eq{"attachment.is_private": false})
  135. }
  136. }
  137. return cond
  138. }
  139. func SearchDatasetByCondition(opts *SearchDatasetOptions, cond builder.Cond) (DatasetList, int64, error) {
  140. if opts.Page <= 0 {
  141. opts.Page = 1
  142. }
  143. var err error
  144. sess := x.NewSession()
  145. defer sess.Close()
  146. datasets := make(DatasetList, 0, opts.PageSize)
  147. selectColumnsSql := "distinct dataset.id,dataset.title, dataset.status, dataset.category, dataset.description, dataset.download_times, dataset.license, dataset.task, dataset.release_id, dataset.user_id, dataset.repo_id, dataset.created_unix,dataset.updated_unix,dataset.num_stars"
  148. count, err := sess.Select(selectColumnsSql).Join("INNER", "repository", "repository.id = dataset.repo_id").
  149. Join("INNER", "attachment", "attachment.dataset_id=dataset.id").
  150. Where(cond).Count(new(Dataset))
  151. if err != nil {
  152. return nil, 0, fmt.Errorf("Count: %v", err)
  153. }
  154. sess.Select(selectColumnsSql).Join("INNER", "repository", "repository.id = dataset.repo_id").
  155. Join("INNER", "attachment", "attachment.dataset_id=dataset.id").
  156. Where(cond).OrderBy(opts.SearchOrderBy.String())
  157. if opts.PageSize > 0 {
  158. sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize)
  159. }
  160. if err = sess.Find(&datasets); err != nil {
  161. return nil, 0, fmt.Errorf("Dataset: %v", err)
  162. }
  163. if err = datasets.loadAttributes(sess); err != nil {
  164. return nil, 0, fmt.Errorf("LoadAttributes: %v", err)
  165. }
  166. return datasets, count, nil
  167. }
  168. type datasetMetaSearch struct {
  169. ID []int64
  170. Rel []*Dataset
  171. }
  172. func (s datasetMetaSearch) Len() int {
  173. return len(s.ID)
  174. }
  175. func (s datasetMetaSearch) Swap(i, j int) {
  176. s.ID[i], s.ID[j] = s.ID[j], s.ID[i]
  177. s.Rel[i], s.Rel[j] = s.Rel[j], s.Rel[i]
  178. }
  179. func (s datasetMetaSearch) Less(i, j int) bool {
  180. return s.ID[i] < s.ID[j]
  181. }
  182. func GetDatasetAttachments(typeCloudBrain int, isSigned bool, user *User, rels ...*Dataset) (err error) {
  183. return getDatasetAttachments(x, typeCloudBrain, isSigned, user, rels...)
  184. }
  185. func getDatasetAttachments(e Engine, typeCloudBrain int, isSigned bool, user *User, rels ...*Dataset) (err error) {
  186. if len(rels) == 0 {
  187. return
  188. }
  189. // To keep this efficient as possible sort all datasets by id,
  190. // select attachments by dataset id,
  191. // then merge join them
  192. // Sort
  193. var sortedRels = datasetMetaSearch{ID: make([]int64, len(rels)), Rel: make([]*Dataset, len(rels))}
  194. var attachments []*Attachment
  195. for index, element := range rels {
  196. element.Attachments = []*Attachment{}
  197. sortedRels.ID[index] = element.ID
  198. sortedRels.Rel[index] = element
  199. }
  200. sort.Sort(sortedRels)
  201. // Select attachments
  202. if typeCloudBrain == -1 {
  203. err = e.
  204. Asc("dataset_id").
  205. In("dataset_id", sortedRels.ID).
  206. Find(&attachments, Attachment{})
  207. if err != nil {
  208. return err
  209. }
  210. } else {
  211. err = e.
  212. Asc("dataset_id").
  213. In("dataset_id", sortedRels.ID).
  214. And("type = ?", typeCloudBrain).
  215. Find(&attachments, Attachment{})
  216. if err != nil {
  217. return err
  218. }
  219. }
  220. // merge join
  221. var currentIndex = 0
  222. for _, attachment := range attachments {
  223. for sortedRels.ID[currentIndex] < attachment.DatasetID {
  224. currentIndex++
  225. }
  226. fileChunks := make([]*FileChunk, 0, 10)
  227. err = e.
  228. Where("uuid = ?", attachment.UUID).
  229. Find(&fileChunks)
  230. if err != nil {
  231. return err
  232. }
  233. attachment.FileChunk = fileChunks[0]
  234. attachment.CanDel = CanDelAttachment(isSigned, user, attachment)
  235. sortedRels.Rel[currentIndex].Attachments = append(sortedRels.Rel[currentIndex].Attachments, attachment)
  236. }
  237. return
  238. }
  239. // AddDatasetAttachments adds a Dataset attachments
  240. func AddDatasetAttachments(DatasetID int64, attachmentUUIDs []string) (err error) {
  241. // Check attachments
  242. attachments, err := GetAttachmentsByUUIDs(attachmentUUIDs)
  243. if err != nil {
  244. return fmt.Errorf("GetAttachmentsByUUIDs [uuids: %v]: %v", attachmentUUIDs, err)
  245. }
  246. for i := range attachments {
  247. attachments[i].DatasetID = DatasetID
  248. // No assign value could be 0, so ignore AllCols().
  249. if _, err = x.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  250. return fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
  251. }
  252. }
  253. return
  254. }
  255. func UpdateDataset(ctx DBContext, rel *Dataset) error {
  256. _, err := ctx.e.ID(rel.ID).AllCols().Update(rel)
  257. return err
  258. }
  259. // GetDatasetByID returns Dataset with given ID.
  260. func GetDatasetByID(id int64) (*Dataset, error) {
  261. rel := new(Dataset)
  262. has, err := x.
  263. ID(id).
  264. Get(rel)
  265. if err != nil {
  266. return nil, err
  267. } else if !has {
  268. return nil, ErrDatasetNotExist{id}
  269. }
  270. return rel, nil
  271. }
  272. func GetDatasetByRepo(repo *Repository) (*Dataset, error) {
  273. dataset := &Dataset{RepoID: repo.ID}
  274. has, err := x.Get(dataset)
  275. if err != nil {
  276. return nil, err
  277. }
  278. if has {
  279. return dataset, nil
  280. } else {
  281. return nil, errors.New("Not Found")
  282. }
  283. }
  284. func DeleteDataset(datasetID int64, uid int64) error {
  285. var err error
  286. sess := x.NewSession()
  287. defer sess.Close()
  288. if err = sess.Begin(); err != nil {
  289. return err
  290. }
  291. dataset := &Dataset{ID: datasetID, UserID: uid}
  292. has, err := sess.Get(dataset)
  293. if err != nil {
  294. return err
  295. } else if !has {
  296. return errors.New("not found")
  297. }
  298. if cnt, err := sess.ID(datasetID).Delete(new(Dataset)); err != nil {
  299. return err
  300. } else if cnt != 1 {
  301. return errors.New("not found")
  302. }
  303. if err = sess.Commit(); err != nil {
  304. sess.Close()
  305. return fmt.Errorf("Commit: %v", err)
  306. }
  307. return nil
  308. }
  309. func GetOwnerDatasetByID(id int64, user *User) (*Dataset, error) {
  310. dataset, err := GetDatasetByID(id)
  311. if err != nil {
  312. return nil, err
  313. }
  314. if !dataset.IsPrivate() {
  315. return dataset, nil
  316. }
  317. if dataset.IsPrivate() && user != nil && user.ID == dataset.UserID {
  318. return dataset, nil
  319. }
  320. return nil, errors.New("dataset not fount")
  321. }
  322. func IncreaseDownloadCount(datasetID int64) error {
  323. // Update download count.
  324. if _, err := x.Exec("UPDATE `dataset` SET download_times=download_times+1 WHERE id=?", datasetID); err != nil {
  325. return fmt.Errorf("increase dataset count: %v", err)
  326. }
  327. return nil
  328. }