mattes / migrate

Database migrations. CLI and Golang library.
Other
2.29k stars 326 forks source link

source driver: unknown driver file (forgotton import?) #335

Closed miguelmota closed 6 years ago

miguelmota commented 6 years ago

Can't figure out why I'm getting the error source driver: unknown driver file (forgotton import?).

Below is my code:

package main

import (
    "database/sql"

    _ "github.com/lib/pq" // required
    "github.com/mattes/migrate" 
    "github.com/mattes/migrate/database/postgres"
    _ "github.com/mattes/migrate/source/file" // required
)

// MigrateDB migrate database
func MigrateDB(connectionStr string) error {
    db, err := sql.Open("postgres", connectionStr)
    defer db.Close()
    if err != nil {
        return err
    }

    driver, err := postgres.WithInstance(db, &postgres.Config{})
    if err != nil {
        return err
    }

    m, err := migrate.NewWithDatabaseInstance(
        "file://migrations",
        "postgres", driver)
    if err != nil {
        return err
    }

    err = m.Steps(0)
    if err != nil {
        return err
    }

    defer m.Close()
    return nil
}

The migrations/ folder is in the same directory as the file above.

Using the CLI does work for me.

# works
$ migrate -database $POSTGRES_URI -path ./migrations/ up 1

Files

$ ls migrations/

1_example.down.sql
1_example.up.sql

Any idea what I'm doing wrong in order to run migrations from the go application?

Thanks

miguelmota commented 6 years ago

Found a workaround:

fsrc, err := (&file.File{}).Open("file://migrations")
if err != nil {
    return err
}

m, err := migrate.NewWithInstance(
    "file",
    fsrc,
    "postgres",
    driver,
)

However, I'm getting file does not exist after I've ran first migration successfully.

Kiura commented 6 years ago

I have the same error when using cli tool, how do I import driver in cli?

Kiura commented 6 years ago

solved my issue by downloading release version with curl

nutmix commented 6 years ago

@Kiura how did you solve this exactly? I am having the same issue. built using:

$ go get -u -d github.com/mattes/migrate/cli github.com/go-sql-driver/mysql $ go install -tags 'mysql'  github.com/mattes/migrate/cli

run using:

$ cli -database "mysql://xxx:yyy@/zzz" -source file://go/src/github.com/xxx/xxx.org/db/schema up

kiura24metrics commented 6 years ago

@nutmix I can't remember exactly how I did it back then, but try this:

curl -L https://github.com/golang-migrate/migrate/releases/download/$version/migrate.$platform-amd64.tar.gz | tar xvz

NOTE: replace $version and $platform.

for example:

curl -L https://github.com/golang-migrate/migrate/releases/download/v3.2.0/migrate.darwin-amd64.tar.gz | tar xvz