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

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