123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817 |
- package gorm
- import (
- "context"
- "database/sql"
- "errors"
- "fmt"
- "reflect"
- "strings"
- "sync"
- "time"
- )
- type DB struct {
- Value interface{}
- Error error
- RowsAffected int64
-
- db SQLCommon
- blockGlobalUpdate bool
- logMode logModeValue
- logger logger
- search *search
- values sync.Map
-
- parent *DB
- callbacks *Callback
- dialect Dialect
- singularTable bool
- }
- type logModeValue int
- const (
- defaultLogMode logModeValue = iota
- noLogMode
- detailedLogMode
- )
- func Open(dialect string, args ...interface{}) (db *DB, err error) {
- if len(args) == 0 {
- err = errors.New("invalid database source")
- return nil, err
- }
- var source string
- var dbSQL SQLCommon
- var ownDbSQL bool
- switch value := args[0].(type) {
- case string:
- var driver = dialect
- if len(args) == 1 {
- source = value
- } else if len(args) >= 2 {
- driver = value
- source = args[1].(string)
- }
- dbSQL, err = sql.Open(driver, source)
- ownDbSQL = true
- case SQLCommon:
- dbSQL = value
- ownDbSQL = false
- default:
- return nil, fmt.Errorf("invalid database source: %v is not a valid type", value)
- }
- db = &DB{
- db: dbSQL,
- logger: defaultLogger,
- callbacks: DefaultCallback,
- dialect: newDialect(dialect, dbSQL),
- }
- db.parent = db
- if err != nil {
- return
- }
-
- if d, ok := dbSQL.(*sql.DB); ok {
- if err = d.Ping(); err != nil && ownDbSQL {
- d.Close()
- }
- }
- return
- }
- func (s *DB) New() *DB {
- clone := s.clone()
- clone.search = nil
- clone.Value = nil
- return clone
- }
- type closer interface {
- Close() error
- }
- func (s *DB) Close() error {
- if db, ok := s.parent.db.(closer); ok {
- return db.Close()
- }
- return errors.New("can't close current db")
- }
- func (s *DB) DB() *sql.DB {
- db, _ := s.db.(*sql.DB)
- return db
- }
- func (s *DB) CommonDB() SQLCommon {
- return s.db
- }
- func (s *DB) Dialect() Dialect {
- return s.dialect
- }
- func (s *DB) Callback() *Callback {
- s.parent.callbacks = s.parent.callbacks.clone()
- return s.parent.callbacks
- }
- func (s *DB) SetLogger(log logger) {
- s.logger = log
- }
- func (s *DB) LogMode(enable bool) *DB {
- if enable {
- s.logMode = detailedLogMode
- } else {
- s.logMode = noLogMode
- }
- return s
- }
- func (s *DB) BlockGlobalUpdate(enable bool) *DB {
- s.blockGlobalUpdate = enable
- return s
- }
- func (s *DB) HasBlockGlobalUpdate() bool {
- return s.blockGlobalUpdate
- }
- func (s *DB) SingularTable(enable bool) {
- modelStructsMap = sync.Map{}
- s.parent.singularTable = enable
- }
- func (s *DB) NewScope(value interface{}) *Scope {
- dbClone := s.clone()
- dbClone.Value = value
- return &Scope{db: dbClone, Search: dbClone.search, Value: value}
- }
- func (s *DB) QueryExpr() *expr {
- scope := s.NewScope(s.Value)
- scope.InstanceSet("skip_bindvar", true)
- scope.prepareQuerySQL()
- return Expr(scope.SQL, scope.SQLVars...)
- }
- func (s *DB) SubQuery() *expr {
- scope := s.NewScope(s.Value)
- scope.InstanceSet("skip_bindvar", true)
- scope.prepareQuerySQL()
- return Expr(fmt.Sprintf("(%v)", scope.SQL), scope.SQLVars...)
- }
- func (s *DB) Where(query interface{}, args ...interface{}) *DB {
- return s.clone().search.Where(query, args...).db
- }
- func (s *DB) Ctx(ctx context.Context) *DB {
- return s.clone().search.Ctx(ctx).db
- }
- func (s *DB) Or(query interface{}, args ...interface{}) *DB {
- return s.clone().search.Or(query, args...).db
- }
- func (s *DB) Not(query interface{}, args ...interface{}) *DB {
- return s.clone().search.Not(query, args...).db
- }
- func (s *DB) Limit(limit interface{}) *DB {
- return s.clone().search.Limit(limit).db
- }
- func (s *DB) Offset(offset interface{}) *DB {
- return s.clone().search.Offset(offset).db
- }
- func (s *DB) Order(value interface{}, reorder ...bool) *DB {
- return s.clone().search.Order(value, reorder...).db
- }
- func (s *DB) Select(query interface{}, args ...interface{}) *DB {
- return s.clone().search.Select(query, args...).db
- }
- func (s *DB) Omit(columns ...string) *DB {
- return s.clone().search.Omit(columns...).db
- }
- func (s *DB) Group(query string) *DB {
- return s.clone().search.Group(query).db
- }
- func (s *DB) Having(query interface{}, values ...interface{}) *DB {
- return s.clone().search.Having(query, values...).db
- }
- func (s *DB) Joins(query string, args ...interface{}) *DB {
- return s.clone().search.Joins(query, args...).db
- }
- func (s *DB) Scopes(funcs ...func(*DB) *DB) *DB {
- for _, f := range funcs {
- s = f(s)
- }
- return s
- }
- func (s *DB) Unscoped() *DB {
- return s.clone().search.unscoped().db
- }
- func (s *DB) Attrs(attrs ...interface{}) *DB {
- return s.clone().search.Attrs(attrs...).db
- }
- func (s *DB) Assign(attrs ...interface{}) *DB {
- return s.clone().search.Assign(attrs...).db
- }
- func (s *DB) First(out interface{}, where ...interface{}) *DB {
- newScope := s.NewScope(out)
- newScope.Search.Limit(1)
- return newScope.Set("gorm:order_by_primary_key", "ASC").
- inlineCondition(where...).callCallbacks(s.parent.callbacks.queries).db
- }
- func (s *DB) Take(out interface{}, where ...interface{}) *DB {
- newScope := s.NewScope(out)
- newScope.Search.Limit(1)
- return newScope.inlineCondition(where...).callCallbacks(s.parent.callbacks.queries).db
- }
- func (s *DB) Last(out interface{}, where ...interface{}) *DB {
- newScope := s.NewScope(out)
- newScope.Search.Limit(1)
- return newScope.Set("gorm:order_by_primary_key", "DESC").
- inlineCondition(where...).callCallbacks(s.parent.callbacks.queries).db
- }
- func (s *DB) Find(out interface{}, where ...interface{}) *DB {
- return s.NewScope(out).inlineCondition(where...).callCallbacks(s.parent.callbacks.queries).db
- }
- func (s *DB) Preloads(out interface{}) *DB {
- return s.NewScope(out).InstanceSet("gorm:only_preload", 1).callCallbacks(s.parent.callbacks.queries).db
- }
- func (s *DB) Scan(dest interface{}) *DB {
- return s.NewScope(s.Value).Set("gorm:query_destination", dest).callCallbacks(s.parent.callbacks.queries).db
- }
- func (s *DB) Row() *sql.Row {
- return s.NewScope(s.Value).row()
- }
- func (s *DB) Rows() (*sql.Rows, error) {
- return s.NewScope(s.Value).rows()
- }
- func (s *DB) ScanRows(rows *sql.Rows, result interface{}) error {
- var (
- scope = s.NewScope(result)
- clone = scope.db
- columns, err = rows.Columns()
- )
- if clone.AddError(err) == nil {
- scope.scan(rows, columns, scope.Fields())
- }
- return clone.Error
- }
- func (s *DB) Pluck(column string, value interface{}) *DB {
- return s.NewScope(s.Value).pluck(column, value).db
- }
- func (s *DB) Count(value interface{}) *DB {
- return s.NewScope(s.Value).count(value).db
- }
- func (s *DB) Related(value interface{}, foreignKeys ...string) *DB {
- return s.NewScope(s.Value).related(value, foreignKeys...).db
- }
- func (s *DB) FirstOrInit(out interface{}, where ...interface{}) *DB {
- c := s.clone()
- if result := c.First(out, where...); result.Error != nil {
- if !result.RecordNotFound() {
- return result
- }
- c.NewScope(out).inlineCondition(where...).initialize()
- } else {
- c.NewScope(out).updatedAttrsWithValues(c.search.assignAttrs)
- }
- return c
- }
- func (s *DB) FirstOrCreate(out interface{}, where ...interface{}) *DB {
- c := s.clone()
- if result := s.First(out, where...); result.Error != nil {
- if !result.RecordNotFound() {
- return result
- }
- return c.NewScope(out).inlineCondition(where...).initialize().callCallbacks(c.parent.callbacks.creates).db
- } else if len(c.search.assignAttrs) > 0 {
- return c.NewScope(out).InstanceSet("gorm:update_interface", c.search.assignAttrs).callCallbacks(c.parent.callbacks.updates).db
- }
- return c
- }
- func (s *DB) Update(attrs ...interface{}) *DB {
- return s.Updates(toSearchableMap(attrs...), true)
- }
- func (s *DB) Updates(values interface{}, ignoreProtectedAttrs ...bool) *DB {
- return s.NewScope(s.Value).
- Set("gorm:ignore_protected_attrs", len(ignoreProtectedAttrs) > 0).
- InstanceSet("gorm:update_interface", values).
- callCallbacks(s.parent.callbacks.updates).db
- }
- func (s *DB) UpdateColumn(attrs ...interface{}) *DB {
- return s.UpdateColumns(toSearchableMap(attrs...))
- }
- func (s *DB) UpdateColumns(values interface{}) *DB {
- return s.NewScope(s.Value).
- Set("gorm:update_column", true).
- Set("gorm:save_associations", false).
- InstanceSet("gorm:update_interface", values).
- callCallbacks(s.parent.callbacks.updates).db
- }
- func (s *DB) Save(value interface{}) *DB {
- scope := s.NewScope(value)
- if !scope.PrimaryKeyZero() {
- newDB := scope.callCallbacks(s.parent.callbacks.updates).db
- if newDB.Error == nil && newDB.RowsAffected == 0 {
- return s.New().FirstOrCreate(value)
- }
- return newDB
- }
- return scope.callCallbacks(s.parent.callbacks.creates).db
- }
- func (s *DB) Create(value interface{}) *DB {
- scope := s.NewScope(value)
- return scope.callCallbacks(s.parent.callbacks.creates).db
- }
- func (s *DB) Delete(value interface{}, where ...interface{}) *DB {
- return s.NewScope(value).inlineCondition(where...).callCallbacks(s.parent.callbacks.deletes).db
- }
- func (s *DB) Raw(sql string, values ...interface{}) *DB {
- return s.clone().search.Raw(true).Where(sql, values...).db
- }
- func (s *DB) Exec(sql string, values ...interface{}) *DB {
- scope := s.NewScope(nil)
- generatedSQL := scope.buildCondition(map[string]interface{}{"query": sql, "args": values}, true)
- generatedSQL = strings.TrimSuffix(strings.TrimPrefix(generatedSQL, "("), ")")
- scope.Raw(generatedSQL)
- return scope.Exec().db
- }
- func (s *DB) Model(value interface{}) *DB {
- c := s.clone()
- c.Value = value
- return c
- }
- func (s *DB) Table(name string) *DB {
- clone := s.clone()
- clone.search.Table(name)
- clone.Value = nil
- return clone
- }
- func (s *DB) Debug() *DB {
- return s.clone().LogMode(true)
- }
- func (s *DB) Begin() *DB {
- c := s.clone()
- if db, ok := c.db.(sqlDb); ok && db != nil {
- tx, err := db.Begin()
- c.db = interface{}(tx).(SQLCommon)
- c.dialect.SetDB(c.db)
- c.AddError(err)
- } else {
- c.AddError(ErrCantStartTransaction)
- }
- return c
- }
- func (s *DB) Commit() *DB {
- var emptySQLTx *sql.Tx
- if db, ok := s.db.(sqlTx); ok && db != nil && db != emptySQLTx {
- s.AddError(db.Commit())
- } else {
- s.AddError(ErrInvalidTransaction)
- }
- return s
- }
- func (s *DB) Rollback() *DB {
- var emptySQLTx *sql.Tx
- if db, ok := s.db.(sqlTx); ok && db != nil && db != emptySQLTx {
- s.AddError(db.Rollback())
- } else {
- s.AddError(ErrInvalidTransaction)
- }
- return s
- }
- func (s *DB) NewRecord(value interface{}) bool {
- return s.NewScope(value).PrimaryKeyZero()
- }
- func (s *DB) RecordNotFound() bool {
- for _, err := range s.GetErrors() {
- if err == ErrRecordNotFound {
- return true
- }
- }
- return false
- }
- func (s *DB) CreateTable(models ...interface{}) *DB {
- db := s.Unscoped()
- for _, model := range models {
- db = db.NewScope(model).createTable().db
- }
- return db
- }
- func (s *DB) DropTable(values ...interface{}) *DB {
- db := s.clone()
- for _, value := range values {
- if tableName, ok := value.(string); ok {
- db = db.Table(tableName)
- }
- db = db.NewScope(value).dropTable().db
- }
- return db
- }
- func (s *DB) DropTableIfExists(values ...interface{}) *DB {
- db := s.clone()
- for _, value := range values {
- if s.HasTable(value) {
- db.AddError(s.DropTable(value).Error)
- }
- }
- return db
- }
- func (s *DB) HasTable(value interface{}) bool {
- var (
- scope = s.NewScope(value)
- tableName string
- )
- if name, ok := value.(string); ok {
- tableName = name
- } else {
- tableName = scope.TableName()
- }
- has := scope.Dialect().HasTable(tableName)
- s.AddError(scope.db.Error)
- return has
- }
- func (s *DB) AutoMigrate(values ...interface{}) *DB {
- db := s.Unscoped()
- for _, value := range values {
- db = db.NewScope(value).autoMigrate().db
- }
- return db
- }
- func (s *DB) ModifyColumn(column string, typ string) *DB {
- scope := s.NewScope(s.Value)
- scope.modifyColumn(column, typ)
- return scope.db
- }
- func (s *DB) DropColumn(column string) *DB {
- scope := s.NewScope(s.Value)
- scope.dropColumn(column)
- return scope.db
- }
- func (s *DB) AddIndex(indexName string, columns ...string) *DB {
- scope := s.Unscoped().NewScope(s.Value)
- scope.addIndex(false, indexName, columns...)
- return scope.db
- }
- func (s *DB) AddUniqueIndex(indexName string, columns ...string) *DB {
- scope := s.Unscoped().NewScope(s.Value)
- scope.addIndex(true, indexName, columns...)
- return scope.db
- }
- func (s *DB) RemoveIndex(indexName string) *DB {
- scope := s.NewScope(s.Value)
- scope.removeIndex(indexName)
- return scope.db
- }
- func (s *DB) AddForeignKey(field string, dest string, onDelete string, onUpdate string) *DB {
- scope := s.NewScope(s.Value)
- scope.addForeignKey(field, dest, onDelete, onUpdate)
- return scope.db
- }
- func (s *DB) RemoveForeignKey(field string, dest string) *DB {
- scope := s.clone().NewScope(s.Value)
- scope.removeForeignKey(field, dest)
- return scope.db
- }
- func (s *DB) Association(column string) *Association {
- var err error
- var scope = s.Set("gorm:association:source", s.Value).NewScope(s.Value)
- if primaryField := scope.PrimaryField(); primaryField.IsBlank {
- err = errors.New("primary key can't be nil")
- } else {
- if field, ok := scope.FieldByName(column); ok {
- if field.Relationship == nil || len(field.Relationship.ForeignFieldNames) == 0 {
- err = fmt.Errorf("invalid association %v for %v", column, scope.IndirectValue().Type())
- } else {
- return &Association{scope: scope, column: column, field: field}
- }
- } else {
- err = fmt.Errorf("%v doesn't have column %v", scope.IndirectValue().Type(), column)
- }
- }
- return &Association{Error: err}
- }
- func (s *DB) Preload(column string, conditions ...interface{}) *DB {
- return s.clone().search.Preload(column, conditions...).db
- }
- func (s *DB) Set(name string, value interface{}) *DB {
- return s.clone().InstantSet(name, value)
- }
- func (s *DB) InstantSet(name string, value interface{}) *DB {
- s.values.Store(name, value)
- return s
- }
- func (s *DB) Get(name string) (value interface{}, ok bool) {
- value, ok = s.values.Load(name)
- return
- }
- func (s *DB) SetJoinTableHandler(source interface{}, column string, handler JoinTableHandlerInterface) {
- scope := s.NewScope(source)
- for _, field := range scope.GetModelStruct().StructFields {
- if field.Name == column || field.DBName == column {
- if many2many, _ := field.TagSettingsGet("MANY2MANY"); many2many != "" {
- source := (&Scope{Value: source}).GetModelStruct().ModelType
- destination := (&Scope{Value: reflect.New(field.Struct.Type).Interface()}).GetModelStruct().ModelType
- handler.Setup(field.Relationship, many2many, source, destination)
- field.Relationship.JoinTableHandler = handler
- if table := handler.Table(s); scope.Dialect().HasTable(table) {
- s.Table(table).AutoMigrate(handler)
- }
- }
- }
- }
- }
- func (s *DB) AddError(err error) error {
- if err != nil {
- if err != ErrRecordNotFound {
- if s.logMode == defaultLogMode {
- go s.print(fileWithLineNum(), err)
- } else {
- s.log(err)
- }
- errors := Errors(s.GetErrors())
- errors = errors.Add(err)
- if len(errors) > 1 {
- err = errors
- }
- }
- s.Error = err
- }
- return err
- }
- func (s *DB) GetErrors() []error {
- if errs, ok := s.Error.(Errors); ok {
- return errs
- } else if s.Error != nil {
- return []error{s.Error}
- }
- return []error{}
- }
- func (s *DB) clone() *DB {
- db := &DB{
- db: s.db,
- parent: s.parent,
- logger: s.logger,
- logMode: s.logMode,
- Value: s.Value,
- Error: s.Error,
- blockGlobalUpdate: s.blockGlobalUpdate,
- dialect: newDialect(s.dialect.GetName(), s.db),
- }
- s.values.Range(func(k, v interface{}) bool {
- db.values.Store(k, v)
- return true
- })
- if s.search == nil {
- db.search = &search{limit: -1, offset: -1}
- } else {
- db.search = s.search.clone()
- }
- db.search.db = db
- return db
- }
- func (s *DB) print(v ...interface{}) {
- s.logger.Print(v...)
- }
- func (s *DB) log(v ...interface{}) {
- if s.logMode == detailedLogMode {
- if s.search.ctx == nil {
- s.print("log", nil, fileWithLineNum(), v)
- } else if reflect.ValueOf(s.search.ctx).IsNil() {
- s.print("log", nil, fileWithLineNum(), v)
- } else {
- s.print("log", s.search.ctx, fileWithLineNum(), v)
- }
- }
- }
- func (s *DB) slog(sql string, t time.Time, vars ...interface{}) {
- if s.logMode == detailedLogMode {
- if s.search.ctx == nil {
- s.print("sql", fileWithLineNum(), NowFunc().Sub(t), sql, vars, s.RowsAffected)
- } else if reflect.ValueOf(s.search.ctx).IsNil() {
- s.print("sql", fileWithLineNum(), NowFunc().Sub(t), sql, vars, s.RowsAffected)
- } else if s.search.ctx.Value("NOLOGFlAG") != true {
- s.print("sql", fileWithLineNum(), NowFunc().Sub(t), sql, vars, s.RowsAffected, s.search.ctx)
- }
- }
- }
|