-
Notifications
You must be signed in to change notification settings - Fork 1
/
postgres.go
103 lines (83 loc) · 2.02 KB
/
postgres.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package db
import (
"database/sql"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file"
_ "github.com/lib/pq"
)
type PostgresDBReader struct {
rows *sql.Rows
}
func (reader *PostgresDBReader) NextRow(dest ...interface{}) (bool, error) {
if reader.rows.Next() {
err := reader.rows.Scan(dest...)
return err == nil, err
}
return false, reader.rows.Err()
}
func (reader *PostgresDBReader) GetRow(dest ...interface{}) error {
found, err := reader.NextRow(dest...)
if !found && err == nil {
err = sql.ErrNoRows
}
return err
}
func (reader *PostgresDBReader) Close() {
if reader.rows != nil {
reader.rows.Close()
}
}
type PostgresDBProvider struct {
connection *sql.DB
}
func (provider *PostgresDBProvider) Query(query string, args ...interface{}) (DBReader, error) {
response, err := provider.connection.Query(query, args...)
return &PostgresDBReader{rows: response}, err
}
func (provider *PostgresDBProvider) Exec(query string, args ...interface{}) (int64, error) {
result, err := provider.connection.Exec(query, args...)
if err != nil {
return 0, err
}
rows, err := result.RowsAffected()
if err != nil {
return 0, err
}
return rows, nil
}
func (provider *PostgresDBProvider) Migrate() (uint, error) {
driver, err := postgres.WithInstance(provider.connection, &postgres.Config{})
if err != nil {
return 0, err
}
migrator, err := migrate.NewWithDatabaseInstance(
"file:///migrations/postgres",
"postgres", driver)
if err != nil {
return 0, err
}
err = migrator.Up()
if err != nil && err != migrate.ErrNoChange {
return 0, err
}
version, _, err := migrator.Version()
if err != nil {
return 0, err
}
return version, nil
}
func CreatePostgresDBProvider(URL string) (DBProvider, error) {
db, err := sql.Open("postgres", URL)
if err != nil {
return nil, err
}
err = db.Ping()
if err != nil {
return nil, err
}
provider := PostgresDBProvider{
connection: db,
}
return &provider, nil
}