repositories.go 12 KB

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