forked from meshery/meshery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsql-utils.go
76 lines (65 loc) · 1.73 KB
/
sql-utils.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
package models
import (
"fmt"
"os"
"strings"
"sync"
"github.com/layer5io/meshkit/database"
"github.com/layer5io/meshkit/logger"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
// sanitizeOrderInput takes in the "order by" query, a validColums
// string slice and returns a sanitized query
//
// it will allow to run order by query only on the columns that are present
// in the validColumns string slice, if any other column is requested in the
// query then it will be IGNORED and an empty query would be returned instead
//
// sanitizeOrderInput also expects the query to be no longer than two words, that is
// the query may look like "updated_at DESC" or "name ASC"
func sanitizeOrderInput(order string, validColumns []string) string {
parsedOrderStr := strings.Split(order, " ")
if len(parsedOrderStr) != 2 {
return ""
}
inputCol := parsedOrderStr[0]
typ := strings.ToLower(parsedOrderStr[1])
for _, col := range validColumns {
if col == inputCol {
if typ == "desc" {
return fmt.Sprintf("%s desc", col)
}
return fmt.Sprintf("%s asc", col)
}
}
return ""
}
var (
dbHandler database.Handler
mx sync.Mutex
)
func setNewDBInstance() {
mx.Lock()
defer mx.Unlock()
// Initialize Logger instance
log, err := logger.New("meshery", logger.Options{
Format: logger.SyslogLogFormat,
})
if err != nil {
log.Error(err)
os.Exit(1)
}
dbHandler, err = database.New(database.Options{
Filename: fmt.Sprintf("file:%s/mesherydb.sql?cache=private&mode=rwc&_busy_timeout=10000&_journal_mode=WAL", viper.GetString("USER_DATA_FOLDER")),
Engine: database.SQLITE,
Logger: log,
})
if err != nil {
logrus.Fatal(err)
}
}
func GetNewDBInstance() *database.Handler {
setNewDBInstance()
return &dbHandler
}