/
init.go
57 lines (47 loc) · 1.31 KB
/
init.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
package vbdb
import (
"database/sql"
"fmt"
"github.com/harwoeck/sqle"
"github.com/vikebot/vbcore"
"go.uber.org/zap"
// Driver import for MariaDB
_ "github.com/go-sql-driver/mysql"
)
var (
db *sql.DB
s *sqle.Sqle
defaultCtx *zap.Logger
conf *Config
)
// Config collects all relevant informations/credentials to access a vikebot
// database
type Config struct {
DbAddr *vbcore.Endpoint
DbUser string
DbPass string
DbName string
}
// Init initializes all internally used structures of vbdb. E.g. a database
// connection pool is created and connections get established. If any errors
// occur durring initialization the error will be returned. The passed zap
// instance is saved and used as default throughout the package if no explicit
// logging-context is provided
func Init(config *Config, logCtx *zap.Logger) (err error) {
conf = config
defaultCtx = logCtx
// Open sql connection
db, err = sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&collation=utf8mb4_unicode_ci", conf.DbUser, conf.DbPass, conf.DbAddr, conf.DbName))
if err != nil {
return err
}
err = db.Ping()
if err != nil {
return err
}
defaultCtx.Info("db connection established and ready to use")
// create sqle
s = sqle.New(db)
defaultCtx.Info("sqle instance created and ready to use")
return nil
}