gorm 阅读3

发布时间 2023-12-20 22:22:27作者: codestacklinuxer

gorm 相互关联

// Config GORM config
type Config struct {
    ----------
	Dialector
    --------
	callbacks  *callbacks
	cacheStore *sync.Map
}
// DB GORM DB definition
type DB struct {
	*Config
	Error        error
	RowsAffected int64
	Statement    *Statement
	clone        int
}

DB的Dialector 实现了AutoMigrate 接口

type Migrator struct {
	migrator.Migrator
}


// Migrator m struct
type Migrator struct {
	Config
}

// Config schema config
type Config struct {
	CreateIndexAfterCreateTable bool
	DB                          *gorm.DB
	gorm.Dialector
}

// AutoMigrate auto migrate values
func (m Migrator) AutoMigrate(values ...interface{})

//对于Statement  其存储在 cacheStore *sync.Map 

/*

创建表时:err := execTx.Migrator().CreateTable(value)
var execTx *gorm.DB  
execTx.Migrator()--->返回的tx.Dialector.Migratory 也就是返回Config --->Migrator 

此时execTx.Migrator().CreateTable(value)--->Migrator.CreateTable(value)
根据value在 stmt.DB.cacheStore.Load(schemaCacheKey) 

根据value 查找schema 结合db 赋值给stmt   statement


// Statement statement
type Statement struct {
	*DB
	TableExpr            *clause.Expr
	Table                string
	Model                interface{}
	Unscoped             bool
	Dest                 interface{}
	ReflectValue         reflect.Value
	Clauses              map[string]clause.Clause
	BuildClauses         []string
	Distinct             bool
	Selects              []string // selected columns
	Omits                []string // omit columns
	Joins                []join
	Preloads             map[string][]interface{}
	Settings             sync.Map
	ConnPool             ConnPool
	Schema               *schema.Schema
	Context              context.Context
	RaiseErrorOnNotFound bool
	SkipHooks            bool
	SQL                  strings.Builder
	Vars                 []interface{}
	CurDestIndex         int
	attrs                []interface{}
	assigns              []interface{}
	scopes               []func(*DB) *DB
}