-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
93 lines (77 loc) · 1.6 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
package main
import (
"log"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"github.com/FrancoLiberali/cql"
"github.com/FrancoLiberali/cql-tutorial/models"
"github.com/FrancoLiberali/cql/logger"
)
func main() {
// connect to db
db, err := NewDBConnection()
if err != nil {
log.Fatalln(err)
}
// createData(db)
// execute tutorial
tutorial(db)
}
func NewDBConnection() (*gorm.DB, error) {
return cql.Open(
sqlite.Open("sqlite:db"),
&gorm.Config{Logger: logger.Default.ToLogMode(logger.Info)},
)
}
func createData(db *gorm.DB) {
if err := db.AutoMigrate(
models.City{},
models.Country{},
); err != nil {
log.Panicln(err)
}
usa := models.Country{
Name: "United States of America",
}
if err := db.Create(&usa).Error; err != nil {
log.Panicln(err)
}
parisUSA := models.City{
Country: &usa,
Name: "Paris",
Population: 25171,
}
if err := db.Create(&parisUSA).Error; err != nil {
log.Panicln(err)
}
washington := models.City{
Country: &usa,
Name: "Washington D. C.",
Population: 689545,
}
if err := db.Create(&washington).Error; err != nil {
log.Panicln(err)
}
usa.CapitalID = washington.ID
if err := db.Save(&usa).Error; err != nil {
log.Panicln(err)
}
france := models.Country{
Name: "France",
}
if err := db.Create(&france).Error; err != nil {
log.Panicln(err)
}
parisFrance := models.City{
Country: &france,
Name: "Paris",
Population: 2161000,
}
if err := db.Create(&parisFrance).Error; err != nil {
log.Panicln(err)
}
france.CapitalID = parisFrance.ID
if err := db.Save(&france).Error; err != nil {
log.Panicln(err)
}
}