1
0

repositories.go 11 KB

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