-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix:tests; feat: db.close panic recover; feat: update do and packages
- Loading branch information
1 parent
66048b1
commit 5c8d75d
Showing
6 changed files
with
203 additions
and
253 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
package dbpool | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
"time" | ||
|
||
"github.com/jmoiron/sqlx" | ||
"github.com/jmoiron/sqlx/reflectx" | ||
) | ||
|
||
///////////////////////////////////////////////////////// Mapper functions | ||
|
||
func JsonMapperFunc() *reflectx.Mapper { | ||
return reflectx.NewMapperFunc("json", func(s string) string { return s }) | ||
} | ||
|
||
///////////////////////////////////////////////////////// | ||
|
||
// GetConnectionByParams - get *sqlx.DB from cache (if exists, with default-json-mapperFunc) or create new and put into cache | ||
func GetConnectionByParams(Ctx context.Context, connCache *SafeDbMapCache, | ||
duration time.Duration, driver, connString string) (*sqlx.DB, error) { | ||
|
||
return GetConnectionWithMapper(Ctx, connCache, duration, driver, connString, JsonMapperFunc()) | ||
} | ||
|
||
// GetConnectionWithMapper - get *sqlx.DB from cache (if exists, with set mapperFunc) or create new and put into cache | ||
func GetConnectionWithMapper( | ||
Ctx context.Context, | ||
connCache *SafeDbMapCache, | ||
duration time.Duration, | ||
driver, connString string, | ||
mapperFunc *reflectx.Mapper) (*sqlx.DB, error) { | ||
|
||
conn, ok := connCache.Get(connString) | ||
if ok && conn != nil { | ||
// ping to check | ||
err := conn.PingContext(Ctx) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
return conn, nil | ||
} | ||
|
||
// create conn | ||
db, err := sqlx.ConnectContext(Ctx, driver, connString) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
db.SetConnMaxLifetime(duration) | ||
db.Mapper = mapperFunc | ||
|
||
// add conn to connCache | ||
connCache.Set(connString, db, duration) | ||
|
||
conn, ok = connCache.Get(connString) | ||
if !ok && conn == nil { | ||
return nil, errors.New("no conn in connCache") | ||
} | ||
|
||
return conn, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.