You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.5 KiB

  1. // Copyright 2019 The Gitea 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 models
  5. import (
  6. "code.gitea.io/gitea/modules/setting"
  7. "xorm.io/builder"
  8. )
  9. // DBContext represents a db context
  10. type DBContext struct {
  11. e Engine
  12. }
  13. // DefaultDBContext represents a DBContext with default Engine
  14. func DefaultDBContext() DBContext {
  15. return DBContext{x}
  16. }
  17. // Committer represents an interface to Commit or Close the dbcontext
  18. type Committer interface {
  19. Commit() error
  20. Close()
  21. }
  22. // TxDBContext represents a transaction DBContext
  23. func TxDBContext() (DBContext, Committer, error) {
  24. sess := x.NewSession()
  25. if err := sess.Begin(); err != nil {
  26. sess.Close()
  27. return DBContext{}, nil, err
  28. }
  29. return DBContext{sess}, sess, nil
  30. }
  31. // WithContext represents executing database operations
  32. func WithContext(f func(ctx DBContext) error) error {
  33. return f(DBContext{x})
  34. }
  35. // WithTx represents executing database operations on a trasaction
  36. func WithTx(f func(ctx DBContext) error) error {
  37. sess := x.NewSession()
  38. if err := sess.Begin(); err != nil {
  39. sess.Close()
  40. return err
  41. }
  42. if err := f(DBContext{sess}); err != nil {
  43. sess.Close()
  44. return err
  45. }
  46. err := sess.Commit()
  47. sess.Close()
  48. return err
  49. }
  50. // Iterate iterates the databases and doing something
  51. func Iterate(ctx DBContext, tableBean interface{}, cond builder.Cond, fun func(idx int, bean interface{}) error) error {
  52. return ctx.e.Where(cond).
  53. BufferSize(setting.Database.IterateBufferSize).
  54. Iterate(tableBean, fun)
  55. }