repos.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. // Copyright 2020 The Gogs 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 db
  5. import (
  6. "context"
  7. "fmt"
  8. "strings"
  9. "time"
  10. api "github.com/gogs/go-gogs-client"
  11. "github.com/pkg/errors"
  12. "gorm.io/gorm"
  13. "gogs.io/gogs/internal/errutil"
  14. "gogs.io/gogs/internal/repoutil"
  15. )
  16. // ReposStore is the persistent interface for repositories.
  17. //
  18. // NOTE: All methods are sorted in alphabetical order.
  19. type ReposStore interface {
  20. // Create creates a new repository record in the database. It returns
  21. // ErrNameNotAllowed when the repository name is not allowed, or
  22. // ErrRepoAlreadyExist when a repository with same name already exists for the
  23. // owner.
  24. Create(ctx context.Context, ownerID int64, opts CreateRepoOptions) (*Repository, error)
  25. // GetByCollaboratorID returns a list of repositories that the given
  26. // collaborator has access to. Results are limited to the given limit and sorted
  27. // by the given order (e.g. "updated_unix DESC"). Repositories that are owned
  28. // directly by the given collaborator are not included.
  29. GetByCollaboratorID(ctx context.Context, collaboratorID int64, limit int, orderBy string) ([]*Repository, error)
  30. // GetByCollaboratorIDWithAccessMode returns a list of repositories and
  31. // corresponding access mode that the given collaborator has access to.
  32. // Repositories that are owned directly by the given collaborator are not
  33. // included.
  34. GetByCollaboratorIDWithAccessMode(ctx context.Context, collaboratorID int64) (map[*Repository]AccessMode, error)
  35. // GetByID returns the repository with given ID. It returns ErrRepoNotExist when
  36. // not found.
  37. GetByID(ctx context.Context, id int64) (*Repository, error)
  38. // GetByName returns the repository with given owner and name. It returns
  39. // ErrRepoNotExist when not found.
  40. GetByName(ctx context.Context, ownerID int64, name string) (*Repository, error)
  41. // Star marks the user to star the repository.
  42. Star(ctx context.Context, userID, repoID int64) error
  43. // Touch updates the updated time to the current time and removes the bare state
  44. // of the given repository.
  45. Touch(ctx context.Context, id int64) error
  46. }
  47. var Repos ReposStore
  48. // BeforeCreate implements the GORM create hook.
  49. func (r *Repository) BeforeCreate(tx *gorm.DB) error {
  50. if r.CreatedUnix == 0 {
  51. r.CreatedUnix = tx.NowFunc().Unix()
  52. }
  53. return nil
  54. }
  55. // BeforeUpdate implements the GORM update hook.
  56. func (r *Repository) BeforeUpdate(tx *gorm.DB) error {
  57. r.UpdatedUnix = tx.NowFunc().Unix()
  58. return nil
  59. }
  60. // AfterFind implements the GORM query hook.
  61. func (r *Repository) AfterFind(_ *gorm.DB) error {
  62. r.Created = time.Unix(r.CreatedUnix, 0).Local()
  63. r.Updated = time.Unix(r.UpdatedUnix, 0).Local()
  64. return nil
  65. }
  66. type RepositoryAPIFormatOptions struct {
  67. Permission *api.Permission
  68. Parent *api.Repository
  69. }
  70. // APIFormat returns the API format of a repository.
  71. func (r *Repository) APIFormat(owner *User, opts ...RepositoryAPIFormatOptions) *api.Repository {
  72. var opt RepositoryAPIFormatOptions
  73. if len(opts) > 0 {
  74. opt = opts[0]
  75. }
  76. cloneLink := repoutil.NewCloneLink(owner.Name, r.Name, false)
  77. return &api.Repository{
  78. ID: r.ID,
  79. Owner: owner.APIFormat(),
  80. Name: r.Name,
  81. FullName: owner.Name + "/" + r.Name,
  82. Description: r.Description,
  83. Private: r.IsPrivate,
  84. Fork: r.IsFork,
  85. Parent: opt.Parent,
  86. Empty: r.IsBare,
  87. Mirror: r.IsMirror,
  88. Size: r.Size,
  89. HTMLURL: repoutil.HTMLURL(owner.Name, r.Name),
  90. SSHURL: cloneLink.SSH,
  91. CloneURL: cloneLink.HTTPS,
  92. Website: r.Website,
  93. Stars: r.NumStars,
  94. Forks: r.NumForks,
  95. Watchers: r.NumWatches,
  96. OpenIssues: r.NumOpenIssues,
  97. DefaultBranch: r.DefaultBranch,
  98. Created: r.Created,
  99. Updated: r.Updated,
  100. Permissions: opt.Permission,
  101. }
  102. }
  103. var _ ReposStore = (*repos)(nil)
  104. type repos struct {
  105. *gorm.DB
  106. }
  107. // NewReposStore returns a persistent interface for repositories with given
  108. // database connection.
  109. func NewReposStore(db *gorm.DB) ReposStore {
  110. return &repos{DB: db}
  111. }
  112. type ErrRepoAlreadyExist struct {
  113. args errutil.Args
  114. }
  115. func IsErrRepoAlreadyExist(err error) bool {
  116. _, ok := err.(ErrRepoAlreadyExist)
  117. return ok
  118. }
  119. func (err ErrRepoAlreadyExist) Error() string {
  120. return fmt.Sprintf("repository already exists: %v", err.args)
  121. }
  122. type CreateRepoOptions struct {
  123. Name string
  124. Description string
  125. DefaultBranch string
  126. Private bool
  127. Mirror bool
  128. EnableWiki bool
  129. EnableIssues bool
  130. EnablePulls bool
  131. Fork bool
  132. ForkID int64
  133. }
  134. func (db *repos) Create(ctx context.Context, ownerID int64, opts CreateRepoOptions) (*Repository, error) {
  135. err := isRepoNameAllowed(opts.Name)
  136. if err != nil {
  137. return nil, err
  138. }
  139. _, err = db.GetByName(ctx, ownerID, opts.Name)
  140. if err == nil {
  141. return nil, ErrRepoAlreadyExist{
  142. args: errutil.Args{
  143. "ownerID": ownerID,
  144. "name": opts.Name,
  145. },
  146. }
  147. } else if !IsErrRepoNotExist(err) {
  148. return nil, err
  149. }
  150. repo := &Repository{
  151. OwnerID: ownerID,
  152. LowerName: strings.ToLower(opts.Name),
  153. Name: opts.Name,
  154. Description: opts.Description,
  155. DefaultBranch: opts.DefaultBranch,
  156. IsPrivate: opts.Private,
  157. IsMirror: opts.Mirror,
  158. EnableWiki: opts.EnableWiki,
  159. EnableIssues: opts.EnableIssues,
  160. EnablePulls: opts.EnablePulls,
  161. IsFork: opts.Fork,
  162. ForkID: opts.ForkID,
  163. }
  164. return repo, db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  165. err = tx.Create(repo).Error
  166. if err != nil {
  167. return errors.Wrap(err, "create")
  168. }
  169. err = NewWatchesStore(tx).Watch(ctx, ownerID, repo.ID)
  170. if err != nil {
  171. return errors.Wrap(err, "watch")
  172. }
  173. return nil
  174. })
  175. }
  176. func (db *repos) GetByCollaboratorID(ctx context.Context, collaboratorID int64, limit int, orderBy string) ([]*Repository, error) {
  177. /*
  178. Equivalent SQL for PostgreSQL:
  179. SELECT * FROM repository
  180. JOIN access ON access.repo_id = repository.id AND access.user_id = @collaboratorID
  181. WHERE access.mode >= @accessModeRead
  182. ORDER BY @orderBy
  183. LIMIT @limit
  184. */
  185. var repos []*Repository
  186. return repos, db.WithContext(ctx).
  187. Joins("JOIN access ON access.repo_id = repository.id AND access.user_id = ?", collaboratorID).
  188. Where("access.mode >= ?", AccessModeRead).
  189. Order(orderBy).
  190. Limit(limit).
  191. Find(&repos).
  192. Error
  193. }
  194. func (db *repos) GetByCollaboratorIDWithAccessMode(ctx context.Context, collaboratorID int64) (map[*Repository]AccessMode, error) {
  195. /*
  196. Equivalent SQL for PostgreSQL:
  197. SELECT
  198. repository.*,
  199. access.mode
  200. FROM repository
  201. JOIN access ON access.repo_id = repository.id AND access.user_id = @collaboratorID
  202. WHERE access.mode >= @accessModeRead
  203. */
  204. var reposWithAccessMode []*struct {
  205. *Repository
  206. Mode AccessMode
  207. }
  208. err := db.WithContext(ctx).
  209. Select("repository.*", "access.mode").
  210. Table("repository").
  211. Joins("JOIN access ON access.repo_id = repository.id AND access.user_id = ?", collaboratorID).
  212. Where("access.mode >= ?", AccessModeRead).
  213. Find(&reposWithAccessMode).
  214. Error
  215. if err != nil {
  216. return nil, err
  217. }
  218. repos := make(map[*Repository]AccessMode, len(reposWithAccessMode))
  219. for _, repoWithAccessMode := range reposWithAccessMode {
  220. repos[repoWithAccessMode.Repository] = repoWithAccessMode.Mode
  221. }
  222. return repos, nil
  223. }
  224. var _ errutil.NotFound = (*ErrRepoNotExist)(nil)
  225. type ErrRepoNotExist struct {
  226. args errutil.Args
  227. }
  228. func IsErrRepoNotExist(err error) bool {
  229. _, ok := err.(ErrRepoNotExist)
  230. return ok
  231. }
  232. func (err ErrRepoNotExist) Error() string {
  233. return fmt.Sprintf("repository does not exist: %v", err.args)
  234. }
  235. func (ErrRepoNotExist) NotFound() bool {
  236. return true
  237. }
  238. func (db *repos) GetByID(ctx context.Context, id int64) (*Repository, error) {
  239. repo := new(Repository)
  240. err := db.WithContext(ctx).Where("id = ?", id).First(repo).Error
  241. if err != nil {
  242. if err == gorm.ErrRecordNotFound {
  243. return nil, ErrRepoNotExist{errutil.Args{"repoID": id}}
  244. }
  245. return nil, err
  246. }
  247. return repo, nil
  248. }
  249. func (db *repos) GetByName(ctx context.Context, ownerID int64, name string) (*Repository, error) {
  250. repo := new(Repository)
  251. err := db.WithContext(ctx).
  252. Where("owner_id = ? AND lower_name = ?", ownerID, strings.ToLower(name)).
  253. First(repo).
  254. Error
  255. if err != nil {
  256. if err == gorm.ErrRecordNotFound {
  257. return nil, ErrRepoNotExist{
  258. args: errutil.Args{
  259. "ownerID": ownerID,
  260. "name": name,
  261. },
  262. }
  263. }
  264. return nil, err
  265. }
  266. return repo, nil
  267. }
  268. func (db *repos) recountStars(tx *gorm.DB, userID, repoID int64) error {
  269. /*
  270. Equivalent SQL for PostgreSQL:
  271. UPDATE repository
  272. SET num_stars = (
  273. SELECT COUNT(*) FROM star WHERE repo_id = @repoID
  274. )
  275. WHERE id = @repoID
  276. */
  277. err := tx.Model(&Repository{}).
  278. Where("id = ?", repoID).
  279. Update(
  280. "num_stars",
  281. tx.Model(&Star{}).Select("COUNT(*)").Where("repo_id = ?", repoID),
  282. ).
  283. Error
  284. if err != nil {
  285. return errors.Wrap(err, `update "repository.num_stars"`)
  286. }
  287. /*
  288. Equivalent SQL for PostgreSQL:
  289. UPDATE "user"
  290. SET num_stars = (
  291. SELECT COUNT(*) FROM star WHERE uid = @userID
  292. )
  293. WHERE id = @userID
  294. */
  295. err = tx.Model(&User{}).
  296. Where("id = ?", userID).
  297. Update(
  298. "num_stars",
  299. tx.Model(&Star{}).Select("COUNT(*)").Where("uid = ?", userID),
  300. ).
  301. Error
  302. if err != nil {
  303. return errors.Wrap(err, `update "user.num_stars"`)
  304. }
  305. return nil
  306. }
  307. func (db *repos) Star(ctx context.Context, userID, repoID int64) error {
  308. return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  309. s := &Star{
  310. UserID: userID,
  311. RepoID: repoID,
  312. }
  313. result := tx.FirstOrCreate(s, s)
  314. if result.Error != nil {
  315. return errors.Wrap(result.Error, "upsert")
  316. } else if result.RowsAffected <= 0 {
  317. return nil // Relation already exists
  318. }
  319. return db.recountStars(tx, userID, repoID)
  320. })
  321. }
  322. func (db *repos) Touch(ctx context.Context, id int64) error {
  323. return db.WithContext(ctx).
  324. Model(new(Repository)).
  325. Where("id = ?", id).
  326. Updates(map[string]any{
  327. "is_bare": false,
  328. "updated_unix": db.NowFunc().Unix(),
  329. }).
  330. Error
  331. }