-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
58 lines (46 loc) · 1.16 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
package sync
import (
"fmt"
"time"
"github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
)
type table struct {
*sqlx.DB
config TableConfig
primaryKeys []string
primaryKeyIndices []int // Indices of the primary keys in the Columns slice
columns []string
}
func (t *table) connect() error {
if t.DB != nil {
return nil // Already connected
}
dsn := t.config.DSN
if dsn == "" {
// If DSN is not directly provided, construct it from the other fields
if t.config.Driver == "mysql" {
cfg := mysql.NewConfig()
cfg.User = t.config.User
cfg.Passwd = t.config.Password
cfg.Addr = fmt.Sprintf("%s:%d", t.config.Host, t.config.Port)
cfg.DBName = t.config.DB
cfg.Net = "tcp"
dsn = cfg.FormatDSN()
} else if t.config.Driver == "sqlite3" {
return fmt.Errorf("for sqlite3, DSN must be provided directly")
} else {
return fmt.Errorf("unsupported driver: %s", t.config.Driver)
}
}
var err error
t.DB, err = sqlx.Connect(t.config.Driver, dsn)
if err != nil {
return err
}
t.DB.SetMaxOpenConns(5)
t.DB.SetMaxIdleConns(5)
t.DB.SetConnMaxLifetime(5 * time.Minute)
return nil
}