-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
91 lines (82 loc) · 1.94 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
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
package go_trellis_db
import (
"flag"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
"github.com/wyattis/z/zconfig"
)
type WebConfig struct {
Root string
}
type StorageConfig struct {
Root string
}
type Config struct {
Web WebConfig
Storage StorageConfig
DB DBConfig
}
type DBConfig struct {
Driver string `default:"mysql"`
Host string `default:"localhost"`
Port int `default:"3306"`
Database string
Username string
Password string
}
func Connect(config DBConfig) (db *sqlx.DB, err error) {
var url string
switch config.Driver {
case "mysql":
url = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?sql_mode=''", config.Username, config.Password, config.Host, config.Port, config.Database)
case "sqlite3":
url = config.Database
}
db, err = sqlx.Connect(config.Driver, url)
if err != nil {
return
}
return
}
func AutoConnect() (db *sqlx.DB, err error) {
envLoc := flag.String("env", ".env", "")
flag.Parse()
config := Config{}
if err = zconfig.New(zconfig.Env(*envLoc, "/var/www/trellis-api/.env"), zconfig.Defaults()).Apply(&config); err != nil {
return
}
return Connect(config.DB)
}
func LoadTranslations(db *sqlx.DB, ids ...string) (translations map[string]*Translation, err error) {
if len(ids) == 0 {
return
}
query, args, err := sqlx.In(`SELECT * FROM translation WHERE id IN (?)`, ids)
if err != nil {
return
}
ts := []Translation{}
query = db.Rebind(query)
err = db.Select(&ts, query, args...)
texts := []TranslationText{}
query, args, err = sqlx.In(`SELECT * FROM translation_text WHERE translation_id IN (?)`, ids)
if err != nil {
return
}
if err = db.Select(&texts, query, args...); err != nil {
return
}
translations = make(map[string]*Translation, len(ts))
for _, tt := range texts {
for i := range ts {
if ts[i].Id == tt.TranslationId {
ts[i].TranslationTexts = append(ts[i].TranslationTexts, tt)
}
}
}
for _, t := range ts {
translations[t.Id] = &t
}
return
}