forked from polothy/pg2mysql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql.go
89 lines (74 loc) · 1.48 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package pg2mysql
import (
"database/sql"
"fmt"
"github.com/go-sql-driver/mysql"
)
func NewMySQLDB(
database string,
username string,
password string,
host string,
port int,
) DB {
config := mysql.Config{
User: username,
Passwd: password,
DBName: database,
Net: "tcp",
Addr: fmt.Sprintf("%s:%d", host, port),
MultiStatements: true,
Params: map[string]string{
"charset": "utf8",
"parseTime": "True",
},
}
return &mySQLDB{
dsn: config.FormatDSN(),
dbName: database,
}
}
type mySQLDB struct {
dsn string
db *sql.DB
dbName string
}
func (m *mySQLDB) Open() error {
db, err := sql.Open("mysql", m.dsn)
if err != nil {
return err
}
m.db = db
return nil
}
func (m *mySQLDB) Close() error {
return m.db.Close()
}
func (m *mySQLDB) GetSchemaRows() (*sql.Rows, error) {
query := `
SELECT table_name,
column_name,
data_type,
character_maximum_length
FROM information_schema.columns
WHERE table_schema = ?`
rows, err := m.db.Query(query, m.dbName)
if err != nil {
return nil, err
}
return rows, nil
}
func (m *mySQLDB) DB() *sql.DB {
return m.db
}
func (m *mySQLDB) ColumnNameForSelect(name string) string {
return fmt.Sprintf("`%s`", name)
}
func (m *mySQLDB) EnableConstraints() error {
_, err := m.db.Exec("SET FOREIGN_KEY_CHECKS = 1;")
return err
}
func (m *mySQLDB) DisableConstraints() error {
_, err := m.db.Exec("SET FOREIGN_KEY_CHECKS = 0;")
return err
}