-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.go
More file actions
142 lines (118 loc) · 2.31 KB
/
database.go
File metadata and controls
142 lines (118 loc) · 2.31 KB
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
package main
import (
"encoding/json"
"log"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
var (
database *gorm.DB
queryModel = new(Query)
userModel = new(User)
keys = []string{
"sareh",
"ganjvajeh",
"slang",
"fa2en",
"en2fa",
"ar2fa",
"dezfuli",
"farhangestan",
"thesis",
"fa2ar",
"isfahani",
"tehrani",
"wiki",
"motaradef",
"quran",
"bakhtiari",
"moein",
"name",
"gonabadi",
"mazani",
"amid",
}
)
func init() {
var err error
database, err = gorm.Open("sqlite3", "database.db")
if err != nil {
log.Fatalln(err)
}
if !database.HasTable(queryModel) {
database.CreateTable(queryModel)
}
database.AutoMigrate(queryModel)
if !database.HasTable(userModel) {
database.CreateTable(userModel)
}
database.AutoMigrate(userModel)
}
type User struct {
gorm.Model
DeviceID string
Dictionary string // json
}
func (u *User) Get() {
database.Model(u).Find(u, "device_id = ?", u.DeviceID)
}
func (u *User) EncodeDictionary() string {
output := ""
m := u.GetDictionary()
for _, key := range keys {
if m[key] {
output += key + ","
}
}
output = output[:len(output)-1]
return output
}
func (u *User) Save() {
database.Model(u).Save(u)
}
func (u *User) GetAllDictionaries() map[string]bool {
m := make(map[string]bool)
for _, i := range keys {
m[i] = true
}
return m
}
func (u *User) CheckEmptyDictionary() bool {
if u.Dictionary == "" {
m := u.GetAllDictionaries()
u.SetDictionary(m)
return true
}
return false
}
func (u *User) Create() {
database.Model(u).Create(u)
}
func (u *User) GetDictionary() map[string]bool {
output := make(map[string]bool)
json.Unmarshal([]byte(u.Dictionary), &output)
return output
}
func (u *User) SetDictionary(input map[string]bool) {
bytes, err := json.Marshal(input)
if err != nil {
log.Println("Error on set dictionary", err)
}
u.Dictionary = string(bytes)
}
type Query struct {
gorm.Model
Query string
DeviceID string
}
func (q *Query) Save() {
database.Model(q).Save(q)
}
func (q *Query) Create() {
database.Model(q).Create(q)
}
func getQueries(deviceID string, limit int, q string) []Query {
list := []Query{}
database.Model(&Query{}).Select("distinct(query)").Where("device_id = ? and query <> ?", deviceID, q).Order("created_at").Limit(limit).Scan(&list)
return list
}