-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathshell.go
399 lines (362 loc) · 9.35 KB
/
shell.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
package korm
import (
"encoding/json"
"errors"
"fmt"
"io"
"os"
"strings"
"github.com/kamalshkeir/argon"
"github.com/kamalshkeir/kinput"
"github.com/kamalshkeir/ksmux"
"github.com/kamalshkeir/lg"
)
const (
red = "\033[1;31m%v\033[0m\n"
green = "\033[1;32m%v\033[0m\n"
yellow = "\033[1;33m%v\033[0m\n"
blue = "\033[1;34m%v\033[0m\n"
magenta = "\033[5;35m%v\033[0m\n"
)
var usedDB DatabaseEntity
const helpS string = `
[
databases, use, tables, columns, migrate, createsuperuser, createuser
query, getall, get, drop, delete, clear/cls, q/quit/exit, help/commands
]
'databases':
list all connected databases
'use':
use a specific database
'tables':
list all tables in database
'columns':
list all columns of a table
'migrate':
migrate or execute sql file
'createsuperuser': (only with dashboard)
create a admin user
'createuser': (only with dashboard)
create a regular user
'query':
query data from database
(accept but not required extra param like : 'query' or 'query select * from users where ...')
'getall':
get all rows given a table name
(accept but not required extra param like : 'getall' or 'getall users')
'get':
get single row
(accept but not required extra param like : 'get' or 'get users email like "%anything%"')
'delete':
delete rows where field equal_to
(accept but not required extra param like : 'delete' or 'delete users email="email@example.com"')
'drop':
drop a table given table name
(accept but not required extra param like : 'drop' or 'drop users')
'clear / cls':
clear shell console
'q / quit / exit / q!':
exit shell
'help':
show this help message
`
const commandsS string = "Commands : [databases, use, tables, columns, migrate, query, getall, get, drop, delete, createsuperuser, createuser, clear/cls, q/q!/quit/exit, help/commands]"
// InitShell init the shell and return true if used to stop main
func InitShell() bool {
args := os.Args
if len(args) < 2 {
return false
}
args = args[1:]
switch args[0] {
case "commands":
fmt.Printf(yellow, "Usage: go run main.go shell")
fmt.Printf(yellow, commandsS)
return true
case "help":
fmt.Printf(yellow, "Usage: go run main.go shell")
fmt.Printf(yellow, helpS)
return true
case "shell":
if len(args) > 1 {
handleCommand(args[1:])
return true
}
databases := GetMemoryDatabases()
usedDB = databases[0]
defer usedDB.Conn.Close()
fmt.Printf(yellow, commandsS)
for {
command, err := kinput.String(kinput.Blue, "> ")
if err != nil {
if errors.Is(err, io.EOF) {
fmt.Printf(blue, "shell shutting down")
}
return true
}
spCommand := strings.Split(command, " ")
if handleCommand(spCommand) {
return true
}
}
case "gendocs", "gendoc":
if len(args) > 1 && args[1] != "" {
ksmux.DocsOutJson = args[1]
_ = ksmux.CheckAndInstallSwagger()
ksmux.GenerateGoDocsComments()
ksmux.GenerateJsonDocs()
} else {
ksmux.DocsOutJson = "./" + staticDir + "/docs"
_ = ksmux.CheckAndInstallSwagger()
ksmux.GenerateGoDocsComments()
ksmux.GenerateJsonDocs()
}
return true
default:
return false
}
}
func handleCommand(commands []string) bool {
command := ""
if len(commands) > 0 {
command = commands[0]
}
switch command {
case "quit", "exit", "q", "q!":
return true
case "clear", "cls":
kinput.Clear()
fmt.Printf(yellow, commandsS)
case "help":
fmt.Printf(yellow, helpS)
case "commands":
fmt.Printf(yellow, commandsS)
case "migrate":
var path string
if len(commands) > 1 {
path = commands[1]
} else {
path = kinput.Input(kinput.Blue, "path to sql file: ")
}
err := migratefromfile(path)
if !lg.CheckError(err) {
fmt.Printf(green, "migrated successfully")
}
case "databases":
fmt.Printf(green, GetMemoryDatabases())
case "use":
var dbName string
if len(commands) > 1 {
dbName = commands[1]
} else {
dbName = kinput.Input(kinput.Blue, "database name: ")
}
db, err := GetMemoryDatabase(dbName)
if err != nil {
lg.Printfs("rd%v\n", err)
}
usedDB = *db
fmt.Printf(green, "you are using database "+usedDB.Name)
case "tables":
fmt.Printf(green, GetAllTables(usedDB.Name))
case "columns":
var tb string
if len(commands) > 1 {
tb = commands[1]
} else {
tb = kinput.Input(kinput.Blue, "Table name: ")
}
if tb == "" {
fmt.Printf(red, "you should specify a table that exist !")
}
mcols, _ := GetAllColumnsTypes(tb, usedDB.Name)
cols := []string{}
for k := range mcols {
cols = append(cols, k)
}
fmt.Printf(green, cols)
case "getall":
if len(commands) > 1 {
getAll(commands[1])
} else {
getAll("")
}
case "get":
if len(commands) > 2 {
getRow(commands[1], strings.Join(commands[2:], " "))
} else {
getRow("", "")
}
case "query":
if len(commands) > 1 {
query(strings.Join(commands[1:], " "))
} else {
query("")
}
case "drop":
if len(commands) > 1 {
dropTable(commands[1])
} else {
dropTable("")
}
case "delete":
if len(commands) > 2 {
deleteRow(commands[1], strings.Join(commands[2:], " "))
} else {
deleteRow("", "")
}
case "createuser":
createuser()
case "createsuperuser":
createsuperuser()
default:
fmt.Printf(red, "command not handled, use 'help' or 'commands' to list available commands"+command)
}
return false
}
func createuser() {
username := kinput.Input(kinput.Blue, "Username : ")
email := kinput.Input(kinput.Blue, "Email : ")
password := kinput.Hidden(kinput.Blue, "Password : ")
if email != "" && password != "" {
err := newuser(username, email, password, false)
if err == nil {
fmt.Printf(green, "User "+email+" created successfully")
} else {
fmt.Printf(red, "unable to create user:"+err.Error())
}
} else {
fmt.Printf(red, "email or password invalid")
}
}
func createsuperuser() {
username := kinput.Input(kinput.Blue, "Username: ")
email := kinput.Input(kinput.Blue, "Email: ")
password := kinput.Hidden(kinput.Blue, "Password: ")
err := newuser(username, email, password, true)
if err == nil {
fmt.Printf(green, "Admin "+email+" created successfully")
} else {
fmt.Printf(red, "error creating user :"+err.Error())
}
}
func getAll(tbName string) {
if tbName == "" {
tbName = kinput.Input(kinput.Blue, "Enter a table name: ")
}
data, err := Table(tbName).Database(usedDB.Name).All()
if err == nil {
d, _ := json.MarshalIndent(data, "", " ")
fmt.Printf(green, string(d))
} else {
fmt.Printf(red, err.Error())
}
}
func query(queryStatement string) {
if queryStatement == "" {
queryStatement = kinput.Input(kinput.Blue, "Query: ")
}
data, err := BuilderMap().QueryM(queryStatement)
if err == nil {
d, _ := json.MarshalIndent(data, "", " ")
fmt.Printf(green, string(d))
} else {
fmt.Printf(red, err.Error())
}
}
func newuser(username, email, password string, admin bool) error {
if email == "" || password == "" {
return fmt.Errorf("email or password empty")
}
if !IsValidEmail(email) {
return fmt.Errorf("email not valid")
}
hash, err := argon.Hash(password)
if err != nil {
return err
}
_, err = Table("users").Insert(map[string]any{
"uuid": GenerateUUID(),
"email": email,
"password": hash,
"username": username,
"is_admin": admin,
"image": "",
})
if err != nil {
return err
}
return nil
}
func getRow(tbName, where string) {
if tbName == "" || where == "" {
tbName = kinput.Input(kinput.Blue, "Table Name: ")
where = kinput.Input(kinput.Blue, "Where Query: ")
}
if tbName != "" && where != "" {
var data map[string]any
var err error
data, err = Table(tbName).Database(usedDB.Name).Where(where).One()
if err == nil {
d, _ := json.MarshalIndent(data, "", " ")
fmt.Printf(green, string(d))
} else {
fmt.Printf(red, "error: "+err.Error())
}
} else {
fmt.Printf(red, "One or more field are empty")
}
}
func migratefromfile(path string) error {
if !SliceContains([]string{POSTGRES, SQLITE, MYSQL, MARIA}, databases[0].Dialect) {
fmt.Printf(red, "database is neither postgres, sqlite3 or mysql ")
return errors.New("database is neither postgres, sqlite3 or mysql ")
}
if path == "" {
fmt.Printf(red, "path cannot be empty ")
return errors.New("path cannot be empty ")
}
statements := []string{}
b, err := os.ReadFile(path)
if err != nil {
return errors.New("error reading from " + path + " " + err.Error())
}
splited := strings.Split(string(b), ";")
statements = append(statements, splited...)
//exec migrations
for i := range statements {
conn := usedDB.Conn
_, err := conn.Exec(statements[i])
if err != nil {
return errors.New("error migrating from " + path + " " + err.Error())
}
}
return nil
}
func dropTable(tbName string) {
if tbName == "" {
tbName = kinput.Input(kinput.Blue, "Table to drop : ")
}
_, err := Table(tbName).Database(usedDB.Name).Drop()
if err != nil {
fmt.Printf(red, "error dropping table :"+err.Error())
} else {
fmt.Printf(green, tbName+" dropped")
}
}
func deleteRow(tbName, where string) {
if tbName == "" || where == "" {
tbName = kinput.Input(kinput.Blue, "Table Name: ")
where = kinput.Input(kinput.Blue, "Where Query: ")
}
if tbName != "" && where != "" {
_, err := Table(tbName).Database(usedDB.Name).Where(where).Delete()
if err == nil {
fmt.Printf(green, tbName+" deleted.")
} else {
fmt.Printf(red, "error deleting row: "+err.Error())
}
} else {
fmt.Printf(red, "some of args are empty")
}
}