jmoiron / sqlx

general purpose extensions to golang's database/sql
http://jmoiron.github.io/sqlx/
MIT License
16.2k stars 1.08k forks source link

No connection pool set? #300

Open yzk0281 opened 7 years ago

yzk0281 commented 7 years ago

Hi How can I set connection pool options with sqlx? Can I change your Open funtion to this for connection pool purpose: db, _ = sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/test?charset=utf8") db.SetMaxOpenConns(2000) db.SetMaxIdleConns(1000)

jhngrant commented 7 years ago

@yzk0281 sqlx.DB contains a pointer to sql.DB

type DB struct {
    *sql.DB
    driverName string
    unsafe     bool
    Mapper     *reflectx.Mapper
}

So you can:

    var DB *sqlx.DB

    DB = sqlx.Connect(driverName, dataSourceName)

    DB.DB.SetMaxOpenConns(1000) // The default is 0 (unlimited)
    DB.DB.SetMaxIdleConns(10) // defaultMaxIdleConns = 2
    DB.DB.SetConnMaxLifetime(0) // 0, connections are reused forever.
yzk0281 commented 7 years ago

@jhngrant Thanks for answering ·~

yzk0281 commented 7 years ago

@jhngrant Good idea

davcamer commented 6 years ago

Since sqlx.DB has a sql.DB as an embedded type, the extra layer of indirection (DB.DB) isn't needed.

Saying it another way:

    var DB *sqlx.DB

    DB = sqlx.Connect(driverName, dataSourceName)

    DB.DB.SetMaxOpenConns(1000) // The default is 0 (unlimited)
    DB.DB.SetMaxIdleConns(10) // defaultMaxIdleConns = 2
    DB.DB.SetConnMaxLifetime(0) // 0, connections are reused forever.

is exactly the same as

    var DB *sqlx.DB

    DB = sqlx.Connect(driverName, dataSourceName)

    DB.SetMaxOpenConns(1000) // The default is 0 (unlimited)
    DB.SetMaxIdleConns(10) // defaultMaxIdleConns = 2
    DB.SetConnMaxLifetime(0) // 0, connections are reused forever.

Effective Go describes this as:

The methods of embedded types come along for free

in the section on embedding.

I wanted to call this out because I was troubleshooting something, came across this issue and had a little panic of "I'm calling these funcs directly on sqlx.DB -- how is it even compiling!"

jhngrant commented 6 years ago

@davcamer promoted fields act like ordinary fields of a struct except that they cannot be used as field names in composite literals of the struct. For example:

type Point struct {
    X, Y int
}

type Circle struct {
    Point
    Radius int
}

type Wheel struct {
    Circle
    Spokes int
}

func main() {
    var w Wheel
    w = Wheel{8, 8, 5, 20}  // compile error: unknown fields
    w = Wheel{X: 8, Y: 8, Radius: 5, Spokes: 20}  // compile error: unknown fields
    w = Wheel{Circle{Point{8, 8}, 5}, 20}  // complies
}

Because of this inconsistency, when names are optional in dot expressions, I prefer to always be explicit.