/
connection.go
110 lines (94 loc) · 2.64 KB
/
connection.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package db
import (
"database/sql"
"log"
"reflect"
_ "github.com/go-sql-driver/mysql" // Makes sure it is using this mysql driver
)
// Connection is the connection to the database
type Connection struct {
Host string
Port string
Database string
Username string
Password string
conn *sql.DB
}
// Default sets the default options for the Connection
func (dbc *Connection) Default() {
if dbc.Host == "" {
dbc.Host = "localhost"
}
if dbc.Port == "" {
dbc.Port = "3306"
}
if dbc.Username == "" {
dbc.Username = "root"
}
}
// Open opens a connection to the database
func (dbc *Connection) Open() error {
pw := ""
if dbc.Password != "" {
pw = ":" + dbc.Password
}
//dbc.Username+pw
conn, err := sql.Open("mysql", dbc.Username+pw+"@tcp("+dbc.Host+":"+dbc.Port+")/"+dbc.Database)
if err != nil {
return err
}
if err = conn.Ping(); err != nil {
return err
}
dbc.conn = conn
return nil
}
// Close closes a connection to the database
func (dbc *Connection) Close() error {
err := dbc.conn.Close()
if err != nil {
return err
}
return nil
}
// ReadRows into array of interface type
func ReadRows(struc interface{}, rows *sql.Rows) []interface{} {
var structs []interface{}
// Read all rows into structs
for rows.Next() {
columns := make([]interface{}, 0)
for i := 0; i < reflect.TypeOf(struc).NumField(); i++ {
// Switch trough all reflect types and set type (interface{} is default)
switch reflect.TypeOf(struc).Field(i).Type {
case reflect.TypeOf(""):
field := reflect.New(reflect.TypeOf(struc).Field(i).Type).Elem().Interface().(string)
columns = append(columns, &field)
case reflect.TypeOf(0):
field := reflect.New(reflect.TypeOf(struc).Field(i).Type).Elem().Interface().(int)
columns = append(columns, &field)
default:
field := reflect.New(reflect.TypeOf(struc).Field(i).Type).Elem().Interface()
columns = append(columns, &field)
}
}
if err := rows.Scan(columns...); err != nil {
log.Fatal(err)
}
structs = append(structs, columns)
}
// Create and format strucs for returning
var retStructs []interface{}
for _, v := range structs {
// Create new struc of struc type then convert interface{} to []interface{}
newStruc := reflect.New(reflect.TypeOf(struc)).Elem()
strucArr := reflect.ValueOf(v).Interface().([]interface{})
// Loop trough all fields in struc
for j := 0; j < reflect.TypeOf(struc).NumField(); j++ {
// select current fieldval and set struc to val
fieldVal := reflect.ValueOf(strucArr[j]).Elem()
newStruc.FieldByName(reflect.TypeOf(struc).Field(j).Name).Set(fieldVal)
}
retStructs = append(retStructs, newStruc.Interface())
}
return retStructs
}