-
Notifications
You must be signed in to change notification settings - Fork 21
/
mongo_orm.gogo
85 lines (72 loc) · 1.85 KB
/
mongo_orm.gogo
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
{{define "mongo_orm"}}package {{.GoPackage}}
{{$obj := .}}
{{if ($obj.DbSwitch "mongo")}}
import (
"time"
//3rd party libs
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
//Own libs
"github.com/ezbuy/ezorm/db"
. "github.com/ezbuy/ezorm/orm"
{{range .GetOrmImports}}
"{{.}}"
{{end}}
)
var _ time.Time
func init() {
{{if .NeedIndex}}
db.SetOnEnsureIndex(init{{.Name}}Index)
addMgoIndexFunc(init{{.Name}}Index)
{{end}}
{{if .NeedMapping}}
db.SetOnFinishInit(init{{.Name}}Mapping)
{{end}}
RegisterEzOrmObjByID("{{.Package}}", "{{.Name}}", new{{.Name}}FindByID)
RegisterEzOrmObjRemove("{{.Package}}", "{{.Name}}", {{.Name}}Mgr.RemoveByID)
{{if .NeedSearch}}
RegisterIndexer("{{.Package}}", "{{.Name}}", {{.Name}}Mgr.SearchRebuild)
{{end}}
}
{{if .NeedMapping}}
func init{{.Name}}Mapping() {
opt := indices.MappingOptions{
Properties: map[string]interface{}{
{{range .GetStringFilterFields}}
"{{.Name}}": map[string]string{"index": "not_analyzed", "type": "string"},
{{end}}
},
}
indices.CreateIndex("{{.SearchIndex}}")
indices.PutMapping("{{.SearchIndex}}", "{{.SearchType}}", {{.Name}}{}, opt)
}
{{end}}
{{if .NeedIndex}}
func init{{.Name}}Index() {
session, collection := {{.Name}}Mgr.GetCol()
defer session.Close()
{{range $index := $obj.Indexes}}
if err := collection.EnsureIndex(mgo.Index{
Key: []string{"{{$index.GetFieldList}}"},
{{- if $index.IsUnique }}
Unique: true,
{{- end}}
Background: true,
{{- if $index.IsSparse }}
Sparse: true,
{{- end}}
}); err != nil {
panic("ensureIndex {{$obj.DbName}}.{{$obj.Name}} {{$index.Name}} error:" + err.Error())
}
{{end}}
}
{{end}}
func new{{.Name}}FindByID(id string) (result EzOrmObj, err error) {
return {{.Name}}Mgr.FindByID(id)
}
{{ .LoadTpl "mongo_mongo" }}
{{ .LoadTpl "mongo_foreign_key" }}
{{ .LoadTpl "mongo_collection" }}
{{ .LoadTpl "mongo_search" }}
{{end}}
{{end}}