/
postgres.go
53 lines (42 loc) · 1.01 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
package postgres
import (
"log"
"github.com/jaloldinov/books-catalog/storage"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
)
type postgres struct {
db *sqlx.DB
authorRepo *authorRepo
bookCategoryRepo *bookCategoryRepo
bookRepo *bookRepo
}
func NewPostgres(str string) storage.StorageI {
db, err := sqlx.Connect("postgres", str)
if err != nil {
log.Fatalf("Could not connect to db: %e", err)
return nil
}
if err = db.Ping(); err != nil {
log.Fatalf("Could not connect to db error ping: %e", err)
return nil
}
return &postgres{
db: db,
authorRepo: &authorRepo{db},
bookRepo: &bookRepo{db},
bookCategoryRepo: &bookCategoryRepo{db},
}
}
func (pg *postgres) CloseDB() error {
return pg.db.Close()
}
func (pg *postgres) AuthorRepo() storage.AuthorI {
return pg.authorRepo
}
func (pg *postgres) BookCategoryRepo() storage.BookCategoryI {
return pg.bookCategoryRepo
}
func (pg *postgres) BookRepo() storage.BookI {
return pg.bookRepo
}