Add en/0.5.x.md syntax highlighting

This commit is contained in:
vCaesar
2017-05-14 15:56:32 +08:00
parent 606e950ea3
commit 76e5d0f3b4
2 changed files with 38 additions and 38 deletions

View File

@@ -7,7 +7,7 @@ Go doesn't provide any official database drivers, unlike other languages like PH
This function is in the `database/sql` package for registering database drivers when you use third-party database drivers. All of these should call the `Register(name string, driver driver.Driver)` function in `init()` in order to register themselves. This function is in the `database/sql` package for registering database drivers when you use third-party database drivers. All of these should call the `Register(name string, driver driver.Driver)` function in `init()` in order to register themselves.
Let's take a look at the corresponding mymysql and sqlite3 driver code: Let's take a look at the corresponding mymysql and sqlite3 driver code:
```Go
//https://github.com/mattn/go-sqlite3 driver //https://github.com/mattn/go-sqlite3 driver
func init() { func init() {
sql.Register("sqlite3", &SQLiteDriver{}) sql.Register("sqlite3", &SQLiteDriver{})
@@ -20,39 +20,39 @@ Let's take a look at the corresponding mymysql and sqlite3 driver code:
Register("SET NAMES utf8") Register("SET NAMES utf8")
sql.Register("mymysql", &d) sql.Register("mymysql", &d)
} }
```
We see that all third-party database drivers implement this function to register themselves, and Go uses a map to save user drivers inside of `database/sql`. We see that all third-party database drivers implement this function to register themselves, and Go uses a map to save user drivers inside of `database/sql`.
```Go
var drivers = make(map[string]driver.Driver) var drivers = make(map[string]driver.Driver)
drivers[name] = driver drivers[name] = driver
```
Therefore, this registration function can register as many drivers as you may require, each with different names. Therefore, this registration function can register as many drivers as you may require, each with different names.
We always see the following code when we use third-party drivers: We always see the following code when we use third-party drivers:
```Go
import ( import (
"database/sql" "database/sql"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
) )
```
Here, the underscore (also known as a 'blank') `_` can be quite confusing for many beginners, but this is a great feature in Go. We already know that this underscore identifier is used for discarding values from function returns, and also that you must use all packages that you've imported in your code in Go. So when the blank is used with import, it means that you need to execute the init() function of that package without directly using it, which is a perfect fit for the use-case of registering database drivers. Here, the underscore (also known as a 'blank') `_` can be quite confusing for many beginners, but this is a great feature in Go. We already know that this underscore identifier is used for discarding values from function returns, and also that you must use all packages that you've imported in your code in Go. So when the blank is used with import, it means that you need to execute the init() function of that package without directly using it, which is a perfect fit for the use-case of registering database drivers.
## driver.Driver ## 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.
```Go
type Driver interface { type Driver interface {
Open(name string) (Conn, error) Open(name string) (Conn, error)
} }
```
This is a one-time Conn, which means it can only be used once per goroutine. The following code will cause errors to occur: This is a one-time Conn, which means it can only be used once per goroutine. The following code will cause errors to occur:
```Go
... ...
go goroutineA (Conn) // query go goroutineA (Conn) // query
go goroutineB (Conn) // insert go goroutineB (Conn) // insert
... ...
```
Because Go has no idea which goroutine does which operation, the query operation may get the result of the insert operation, and vice-versa. Because Go has no idea which goroutine does which operation, the query operation may get the result of the insert operation, and vice-versa.
All third-party drivers should have this function to parse the name of Conn and return the correct results. All third-party drivers should have this function to parse the name of Conn and return the correct results.
@@ -60,13 +60,13 @@ All third-party drivers should have this function to parse the name of Conn and
## driver.Conn ## driver.Conn
This is a database connection interface with some methods, and as i've said above, the same Conn can only be used once per goroutine. This is a database connection interface with some methods, and as i've said above, the same Conn can only be used once per goroutine.
```Go
type Conn interface { type Conn interface {
Prepare(query string) (Stmt, error) Prepare(query string) (Stmt, error)
Close() error Close() error
Begin() (Tx, error) Begin() (Tx, error)
} }
```
- `Prepare` returns the prepare status of corresponding SQL commands for querying and deleting, etc. - `Prepare` returns the prepare status of corresponding SQL commands for querying and deleting, etc.
- `Close` closes the current connection and cleans resources. Most third-party drivers implement some kind of connection pool, so you don't need to cache connections which can cause unexpected errors. - `Close` closes the current connection and cleans resources. Most third-party drivers implement some kind of connection pool, so you don't need to cache connections which can cause unexpected errors.
- `Begin` returns a Tx that represents a transaction handle. You can use it for querying, updating, rolling back transactions, etc. - `Begin` returns a Tx that represents a transaction handle. You can use it for querying, updating, rolling back transactions, etc.
@@ -74,14 +74,14 @@ This is a database connection interface with some methods, and as i've said abov
## driver.Stmt ## driver.Stmt
This is a ready status that corresponds with Conn, so it can only be used once per goroutine (as is the case with Conn). This is a ready status that corresponds with Conn, so it can only be used once per goroutine (as is the case with Conn).
```Go
type Stmt interface { type Stmt interface {
Close() error Close() error
NumInput() int NumInput() int
Exec(args []Value) (Result, error) Exec(args []Value) (Result, error)
Query(args []Value) (Rows, error) Query(args []Value) (Rows, error)
} }
```
- `Close` closes the current connection but still returns row data if it is executing a query operation. - `Close` closes the current connection but still returns row data if it is executing a query operation.
- `NumInput` returns the number of obligate arguments. Database drivers should check their caller's arguments when the result is greater than 0, and it returns -1 when database drivers don't know any obligate argument. - `NumInput` returns the number of obligate arguments. Database drivers should check their caller's arguments when the result is greater than 0, and it returns -1 when database drivers don't know any obligate argument.
- `Exec` executes the `update/insert` SQL commands prepared in `Prepare`, returns `Result`. - `Exec` executes the `update/insert` SQL commands prepared in `Prepare`, returns `Result`.
@@ -90,44 +90,44 @@ This is a ready status that corresponds with Conn, so it can only be used once p
## driver.Tx ## driver.Tx
Generally, transaction handles only have submit or rollback methods, and database drivers only need to implement these two methods. Generally, transaction handles only have submit or rollback methods, and database drivers only need to implement these two methods.
```Go
type Tx interface { type Tx interface {
Commit() error Commit() error
Rollback() error Rollback() error
} }
```
## driver.Execer ## driver.Execer
This is an optional interface. This is an optional interface.
```Go
type Execer interface { type Execer interface {
Exec(query string, args []Value) (Result, error) Exec(query string, args []Value) (Result, error)
} }
```
If the driver doesn't implement this interface, when you call DB.Exec, it will automatically call Prepare, then return Stmt. After that it executes the Exec method of Stmt, then closes Stmt. If the driver doesn't implement this interface, when you call DB.Exec, it will automatically call Prepare, then return Stmt. After that it executes the Exec method of Stmt, then closes Stmt.
## driver.Result ## driver.Result
This is the interface for results of `update/insert` operations. This is the interface for results of `update/insert` operations.
```Go
type Result interface { type Result interface {
LastInsertId() (int64, error) LastInsertId() (int64, error)
RowsAffected() (int64, error) RowsAffected() (int64, error)
} }
```
- `LastInsertId` returns auto-increment Id number after a database insert operation. - `LastInsertId` returns auto-increment Id number after a database insert operation.
- `RowsAffected` returns rows that were affected by query operations. - `RowsAffected` returns rows that were affected by query operations.
## driver.Rows ## driver.Rows
This is the interface for the result of a query operation. This is the interface for the result of a query operation.
```Go
type Rows interface { type Rows interface {
Columns() []string Columns() []string
Close() error Close() error
Next(dest []Value) error Next(dest []Value) error
} }
```
- `Columns` returns field information of database tables. The slice has a one-to-one correspondence with SQL query fields only, and does not return all fields of that database table. - `Columns` returns field information of database tables. The slice has a one-to-one correspondence with SQL query fields only, and does not return all fields of that database table.
- `Close` closes Rows iterator. - `Close` closes Rows iterator.
- `Next` returns next data and assigns to dest, converting all strings into byte arrays, and gets io.EOF error if no more data is available. - `Next` returns next data and assigns to dest, converting all strings into byte arrays, and gets io.EOF error if no more data is available.
@@ -135,36 +135,36 @@ This is the interface for the result of a query operation.
## driver.RowsAffected ## driver.RowsAffected
This is an alias of int64, but it implements the Result interface. This is an alias of int64, but it implements the Result interface.
```Go
type RowsAffected int64 type RowsAffected int64
func (RowsAffected) LastInsertId() (int64, error) func (RowsAffected) LastInsertId() (int64, error)
func (v RowsAffected) RowsAffected() (int64, error) func (v RowsAffected) RowsAffected() (int64, error)
```
## driver.Value ## driver.Value
This is an empty interface that can contain any kind of data. This is an empty interface that can contain any kind of data.
```Go
type Value interface{} type Value interface{}
```
The Value must be something that drivers can operate on or nil, so it should be one of the following types: The Value must be something that drivers can operate on or nil, so it should be one of the following types:
```Go
int64 int64
float64 float64
bool bool
[]byte []byte
string [*] Except Rows.Next which cannot return string string [*] Except Rows.Next which cannot return string
time.Time time.Time
```
## driver.ValueConverter ## driver.ValueConverter
This defines an interface for converting normal values to driver.Value. This defines an interface for converting normal values to driver.Value.
```Go
type ValueConverter interface { type ValueConverter interface {
ConvertValue(v interface{}) (Value, error) ConvertValue(v interface{}) (Value, error)
} }
```
This interface is commonly used in database drivers and has many useful features: This interface is commonly used in database drivers and has many useful features:
- Converts driver.Value to a corresponding database field type, for example converts int64 to uint16. - Converts driver.Value to a corresponding database field type, for example converts int64 to uint16.
@@ -174,11 +174,11 @@ This interface is commonly used in database drivers and has many useful features
## driver.Valuer ## driver.Valuer
This defines an interface for returning driver.Value. This defines an interface for returning driver.Value.
```Go
type Valuer interface { type Valuer interface {
Value() (Value, error) Value() (Value, error)
} }
```
Many types implement this interface for conversion between driver.Value and itself. Many types implement this interface for conversion between driver.Value and itself.
At this point, you should know a bit about developing database drivers in Go. Once you can implement interfaces for operations like add, delete, update, etc., there are only a few problems left related to communicating with specific databases. At this point, you should know a bit about developing database drivers in Go. Once you can implement interfaces for operations like add, delete, update, etc., there are only a few problems left related to communicating with specific databases.
@@ -186,7 +186,7 @@ At this point, you should know a bit about developing database drivers in Go. On
## database/sql ## database/sql
database/sql defines even more high-level methods on top of database/sql/driver for more convenient database operations, and it suggests that you implement a connection pool. database/sql defines even more high-level methods on top of database/sql/driver for more convenient database operations, and it suggests that you implement a connection pool.
```Go
type DB struct { type DB struct {
driver driver.Driver driver driver.Driver
dsn string dsn string
@@ -194,7 +194,7 @@ database/sql defines even more high-level methods on top of database/sql/driver
freeConn []driver.Conn freeConn []driver.Conn
closed bool 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 freeConn. 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. 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 freeConn. 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.
## Links ## Links

View File

@@ -18,7 +18,7 @@ I'll use the first driver in the following examples (I use this one in my person
## Samples ## Samples
In the following sections, I'll use the same database table structure for different databases, then create SQL as follows: In the following sections, I'll use the same database table structure for different databases, then create SQL as follows:
```sql
CREATE TABLE `userinfo` ( CREATE TABLE `userinfo` (
`uid` INT(10) NOT NULL AUTO_INCREMENT, `uid` INT(10) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(64) NULL DEFAULT NULL, `username` VARCHAR(64) NULL DEFAULT NULL,
@@ -26,9 +26,9 @@ In the following sections, I'll use the same database table structure for differ
`created` DATE NULL DEFAULT NULL, `created` DATE NULL DEFAULT NULL,
PRIMARY KEY (`uid`) PRIMARY KEY (`uid`)
); );
```
The following example shows how to operate on a database based on the `database/sql` interface standards. The following example shows how to operate on a database based on the `database/sql` interface standards.
```Go
package main package main
import ( import (
@@ -102,7 +102,7 @@ The following example shows how to operate on a database based on the `database/
panic(err) panic(err)
} }
} }
```
Let me explain a few of the important functions here: Let me explain a few of the important functions here:
- `sql.Open()` opens a registered database driver. The Go-MySQL-Driver registered the mysql driver here. The second argument is the DSN (Data Source Name) that defines information pertaining to the database connection. It supports following formats: - `sql.Open()` opens a registered database driver. The Go-MySQL-Driver registered the mysql driver here. The second argument is the DSN (Data Source Name) that defines information pertaining to the database connection. It supports following formats: