forked from coaidev/coai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.go
317 lines (283 loc) · 7.59 KB
/
database.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
package connection
import (
"chat/globals"
"chat/utils"
"crypto/tls"
"database/sql"
"fmt"
"github.com/go-sql-driver/mysql"
_ "github.com/go-sql-driver/mysql"
_ "github.com/mattn/go-sqlite3"
"github.com/spf13/viper"
)
var DB *sql.DB
func InitMySQLSafe() *sql.DB {
ConnectDatabase()
// using DB as a global variable to point to the latest db connection
MysqlWorker(DB)
return DB
}
func getConn() *sql.DB {
if viper.GetString("mysql.host") == "" {
globals.SqliteEngine = true
globals.Warn("[connection] mysql host is not set, using sqlite (~/db/chatnio.db)")
db, err := sql.Open("sqlite3", utils.FileSafe("./db/chatnio.db"))
if err != nil {
panic(err)
}
return db
}
mysqlUrl := fmt.Sprintf(
"%s:%s@tcp(%s:%d)/%s",
viper.GetString("mysql.user"),
viper.GetString("mysql.password"),
viper.GetString("mysql.host"),
viper.GetInt("mysql.port"),
utils.GetStringConfs("mysql.database", "mysql.db"),
)
if viper.GetBool("mysql.tls") {
mysql.RegisterTLSConfig("tls", &tls.Config{
MinVersion: tls.VersionTLS12,
ServerName: viper.GetString("mysql.host"),
})
mysqlUrl += "?tls=tls"
}
// connect to MySQL
db, err := sql.Open("mysql", mysqlUrl)
if pingErr := db.Ping(); err != nil || pingErr != nil {
errMsg := utils.Multi[string](err != nil, utils.GetError(err), utils.GetError(pingErr)) // err.Error() may contain nil pointer
globals.Warn(
fmt.Sprintf("[connection] failed to connect to mysql server: %s (message: %s), will retry in 5 seconds",
viper.GetString("mysql.host"), errMsg,
),
)
utils.Sleep(5000)
db.Close()
return getConn()
}
globals.Debug(fmt.Sprintf("[connection] connected to mysql server (host: %s)", viper.GetString("mysql.host")))
return db
}
func ConnectDatabase() *sql.DB {
db := getConn()
db.SetMaxOpenConns(512)
db.SetMaxIdleConns(64)
CreateUserTable(db)
CreateConversationTable(db)
CreateMaskTable(db)
CreateSharingTable(db)
CreatePackageTable(db)
CreateQuotaTable(db)
CreateSubscriptionTable(db)
CreateApiKeyTable(db)
CreateInvitationTable(db)
CreateRedeemTable(db)
CreateBroadcastTable(db)
if err := doMigration(db); err != nil {
fmt.Println(fmt.Sprintf("migration error: %s", err))
}
DB = db
return db
}
func InitRootUser(db *sql.DB) {
// create root user if totally empty
var count int
err := globals.QueryRowDb(db, "SELECT COUNT(*) FROM auth").Scan(&count)
if err != nil {
globals.Warn(fmt.Sprintf("[service] failed to query user count: %s", err.Error()))
return
}
if count == 0 {
globals.Debug("[service] no user found, creating root user (username: root, password: chatnio123456, email: [email protected])")
_, err := globals.ExecDb(db, `
INSERT INTO auth (username, password, email, is_admin, bind_id, token)
VALUES (?, ?, ?, ?, ?, ?)
`, "root", utils.Sha2Encrypt("chatnio123456"), "[email protected]", true, 0, "root")
if err != nil {
globals.Warn(fmt.Sprintf("[service] failed to create root user: %s", err.Error()))
}
} else {
globals.Debug(fmt.Sprintf("[service] %d user(s) found, skip creating root user", count))
}
}
func CreateUserTable(db *sql.DB) {
_, err := globals.ExecDb(db, `
CREATE TABLE IF NOT EXISTS auth (
id INT PRIMARY KEY AUTO_INCREMENT,
bind_id INT UNIQUE,
username VARCHAR(24) UNIQUE,
token VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE,
password VARCHAR(64) NOT NULL,
is_admin BOOLEAN DEFAULT FALSE,
is_banned BOOLEAN DEFAULT FALSE
);
`)
if err != nil {
fmt.Println(err)
}
InitRootUser(db)
}
func CreatePackageTable(db *sql.DB) {
_, err := globals.ExecDb(db, `
CREATE TABLE IF NOT EXISTS package (
id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT,
type VARCHAR(255),
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES auth(id),
UNIQUE KEY (user_id, type)
);
`)
if err != nil {
fmt.Println(err)
}
}
func CreateQuotaTable(db *sql.DB) {
_, err := globals.ExecDb(db, `
CREATE TABLE IF NOT EXISTS quota (
id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT UNIQUE,
quota DECIMAL(24, 6),
used DECIMAL(24, 6),
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES auth(id)
);
`)
if err != nil {
fmt.Println(err)
}
}
func CreateConversationTable(db *sql.DB) {
_, err := globals.ExecDb(db, `
CREATE TABLE IF NOT EXISTS conversation (
id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT,
conversation_id INT,
conversation_name VARCHAR(255),
data MEDIUMTEXT,
model VARCHAR(255) NOT NULL DEFAULT 'gpt-3.5-turbo-0613',
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY (user_id, conversation_id)
);
`)
if err != nil {
fmt.Println(err)
}
}
func CreateMaskTable(db *sql.DB) {
_, err := globals.ExecDb(db, `
CREATE TABLE IF NOT EXISTS mask (
id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT,
avatar VARCHAR(255),
name VARCHAR(255),
description TEXT,
context TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES auth(id)
);
`)
if err != nil {
fmt.Println(err)
}
}
func CreateSharingTable(db *sql.DB) {
// refs is an array of message id, separated by comma (-1 means all messages)
_, err := globals.ExecDb(db, `
CREATE TABLE IF NOT EXISTS sharing (
id INT PRIMARY KEY AUTO_INCREMENT,
hash CHAR(32) UNIQUE,
user_id INT,
conversation_id INT,
refs TEXT,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES auth(id)
);
`)
if err != nil {
fmt.Println(err)
}
}
func CreateSubscriptionTable(db *sql.DB) {
_, err := globals.ExecDb(db, `
CREATE TABLE IF NOT EXISTS subscription (
id INT PRIMARY KEY AUTO_INCREMENT,
level INT DEFAULT 1,
user_id INT UNIQUE,
expired_at DATETIME,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
total_month INT DEFAULT 0,
enterprise BOOLEAN DEFAULT FALSE,
FOREIGN KEY (user_id) REFERENCES auth(id)
);
`)
if err != nil {
fmt.Println(err)
}
}
func CreateApiKeyTable(db *sql.DB) {
_, err := globals.ExecDb(db, `
CREATE TABLE IF NOT EXISTS apikey (
id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT UNIQUE,
api_key VARCHAR(255) UNIQUE,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES auth(id)
);
`)
if err != nil {
fmt.Println(err)
}
}
func CreateInvitationTable(db *sql.DB) {
_, err := globals.ExecDb(db, `
CREATE TABLE IF NOT EXISTS invitation (
id INT PRIMARY KEY AUTO_INCREMENT,
code VARCHAR(255) UNIQUE,
quota DECIMAL(16, 4),
type VARCHAR(255),
used BOOLEAN DEFAULT FALSE,
used_id INT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY (used_id, type),
FOREIGN KEY (used_id) REFERENCES auth(id)
);
`)
if err != nil {
fmt.Println(err)
}
}
func CreateRedeemTable(db *sql.DB) {
_, err := globals.ExecDb(db, `
CREATE TABLE IF NOT EXISTS redeem (
id INT PRIMARY KEY AUTO_INCREMENT,
code VARCHAR(255) UNIQUE,
quota DECIMAL(16, 4),
used BOOLEAN DEFAULT FALSE,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
`)
if err != nil {
fmt.Println(err)
}
}
func CreateBroadcastTable(db *sql.DB) {
_, err := globals.ExecDb(db, `
CREATE TABLE IF NOT EXISTS broadcast (
id INT PRIMARY KEY AUTO_INCREMENT,
poster_id INT,
content TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (poster_id) REFERENCES auth(id)
);
`)
if err != nil {
fmt.Println(err)
}
}