repos.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. type ReposStore interface {
  18. // Create creates a new repository record in the database. It returns
  19. // ErrNameNotAllowed when the repository name is not allowed, or
  20. // ErrRepoAlreadyExist 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 Repos ReposStore
  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 _ ReposStore = (*repos)(nil)
  108. type repos struct {
  109. *gorm.DB
  110. }
  111. // NewReposStore returns a persistent interface for repositories with given
  112. // database connection.
  113. func NewReposStore(db *gorm.DB) ReposStore {
  114. return &repos{DB: db}
  115. }
  116. type ErrRepoAlreadyExist struct {
  117. args errutil.Args
  118. }
  119. func IsErrRepoAlreadyExist(err error) bool {
  120. _, ok := err.(ErrRepoAlreadyExist)
  121. return ok
  122. }
  123. func (err ErrRepoAlreadyExist) Error() string {
  124. return fmt.Sprintf("repository already exists: %v", err.args)
  125. }
  126. type CreateRepoOptions struct {
  127. Name string
  128. Description string
  129. DefaultBranch string
  130. Private bool
  131. Mirror bool
  132. EnableWiki bool
  133. EnableIssues bool
  134. EnablePulls bool
  135. Fork bool
  136. ForkID int64
  137. }
  138. func (db *repos) Create(ctx context.Context, ownerID int64, opts CreateRepoOptions) (*Repository, error) {
  139. err := isRepoNameAllowed(opts.Name)
  140. if err != nil {
  141. return nil, err
  142. }
  143. _, err = db.GetByName(ctx, ownerID, opts.Name)
  144. if err == nil {
  145. return nil, ErrRepoAlreadyExist{
  146. args: errutil.Args{
  147. "ownerID": ownerID,
  148. "name": opts.Name,
  149. },
  150. }
  151. } else if !IsErrRepoNotExist(err) {
  152. return nil, err
  153. }
  154. repo := &Repository{
  155. OwnerID: ownerID,
  156. LowerName: strings.ToLower(opts.Name),
  157. Name: opts.Name,
  158. Description: opts.Description,
  159. DefaultBranch: opts.DefaultBranch,
  160. IsPrivate: opts.Private,
  161. IsMirror: opts.Mirror,
  162. EnableWiki: opts.EnableWiki,
  163. EnableIssues: opts.EnableIssues,
  164. EnablePulls: opts.EnablePulls,
  165. IsFork: opts.Fork,
  166. ForkID: opts.ForkID,
  167. }
  168. return repo, db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  169. err = tx.Create(repo).Error
  170. if err != nil {
  171. return errors.Wrap(err, "create")
  172. }
  173. err = NewReposStore(tx).Watch(ctx, ownerID, repo.ID)
  174. if err != nil {
  175. return errors.Wrap(err, "watch")
  176. }
  177. return nil
  178. })
  179. }
  180. func (db *repos) GetByCollaboratorID(ctx context.Context, collaboratorID int64, limit int, orderBy string) ([]*Repository, error) {
  181. /*
  182. Equivalent SQL for PostgreSQL:
  183. SELECT * FROM repository
  184. JOIN access ON access.repo_id = repository.id AND access.user_id = @collaboratorID
  185. WHERE access.mode >= @accessModeRead
  186. ORDER BY @orderBy
  187. LIMIT @limit
  188. */
  189. var repos []*Repository
  190. return repos, db.WithContext(ctx).
  191. Joins("JOIN access ON access.repo_id = repository.id AND access.user_id = ?", collaboratorID).
  192. Where("access.mode >= ?", AccessModeRead).
  193. Order(orderBy).
  194. Limit(limit).
  195. Find(&repos).
  196. Error
  197. }
  198. func (db *repos) GetByCollaboratorIDWithAccessMode(ctx context.Context, collaboratorID int64) (map[*Repository]AccessMode, error) {
  199. /*
  200. Equivalent SQL for PostgreSQL:
  201. SELECT
  202. repository.*,
  203. access.mode
  204. FROM repository
  205. JOIN access ON access.repo_id = repository.id AND access.user_id = @collaboratorID
  206. WHERE access.mode >= @accessModeRead
  207. */
  208. var reposWithAccessMode []*struct {
  209. *Repository
  210. Mode AccessMode
  211. }
  212. err := db.WithContext(ctx).
  213. Select("repository.*", "access.mode").
  214. Table("repository").
  215. Joins("JOIN access ON access.repo_id = repository.id AND access.user_id = ?", collaboratorID).
  216. Where("access.mode >= ?", AccessModeRead).
  217. Find(&reposWithAccessMode).
  218. Error
  219. if err != nil {
  220. return nil, err
  221. }
  222. repos := make(map[*Repository]AccessMode, len(reposWithAccessMode))
  223. for _, repoWithAccessMode := range reposWithAccessMode {
  224. repos[repoWithAccessMode.Repository] = repoWithAccessMode.Mode
  225. }
  226. return repos, nil
  227. }
  228. var _ errutil.NotFound = (*ErrRepoNotExist)(nil)
  229. type ErrRepoNotExist struct {
  230. args errutil.Args
  231. }
  232. func IsErrRepoNotExist(err error) bool {
  233. _, ok := err.(ErrRepoNotExist)
  234. return ok
  235. }
  236. func (err ErrRepoNotExist) Error() string {
  237. return fmt.Sprintf("repository does not exist: %v", err.args)
  238. }
  239. func (ErrRepoNotExist) NotFound() bool {
  240. return true
  241. }
  242. func (db *repos) GetByID(ctx context.Context, id int64) (*Repository, error) {
  243. repo := new(Repository)
  244. err := db.WithContext(ctx).Where("id = ?", id).First(repo).Error
  245. if err != nil {
  246. if err == gorm.ErrRecordNotFound {
  247. return nil, ErrRepoNotExist{errutil.Args{"repoID": id}}
  248. }
  249. return nil, err
  250. }
  251. return repo, nil
  252. }
  253. func (db *repos) GetByName(ctx context.Context, ownerID int64, name string) (*Repository, error) {
  254. repo := new(Repository)
  255. err := db.WithContext(ctx).
  256. Where("owner_id = ? AND lower_name = ?", ownerID, strings.ToLower(name)).
  257. First(repo).
  258. Error
  259. if err != nil {
  260. if err == gorm.ErrRecordNotFound {
  261. return nil, ErrRepoNotExist{
  262. args: errutil.Args{
  263. "ownerID": ownerID,
  264. "name": name,
  265. },
  266. }
  267. }
  268. return nil, err
  269. }
  270. return repo, nil
  271. }
  272. func (db *repos) recountStars(tx *gorm.DB, userID, repoID int64) error {
  273. /*
  274. Equivalent SQL for PostgreSQL:
  275. UPDATE repository
  276. SET num_stars = (
  277. SELECT COUNT(*) FROM star WHERE repo_id = @repoID
  278. )
  279. WHERE id = @repoID
  280. */
  281. err := tx.Model(&Repository{}).
  282. Where("id = ?", repoID).
  283. Update(
  284. "num_stars",
  285. tx.Model(&Star{}).Select("COUNT(*)").Where("repo_id = ?", repoID),
  286. ).
  287. Error
  288. if err != nil {
  289. return errors.Wrap(err, `update "repository.num_stars"`)
  290. }
  291. /*
  292. Equivalent SQL for PostgreSQL:
  293. UPDATE "user"
  294. SET num_stars = (
  295. SELECT COUNT(*) FROM star WHERE uid = @userID
  296. )
  297. WHERE id = @userID
  298. */
  299. err = tx.Model(&User{}).
  300. Where("id = ?", userID).
  301. Update(
  302. "num_stars",
  303. tx.Model(&Star{}).Select("COUNT(*)").Where("uid = ?", userID),
  304. ).
  305. Error
  306. if err != nil {
  307. return errors.Wrap(err, `update "user.num_stars"`)
  308. }
  309. return nil
  310. }
  311. func (db *repos) Star(ctx context.Context, userID, repoID int64) error {
  312. return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  313. s := &Star{
  314. UserID: userID,
  315. RepoID: repoID,
  316. }
  317. result := tx.FirstOrCreate(s, s)
  318. if result.Error != nil {
  319. return errors.Wrap(result.Error, "upsert")
  320. } else if result.RowsAffected <= 0 {
  321. return nil // Relation already exists
  322. }
  323. return db.recountStars(tx, userID, repoID)
  324. })
  325. }
  326. func (db *repos) Touch(ctx context.Context, id int64) error {
  327. return db.WithContext(ctx).
  328. Model(new(Repository)).
  329. Where("id = ?", id).
  330. Updates(map[string]any{
  331. "is_bare": false,
  332. "updated_unix": db.NowFunc().Unix(),
  333. }).
  334. Error
  335. }
  336. func (db *repos) ListWatches(ctx context.Context, repoID int64) ([]*Watch, error) {
  337. var watches []*Watch
  338. return watches, db.WithContext(ctx).Where("repo_id = ?", repoID).Find(&watches).Error
  339. }
  340. func (db *repos) recountWatches(tx *gorm.DB, repoID int64) error {
  341. /*
  342. Equivalent SQL for PostgreSQL:
  343. UPDATE repository
  344. SET num_watches = (
  345. SELECT COUNT(*) FROM watch WHERE repo_id = @repoID
  346. )
  347. WHERE id = @repoID
  348. */
  349. return tx.Model(&Repository{}).
  350. Where("id = ?", repoID).
  351. Update(
  352. "num_watches",
  353. tx.Model(&Watch{}).Select("COUNT(*)").Where("repo_id = ?", repoID),
  354. ).
  355. Error
  356. }
  357. func (db *repos) Watch(ctx context.Context, userID, repoID int64) error {
  358. return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
  359. w := &Watch{
  360. UserID: userID,
  361. RepoID: repoID,
  362. }
  363. result := tx.FirstOrCreate(w, w)
  364. if result.Error != nil {
  365. return errors.Wrap(result.Error, "upsert")
  366. } else if result.RowsAffected <= 0 {
  367. return nil // Relation already exists
  368. }
  369. return db.recountWatches(tx, repoID)
  370. })
  371. }
  372. func (db *repos) HasForkedBy(ctx context.Context, repoID, userID int64) bool {
  373. var count int64
  374. db.WithContext(ctx).Model(new(Repository)).Where("owner_id = ? AND fork_id = ?", userID, repoID).Count(&count)
  375. return count > 0
  376. }