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

package_version.go 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package packages
  5. import (
  6. "context"
  7. "errors"
  8. "strconv"
  9. "strings"
  10. "code.gitea.io/gitea/models/db"
  11. "code.gitea.io/gitea/modules/timeutil"
  12. "code.gitea.io/gitea/modules/util"
  13. "xorm.io/builder"
  14. )
  15. // ErrDuplicatePackageVersion indicates a duplicated package version error
  16. var ErrDuplicatePackageVersion = errors.New("Package version already exists")
  17. func init() {
  18. db.RegisterModel(new(PackageVersion))
  19. }
  20. // PackageVersion represents a package version
  21. type PackageVersion struct {
  22. ID int64 `xorm:"pk autoincr"`
  23. PackageID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  24. CreatorID int64 `xorm:"NOT NULL DEFAULT 0"`
  25. Version string `xorm:"NOT NULL"`
  26. LowerVersion string `xorm:"UNIQUE(s) INDEX NOT NULL"`
  27. CreatedUnix timeutil.TimeStamp `xorm:"created INDEX NOT NULL"`
  28. IsInternal bool `xorm:"INDEX NOT NULL DEFAULT false"`
  29. MetadataJSON string `xorm:"metadata_json TEXT"`
  30. DownloadCount int64 `xorm:"NOT NULL DEFAULT 0"`
  31. }
  32. // GetOrInsertVersion inserts a version. If the same version exist already ErrDuplicatePackageVersion is returned
  33. func GetOrInsertVersion(ctx context.Context, pv *PackageVersion) (*PackageVersion, error) {
  34. e := db.GetEngine(ctx)
  35. key := &PackageVersion{
  36. PackageID: pv.PackageID,
  37. LowerVersion: pv.LowerVersion,
  38. }
  39. has, err := e.Get(key)
  40. if err != nil {
  41. return nil, err
  42. }
  43. if has {
  44. return key, ErrDuplicatePackageVersion
  45. }
  46. if _, err = e.Insert(pv); err != nil {
  47. return nil, err
  48. }
  49. return pv, nil
  50. }
  51. // UpdateVersion updates a version
  52. func UpdateVersion(ctx context.Context, pv *PackageVersion) error {
  53. _, err := db.GetEngine(ctx).ID(pv.ID).Update(pv)
  54. return err
  55. }
  56. // IncrementDownloadCounter increments the download counter of a version
  57. func IncrementDownloadCounter(ctx context.Context, versionID int64) error {
  58. _, err := db.GetEngine(ctx).Exec("UPDATE `package_version` SET `download_count` = `download_count` + 1 WHERE `id` = ?", versionID)
  59. return err
  60. }
  61. // GetVersionByID gets a version by id
  62. func GetVersionByID(ctx context.Context, versionID int64) (*PackageVersion, error) {
  63. pv := &PackageVersion{}
  64. has, err := db.GetEngine(ctx).ID(versionID).Get(pv)
  65. if err != nil {
  66. return nil, err
  67. }
  68. if !has {
  69. return nil, ErrPackageNotExist
  70. }
  71. return pv, nil
  72. }
  73. // GetVersionByNameAndVersion gets a version by name and version number
  74. func GetVersionByNameAndVersion(ctx context.Context, ownerID int64, packageType Type, name, version string) (*PackageVersion, error) {
  75. return getVersionByNameAndVersion(ctx, ownerID, packageType, name, version, false)
  76. }
  77. // GetInternalVersionByNameAndVersion gets a version by name and version number
  78. func GetInternalVersionByNameAndVersion(ctx context.Context, ownerID int64, packageType Type, name, version string) (*PackageVersion, error) {
  79. return getVersionByNameAndVersion(ctx, ownerID, packageType, name, version, true)
  80. }
  81. func getVersionByNameAndVersion(ctx context.Context, ownerID int64, packageType Type, name, version string, isInternal bool) (*PackageVersion, error) {
  82. pvs, _, err := SearchVersions(ctx, &PackageSearchOptions{
  83. OwnerID: ownerID,
  84. Type: packageType,
  85. Name: SearchValue{
  86. ExactMatch: true,
  87. Value: name,
  88. },
  89. Version: SearchValue{
  90. ExactMatch: true,
  91. Value: version,
  92. },
  93. IsInternal: isInternal,
  94. Paginator: db.NewAbsoluteListOptions(0, 1),
  95. })
  96. if err != nil {
  97. return nil, err
  98. }
  99. if len(pvs) == 0 {
  100. return nil, ErrPackageNotExist
  101. }
  102. return pvs[0], nil
  103. }
  104. // GetVersionsByPackageType gets all versions of a specific type
  105. func GetVersionsByPackageType(ctx context.Context, ownerID int64, packageType Type) ([]*PackageVersion, error) {
  106. pvs, _, err := SearchVersions(ctx, &PackageSearchOptions{
  107. OwnerID: ownerID,
  108. Type: packageType,
  109. })
  110. return pvs, err
  111. }
  112. // GetVersionsByPackageName gets all versions of a specific package
  113. func GetVersionsByPackageName(ctx context.Context, ownerID int64, packageType Type, name string) ([]*PackageVersion, error) {
  114. pvs, _, err := SearchVersions(ctx, &PackageSearchOptions{
  115. OwnerID: ownerID,
  116. Type: packageType,
  117. Name: SearchValue{
  118. ExactMatch: true,
  119. Value: name,
  120. },
  121. })
  122. return pvs, err
  123. }
  124. // DeleteVersionByID deletes a version by id
  125. func DeleteVersionByID(ctx context.Context, versionID int64) error {
  126. _, err := db.GetEngine(ctx).ID(versionID).Delete(&PackageVersion{})
  127. return err
  128. }
  129. // HasVersionFileReferences checks if there are associated files
  130. func HasVersionFileReferences(ctx context.Context, versionID int64) (bool, error) {
  131. return db.GetEngine(ctx).Get(&PackageFile{
  132. VersionID: versionID,
  133. })
  134. }
  135. // SearchValue describes a value to search
  136. // If ExactMatch is true, the field must match the value otherwise a LIKE search is performed.
  137. type SearchValue struct {
  138. Value string
  139. ExactMatch bool
  140. }
  141. // PackageSearchOptions are options for SearchXXX methods
  142. // Besides IsInternal are all fields optional and are not used if they have their default value (nil, "", 0)
  143. type PackageSearchOptions struct {
  144. OwnerID int64
  145. RepoID int64
  146. Type Type
  147. PackageID int64
  148. Name SearchValue // only results with the specific name are found
  149. Version SearchValue // only results with the specific version are found
  150. Properties map[string]string // only results are found which contain all listed version properties with the specific value
  151. IsInternal bool
  152. HasFileWithName string // only results are found which are associated with a file with the specific name
  153. HasFiles util.OptionalBool // only results are found which have associated files
  154. Sort string
  155. db.Paginator
  156. }
  157. func (opts *PackageSearchOptions) toConds() builder.Cond {
  158. var cond builder.Cond = builder.Eq{"package_version.is_internal": opts.IsInternal}
  159. if opts.OwnerID != 0 {
  160. cond = cond.And(builder.Eq{"package.owner_id": opts.OwnerID})
  161. }
  162. if opts.RepoID != 0 {
  163. cond = cond.And(builder.Eq{"package.repo_id": opts.RepoID})
  164. }
  165. if opts.Type != "" && opts.Type != "all" {
  166. cond = cond.And(builder.Eq{"package.type": opts.Type})
  167. }
  168. if opts.PackageID != 0 {
  169. cond = cond.And(builder.Eq{"package.id": opts.PackageID})
  170. }
  171. if opts.Name.Value != "" {
  172. if opts.Name.ExactMatch {
  173. cond = cond.And(builder.Eq{"package.lower_name": strings.ToLower(opts.Name.Value)})
  174. } else {
  175. cond = cond.And(builder.Like{"package.lower_name", strings.ToLower(opts.Name.Value)})
  176. }
  177. }
  178. if opts.Version.Value != "" {
  179. if opts.Version.ExactMatch {
  180. cond = cond.And(builder.Eq{"package_version.lower_version": strings.ToLower(opts.Version.Value)})
  181. } else {
  182. cond = cond.And(builder.Like{"package_version.lower_version", strings.ToLower(opts.Version.Value)})
  183. }
  184. }
  185. if len(opts.Properties) != 0 {
  186. var propsCond builder.Cond = builder.Eq{
  187. "package_property.ref_type": PropertyTypeVersion,
  188. }
  189. propsCond = propsCond.And(builder.Expr("package_property.ref_id = package_version.id"))
  190. propsCondBlock := builder.NewCond()
  191. for name, value := range opts.Properties {
  192. propsCondBlock = propsCondBlock.Or(builder.Eq{
  193. "package_property.name": name,
  194. "package_property.value": value,
  195. })
  196. }
  197. propsCond = propsCond.And(propsCondBlock)
  198. cond = cond.And(builder.Eq{
  199. strconv.Itoa(len(opts.Properties)): builder.Select("COUNT(*)").Where(propsCond).From("package_property"),
  200. })
  201. }
  202. if opts.HasFileWithName != "" {
  203. fileCond := builder.Expr("package_file.version_id = package_version.id").And(builder.Eq{"package_file.lower_name": strings.ToLower(opts.HasFileWithName)})
  204. cond = cond.And(builder.Exists(builder.Select("package_file.id").From("package_file").Where(fileCond)))
  205. }
  206. if !opts.HasFiles.IsNone() {
  207. var filesCond builder.Cond = builder.Exists(builder.Select("package_file.id").From("package_file").Where(builder.Expr("package_file.version_id = package_version.id")))
  208. if opts.HasFiles.IsFalse() {
  209. filesCond = builder.Not{filesCond}
  210. }
  211. cond = cond.And(filesCond)
  212. }
  213. return cond
  214. }
  215. func (opts *PackageSearchOptions) configureOrderBy(e db.Engine) {
  216. switch opts.Sort {
  217. case "alphabetically":
  218. e.Asc("package.name")
  219. case "reversealphabetically":
  220. e.Desc("package.name")
  221. case "highestversion":
  222. e.Desc("package_version.version")
  223. case "lowestversion":
  224. e.Asc("package_version.version")
  225. case "oldest":
  226. e.Asc("package_version.created_unix")
  227. default:
  228. e.Desc("package_version.created_unix")
  229. }
  230. }
  231. // SearchVersions gets all versions of packages matching the search options
  232. func SearchVersions(ctx context.Context, opts *PackageSearchOptions) ([]*PackageVersion, int64, error) {
  233. sess := db.GetEngine(ctx).
  234. Where(opts.toConds()).
  235. Table("package_version").
  236. Join("INNER", "package", "package.id = package_version.package_id")
  237. opts.configureOrderBy(sess)
  238. if opts.Paginator != nil {
  239. sess = db.SetSessionPagination(sess, opts)
  240. }
  241. pvs := make([]*PackageVersion, 0, 10)
  242. count, err := sess.FindAndCount(&pvs)
  243. return pvs, count, err
  244. }
  245. // SearchLatestVersions gets the latest version of every package matching the search options
  246. func SearchLatestVersions(ctx context.Context, opts *PackageSearchOptions) ([]*PackageVersion, int64, error) {
  247. cond := opts.toConds().
  248. And(builder.Expr("pv2.id IS NULL"))
  249. sess := db.GetEngine(ctx).
  250. Table("package_version").
  251. Join("LEFT", "package_version pv2", "package_version.package_id = pv2.package_id AND (package_version.created_unix < pv2.created_unix OR (package_version.created_unix = pv2.created_unix AND package_version.id < pv2.id))").
  252. Join("INNER", "package", "package.id = package_version.package_id").
  253. Where(cond)
  254. opts.configureOrderBy(sess)
  255. if opts.Paginator != nil {
  256. sess = db.SetSessionPagination(sess, opts)
  257. }
  258. pvs := make([]*PackageVersion, 0, 10)
  259. count, err := sess.FindAndCount(&pvs)
  260. return pvs, count, err
  261. }