2022-12-07 10:20:08 +03:00
|
|
|
# micro-wrapper-sql
|
2021-03-15 15:49:54 +03:00
|
|
|
|
|
|
|
Example for For postgres
|
|
|
|
|
|
|
|
```go
|
2023-01-06 23:42:34 +03:00
|
|
|
package storage
|
2022-12-07 10:20:08 +03:00
|
|
|
|
2021-03-15 15:49:54 +03:00
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/url"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/jackc/pgx/v4"
|
|
|
|
"github.com/jackc/pgx/v4/stdlib"
|
|
|
|
"github.com/jmoiron/sqlx"
|
2022-12-07 10:20:56 +03:00
|
|
|
wrapper "go.unistack.org/micro-wrapper-sql/v3"
|
2021-03-15 15:49:54 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
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
|
2023-01-06 23:42:34 +03:00
|
|
|
// dbConf.PreferSimpleProtocol = true
|
2021-03-15 15:49:54 +03:00
|
|
|
// 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
|
|
|
|
2023-01-06 23:42:34 +03:00
|
|
|
wrapper.DefaultMeterStatsInterval = 1 * time.Second
|
|
|
|
logger.DefaultLogger = logger.NewLogger(logger.WithLevel(logger.DebugLevel))
|
|
|
|
|
|
|
|
if err := logger.DefaultLogger.Init(); err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
2023-02-17 23:54:50 +03:00
|
|
|
// for postgres user stdlib.GetDefaultDriver() or it fails
|
2023-01-06 23:42:34 +03:00
|
|
|
sql.Register("micro-wrapper-sql", wrapper.NewWrapper(&sqlite.Driver{},
|
|
|
|
wrapper.DatabaseHost("localhost"),
|
|
|
|
wrapper.DatabaseName("mydb"),
|
|
|
|
wrapper.LoggerLevel(logger.DebugLevel),
|
|
|
|
wrapper.LoggerEnabled(true),
|
|
|
|
))
|
|
|
|
|
2021-10-27 18:49:33 +03:00
|
|
|
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
|
|
|
|
}
|
|
|
|
```
|