-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
46 lines (37 loc) · 1.03 KB
/
db.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
package demo
import (
"database/sql"
"errors"
"fmt"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq" // we use postgres, we need to iport the library for side effect
)
// ErrNothingDone is returned by DB operations that didn't do anything but there was no error
// Like using ExecOnce to delete a specific row that does not exist
var ErrNothingDone = errors.New("nothing done")
// DB is our main database object
var db *sqlx.DB
// Init initialize the library by supply database object
func Init(d *sql.DB) {
db = sqlx.NewDb(d, "postgres")
}
// execOnce is use to run a query that is supposed to modify exactly one record (like add)
// it return nil if the query did it, otherwise it return an error
func execOnce(query string, args ...interface{}) error {
res, err := db.Exec(query, args...)
if err != nil {
return err
}
affected, err := res.RowsAffected()
if err != nil {
return err
}
switch affected {
case 1:
return nil
case 0:
return ErrNothingDone
default:
return fmt.Errorf("too many lines changed: %d", affected)
}
}