This commit is contained in:
jesusjjf
2015-04-01 20:06:39 -07:00
committed by James Miranda
parent 033c0582de
commit 7fda55b543

View File

@@ -12,7 +12,7 @@ Let's take a look at the corresponding mymysql and sqlite3 driver code:
func init() {
sql.Register("sqlite3", &SQLiteDriver{})
}
//https://github.com/mikespook/mymysql driver
// Driver automatically registered in database/sql
var d = Driver{proto: "tcp", raddr: "127.0.0.1:3306"}
@@ -21,10 +21,10 @@ Let's take a look at the corresponding mymysql and sqlite3 driver code:
sql.Register("mymysql", &d)
}
We see that all third-party database drivers have implemented this function to register themselves, and Go uses a map to save user drivers inside of `databse/sql`.
We see that all third-party database drivers have implemented this function to register themselves, and Go uses a map to save user drivers inside of `database/sql`.
var drivers = make(map[string]driver.Driver)
drivers[name] = driver
Therefore, this register function can register drivers as many as you want with different names.
@@ -40,8 +40,8 @@ Here the underscore (also known as a 'blank') `_` can be quite confusing for man
## driver.Driver
`Driver` is an interface containing an `Open(name string)` method that returns a `Conn` interface.
`Driver` is an interface containing an `Open(name string)` method that returns a `Conn` interface.
type Driver interface {
Open(name string) (Conn, error)
}
@@ -137,9 +137,9 @@ This is the interface for the result of a query operation.
This is an alias of int64, but it implements the Result interface.
type RowsAffected int64
func (RowsAffected) LastInsertId() (int64, error)
func (v RowsAffected) RowsAffected() (int64, error)
## driver.Value
@@ -193,7 +193,7 @@ databse/sql defines even more high-level methods on top of database/sql/driver f
mu sync.Mutex // protects freeConn and closed
freeConn []driver.Conn
closed bool
}
}
As you can see, the `Open` function returns a DB that has a freeConn, and this is a simple connection pool. Its implementation is very simple and ugly. It uses `defer db.putConn(ci, err)` in the Db.prepare function to put a connection into the connection pool. Everytime you call the Conn function, it checks the length of freeCoon. If it's greater than 0, that means there is a reusable connection and it directly returns to you. Otherwise it creates a new connection and returns.