-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdatabase.go
64 lines (53 loc) · 1.2 KB
/
database.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
package database
import (
"context"
"errors"
"fmt"
"log"
_ "github.com/lib/pq"
"github.com/sno6/gosane/ent"
)
type Database struct {
Client *ent.Client
Config *Config
}
type Config struct {
Name string
Host string
Port string
User string
Pass string
MigrationDir string
LogMode bool
}
func New(cfg *Config) (*Database, error) {
client, err := initDB(cfg)
if err != nil {
return nil, err
}
return &Database{
Client: client,
Config: cfg,
}, nil
}
func initDB(cfg *Config) (*ent.Client, error) {
for _, s := range []string{cfg.Name, cfg.Host, cfg.Port, cfg.User, cfg.Pass} {
if s == "" {
return nil, errors.New("incomplete environment for database")
}
}
connStr := fmt.Sprintf("dbname=%s host=%s port=%s user=%s password=%s sslmode=disable",
cfg.Name, cfg.Host, cfg.Port, cfg.User, cfg.Pass)
client, err := ent.Open("postgres", connStr)
if err != nil {
return nil, err
}
if cfg.LogMode {
client = client.Debug()
}
// TODO (sno6): This will not be auto generated in the future.
if err := client.Schema.Create(context.Background()); err != nil {
log.Fatalf("failed creating schema resources: %v", err)
}
return client, nil
}