-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdb_test.go
50 lines (42 loc) · 995 Bytes
/
db_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package twowaysql
import (
"context"
"database/sql"
"fmt"
"os"
"testing"
)
func TestDBConnection(t *testing.T) {
//データベースは/postgres/init以下のsqlファイルを用いて初期化されている。
var db *sql.DB
var err error
if host := os.Getenv("POSTGRES_HOST"); host != "" {
db, err = sql.Open("pgx", fmt.Sprintf("host=%s user=postgres password=postgres dbname=postgres sslmode=disable", host))
} else {
db, err = sql.Open("pgx", "host=localhost user=postgres password=postgres dbname=postgres sslmode=disable")
}
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
db.Close()
})
ctx := context.Background()
rows, err := db.QueryContext(ctx, "SELECT first_name from persons")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
rows.Close()
})
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
t.Error(err)
}
t.Logf("first_name: %v\n", name)
}
if err := rows.Err(); err != nil {
t.Error(err)
}
}