-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
100 lines (86 loc) · 1.89 KB
/
main.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
package main
import (
"fmt"
"time"
"github.com/k0kubun/pp"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type User struct {
ID int
Name string
}
func main() {
db := connection()
migration(db)
insertData(db)
var users1, users2, users3, users4 []User
var userInputID string
// OK: SELECT * FROM `users` WHERE `users`.`id` = '1'
userInputID = "1"
if err := db.Debug().Find(&users1, userInputID).Error; err != nil {
panic(err)
}
pp.Println(users1)
// NG: SELECT * FROM `users` WHERE 1=1
userInputID = "1=1"
if err := db.Debug().Find(&users2, userInputID).Error; err != nil {
panic(err)
}
pp.Println(users2)
// NG: SELECT * FROM `users` WHERE 1=1 ORDER BY `users`.`id` LIMIT 1
userInputID = "1=1"
if err := db.Debug().First(&users3, userInputID).Error; err != nil {
panic(err)
}
pp.Println(users3)
// NG: DELETE FROM `users` WHERE 1=1
userInputID = "1=1"
if err := db.Debug().Delete(&users4, userInputID).Error; err != nil {
panic(err)
}
pp.Println(users4)
}
func connection() *gorm.DB {
connectTemplate := "%s:%s@%s/%s?parseTime=true"
user := "docker"
password := "docker"
protocol := "tcp(127.0.0.1:13306)"
dbName := "test"
connectUrl := fmt.Sprintf(connectTemplate, user, password, protocol, dbName)
db, err := gorm.Open(mysql.Open(connectUrl))
if err != nil {
panic(err)
}
d, err := db.DB()
if err != nil {
panic(err)
}
d.SetMaxOpenConns(10)
d.SetMaxIdleConns(10)
d.SetConnMaxLifetime(time.Duration(10) * time.Second)
return db
}
func migration(db *gorm.DB) {
if err := db.AutoMigrate(User{}); err != nil {
panic(err)
}
}
func insertData(db *gorm.DB) {
tx := db.Begin()
TestData := []*User{
{Name: "Tiara"},
{Name: "Rosetta"},
{Name: "Lavie"},
{Name: "Ashley"},
{Name: "Lynette"},
}
for _, data := range TestData {
if err := tx.Create(data).Error; err != nil {
panic(err)
}
}
if err := tx.Commit().Error; err != nil {
panic(err)
}
}