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.

55 lines
1.2 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. // DBContext represents a db context
  6. type DBContext struct {
  7. e Engine
  8. }
  9. // DefaultDBContext represents a DBContext with default Engine
  10. func DefaultDBContext() DBContext {
  11. return DBContext{x}
  12. }
  13. // Committer represents an interface to Commit or Close the dbcontext
  14. type Committer interface {
  15. Commit() error
  16. Close()
  17. }
  18. // TxDBContext represents a transaction DBContext
  19. func TxDBContext() (DBContext, Committer, error) {
  20. sess := x.NewSession()
  21. if err := sess.Begin(); err != nil {
  22. sess.Close()
  23. return DBContext{}, nil, err
  24. }
  25. return DBContext{sess}, sess, nil
  26. }
  27. // WithContext represents executing database operations
  28. func WithContext(f func(ctx DBContext) error) error {
  29. return f(DBContext{x})
  30. }
  31. // WithTx represents executing database operations on a trasaction
  32. func WithTx(f func(ctx DBContext) error) error {
  33. sess := x.NewSession()
  34. if err := sess.Begin(); err != nil {
  35. sess.Close()
  36. return err
  37. }
  38. if err := f(DBContext{sess}); err != nil {
  39. sess.Close()
  40. return err
  41. }
  42. err := sess.Commit()
  43. sess.Close()
  44. return err
  45. }