2019-09-24 10:32:49 +05:30
|
|
|
// Copyright 2019 The Gitea Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a MIT-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package models
|
|
|
|
|
2020-01-21 01:31:19 +05:30
|
|
|
import (
|
|
|
|
"code.gitea.io/gitea/modules/setting"
|
|
|
|
|
|
|
|
"xorm.io/builder"
|
|
|
|
)
|
|
|
|
|
2019-09-24 10:32:49 +05:30
|
|
|
// DBContext represents a db context
|
|
|
|
type DBContext struct {
|
|
|
|
e Engine
|
|
|
|
}
|
|
|
|
|
|
|
|
// DefaultDBContext represents a DBContext with default Engine
|
|
|
|
func DefaultDBContext() DBContext {
|
|
|
|
return DBContext{x}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Committer represents an interface to Commit or Close the dbcontext
|
|
|
|
type Committer interface {
|
|
|
|
Commit() error
|
2020-06-16 02:16:01 +05:30
|
|
|
Close() error
|
2019-09-24 10:32:49 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
// TxDBContext represents a transaction DBContext
|
|
|
|
func TxDBContext() (DBContext, Committer, error) {
|
|
|
|
sess := x.NewSession()
|
|
|
|
if err := sess.Begin(); err != nil {
|
|
|
|
sess.Close()
|
|
|
|
return DBContext{}, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return DBContext{sess}, sess, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// WithContext represents executing database operations
|
|
|
|
func WithContext(f func(ctx DBContext) error) error {
|
|
|
|
return f(DBContext{x})
|
|
|
|
}
|
|
|
|
|
2021-07-08 17:08:13 +05:30
|
|
|
// WithTx represents executing database operations on a transaction
|
2019-09-24 10:32:49 +05:30
|
|
|
func WithTx(f func(ctx DBContext) error) error {
|
|
|
|
sess := x.NewSession()
|
|
|
|
if err := sess.Begin(); err != nil {
|
|
|
|
sess.Close()
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := f(DBContext{sess}); err != nil {
|
|
|
|
sess.Close()
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
err := sess.Commit()
|
|
|
|
sess.Close()
|
|
|
|
return err
|
|
|
|
}
|
2020-01-21 01:31:19 +05:30
|
|
|
|
|
|
|
// Iterate iterates the databases and doing something
|
|
|
|
func Iterate(ctx DBContext, tableBean interface{}, cond builder.Cond, fun func(idx int, bean interface{}) error) error {
|
|
|
|
return ctx.e.Where(cond).
|
|
|
|
BufferSize(setting.Database.IterateBufferSize).
|
|
|
|
Iterate(tableBean, fun)
|
|
|
|
}
|
2021-09-08 20:49:30 +05:30
|
|
|
|
|
|
|
// Insert inserts records into database
|
|
|
|
func Insert(ctx DBContext, beans ...interface{}) error {
|
|
|
|
_, err := ctx.e.Insert(beans...)
|
|
|
|
return err
|
|
|
|
}
|