Add gorm.Wrap to wrap an existing db connection with gorm.

This commit gives you the ability to specify the db connection that
gorm will use.  The code is based on the gorm.Open command, but
stripped down.  Since the connection already exists, there is much
less work needed.

This features lets you integrate with goose, which provides an
existing transaction to each migration.  Goose runs the migration
infrastructure, and gorm can provide the SQL.
This commit is contained in:
Joel 2014-11-11 00:33:08 -08:00 committed by jnfeinstein
parent a405f08f3a
commit 003bf8d080

22
main.go
View File

@ -35,7 +35,7 @@ type DB struct {
values map[string]interface{} values map[string]interface{}
} }
func Open(dialect string, drivesources ...string) (DB, error) { func makeDB(dialect string, drivesources ...string) (*DB, string, string, error) {
var db DB var db DB
var err error var err error
var driver = dialect var driver = dialect
@ -54,10 +54,26 @@ func Open(dialect string, drivesources ...string) (DB, error) {
db = DB{dialect: NewDialect(dialect), tagIdentifier: "sql", db = DB{dialect: NewDialect(dialect), tagIdentifier: "sql",
logger: defaultLogger, callback: DefaultCallback, source: source, logger: defaultLogger, callback: DefaultCallback, source: source,
values: map[string]interface{}{}} values: map[string]interface{}{}}
db.db, err = sql.Open(driver, source)
db.parent = &db db.parent = &db
} }
return db, err
return &db, driver, source, err
}
func Open(dialect string, drivesources ...string) (DB, error) {
db, driver, source, err := makeDB(dialect, drivesources...)
if err == nil {
db.db, err = sql.Open(driver, source)
}
return *db, err
}
func Wrap(wrapDb sqlCommon, dialect string, drivesources ...string) (DB, error) {
db, _, _, err := makeDB(dialect, drivesources...)
if err == nil {
db.db = wrapDb
}
return *db, err
} }
func (s *DB) Close() error { func (s *DB) Close() error {