github.com/Systemnick/migrate@v3.5.4+incompatible/database/cockroachdb/cockroachdb_test.go (about) 1 package cockroachdb 2 3 // error codes https://github.com/lib/pq/blob/master/error.go 4 5 import ( 6 //"bytes" 7 "database/sql" 8 "fmt" 9 "io" 10 "testing" 11 12 "bytes" 13 dt "github.com/golang-migrate/migrate/database/testing" 14 mt "github.com/golang-migrate/migrate/testing" 15 "github.com/lib/pq" 16 ) 17 18 var versions = []mt.Version{ 19 {Image: "cockroachdb/cockroach:v1.0.2", Cmd: []string{"start", "--insecure"}}, 20 } 21 22 func isReady(i mt.Instance) bool { 23 db, err := sql.Open("postgres", fmt.Sprintf("postgres://root@%v:%v?sslmode=disable", i.Host(), i.PortFor(26257))) 24 if err != nil { 25 return false 26 } 27 defer db.Close() 28 err = db.Ping() 29 if err == io.EOF { 30 _, err = db.Exec("CREATE DATABASE migrate") 31 return err == nil 32 } else if e, ok := err.(*pq.Error); ok { 33 if e.Code.Name() == "cannot_connect_now" { 34 return false 35 } 36 } 37 38 _, err = db.Exec("CREATE DATABASE migrate") 39 return err == nil 40 41 return true 42 } 43 44 func Test(t *testing.T) { 45 mt.ParallelTest(t, versions, isReady, 46 func(t *testing.T, i mt.Instance) { 47 c := &CockroachDb{} 48 addr := fmt.Sprintf("cockroach://root@%v:%v/migrate?sslmode=disable", i.Host(), i.PortFor(26257)) 49 d, err := c.Open(addr) 50 if err != nil { 51 t.Fatalf("%v", err) 52 } 53 dt.Test(t, d, []byte("SELECT 1")) 54 }) 55 } 56 57 func TestMultiStatement(t *testing.T) { 58 mt.ParallelTest(t, versions, isReady, 59 func(t *testing.T, i mt.Instance) { 60 c := &CockroachDb{} 61 addr := fmt.Sprintf("cockroach://root@%v:%v/migrate?sslmode=disable", i.Host(), i.Port()) 62 d, err := c.Open(addr) 63 if err != nil { 64 t.Fatalf("%v", err) 65 } 66 if err := d.Run(bytes.NewReader([]byte("CREATE TABLE foo (foo text); CREATE TABLE bar (bar text);"))); err != nil { 67 t.Fatalf("expected err to be nil, got %v", err) 68 } 69 70 // make sure second table exists 71 var exists bool 72 if err := d.(*CockroachDb).db.QueryRow("SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'bar' AND table_schema = (SELECT current_schema()))").Scan(&exists); err != nil { 73 t.Fatal(err) 74 } 75 if !exists { 76 t.Fatalf("expected table bar to exist") 77 } 78 }) 79 } 80 81 func TestFilterCustomQuery(t *testing.T) { 82 mt.ParallelTest(t, versions, isReady, 83 func(t *testing.T, i mt.Instance) { 84 c := &CockroachDb{} 85 addr := fmt.Sprintf("cockroach://root@%v:%v/migrate?sslmode=disable&x-custom=foobar", i.Host(), i.PortFor(26257)) 86 _, err := c.Open(addr) 87 if err != nil { 88 t.Fatalf("%v", err) 89 } 90 }) 91 }