-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.go
120 lines (113 loc) · 2.56 KB
/
database.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
111
112
113
114
115
116
117
118
119
120
package main
import (
"database/sql"
"fmt"
"log"
"os"
"github.com/go-mysql-org/go-mysql/client"
_ "github.com/go-sql-driver/mysql"
)
var (
port = "3306"
host = os.Getenv("DB_HOST")
user = os.Getenv("DB_USER")
pass = os.Getenv("DB_PASS")
dbName = os.Getenv("DB_NAME")
)
func InitializeDatabase(user, pass, host, port, dbname string) *sql.DB {
url := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", user, pass, host, port, dbname)
fmt.Printf("Connecting to %s...\n", url)
db, err := sql.Open(
"mysql",
url,
)
if err != nil {
fmt.Println("Error while connecting to database")
panic(err)
}
err = db.Ping()
if err != nil {
fmt.Println("Error while pinging database")
panic(err)
}
log.Println("Database was successfully connected to")
return db
}
func InitOverseerConnection() *sql.DB {
// create connection to ask user what should be imposed
return InitializeDatabase(user, pass, host, port, dbName)
}
func InitLocalDatabase() *client.Conn {
c, err := client.Connect("localhost:3306", "root", "mypassword", "")
if err != nil {
fmt.Println("Error while connecting to database")
panic(err)
}
err = c.Ping()
if err != nil {
fmt.Println("Error while pinging database")
panic(err)
}
return c
}
func QueryFor(db *sql.DB, query string) []string {
props := []string{}
log.Printf(query)
rows, err := db.Query(query)
if err != nil {
fmt.Println("Error while connecting to database")
panic(err)
}
defer rows.Close()
for rows.Next() {
var s string
rows.Scan(&s)
props = append(props, s)
}
return props
}
func QueryForTwoColumns(db *sql.DB, query string) [][2]string {
props := [][2]string{}
log.Printf(query)
rows, err := db.Query(query)
if err != nil {
fmt.Println("Error while connecting to database")
panic(err)
}
defer rows.Close()
for rows.Next() {
s := [2]string{}
rows.Scan(&s[0], &s[1])
props = append(props, s)
}
return props
}
func Populate(db *client.Conn, dbName, query string, inserts []string) {
_, err := db.Execute(DROP_DB(dbName))
if err != nil {
fmt.Println("Error while dropping imposter database")
panic(err)
}
_, err = db.Execute(CREATE_DB(dbName))
if err != nil {
fmt.Println("Error while creating imposter database")
panic(err)
}
_, err = db.Execute(USE_DB(dbName))
if err != nil {
fmt.Println("Error while using database")
panic(err)
}
_, err = db.Execute(query)
if err != nil {
fmt.Println("Error while creating spoofed table")
panic(err)
}
for _, ins := range inserts {
_, err = db.Execute(ins)
if err != nil {
fmt.Println("Error while inserting spoofed data")
panic(err)
}
}
}