gorm目录文件如下:
主要文件是callback main scope search field dialect(.go)这几个文件
- callback.go
type Callback struct
包含所有CRUD的回调函数, DefaultCallback是gorm框架用的回调变量 - association.go
type Association struct
包含很多与关系相关的帮助函数. 如Association::Find
,Association::Append
等- 具体用法见gorm教程的"关联"部分
- dialect.go
type Dialect interface
包含一些数据库相关的操作, 不同的数据库(mysql, sqlite, postgress)的具体实现不同 - error.go 用var定义了一些error
另外定义了var ( // ErrRecordNotFound returns a "record not found error". Occurs only when attempting to query the database with a struct; querying with a slice won't return this error ErrRecordNotFound = errors.New("record not found") ... )
type Errors []error
, 且实现了Error接口,让其可以像Error一样使用. - field.go
type Field struct
// Field model field definition type Field struct { *StructField IsBlank bool Field reflect.Value }
- interface.go 定义了SQLCommon, sqlDb, sqlTx三个接口
- logger.go 最关键定义了
type Logger struct
:func (logger Logger) Print(values ...interface{}) { logger.Println(LogFormatter(values...)...) }
- main.go 主要定义了DB
- model.go 主要定义了
type Model struct
:// Model base model definition, including fields `ID`, `CreatedAt`, `UpdatedAt`, `DeletedAt`, which could be embedded in your models // type User struct { // gorm.Model // } type Model struct { ID uint `gorm:"primary_key"` CreatedAt time.Time UpdatedAt time.Time DeletedAt *time.Time `sql:"index"` }
- model_struct.go 定义了ModelStruct, StructField, Relationship三个struct, 并为Scope定义了两个成员函数(为何要在这定义). 你在实体struct中编写tag后,就会被解析到这三个类中.
- naming.go 定义了Namer函数和NamingStrategy结构体,NamingStrategy定义了数据库、表、列的命名方式(都是驼峰转下划线)
// Namer is a function type which is given a string and return a string type Namer func(string) string // NamingStrategy represents naming strategies type NamingStrategy struct { DB Namer Table Namer Column Namer } // TheNamingStrategy is being initialized with defaultNamingStrategy var TheNamingStrategy = &NamingStrategy{ DB: defaultNamer, Table: defaultNamer, Column: defaultNamer, }
- scope.go
type Scope struct
包含了当前你要操作的各种操作 - search.go 包含了搜索条件
- utils.go 放了很多工具函数