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 12 kB

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