Add DB method

This commit is contained in:
Jinzhu 2020-06-17 19:56:03 +08:00
parent d716e456f4
commit e487f355a0
2 changed files with 25 additions and 0 deletions

16
gorm.go
View File

@ -3,6 +3,7 @@ package gorm
import (
"context"
"database/sql"
"errors"
"fmt"
"sync"
"time"
@ -220,6 +221,21 @@ func (db *DB) AddError(err error) error {
return db.Error
}
// DB returns `*sql.DB`
func (db *DB) DB() (*sql.DB, error) {
connPool := db.ConnPool
if stmtDB, ok := connPool.(*PreparedStmtDB); ok {
connPool = stmtDB.ConnPool
}
if sqldb, ok := connPool.(*sql.DB); ok {
return sqldb, nil
}
return nil, errors.New("invalid db")
}
func (db *DB) getInstance() *DB {
if db.clone > 0 {
tx := &DB{Config: db.Config}

View File

@ -24,6 +24,15 @@ func init() {
log.Printf("failed to connect database, got error %v\n", err)
os.Exit(1)
} else {
sqlDB, err := DB.DB()
if err == nil {
err = sqlDB.Ping()
}
if err != nil {
log.Printf("failed to connect database, got error %v\n", err)
}
RunMigrations()
}
}