-
Notifications
You must be signed in to change notification settings - Fork 2
/
mysql.go
65 lines (53 loc) · 1.13 KB
/
mysql.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
package clean_like_gopher
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
type Mysql struct {
db *sql.DB
}
// creates new cleaner for mysql driver
func NewMysqlConnection(options map[string]string) (*Mysql, error) {
hostWithPort, ok := options["host_port"]
if !ok {
hostWithPort = ""
}
username, ok := options["username"]
if !ok {
return nil, &GopherError{Message: "missing username!"}
}
password, ok := options["password"]
if !ok {
password = ""
}
protocol, ok := options["protocol"]
if !ok {
protocol = ""
}
dbName, ok := options["dbName"]
if !ok {
return nil, &GopherError{"missing db name!"}
}
conn, err := sql.Open("mysql", username+":"+password+"@"+protocol+hostWithPort+"/"+dbName)
if err != nil {
return nil, err
} else {
return &Mysql{db: conn}, nil
}
}
// returns all table names
func (m *Mysql) TableNames() []string {
var name string
tablesNames := make([]string, 0)
rows, _ := m.db.Query("show tables")
for rows.Next() {
_ = rows.Scan(&name)
if len(name) > 1 {
tablesNames = append(tablesNames, name)
}
}
return tablesNames
}
func (m *Mysql) DB() *sql.DB {
return m.db
}