repositories.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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, userID, repoID int64) 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(ctx, ownerID, repo.ID)
  173. if err != nil {
  174. return errors.Wrap(err, "watch")
  175. }
  176. return nil
  177. })
  178. }
  179. func (db *repositories) GetByCollaboratorID(ctx context.Context, collaboratorID int64, limit int, orderBy string) ([]*Repository, error) {
  180. /*
  181. Equivalent SQL for PostgreSQL:
  182. SELECT * FROM repository
  183. JOIN access ON access.repo_id = repository.id AND access.user_id = @collaboratorID
  184. WHERE access.mode >= @accessModeRead
  185. ORDER BY @orderBy
  186. LIMIT @limit
  187. */
  188. var repos []*Repository
  189. return repos, db.WithContext(ctx).
  190. Joins("JOIN access ON access.repo_id = repository.id AND access.user_id = ?", collaboratorID).
  191. Where("access.mode >= ?", AccessModeRead).
  192. Order(orderBy).
  193. Limit(limit).
  194. Find(&repos).
  195. Error
  196. }
  197. func (db *repositories) GetByCollaboratorIDWithAccessMode(ctx context.Context, collaboratorID int64) (map[*Repository]AccessMode, error) {
  198. /*
  199. Equivalent SQL for PostgreSQL:
  200. SELECT
  201. repository.*,
  202. access.mode
  203. FROM repository
  204. JOIN access ON access.repo_id = repository.id AND access.user_id = @collaboratorID
  205. WHERE access.mode >= @accessModeRead
  206. */
  207. var reposWithAccessMode []*struct {
  208. *Repository
  209. Mode AccessMode
  210. }
  211. err := db.WithContext(ctx).
  212. Select("repository.*", "access.mode").
  213. Table("repository").
  214. Joins("JOIN access ON access.repo_id = repository.id AND access.user_id = ?", collaboratorID).
  215. Where("access.mode >= ?", AccessModeRead).
  216. Find(&reposWithAccessMode).
  217. Error
  218. if err != nil {
  219. return nil, err
  220. }
  221. repos := make(map[*Repository]AccessMode, len(reposWithAccessMode))
  222. for _, repoWithAccessMode := range reposWithAccessMode {
  223. repos[repoWithAccessMode.Repository] = repoWithAccessMode.Mode
  224. }
  225. return repos, nil
  226. }
  227. var _ errutil.NotFound = (*ErrRepoNotExist)(nil)
  228. type ErrRepoNotExist struct {
  229. args errutil.Args
  230. }
  231. func IsErrRepoNotExist(err error) bool {
  232. return errors.As(err, &ErrRepoNotExist{})
  233. }
  234. func (err ErrRepoNotExist) Error() string {
  235. return fmt.Sprintf("repository does not exist: %v", err.args)
  236. }
  237. func (ErrRepoNotExist) NotFound() bool {
  238. return true
  239. }
  240. func (db *repositories) GetByID(ctx context.Context, id int64) (*Repository, error) {
  241. repo := new(Repository)
  242. err := db.WithContext(ctx).Where("id = ?", id).First(repo).Error
  243. if err != nil {
  244. if errors.Is(err, gorm.ErrRecordNotFound) {
  245. return nil, ErrRepoNotExist{errutil.Args{"repoID": id}}
  246. }
  247. return nil, err
  248. }
  249. return repo, nil
  250. }
  251. func (db *repositories) GetByName(ctx context.Context, ownerID int64, name string) (*Repository, error) {
  252. repo := new(Repository)
  253. err := db.WithContext(ctx).
  254. Where("owner_id = ? AND lower_name = ?", ownerID, strings.ToLower(name)).
  255. First(repo).
  256. Error
  257. if err != nil {
  258. if errors.Is(err, gorm.ErrRecordNotFound) {
  259. return nil, ErrRepoNotExist{
  260. args: errutil.Args{
  261. "ownerID": ownerID,
  262. "name": name,
  263. },
  264. }
  265. }
  266. return nil, err
  267. }
  268. return repo, nil
  269. }
  270. func (db *repositories) recountStars(tx *gorm.DB, userID, repoID int64) error {
  271. /*
  272. Equivalent SQL for PostgreSQL:
  273. UPDATE repository
  274. SET num_stars = (
  275. SELECT COUNT(*) FROM star WHERE repo_id = @repoID
  276. )
  277. WHERE id = @repoID
  278. */
  279. err := tx.Model(&Repository{}).
  280. Where("id = ?", repoID).
  281. Update(
  282. "num_stars",
  283. tx.Model(&Star{}).Select("COUNT(*)").Where("repo_id = ?", repoID),
  284. ).
  285. Error
  286. if err != nil {
  287. return errors.Wrap(err, `update "repository.num_stars"`)
  288. }
  289. /*
  290. Equivalent SQL for PostgreSQL:
  291. UPDATE "user"
  292. SET num_stars = (
  293. SELECT COUNT(*) FROM star WHERE uid = @userID
  294. )
  295. WHERE id = @userID
  296. */
  297. err = tx.Model(&User{}).
  298. Where("id = ?", userID).
  299. Update(
  300. "num_stars",
  301. tx.Model(&Star{}).Select("COUNT(*)").Where("uid = ?", userID),
  302. ).
  303. Error
  304. if err != nil {
  305. return errors.Wrap(err, `update "user.num_stars"`)
  306. }
  307. return nil
  308. }
  309. func (db *repositories) Star(ctx context.Context, userID, repoID int64) error {
  310. return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  311. s := &Star{
  312. UserID: userID,
  313. RepoID: repoID,
  314. }
  315. result := tx.FirstOrCreate(s, s)
  316. if result.Error != nil {
  317. return errors.Wrap(result.Error, "upsert")
  318. } else if result.RowsAffected <= 0 {
  319. return nil // Relation already exists
  320. }
  321. return db.recountStars(tx, userID, repoID)
  322. })
  323. }
  324. func (db *repositories) Touch(ctx context.Context, id int64) error {
  325. return db.WithContext(ctx).
  326. Model(new(Repository)).
  327. Where("id = ?", id).
  328. Updates(map[string]any{
  329. "is_bare": false,
  330. "updated_unix": db.NowFunc().Unix(),
  331. }).
  332. Error
  333. }
  334. func (db *repositories) ListWatches(ctx context.Context, repoID int64) ([]*Watch, error) {
  335. var watches []*Watch
  336. return watches, db.WithContext(ctx).Where("repo_id = ?", repoID).Find(&watches).Error
  337. }
  338. func (db *repositories) recountWatches(tx *gorm.DB, repoID int64) error {
  339. /*
  340. Equivalent SQL for PostgreSQL:
  341. UPDATE repository
  342. SET num_watches = (
  343. SELECT COUNT(*) FROM watch WHERE repo_id = @repoID
  344. )
  345. WHERE id = @repoID
  346. */
  347. return tx.Model(&Repository{}).
  348. Where("id = ?", repoID).
  349. Update(
  350. "num_watches",
  351. tx.Model(&Watch{}).Select("COUNT(*)").Where("repo_id = ?", repoID),
  352. ).
  353. Error
  354. }
  355. func (db *repositories) Watch(ctx context.Context, userID, repoID int64) error {
  356. return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  357. w := &Watch{
  358. UserID: userID,
  359. RepoID: repoID,
  360. }
  361. result := tx.FirstOrCreate(w, w)
  362. if result.Error != nil {
  363. return errors.Wrap(result.Error, "upsert")
  364. } else if result.RowsAffected <= 0 {
  365. return nil // Relation already exists
  366. }
  367. return db.recountWatches(tx, repoID)
  368. })
  369. }
  370. func (db *repositories) HasForkedBy(ctx context.Context, repoID, userID int64) bool {
  371. var count int64
  372. db.WithContext(ctx).Model(new(Repository)).Where("owner_id = ? AND fork_id = ?", userID, repoID).Count(&count)
  373. return count > 0
  374. }