92 lines
1.5 KiB
Go
92 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
|
|
"github.com/DataDog/go-sqllexer"
|
|
)
|
|
|
|
type QueryType int
|
|
|
|
const (
|
|
NONE QueryType = iota
|
|
SELECT
|
|
UPDATE
|
|
INSERT
|
|
DELETE
|
|
)
|
|
|
|
type Query struct {
|
|
Type QueryType
|
|
FullSql string
|
|
IsValid bool
|
|
}
|
|
|
|
func IsTokenEndOfStatement(token *sqllexer.Token) bool {
|
|
return (token.Type == sqllexer.EOF || token.Value == ";")
|
|
}
|
|
|
|
func GetQueryTypeFromToken(token *sqllexer.Token) QueryType {
|
|
if token.Type != sqllexer.COMMAND {
|
|
return NONE
|
|
}
|
|
|
|
var foundType QueryType
|
|
switch strings.ToUpper(token.Value) {
|
|
case "SELECT":
|
|
foundType = SELECT
|
|
case "UPDATE":
|
|
foundType = UPDATE
|
|
case "INSERT":
|
|
foundType = INSERT
|
|
case "DELETE":
|
|
foundType = DELETE
|
|
default:
|
|
foundType = NONE
|
|
}
|
|
|
|
return foundType
|
|
}
|
|
|
|
func IsCrudSqlStatement(token *sqllexer.Token) bool {
|
|
queryType := GetQueryTypeFromToken(token)
|
|
return (queryType > 0 && queryType <= 4) // TODO: Update if QueryTypes Change
|
|
}
|
|
|
|
func GetQueryTypeFromSql(sql string) QueryType {
|
|
var queryType QueryType
|
|
|
|
lexer := sqllexer.New(sql)
|
|
for {
|
|
token := lexer.Scan()
|
|
if IsTokenEndOfStatement(token) {
|
|
break
|
|
}
|
|
|
|
queryType = GetQueryTypeFromToken(token)
|
|
if queryType > 0 {
|
|
break
|
|
}
|
|
}
|
|
|
|
return queryType
|
|
}
|
|
|
|
func main() {
|
|
query := "DELETE * FROM users \n WHERE id = something AND SELECT;"
|
|
newQuery := GetQueryTypeFromSql(query)
|
|
|
|
fmt.Println(newQuery)
|
|
|
|
//lexer := sqllexer.New(query)
|
|
//for {
|
|
// token := lexer.Scan()
|
|
// fmt.Println(token.Value, token.Type)
|
|
|
|
// if token.Type == sqllexer.EOF {
|
|
// break
|
|
// }
|
|
//}
|
|
}
|