-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate_model_repo.go
63 lines (55 loc) · 1.53 KB
/
create_model_repo.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
package model
import (
"strings"
)
func (repo *Repo) DropRepoDB(db DB) error {
repo.Clean()
tableName := repo.QuotedTableName()
_, err := db.Exec("DROP TABLE " + tableName)
return err
}
// DropRepo will drop the database table about the repo
func (repo *Repo) DropRepo() error {
return repo.DropRepoDB(GetDefaultDB())
}
func (repo *Repo) CreateRepo() error {
return repo.CreateRepoDB(GetDefaultDB())
}
// CreateRepo will create database table about the repo
func (repo *Repo) CreateRepoDB(db DB) error {
sqlang, indexes := repo.forCreateTable()
if _, err := db.Exec(sqlang, repo.Params()...); err != nil {
return err
}
for _, index := range indexes {
if _, err := db.Exec(index); err != nil {
return err
}
}
return nil
}
// forCreateTable generate the create database table sql lang and create database index sql lang
func (repo *Repo) forCreateTable() (sqlang string, indexes []string) {
sqlang = "CREATE TABLE " + repo.QuotedTableName()
indexes = []string{}
cols := []string{}
repo.model.(Mapable).Mapper().each(func(fd *fieldDescriptor) bool {
col := []string{fd.colname, fd.coltype}
if fd.ispk {
col = append(col, "PRIMARY KEY")
}
if !fd.nullable {
col = append(col, "NOT NULL")
}
if fd.isuk {
tn := repo.model.(Model).TableName()
index := "CREATE UNIQUE INDEX ui_" + tn + "_" + fd.colname +
" ON " + tn + " (" + fd.colname + ")"
indexes = append(indexes, index)
}
cols = append(cols, strings.Join(col, " "))
return true
})
sqlang += "(\n\t" + strings.Join(cols, ",\n\t") + "\n)"
return
}