package sql 中最核心的的数据结构是sql.DB, 其为上层应用程序提供一个统一的抽象体,它不代表一个数据库连接,也不代表一个连接池,其是sql的包的作者为了实现:并发访问安全控制,连接池等诸多功能而设计的一个综合抽象数据结构。具体见代码注释
221 type DB struct {
#通过driverName获取driver,通过driver的Open()方法获得到DB的原始连接,sql.Open() 创建一个DB实例
222 driver driver.Driver
#DB连接字符串,创建DB实例不会理解创建连接,只有使用的时候才去创建连接
223 dsn string
224 // numClosed is an atomic counter which represents a total number of
225 // closed connections. Stmt.openStmt checks it before cleaning closed
226 // connections in Stmt.css.
#启动以来关闭的连接数
227 numClosed uint64
228
229 mu sync.Mutex // protects following fields
#空闲连接池,使用后的连接立马放到连接池中
230 freeConn []*driverConn
#当db.numOpen >= db.maxOpen时,排队等待创建的连接都会添加到改数据结构中
231 connRequests []chan connRequest
#当前打开的连接数
232 numOpen int
#当前等待创建的连接数,len(connRequests)和pendingOpens区别是:一个是等待排队连接,还没有获得创建连接的资格,一个是已经拿到资格准备创建
233 pendingOpens int
234 // Used to signal the need for new connections
235 // a goroutine running connectionOpener() reads on this chan and
236 // maybeOpenNewConnections sends on the chan (one send per needed connection)
237 // It is closed during db.Close(). The close tells the connectionOpener
238 // goroutine to exit.
#等待database 启动一个独立的goroutine创建连接所需连接,将创建的连接直接发到connRequests chan中或者放到空闲连接池
239 openerCh chan struct{}
#关闭状态
240 closed bool
#依赖关系维护,用户维护DB和其他数据结构的依赖关系,由于数据结构之间存在相互引用和依赖以及复用,在清理关闭资源时必须把依赖关系给释放掉
241 dep map[finalCloser]depSet
242 lastPut map[*driverConn]string // stacktrace of last conn's put; debug only
#最大的空闲连接数
243 maxIdle int // zero means defaultMaxIdleConns; negative means 0
#最大连接数,0表示不受限制
244 maxOpen int // <= 0 means unlimited
245 }