sharding
sharding copied to clipboard
替换sql, 让日志中记录真实执行的sql
Describe the feature
替换原sql, gorm 追踪记录新的sql内容
Motivation
希望执行分表后生成新的sql记录到日志中,而不是原来的sql。
Related Issues
conn_pool.go
type ConnPool struct {
// db, This is global db instance
sharding *Sharding
gorm.ConnPool
currentDB *gorm.DB // 记录当前的db实例
}
func (pool ConnPool) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) {
// ....
pool.sharding.querys.Store("last_query", stQuery)
// 重置sql
oldSqlCap := pool.currentDB.Statement.SQL.Cap()
pool.currentDB.Statement.SQL.Reset()
pool.currentDB.Statement.SQL.Grow(oldSqlCap + 5)
pool.currentDB.Statement.SQL.WriteString(stQuery)
// ...
}
func (pool ConnPool) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) {
// ...
pool.sharding.querys.Store("last_query", stQuery)
// 重置sql
oldSqlCap := pool.currentDB.Statement.SQL.Cap()
pool.currentDB.Statement.SQL.Reset()
pool.currentDB.Statement.SQL.Grow(oldSqlCap + 5)
pool.currentDB.Statement.SQL.WriteString(stQuery)
// ...
}
sharding.go
func (s *Sharding) switchConn(db *gorm.DB) {
// Support ignore sharding in some case, like:
// When DoubleWrite is enabled, we need to query database schema
// information by table name during the migration.
if _, ok := db.Get(ShardingIgnoreStoreKey); !ok {
s.ConnPool = &ConnPool{ConnPool: db.Statement.ConnPool, sharding: s, currentDB: db} // 记录当前的db实例
db.Statement.ConnPool = s.ConnPool
}
}