-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdb.go
227 lines (201 loc) · 5.63 KB
/
db.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package main
import (
"database/sql"
"log"
"net/http"
"os"
"time"
"github.com/coopernurse/gorp"
"github.com/dchest/uniuri"
"github.com/extemporalgenome/slug"
"github.com/go-martini/martini"
_ "github.com/go-sql-driver/mysql"
)
type DB interface {
// An anonymous field, all fields of DbMap are promoted into Orm
//gorp.DbMap
gorp.SqlExecutor
// It's the iterface for querying DB
}
// The only one instance of db
var db DB
const (
dbname = "db"
dbuser = "app"
dbpass = "SecretPassword!"
)
func OrmMiddleware(c martini.Context, w http.ResponseWriter, r *http.Request) {
// Inject our db when it is requested by handlers
c.MapTo(db, (*DB)(nil))
}
func init() {
log.Println("Connecting to database...")
// connect to db using standard Go database/sql API
// use whatever database/sql driver you wish
dbopen, err := sql.Open("mysql", dbuser+":"+dbpass+"@/"+dbname+"?charset=utf8&parseTime=true")
if err != nil {
panic(err.Error()) // Just for example purpose. You should use proper error handling instead of panic
}
//defer db.Close() // I DUNNO IF IT WORKS HERE, LETS TEST
dialect := gorp.MySQLDialect{"InnoDB", "UTF8"}
// construct a gorp DbMap
dbmap := gorp.DbMap{Db: dbopen, Dialect: dialect}
log.Println("Database connected!")
// Adding schemes to my ORM
dbmap.AddTableWithName(User{}, "user").SetKeys(false, "userid")
dbmap.AddTableWithName(Profile{}, "profile").SetKeys(false, "profileid")
dbmap.AddTableWithName(Pic{}, "pic").SetKeys(false, "picid")
dbmap.AddTableWithName(Token{}, "token").SetKeys(false, "tokenid", "userid")
dbmap.AddTableWithName(Category{}, "category").SetKeys(false, "categoryid")
dbmap.AddTableWithName(Image{}, "image").SetKeys(false, "imageid")
dbmap.AddTableWithName(Url{}, "url").SetKeys(false, "urlid")
dbmap.AddTableWithName(Content{}, "content").SetKeys(false, "contentid")
dbmap.AddTableWithName(FullContent{}, "fullcontent").SetKeys(false, "contentid")
dbmap.AddTableWithName(ContentLike{}, "contentlike").SetKeys(false, "contentid", "userid")
dbmap.AddTableWithName(Access{}, "access").SetKeys(false, "accessid")
// Adding to local vairable
db = &dbmap
log.Println("Start routine to create the default values of our datas...")
checkAndCreateDefaultPic(db)
checkAndCreateDefaultImage(db)
checkAndCreateAnonymousUser(db)
checkAndCreateCategories(db)
log.Println("All default values has been created.")
dbmap.TraceOn("[SQL]", log.New(os.Stdout, "[DB]", log.Lmicroseconds))
}
func checkAndCreateDefaultPic(db DB) {
// Adding default value to pic
// pic/default.png !
count, err := db.SelectInt("select count(*) from pic where picid=?", "default")
if err == nil {
if count == 0 {
pic := &Pic{
PicId: "default",
Creation: time.Now(),
Deleted: false,
}
err := db.Insert(pic)
if err != nil {
log.Printf("Error creating default pic. %s\n", err)
} else {
log.Println("Default pic created!")
}
}
} else {
log.Printf("Error searching for default pic. %s\n", err)
}
}
func checkAndCreateDefaultImage(db DB) {
// Adding default value to image
// img/default-small.png
// img/default-medium.png
// img/default-large.png
count, err := db.SelectInt("select count(*) from image where imageid=?", "default")
if err == nil {
if count == 0 {
image := &Image{
ImageId: "default",
Creation: time.Now(),
Deleted: false,
}
err := db.Insert(image)
if err != nil {
log.Printf("Error creating default image. %s\n", err)
} else {
log.Printf("Default image created!\n")
}
}
} else {
log.Printf("Error searching for default image. %s\n", err)
}
}
func checkAndCreateAnonymousUser(db DB) {
count, err := db.SelectInt("select count(*) from user where userid=?", "anonymous")
if err == nil {
if count == 0 {
anonymous := &User{
UserId: "anonymous",
UserName: "Anonimo",
PicId: "default",
FullName: "Usuario Anonimo",
LikeCount: 0,
Creation: time.Now(),
LastUpdate: time.Now(),
Deleted: false,
Admin: false,
}
err := db.Insert(anonymous)
if err != nil {
log.Printf("Error creating the anonymous user. %s\n", err)
} else {
log.Println("User anonymous created!")
}
}
} else {
log.Printf("Error searching for user anonymous. %s\n", err)
}
}
func checkAndCreateCategories(db DB) {
for i, categoryName := range categoryList {
categorySlug := slug.Slug(categoryName)
count, err := db.SelectInt("select count(*) from category where categoryslug=?", categorySlug)
if err != nil {
log.Printf("Error searching for the category with categorySlug %s\n", categorySlug)
log.Println("Stopping the creation of categories")
return
}
if count == 0 {
category := &Category{
CategoryId: uniuri.NewLen(20),
CategoryName: categoryName,
CategorySlug: categorySlug,
LikeCount: 0,
}
if i == 0 { // "Sem Categoria" is my default category
category.CategoryId = "default"
}
err := db.Insert(category)
if err != nil {
log.Printf("Error when creating the category %s. %s\n", category.CategoryName, err)
} else {
log.Printf("Category %s created!\n", category.CategoryName)
}
}
}
}
var categoryList = []string{
"Sem categoria",
"Animais",
"Arte e Cultura",
"Beleza e Estilo",
"Carros e Motos",
"Casa e Decoração",
"Ciência e Tecnologia",
"Comidas e Bebidas",
"Crianças",
"Curiosidades",
"Downloads",
"Educação",
"Entretenimento",
"Esporte",
"Eventos",
"Família",
"Filmes",
"Fotos",
"Futebol",
"Humor",
"Internacional",
"Internet",
"Jogos",
"Livro",
"Meio ambiente",
"Mulher",
"Música",
"Negócios",
"Notícias",
"Pessoas e Blogs",
"Política",
"Saúde",
"Turismo e Viagem",
"Vídeos",
}