user6687213
user6687213

Reputation: 21

How to determine name of database driver I'm using?

In code which tries to be database agnostic, I would like to perform some database specific queries, so I need to know name of Database Driver in Go language:

   db,err := sql.Open(dbstr, dbconnstr)
    if err != nil {
            log.Fatal(err)
    }
    errp := db.Ping()
    if errp != nil {
            log.Fatal(errp)
    }
    log.Printf("%s\n", db.Driver())

How I can determine name of database driver I'm using?

Upvotes: 2

Views: 1648

Answers (2)

Mayank Patel
Mayank Patel

Reputation: 8546

Give your database string in url format like postgres://postgres@localhost:5432/db_name?sslmode=disable.

And then find the database type you are using Parse function of url package. Based on the database type, run db specific queries.

func New(url string) (Driver, error) {
    u, err := neturl.Parse(url)
    if err != nil {
        return nil, err
    }

    switch u.Scheme {
    case "postgres":
        d := &postgres.Driver{}
        if err := d.Initialize(url); err != nil {
            return nil, err
        }
        return d, nil

    case "mysql":
        d := &mysql.Driver{}
        if err := d.Initialize(url); err != nil {
            return nil, err
        }
        return d, nil

    case "bash":
        d := &bash.Driver{}
        if err := d.Initialize(url); err != nil {
            return nil, err
        }
        return d, nil

    case "cassandra":
        d := &cassandra.Driver{}
        if err := d.Initialize(url); err != nil {
            return nil, err
        }
        return d, nil
    case "sqlite3":
        d := &sqlite3.Driver{}
        if err := d.Initialize(url); err != nil {
            return nil, err
        }
        return d, nil
    default:
        return nil, errors.New(fmt.Sprintf("Driver '%s' not found.", u.Scheme))
    }
}

Upvotes: 3

Simone Carletti
Simone Carletti

Reputation: 176472

You should already know the name of the database driver because its represented by the parameter you identified with the dbstr variable.

db, err := sql.Open("postgres", "user= ... ")
if err != nil {
    log.Fatal(err)
}

db.Driver() correctly returns the underlying driver in use, but you are formatting it as string (because of %s). If you change %s with %T you will see that it correctly prints out the type:

log.Printf("%T\n", db.Driver())

For example, if you use github.com/lib/pq, the output is *pq.drv. This is the same of using the reflect package:

log.Printf("%s\n", reflect.TypeOf(db.Driver()))

It may be impractical to use that value for performing conditional executions. Moreover, the Driver interface doesn't specify any way to get the specific driver information, except the Open() function.

If you have specific needs, you may want to either use the driver name passed when you open the connection, or create specific drivers that delegate to the original ones and handle your custom logic.

Upvotes: 1

Related Questions