gorm 源码解析
gorm 使用示例
1  | package main  | 
gorm 一般的初始化方式
1  | db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local")  | 
gorm 中 DB 结构体的定义:
1  | // DB的结构体  | 
SQLCommon 定义基本的查询接口
1  | // SQLCommon is the minimal database connection functionality gorm requires. Implemented by *sql.DB.  | 
gorm 的 Open 方法:
1  | func Open(dialect string, args ...interface{}) (db *DB, err error) {  | 
gorm 是通过多个 callbsck 方法来实现 curd 的,具体流程以一个查询为例:
1  | DBEngine.Table(entry.TableName).  | 
执行步骤:
1.执行 Table 方法,添加 tablename 条件:
1  | func (s *DB) Table(name string) *DB {  | 
2.执行 Where 方法,添加 where 条件:
1  | // 首先也是调用clone方法,然后调用search的Where方法  | 
3.执行 Order 方法,添加 order 条件:
1  | // 类似Where,reorder为true会强制刷掉gorm默认的order by  | 
4.执行 Find 方法,真正实现查询:
1  | // 首先先创建一个scope(可以理解成只针对本次数据库操作有效的一个环境),再调用inlineCondition内部方法,最后执行callcallbacks一系列方法实现真正的查询操作,并将db返回  |