repositories.go 10 KB

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