From 003bf8d0805db346d4aad20fb29319df113f2eee Mon Sep 17 00:00:00 2001 From: Joel Date: Tue, 11 Nov 2014 00:33:08 -0800 Subject: [PATCH] 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. --- main.go | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/main.go b/main.go index 14a76b19..7744b04c 100644 --- a/main.go +++ b/main.go @@ -35,7 +35,7 @@ type DB struct { 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 err error var driver = dialect @@ -54,10 +54,26 @@ func Open(dialect string, drivesources ...string) (DB, error) { db = DB{dialect: NewDialect(dialect), tagIdentifier: "sql", logger: defaultLogger, callback: DefaultCallback, source: source, values: map[string]interface{}{}} - db.db, err = sql.Open(driver, source) 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 {