2021-03-15 15:49:54 +03:00
|
|
|
# micro-wrapper-sqlpackage postgres
|
|
|
|
|
|
|
|
Example for For postgres
|
|
|
|
|
|
|
|
```go
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/url"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/jackc/pgx/v4"
|
|
|
|
"github.com/jackc/pgx/v4/stdlib"
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
|
|
)
|
|
|
|
|
|
|
|
func Connect(cfg *PostgresConfig) (*sqlx.DB, error) {
|
|
|
|
// format connection string
|
2021-10-27 18:49:33 +03:00
|
|
|
cstr := fmt.Sprintf(
|
2021-03-15 15:49:54 +03:00
|
|
|
"postgres://%s:%s@%s/%s?sslmode=disable&statement_cache_mode=describe",
|
|
|
|
cfg.Login,
|
|
|
|
url.QueryEscape(cfg.Passw),
|
|
|
|
cfg.Addr,
|
|
|
|
cfg.DBName,
|
|
|
|
)
|
|
|
|
|
|
|
|
// parse connection string
|
2021-10-27 18:49:33 +03:00
|
|
|
dbConf, err := pgx.ParseConfig(cstr)
|
2021-03-15 15:49:54 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// needed for pgbouncer
|
|
|
|
dbConf.RuntimeParams = map[string]string{
|
|
|
|
"standard_conforming_strings": "on",
|
|
|
|
"application_name": cfg.AppName,
|
|
|
|
}
|
|
|
|
// may be needed for pbbouncer, needs to check
|
|
|
|
//dbConf.PreferSimpleProtocol = true
|
|
|
|
// register pgx conn
|
2021-10-27 18:49:33 +03:00
|
|
|
dsn := stdlib.RegisterConnConfig(dbConf)
|
2021-03-15 15:49:54 +03:00
|
|
|
|
2021-10-27 18:49:33 +03:00
|
|
|
|
|
|
|
sql.Register("micro-wrapper-sql", wrapper.WrapDriver(
|
|
|
|
&stdlib.Driver{},
|
|
|
|
wrapper.Tracer(some.NewTracer()),
|
|
|
|
))
|
|
|
|
wdb, err := sql.Open("micro-wrapper-sql", dsn)
|
2021-03-15 15:49:54 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2021-10-27 18:49:33 +03:00
|
|
|
|
|
|
|
db := sqlx.NewDb(wdb, "pgx")
|
2021-03-15 15:49:54 +03:00
|
|
|
db.SetMaxOpenConns(int(cfg.ConnMax))
|
2021-10-27 18:49:33 +03:00
|
|
|
db.SetMaxIdleConns(int(cfg.ConnMaxIdle))
|
2021-03-15 15:49:54 +03:00
|
|
|
db.SetConnMaxLifetime(time.Duration(cfg.ConnLifetime) * time.Second)
|
|
|
|
db.SetConnMaxIdleTime(time.Duration(cfg.ConnMaxIdleTime) * time.Second)
|
2021-10-27 18:49:33 +03:00
|
|
|
|
2021-03-15 15:49:54 +03:00
|
|
|
return db, nil
|
|
|
|
}
|
|
|
|
```
|