2

What's the best way to convert the type sqlx.DB (jmoiron/sqlx) to sql.DB (database/sql)?

I'm currently using the package github.com/golang-migrate/migrate and it requires an existing connection to follow sql.DB interface.


func Migrate(db *sqlx.DB) error {
    driver, err := postgres.WithInstance(db, &postgres.Config{})
    m, err := migrate.NewWithDatabaseInstance(
        "file://src/db/migrations",
        "postgres", driver)
    if err != nil {
        return err
    }

    return m.Up()
}

Update: I mixed the description and added more details. The title was correct.

0

2 Answers 2

9

You can convert an sql.DB (which is a struct, not an interface) to an sqlx.DB using sqlx's NewDb method: Code

This method requires your *sql.DB as well as the driver name as a string.

Here's an example using "mysql" for the driver:

var myDb *sql.DB

...

anSqlxDb := sqlx.NewDb(myDb, "mysql") // returns *sqlx.DB

Edit: to add the answer to the new question which was asked in the comments, it is also possible to do the reverse and get an *sql.DB from an *sqlx.DB.

The *sqlx.DB struct contains an embedded *sql.DB (Code). As an embedded struct, it can be retrieved using its type name (DB):

var mySqlxDb *sqlx.DB

...

var anSqlDb := mySqlxDb.DB
Sign up to request clarification or add additional context in comments.

4 Comments

How would you convert from sql to sqlx?
Convert what, specifically? The above code is how an instance of sql.Db can be converted to an instance of sqlx.DB.
Convert the opposite, from sqlx.DB to sql.Db
Let me add that to my answer (although it is a different question).
5

In doc

sqlx.DB is a wrapper around sql.DB which keeps track of the driverName upon Open, used mostly to automatically bind named queries using the right bindvars.

So you can do like

db, err := sqlx.Connect("postgres", "user=foo dbname=bar sslmode=disable")
sqlDB := db.DB // sqlDB is *sql.DB

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.